Professional Documents
Culture Documents
.
Figure 4.1: Yaw Control
19
Chapter 4. Mechanical Design 4.2. Frame Design
4.1.2 Pitch Control
Pitch is controlled by using several complex techniques such as pendulum balancing and
longitudinal cyclic pitch control in the real V-22 Osprey. The model V-22 controls pitch
by the addition of a tail fan unit. This provides a much simpler and decoupled control
method than that employed by the real V-22 Osprey at the expense of model aesthetics.
The frame therefore provides facilities to mount a small ducted fan at the rear.
Given the helicopter nature of the V-22 Osprey, when in hover pitch is highly coupled
with forward translation. Thus if the aircraft pitches forward it will move forward as well
due to the thrust being slightly non-vertical.
4.1.3 Roll Control
Roll in the real V-22 Osprey is produced by creating a dierential thrust at each proprotor.
This dierential thrust creates a moment about the centre of mass and causes rotation
about its longitudinal axis. The real V-22 Osprey creates this thrust dierential by
adjusting the collective pitch of each proprotor since speed control is too slow due to
the large rotational inertia of the propellers. To simplify this, the model V-22 uses two
separate motors and creates the dierential thrust simply by dierential motor speeds.
4.1.4 Translation Control
The real V-22 Osprey controls vertical translation by collectively changing the thrust at
each proprotor. This is achieved in the model V-22 by collectively changing the motor
speeds.
The actual V-22 Osprey can strafe in the horizontal axis by laterally adjusting the angle
of the proprotors. This feature is neglected on the model V-22 due to the associated
complexities in both the mechanical and control system designs. Thus control of horizontal
translation is achieved through the natural coupling with pitch and roll.
4.2 Frame Design
A general aircraft frame must be as light as possible while still being suciently strong
to carry all components and not fail. Furthermore for a VTOL platform the frame must
20
4.2. Frame Design Chapter 4. Mechanical Design
provide sucient actuation, as just discussed, to enable a sustained, stable hover. The
frame must also be suciently congurable to accommodate any design changes.
The frame was designed using the Computer Aided Design (CAD) package SolidEdge.
SolidEdge models parts as solids, with associated physical properties such as density.
This allows the monitoring of the total system mass, the centre of mass and the rotational
moments of inertia about the centre of mass. All of these properties are important when
designing a control system.
4.2.1 Materials
According to Newman (2005), materials commonly used in the construction of model
aircraft are Aluminium, Balsa Wood, Birch Wood, Carbon Fibre Tube, Cellfoam 88
and Depron. The relevant mechanical properties are shown in Table 4.1. Due to the
similar properties of Cellfoam 88 and Depron they have both been included as the Foamed
Polymer entry.
Table 4.1: Mechanical Properties of Common Model Aircraft Materials
Material Density
(kg/m
3
)
Youngs
Modulus
E(GPa)
Ultimate Tensile
Strength
ut
(MPa)
6060 T4 Aluminium 2710 70 160
Balsa Wood 110 - 150 2.6 - 3.5 10 - 12
Birch Wood 500 - 700 4.5 - 10.3 27 - 40
Carbon Fibre Tube 1500 - 1600 60 - 160 300 - 800
Foamed Polymer 50 - 77 0.0034 - 0.032 0.01 - 0.9
Aluminium was chosen as the base frame material due to its low cost and easy fabrication
properties, despite Carbon Fibre Tubing having a signicant strength to weight advantage.
4.2.2 Tilt Rotor Concepts
As previously discussed the nacelle of our proposed model design must be able to rotate
over 90
to meet the control requirements. Several concepts to allow this were considered,
before the current solution was chosen.
The concept of a rotating motor mount directly coupled to a servo motor is shown in
Figure 4.2. This concept is mechanically sound, providing the required rotation with the
21
Chapter 4. Mechanical Design 4.2. Frame Design
forces supported by the bearings. The directly coupled servo motor provides a direct,
linear link between the servo motor angles and the angle of the propulsion system. The
main disadvantage of this concept is the considerable mass and size associated with the
large wing-arm section. The servo motor and bearing required would also be quite large,
necessitating a larger scale model to accommodate it all.
Figure 4.2: Rotating Mount Concept
An alternative solution of placing the motors inside the frame, driving the propellers
through 90
gearboxes, is shown in Figure 4.3. This concept removes the weight of the
bulky components from the end of the wing, allowing for a lighter wing section. There
are several disadvantages to this concept. Firstly, having the weight close to the centre of
mass reduces the rotational moment of inertia, making the platform less stable as it will
rotate more quickly. Secondly, the centre of nacelle rotation must be based at the same
point as the motor shaft passes through. A consequence of this is that when the nacelle
rotates the propeller speed will change due to relative speed dierences. Additionally long
shaft sections rotating at high speeds are prone to vibration.
4.2.3 Final Tilt-Rotor Design
Combining several of the advantages of the concept solution, the nal solution is shown
in Figure 4.4. It features a servo motor directly coupled to the aluminium tube which
supports the motor. The bearing and servo motor are located on the fuselage, removing all
bulky components except the motor and gearbox from the wing itself. An interchangeable
mount is used at the end of the tube to provide versatility should a dierent motor be
required. The motor and motor mount at the outer end of the tube are shown in Figure
4.5. For the details of the wing arm parts and assembly refer to Appendix A.
22
4.2. Frame Design Chapter 4. Mechanical Design
Figure 4.3: Internal Motor Concept
Figure 4.4: Final Motor Rotation Conguration
23
Chapter 4. Mechanical Design 4.2. Frame Design
Figure 4.5: Motor and Motor Mount
4.2.4 Frame Concepts
Referring to Section 4.2.1, Aluminium was chosen as the base frame material. To simplify
fabrication it was decided that standard Aluminium sections would be used. Originally
using 12 20 1.5 mm unequal angle sections and 10 1.2 mm tube, the rst frame
concept shown in Figure 4.6 was constructed in SolidEdge. This frame had several strong
features, including rotating wing arms, a rigid central mount for the IMU to locate it at
the model V-22s centre of mass, and versatile motor mounts. It was scaled to t inside a
1:15 scale model size of the actual V-22 Osprey. The major drawback of this design was
its weight, approximately 800 g according to SolidEdge. This was considered too heavy
for just a bare frame.
Following this, the frame was redesigned to be lighter by using less Aluminium and better
utilising Balsa wood as a material. The concept is shown in Figure 4.7.
As a further evolution to the weight reduction by making the frame as small as possible,
the concept shown in Figure 4.8 was considered. Although this concept frame has much
less room for components than the previous two, its lighter weight makes it a desirable
solution.
24
4.2. Frame Design Chapter 4. Mechanical Design
Figure 4.6: First Frame Concept
25
Chapter 4. Mechanical Design 4.2. Frame Design
Figure 4.7: Redesigned Frame Concept
26
4.2. Frame Design Chapter 4. Mechanical Design
Figure 4.8: Final Frame Concept Sketch
27
Chapter 4. Mechanical Design 4.3. Propulsion
4.2.5 Final Frame Design
The nal frame design is an evolution of the concepts, and as such it closely resembles the
concept sketch in Figure 4.8. Upon construction in SolidEdge it was evident this concept
solution may not accommodate all of the components. A Balsa wood subcarriage was
considered to hold some of the bulky components such as batteries, as shown in Figure
4.9, however it was not used as the hardware was attached to both the top and bottom
of the frame, alleviating the need for an undercarriage.
Figure 4.9: Final Frame Design
The frame was constructed without the balsa-wood subcarriage is shown in Figure 4.10.
The frame as-built diers from the previous design slightly due to the recommendations
of the workshop sta. These recommendations included the use of thicker wing-arm and
rear-arm tubing, now 162 mm aluminium tube, and the inclusion of a top plate between
the bearing blocks to reduce lateral deection under load.
The nal frame design is estimated to weigh the same as the rst concept designed in
SolidEdge, however through the use of larger materials its strength and hence robustness
against damage was greatly increased. For the full details of the frame construction,
please refer to Appendix A.
4.3 Propulsion
The propulsion unit in a VTOL aircraft is of extreme importance, as it is responsible
for generating enough thrust to overcome the mass of the aircraft. Propulsion units are
28
4.3. Propulsion Chapter 4. Mechanical Design
Figure 4.10: Frame As Built
generally comprised of a motor that drives some kind of propeller/impeller and a power
source. The most appropriate motor, propeller and power source combination for this
design were considered for selection.
4.3.1 Propeller
The actual V-22 Osprey operates variable-pitch proprotors to obtain the required thrust
outputs (Boeing, 2005). The proprotor system of the Osprey incorporates a tri-blade hub,
with automatic folding graphite/breglass blades. The approximate diameter of the rotor
system is 11.58 m and thus they have signicant rotational inertia due to their large size.
For this reason the V-22 Osprey proprotors operate at a constant speed with variable
pitch utilised to adjust thrust.
The propeller choice for this project was primarily dependant on the static thrust required
to achieve stable hover. The actual selection was an iterative process, as the required
maximum thrust was dependant on the nal weight of the model. However, the weight
of the model depended signicantly on the choice of the motors, propellers and batteries.
Thus the nal weight of the model had to be estimated using the weight of known
components, the frame and choosing an appropriate sized motor and battery to suit.
The chosen propeller must be available as a pusher/tractor pair, this is when two propellers
are identical but designed to operate in dierent rotational directions. By doing this the
drag forces which act on the propeller to create a yawing moment on the frame are
cancelled out by their counter-rotation.
29
Chapter 4. Mechanical Design 4.3. Propulsion
4.3.2 Propeller Theory
Basic propeller theory contains several equations that were used as a guide in the selection
of an appropriate propeller (McCormick, 1995). The most important of these equations
is that which determines an appropriate blade diameter D based on required static thrust
T and the induced power at static thrust P
i
0
:
T = P
2
3
i
0
1
2
D
2
1
3
(4.1)
where is the density of air.
Estimating the required static thrust to be 24.5N and using the required induced power to
be 375W from data obtained during Section 3.2.2, the required propeller was estimated
to be 15. However this was a lower bounds estimate as the in-ground eects caused
by the propeller sucking in its own downwash had not been considered. According to
Newman (2005) an in-ground eect correction factor of 1.3 was needed to be factored into
the thrust and yielded an estimated propeller diameter of 21.
4.3.2.1 Fixed vs Variable Pitch
For propellers with a large rotational inertia, variable thrust is accomplished by varying
the pitch of the propeller, whilst maintaining a constant rotational speed. This type
of thrust control signicantly adds to the complexity of the mechanical design. The
alternative method consists of using a xed pitch propeller and varying the rotational
velocity to vary the thrust response. This type of thrust control is limited by the torquing
capabilities of the motor providing the power and is heavily dependant on the rotational
inertia of the chosen propeller. Due to the reduction in both mechanical and control
system design and the low inertia associated with the use of xed pitch model aircraft
propellers, they were selected over variable-pitch propellers as the method for thrust
variation in the design.
4.3.2.2 Number of Blades
It was decided to use two-blade propellers as compared to the three-bladed system used by
the real V-22 Osprey. This is due to the increased eciency of the two-bladed propellers
over the three-bladed propellers (HazelProp, 2005).
30
4.3. Propulsion Chapter 4. Mechanical Design
4.3.2.3 Material
The material of the propeller needed to be light weight, rigid and extremely durable, as
the model would be subject to potential failures where the propeller could experience
possible impacts. According to Aireld Models (2005) the ve commonly used materials
for model aircraft propellers are wood, nylon, breglass-reinforced nylon, breglass and
carbon bre. Wood propellers were not considered as they lacked sucient strength,
particularly in the larger designs. Nylon propellers were also not a practical choice of
material, although they are highly resilient to impact they are exceedingly exible and
thus cause a continual change to pitch in addition to high levels of vibration. Both carbon
bre and breglass propellers were viable options, however, due to the expensiveness of
carbon bre and the non-durable nature of breglass they were not considered as suitable
propeller choices. Glass-lled nylon or breglass-reinforced nylon were chosen as the most
desirable propeller materials as they are highly durable, rigid and reasonably inexpensive,
though less ecient than carbon bre propellers.
4.3.2.4 Size
The size of the propeller is specied by the tip to tip diameter and the associated pitch.
In this case MotoCalc was used to determine the most suitable propeller size based on the
required static thrust and induced power of the electric motor. The result of MotoCalc
was that a diameter of at least 18 and a pitch no less than 10 was required for 25 N of
thrust at maximum eciency. The motor/propeller combination must have a steep speed
gradient at their hover point in order to give adequate authority for the control system,
so a small pitch had to be used as this gives ner speed control.
4.3.2.5 Final Selection
The nal choice of propeller consisted of a 20 10 APC glass-lled nylon two-blade
xed-pitch propeller, which is available as a pusher/tractor pair. The size constraints
were conrmed by basic propeller theory, which estimated the propeller diameter to be
approximately 15. This is a lower estimate because it does not consider in-ground eects,
which will occur during initial stages of hover. When such eects are factored into the
calculations, a resultant propeller diameter of approximately 21 is found, which agrees
with the estimation made by MotoCalc.
31
Chapter 4. Mechanical Design 4.3. Propulsion
4.3.3 Motor
Consideration was given to the use of several types of motors, ranging from small jet
engines through to internal combustion engines. However, following the recommendations
of Jarrett et al. (2004) and the selection criteria of cost, eciency, reliability, size, weight
and ease of operation it was decided to use electric motors to drive the propellers. Two
possible types of electric motors were considered for selection, brushed and brushless.
4.3.3.1 Brushed Motors
Brushed electric motors are the simplest form of direct current (DC) motor to use. They
operate with permanent magnets attached to the case and windings attached to their
rotor, using brushes to produce mechanical commutation. Whilst they are easy to use
they typically operate at a lower eciency than the equivalent brushless motor and are
not commonly used in remote control motors of the power rating required for the project.
Due to the wear on the brushes, from the nature of mechanical commutation, the motor
performance will vary with long-term operation. Hence any motor constants used in the
construction of the control system will change over time as the motor wears.
4.3.3.2 Brushless Motors
The brushless DC electric motor uses an electronically controlled commutation system,
instead of a mechanically controlled commutation system (Wikipedia, 2005). The benets
of using a brushless motor over a conventional brushed motor include higher reliability,
longer lifetime (no brush erosion), elimination of ionizing sparks from the commutator,
and overall reduction of electromagnetic interference. Brushless motors generally operate
at eciencies between 80% and 90% while brushed motors of the same capacity typically
operate at 60-70% (RS Automation, 2005). Furthermore, brushless motors are able to
operate consistently at higher RPM and with higher cogging-torque, they are ideal for
use in this application because of both the large size and expected high speeds of the
propellers.
There are two types of DC brushless motor used in RC equipment, the standard brushless
motor (also known as the inrunner) and the outrunner. Both types of motor contain
xed windings with rotating permanent magnets, the dierence being the standard
brushless motor has the permanent magnets attached to the rotor, while on an outrunner
they are attached to a section of the outer casing which rotates, driving the rotor through
32
4.3. Propulsion Chapter 4. Mechanical Design
gears. The outrunner has a higher start-up torque than a standard brushless motor, but
it was decided against using these due to their increased mounting complexities, smaller
product range and relative infancy.
Given their windings are xed, brushless DC motors require a three-phase power supply in
order to operate. This is provided by an Electronic Speed Controller (ESC) which chops
the DC supply voltage into a three-phase signal for powering the motor and controlling
its speed.
4.3.3.3 Final Selection
Brushless motors were chosen over conventional brushed motors to drive the propellers
based on their high RPM and torque capabilities in conjunction with the minimal
associated wear, resulting in constant motor characteristics over the life of operation.
As with the propeller selection, the choice of motor was determined through the
comparative ability of the MotoCalc software (Newman, 2005) These calculations
compensate for motor heating eects, which is important as motor eciency changes with
temperature. The primary consideration in the selection of the motor was the required
static thrust. Although the static thrust was dependant on the weight of the motor itself,
an estimation was used and a motor selected which would attain the required static thrust
to maintain hover at as close to maximum eciency as possible. The associated thrust
value estimated to be needed at maximum eciency was 25 N.
An iterative process of determining the ideal motor based on the desired thrust and known
constraints led to the selection of the Plettenberg 220/30/A3 P4 brushless motor, with a
planetary gearbox at a ratio of 5:1. This motor and propeller combination, although not
the optimum solution for maximum eciency at hover, was the best combination that
could be found without undertaking a substantial optimisation analysis. To drive the
Plettenberg motors, an 80 A Hyperion ESC was selected.
4.3.4 Batteries
A number of requirements were placed about the selection of battery. Firstly, the battery
needed to be rechargeable, with a large number of charge cycles (100) possible. Secondly,
the battery was required to output a minimum of 20A at a minimum of 10V, in order to
eectively drive the above motor and propeller combination (ICARE, 2005). Finally, the
selection of battery type was heavily dependant on energy density, as the weight budget
of the model is a crucial factor for a model VTOL aircraft. Three commonly used battery
33
Chapter 4. Mechanical Design 4.3. Propulsion
types were considered to drive the brushless electric motors. These were Nickel-Cadmium
(NiCd), Nickel-Metal Hydride (NiMH) and Lithium Polymer (LiPo) and the comparative
analysis can be seen in Table 4.2, where the gravimetric energy density is the value of
average power discharge multiplied by the number of service hours divided by the mass
of the battery.
Table 4.2: Comparison of Battery Types
Battery Type
Characteristic NiCd NiMH LiPo
Voltage (V ) 9.6 12 8.4 12 12 7.4 11.1 11.1
Capacity (mAh) 2400 2400 3000 1000 3000 1700 2250 3600
Weight (g) 495 670 442 205 600 82 150 302
Gravimetric Energy
Density (Wh/kg)
45-80 60-120 100-130
From this table, the decision was made to use Lithium Polymer batteries because of their
higher gravimetric energy density. The Plettenberg 220/30/A3 P4 brushless motors were
easily powered from 11.1V, however commonly attainable LiPo packs of 2450mAh were
unable to provide the continuously required current. Thus two 11.1V (3S1P) LiPo battery
packs were chosen to be used in parallel to eectively power the propulsion unit. This
conguration also increases the ight time. The batteries selected were the Tanic 11.1V,
2450mAh LiPo packs. These each weighed 165g, resulting in a net battery weight of 660g
for the main motors.
4.3.5 Propulsion Component Summary
Thus the nal selection for the propulsion unit of the model consisted of two Plettenberg
220/30/A3 P4 brushless motors geared 5:1, each connected to a 2010 APC glass-lled
nylon two-blade xed pitch propeller. Each motor is controlled using an 80 Amp Hyperion
Brushless ESC, and is to be powered by two Tanic 11.1V 2450mAh LiPo battery packs
in parallel.
The theoretical thrust levels attained by each motor and propeller combination were
estimated by MotoCalc to be 27 N using a 2010 propeller. The actual thrust attained
during testing was approximately 25N. This discrepancy was likely due to signicant in-
ground eects in the conned area of testing and motor losses.
34
4.3. Propulsion Chapter 4. Mechanical Design
Figure 4.11: Selected Motor, Propeller and ESC.
4.3.6 Tail Thrust
As discussed in Section 4.1 it was decided to use a thrust unit at the tail of the plane to
control pitch. The thrust (T) generated by the primary motors creates a moment (M)
about the aircrafts centre of mass, dened by:
M = T d (4.2)
where d is the perpendicular distance between the vertical thrust line and the centre of
mass, as shown in Figure 4.12.
Figure 4.12: Moment About CoM from Primary Thrust
By the addition of an tail fan at the rear of the aircraft generating a thrust (T
t
) at a
distance (d
t
) from the centre of mass of the aircraft another moment (M
t
) is created as
35
Chapter 4. Mechanical Design 4.4. Sensors
shown in Figure 4.13. By balancing these moments the minimum required static thrust
at the tail was calculated using:
T
t
= T
d
d
t
(4.3)
The ratio of distances,
d
d
t
, is relatively small, estimated using SolidEdge at being
approximately
45
750
= 0.06, thus the required thrust at the tail is relatively small. Given
an estimated primary thrust of 25N during standard hover, the required thrust at the tail
would be a minimum of 1.5N. It is desired that the tail thrust unit produce at least twice
this value to ensure sucient controllability. Pitch control in both directions is achieved
by either increasing or decreasing the thrust provided by the tail fan about the point
where it cancels the moment generated by the primary propellers.
Figure 4.13: Net Moment of Zero About CoM
The tail thrust is attained through the use of a WeMoTec 5-blade ducted micro-fan,
driven by a brushless Himax 2015 4100 electric motor. The motor is powered using a 20A
Hyperion ESC. The components of the tail unit can be seen in Figure 4.14. The thrust
levels attained by this unit were estimated to be 3.0 N, which provides adequate pitch
authority.
4.4 Sensors
Sensors are required to return data of the planes position and orientation to the controller.
Sensors constitute a large proportion of the cost of the plane and the controller system.
36
4.4. Sensors Chapter 4. Mechanical Design
Figure 4.14: Rear Thrust Unit - Brushless Motor, Ducted Mini-Fan, ESC
4.4.1 Inertial Measurement Unit (IMU)
The Inertial Measurement Unit (IMU) is a device used to obtain information about the
current state of the aircraft, specically the accelerations, Euler angles and angular rates.
The MicroStrain 3DM-GX1 was chosen as the IMU for this aircraft due to its gyro-
stabilised output which eliminates accelerometer drift and hence the need for an external
Kalman lter. The 3DM-GX1 combines three angular rate gyros with three orthogonal DC
accelerometers, three orthogonal magnetometers, multiplexer, 12 bit A/D converter, and
embedded microcontroller. This enables it to measure the three orientation angles (pitch,
roll and yaw), the three angular rates (pitch rate, roll rate and yaw rate) and acceleration
in the three linear axes (X, Y and Z) in both dynamic and static environments.
The IMU communicates using an RS-232 serial connection with a maximum data rate of
115.2 kbaud. With a maximum data output rate of 100Hz the 3DM-GX1 easily provides
sucient feedback to the control system to achieve a stable hover.
Due to the high cost (approximately half the expected commercial cost of the aircraft),
the use of the 3DM-GX1 is a short term solution. In the long term, an aordable IMU
incorporating a Kalman lter may be developed as a level four Mechanical Engineering
project.
4.4.2 Rate Gyroscopes
In order to make the aircraft more aordable to the every-day enthusiast it is envisioned
that the expensive IMU will be replaced with cheaper rate gyroscopes. This will result in
a loss of precision and an increase in computational eort by the embedded controller in
order to maintain the aircraft in a stable hover.
37
Chapter 4. Mechanical Design 4.5. Actuators
This year the project did not progress to a stage where rate gyroscopes had to be
considered, hence they were not thoroughly investigated. Reference to rate gyroscopes is
made in Section 11.2.4.
4.5 Actuators
4.5.1 Servo Motors
Servo motors allow accurate open-loop command following of their shaft angle thanks
to their on-board controller circuit. They are controlled by a Pulse-Width-Modulated
(PWM) signal where the desired servo motor angle is proportional to the pulse width,
as discussed further in Section 7.1.1.1. RC servo motors generally run between 4 and 8
Volts and may oscillate if they are supplied with a voltage that is too high. Servo motors
typically draw 130mA under normal operation, but they can draw over 1A when under
full load.
To rotate the wing arms the JR 577 standard servo motor were initially chosen. However
these proved inadequate as discussed later in Section 10.4. Following this the JR 579
servo motors, which feature metal gears, a ball-race and can provide 0.824 N.m torque
when run at 4.8V (Modelight, 2005) were chosen. The JR 579 servo motor mounted to
the wing arm is shown in Figure 4.15.
Figure 4.15: Servo Mounted on Wing Arm
38
Chapter 5
Mathematical System Model
5.1 Introduction
To be able to design a state space controller for the model aircraft a set of state space
equations are required. These must be formulated from physical laws and simplied to
allow for the development of a working linear controller.
A diagram of the axes system used to derive the equations is presented in Figure 5.1. It
is important to note that this system does not share the complexities of more common
aircraft axes systems. Moments about axes and angular velocities are not given separate
labels. The system originates at the centre of mass of the plane with the longitudinal axis
(X) running through the fuselage in the direction of the nose of the plane. The lateral axis
(Y) is positive out of the left (port) wing of the plane. The vertical axis (Z) is positive in
the upward direction. All forces, displacements and velocities along each of these three
body reference axes are positive in the directions indicated. Pitch moments, angles and
angular velocities of the aircraft are positive in a nose-up direction. Yaw moments, angles
and angular velocities are positive in the nose-left direction. Roll moments, angles and
angular velocities are positive for left wing down rotations.
5.2 State Equations
5.2.1 Linearisation Methods Used
To allow for the implementation of a state space controller a linearised state model is
required. This model is derived from the state equations through the linearisation of non-
39
Chapter 5. Mathematical System Model 5.2. State Equations
Figure 5.1: Basic Diagram of Model Layout
linear terms in the equations. The following simplications are applied in the derivation
of the model.
Where is small, we assume sin = and cos = 1. The lift generated by the propellers
is proportional to angular velocity squared (
i
2
). We assume that lift can be approximated
as a linear function of angular velocity when near the angular velocity required for hover.
Hence:
2
i
i
(5.1)
where:
0
is the angular velocity of the propellers at hover.
i
is the angular velocity of the propellers.
5.2.2 Propeller Angles
In order to aect control in various degrees of freedom the propellers are required to rotate
independently relative to the XY axis of the plane as in Section 5.2. These angles are
L
and
R
(for left and right propeller angles respectively). For transition to normal ight
the propellers must both rotate around to the position of a standard plane. However, for
the purposes of the state model for hover the rotation angles will be restricted to small
values. Gyroscopic eects either directly or indirectly caused by the servo motors or the
dynamic movement of angle of the propeller are assumed negligible. The servo motors
are controlled by Pulse Width Modulation (PWM), so for simplicity it will be assumed
that is the input to the equations. In practice the values of will be related to the
servo motors as PWM outputs from the microcontroller.
40
5.2. State Equations Chapter 5. Mathematical System Model
Figure 5.2: Propeller Angles
5.2.3 Left and Right Propeller State Equations
The torque balance and electrical motor equation derivations are directly from the analysis
of the Quanser 3DOF Hover platform (Cazzolato, 2005a).
If we start with the torque balance from the motor then we have the following non-linear
equation:
J
m
m
+b
m
m
+k
D
(
Mm
)
2
= k
T
i
a
(5.2)
where:
J
m
is the moment of inertia of the propeller and motor rotor.
b
m
is the viscous friction in the motor rotor.
k
D
(
m
)
2
is the reactive torque, in free air, by the propeller due aerodynamic drag.
k
D
> 0 is the drag constant of the propellers, which is a factor of the air density, the
propeller dimensions and other factors.
k
T
is the torque constant of the motor.
i
a
is the armature current.
m
is the angular position of the rotor.
Another system of equations that governs the dynamics is the electrical equation of the
motor:
41
Chapter 5. Mathematical System Model 5.2. State Equations
L
a
i
a
+R
a
i
a
= V
a
k
e
m
(5.3)
where:
L
a
is the armature inductance.
R
a
is the armature resistance.
k
a
is the back EMF constant and is equal to the torque constant of the motor when in SI
units.
V
a
is the voltage applied to the motor.
In many cases the relative eect of the inductance is negligible compared to the mechanical
motion and can be neglected in Equation 5.3. This leave us with:
R
a
i
a
= V
a
k
e
m
(5.4)
Combining Equations 5.2 and 5.4 yields:
J
m
m
+ (b
m
+
k
T
k
e
R
a
+k
D
m,0
)
m
=
k
T
R
a
V
a
(5.5)
J
m
m
=
k
T
R
a
V
a
(b
m
+
k
T
k
e
R
a
+k
D
m,0
)
m
(5.6)
Equation 5.6 can be written for each propeller:
L
=
1
J
prop
k
T
R
a
V
L
K
mp
(5.7)
R
=
1
J
prop
k
T
R
a
V
R
K
mp
(5.8)
where K
mp
= b
m
+
k
T
k
e
R
a
+k
D
m,0
42
5.2. State Equations Chapter 5. Mathematical System Model
5.2.4 Rear Impeller Equation
The rear ducted fan impeller is expected to have a moment of inertia (J) low enough
such that it can be assumed to have negligible eect on the angular acceleration of the
impeller. Removing this term from Equation 5.6 and rearranging yields:
V
B
=
R
B
k
B
(b
B
+
k
B
k
e
R
B
+k
D,rear
B,0
)
B
(5.9)
V
B
= K
B
B
(5.10)
where:
K
B
=
R
B
k
B
(b
B
+
k
B
k
e
R
B
+k
D,rear
B,0
) (5.11)
5.2.5 Pitch Axis
Taking the torque balance about the pitch axis, the following expression can be derived:
J
p
p l
1
(F
L
+F
R
) l
2
F
b
(5.12)
Therefore:
p =
l
1
J
p
(F
L
cos
L
+F
R
cos
R
)
l
2
J
p
F
B
(5.13)
Simplifying by applying trigonometric linearisation:
p =
l
1
Jp
(F
L
+F
R
)
l
2
J
p
F
B
l
1
K
prop
J
p
(V
L
+V
R
)
l
2
K
rear
J
P
V
B
(5.14)
where:
J
P
is the moment of inertia of the body about the pitch axis.
l
1
is the distance from the pitch axis to either front propeller centre.
l
2
is the distance from the pitch axis to the back propeller centre.
k
l
is the coecient of lift for the two front propellers.
43
Chapter 5. Mathematical System Model 5.2. State Equations
k
l,rear
is the coecient of lift for the back propeller.
L
,
R
and
B
are the angular velocity of the left and right propellers and back fan
respectively.
K
prop
=
k
l
0
k
T
R
a
K
mp
is the approximated (linearised) lift supplied by the propellers for a given
input voltage.
K
rear
=
k
l,rear
0,B
K
B
is the lift supplied by the rear fan for a given input voltage.
It should be noted that the longitudinal distance between the centre of mass and the lift
point of the propellers (l
1
) is aected by the angle of the motors. The lift point is moved
when the motors are not parallel to the pitch axis. This change in l
1
is non-linear and
assumed negligible.
5.2.6 Roll Axis
Taking the torque balance about the roll axis, the following expressions can be derived:
J
r
r l
3
(F
l
F
r
) (5.15)
Therefore:
r =
l
3
J
r
(F
L
cos
L
F
B
cos
R
) (5.16)
Simplify by applying trigonometric linearisation:
r =
l
3
J
r
(F
L
F
R
) =
l
3
K
prop
J
r
(V
L
V
R
) (5.17)
where:
J
r
is the moment of inertia of the body about the roll axis.
l
3
is the distance from the roll axis to either propeller centre.
L
and
R
are the angular velocity of the left and right propellers respectively.
K
prop
=
k
l
0
k
T
R
a
K
mp
is the approximated (linearised) lift supplied by the propellers for a given
input voltage.
44
5.2. State Equations Chapter 5. Mathematical System Model
5.2.7 Yaw Axis
Taking the torque balance about the yaw axis yields:
J
y
y l
3
(F
L,yaw
+F
R,yaw
) +
L
R
+
B
(5.18)
y =
l
3
J
y
(F
L
sin
L
F
R
sin
L
) +
K
D,prop
J
y
(V
L
V
R
) +
K
D,rear
J
y
V
B
(5.19)
Simplifying by applying trigonometric linearisation:
y =
1
J
y
(l
3
(F
L
L
+F
R
R
) +K
D,prop
(V
L
V
R
) +K
D,rear
V
B
) (5.20)
This can be approximated by:
y =
1
J
y
(l
3
K
prop
(V
L
L
+V
R
R
) +K
D,prop
(V
L
V
R
) +K
D,rear
V
B
) (5.21)
This is linearised by removal of the multiplication between the input voltage and propeller
angle.
y =
1
J
y
(l
3
K
prop
(V
hov
L
+V
hov
R
) +K
D,prop
(V
L
V
R
) +K
D,rear
V
B
) (5.22)
where:
J
y
is the moment of inertia of the body about the yaw axis.
l
3
is the distance from the roll axis to either propeller centre.
L
and
R
are the angular velocity of the left and right propellers respectively.
B
is the angular velocity of the rear impeller.
0
is the angular velocity of the front propellers at hover.
0,B
is the angular velocity of the rear impeller at hover.
V
hov
is the voltage supplied to the front propellers for hover.
45
Chapter 5. Mathematical System Model 5.2. State Equations
K
prop
=
k
l
0
k
T
R
A
K
mp
is the approximated lift supplied by the propellers (at hover angular
velocity) for a given motor input voltage.
K
D,prop
=
k
D
0
k
T
R
A
K
mp
is the torque constant that relates the torque generated by the propeller
when a voltage is applied to the motor.
K
D,rear
=
k
D,rear
0
k
T
R
A
K
mp
is the torque constant that relates the torque generated by the rear
impeller when a voltage is applied to the motor.
5.2.8 Vertical Translation
For z-axis translation, it is assumed that in-ground eects are negligible and that the
translational velocity is too low to induce signicant drag. All translations are expressed
in body reference frame.
Therefore:
M
P
z =
F
z
F
L
cos
L
+F
R
cos
R
+F
B
W (5.23)
where W = M
P
g the total weight of the model.
Linearising the cosine terms and replacing the forces with voltage input relationships
gives:
M
P
z = K
prop
V
L
+K
prop
V
R
+K
rear
V
B
W (5.24)
M
P
z = K
prop
(V
L
+V
R
) +K
rear
V
B
W (5.25)
5.2.9 Lateral and Longitudinal Translation
For both lateral and longitudinal translation it is assumed that drag is negligible due to
low velocity. Since there are no translation forces acting along the lateral axis the lateral
translation is not considered. Thus:
M
P
y = 0 (5.26)
In the longitudinal direction the only translational forces are from the tilted propellers.
Thus:
46
5.3. Virtual Reality Model Chapter 5. Mathematical System Model
M
P
x =
F
x
F
L
sin
L
+F
R
sin
R
(5.27)
Simplifying by applying trigonometric linearisation:
M
P
x = F
L
L
+F
R
R
= K
prop
(V
L
L
+V
R
R
) (5.28)
This equation can be simplied further by assuming that the motors will be running at a
voltage near their hover voltage.
M
P
x = K
prop
(V
hov
L
+V
hov
R
) (5.29)
5.3 Virtual Reality Model
The virtual reality (VR) model was developed in order to be able to visualise the aircrafts
expected behaviour during ight. Initially a simple model was created using the VRML
Editor software V-Realm Builder 2.0 editor and the Matlab VR toolkit. This model was
used to learn the basic concepts of using the VR software and can be seen in Figure 5.3.
When these concepts were understood a more advanced model was developed. Accurate
3D models of the V-22 Osprey are available for purchase on a number of dedicated 3D
model websites but are generally more expensive than necessary (approximately US$90).
A model of the Osprey developed using Gmax 1.2 by Travis FitzPatrick as a le for the
MS Flight Simulator computer game was discovered as a freely available download on the
Internet.
This le format is not compatible with the CAD and design software available at university
so the freeware computer game model design program Gmax was downloaded. The
developer of Gmax is Discreet Software (also developers of 3D Studio Max); however
the company has made it extremely dicult to convert les from one format to the other
for commercial reasons. The solution to this was to convert the Gmax le to a Quake
3 model (M3D) using Tempest (also freeware game model design software) and then to
a Raw Object le using 3D Exploration (shareware). The Matlab VRML Editor (V-
Realm 2.0) can be used to convert the Raw object into a VRML le, but the shapes are
scrambled within a single node and cannot be individually manipulated. The solution to
this was to use the universitys educational version of 3DS Max to convert the VRML to
a .max le and reclassify all shapes as individual nodes. From here individual shapes were
grouped into functional parts such as the propellers and motors before being exported
47
Chapter 5. Mathematical System Model 5.3. Virtual Reality Model
Figure 5.3: Basic Virtual Reality Model
as a VRML le. In the Matlab V-realm editor some aspects of the VRML le such as
rotational centres of nodes were redened to allow for accurate animation as can be seen
in Figure 5.4. To complete the model colour changes were made to some components and
a background was added. The nal model can be seen in Figure 5.5.
The Virtual Reality model is manipulated directly through Simulink using the VR Sink
block such as in Figure 5.6. The VR Sink block allows values for orientation and position
of each node to be altered relative to its parent node. The orientation of the whole model
is manipulated by inputting a vector consisting of four values into the VR Sink block
targeted at the V2Grp01 node which represents all nodes of the model. These values
include pitch, yaw and roll weighting as well as a sum of the three angles in radians.
Position in space is aected by a vector input in the three axes of the VR space again
targeted at the V2Grp01 node. The motors of the Osprey are manipulated by altering
the value of the angles of rotation of the two motor group nodes relative to the axis along
the wing. Rotation of the propellers is achieved by continuously increasing the angle
about the vertical axis relative to the motors. Models with a tail fan in place rotate the
blades of the tail fan in the same manner as the propellers. These inputs provide the
model with all of the functionality required for the current scope of the project. However,
features of the model such as the ight surfaces and landing gear have been left on the
model to be used at a later date if required. Furthermore, an advanced virtual world
could be constructed within which the Osprey could y among xed objects, complete
with collisions and lighting eects.
48
5.3. Virtual Reality Model Chapter 5. Mathematical System Model
Figure 5.4: V-22 Osprey Model in V-Realm Builder
Figure 5.5: Final V-22 Osprey VR Model
49
Chapter 5. Mathematical System Model 5.3. Virtual Reality Model
Figure 5.6: Simulink Model Driving the VR Block
50
Chapter 6
Control System
The control system for the RC VTOL aircraft forms a large part of the project. The
reason for this is the aircraft itself is inherently unstable in hover and thus would be
dicult to y without a control system.
6.1 Classical Control (PID Controller)
6.1.1 Background
For Single Input Single Output (SISO) systems, the controller that is most commonly
used in industrial process control is the three-term or PID controller. This controller has
the following transfer function:
G
c
(s) = K
P
+
K
I
s
+K
D
s (6.1)
where K
P
, K
I
and K
D
the proportional, integral and derivative gains respectively.
Equation 6.1 is often rewritten in terms of time constants:
G
c
(s) = K +
K
T
I
s
+KT
D
s (6.2)
where K is the overall gain, T
I
and T
D
are the integral and derivative time constants
respectively.
51
Chapter 6. Control System 6.1. Classical Control (PID Controller)
This controller is termed a PID controller because Equation 6.1 has a proportional,
integral and derivative term. Although these controllers are simple, they are quite robust,
simple to tune and often provide sucient control. PID controllers have well known
tuning methods such as the Ziegler-Nichols Step and Ultimate Gain Methods (Dorf and
Bishop, 2001). Whilst these tuning methods are unlikely to produce an optimally tuned
controller, they do provide a good starting point for further optimisation.
The default PID block in Simulink is quite limited and an improved model was used
in this project. The improved model included an integrator anti-windup loop, setpoint
weighting, output saturation and a low-pass lter on the derivative term to reduce the
eect of noise (Cazzolato, 2005b). This model is shown in Figure 6.1.
Figure 6.1: Generalised PID Controller (Cazzolato, 2005b)
6.1.2 Application
It is possible to control a system such our aircraft using decoupled PID loops. Such
loops would view the coupling between axes purely as a disturbance and should be able
to compensate in a robust manner. This is the type of controller used by Jarrett et al.
(2004). A Simulink implementation of such a system is shown in Figure 6.2.
6.1.3 Controller Tuning
The group decided that the PID loops would be tuned one at a time, leaving any untuned
degrees of freedom in an open-loop (when feedback is not applied conguration). However
52
6.2. State Space Control Chapter 6. Control System
Figure 6.2: Decoupled PID Control System
the tuning of the controller while the aircraft was attached on the gimble proved dicult
due to the non-linearities introduced by having a pivot not located at the centre of mass
of the aircraft, as discussed in Section 10.6.
The aircraft was moved to its semi-tethered conguration and it was then attempted to
tune the controller. However due to the mechanical failure discussed in Section 10.3.2 this
was not completed.
6.2 State Space Control
6.2.1 Background
While classical control is quite successful in controlling SISO systems, it is often less
successful in controlling Multiple Input Multiple Output (MIMO) systems. Fortunately
state space or modern control techniques often provide adequate control. If the state
vector is dened as x = [x
1
x
2
. . . x
n
] then the dierential equations governing the system
can be written in matrix form as:
x = Ax +Bu (6.3)
53
Chapter 6. Control System 6.2. State Space Control
y = Cx +Du (6.4)
State space controllers can be designed using pole placement or optimal control using a
Linear Quadratic Regulator (LQR). State space techniques have the potential to produce
a high-performance controller, however they require an accurate model of the plant
(Cazzolato, 2005c). Matlab has extensive optimal controller development tools which
can be used to determine the controller and observer gains. These calculated gains can
be used in Simulink with the dSPACE DS-1104 boards (and with the VR model) until
the controller is working as desired. Dr. Ben Cazzolato kindly provided a template state
space controller Matlab le to assist in the development of the controller.
Figure 6.3: Full State Space Controller (Cazzolato, 2005c)
6.2.2 Controller Design
Initially the mathematical equations derived in Chapter 5 were converted to a set of state
matrices as in Equation 6.5. Using Matlab and the template m-le for a state space
controller provided by Dr. Cazzolato the controller was developed around these state
matrices.
The mathematical equations for the behaviour of the plane were converted to a set of
state matrices. Relationships between states such as angular rates to angular positions
54
6.2. State Space Control Chapter 6. Control System
were represented by integral relationships. Initially there were 16 states; six for the yaw,
pitch and roll angular rates and positions, six for the translational velocity and positions
and an angular position and velocity state for each of the left and right motors. However,
the Y translation states were not implemented since they always equal zero.
y
y
p
p
r
r
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0
l
1
K
prop
J
p
0
l
1
K
prop
J
p
0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0
l
3
K
prop
J
r
0
l
3
K
prop
J
r
0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0
K
mp
J
prop
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
K
mp
J
prop
0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0
K
prop
M
p
0
K
prop
M
p
0 0 0 0 0 0
y
y
p
p
r
r
R
X
X
Y
Y
Z
0 0 0 0 0
0 0 K
D,rear
l
3
K
prop
V
hov
J
y
l
3
K
prop
V
hov
J
y
0 0 0 0 0
0 0
l
2
K
rear
J
p
0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
k
T
R
a
J
prop
0 0 0 0
0 0 0 0 0
0
k
T
R
a
J
prop
0 0 0
0 0 0 0 0
0 0 0
K
prop
V
hov
M
p
K
prop
V
hov
M
p
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0
K
rear
M
p
0 0
V
L
V
R
V
B
(6.5)
55
Chapter 6. Control System 6.2. State Space Control
During preliminary testing a number of states were removed from the state matrices.
The values of the angular position of the left and right motor/propeller states were
accumulating to very high levels and overloading the simulation. Since the thrust
generated by the propellers is relative to angular velocity, the angular position states
were irrelevant and were also removed. Furthermore, the X translation states were also
removed as the aim of this particular controller was only to facilitate stable hover. The
Z translation state was also removed due to the fact that the IMU can only measure
translational accelerations (double integration of the acceleration to measure position is
prone to large oset errors). The yaw position state was also removed as yaw rate was
deemed a more intuitive set-point input for a pilot. After the removal of these states the
state matrices were rearranged to facilitate the development of the reduced order observer
as discussed in Section 6.2.3. The nal set of state matrices are 6.6 with outputs 6.7.
y
p
r
Z
p
r
0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0
K
prop
M
p
K
prop
M
p
0 0 0 0 0 0
l
1
K
prop
J
p
l
1
K
prop
J
p
0 0 0 0 0 0
l
3
K
prop
J
r
l
3
K
prop
J
r
0 0 0 0 0 0
K
mp
J
pr
0
0 0 0 0 0 0 0
K
mp
J
pr
y
p
r
Z
p
r
K
d
K
d
K
d,rear
l
3
K
p
V
hov
J
y
l
3
K
p
V
hov
J
y
0 0 0 0 0
0 0 0 0 0
0 0
K
r
J
p
0 0
0 0
l
2
K
r
J
r
0 0
0 0 0 0 0
k
t
R
a
J
pr
0 0 0 0
0
k
t
R
a
J
pr
0 0 0
V
L
V
R
V
B
(6.6)
56
6.2. State Space Control Chapter 6. Control System
y
p
r
1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0
y
p
r
Z
p
r
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
V
L
V
R
V
B
(6.7)
The Matlab m-le uses Linear Quadratic Regulator (LQR) theory to determine the gain
matrices for the controller. LQR is a tool used in optimal control which involves the
setting of state weighting and control (eort) weighting matrices. These two matrices are
used in conjunction with the state matrices to develop a function of the physical cost of
controlling the plant with respect to the mathematical model. LQR determines a gain
matrix to minimise this cost function. If the equations model the behaviour of the plant
accurately then the controller can be tuned by altering the state weighting and control
penalty matrices and recalculating the gain matrix.
The mathematical model denes a number of constants required to enable implementation
of the controller. The accuracy of these constants is crucial to the development of
a working state space controller. Sourcing accurate values for some of the required
constants proved dicult, as a result some values had to be measured experimentally.
The torque constant and armature resistance of the motors were available from the
manufacturer. However, other constants considered in the mathematical model such as
the viscous resistance and armature current were unavailable. Data regarding the lift
and drag characteristics of the propellers is not published by the manufacturers, although
generic data is available from various enthusiasts and computer programs. PropCalc and
ThrustHP were used to estimate propeller performance relative to power input. These
programs claim to be within 10% of the true thrust for available RC propellers. The
rotational moment of inertia of the propellers was calculated using a generic equation
for 2-bladed RC propellers. After testing it was discovered that the accuracy of the
programs was within the claimed percentage (26.7 N estimated vs 24.5 N measured) and
almost identical after considering losses in the electric motor. Due to the unavailability
of motor constants for the rear fan this too had to be estimated until it was determined
experimentally. Rotational moments of inertia for the fuselage were calculated on the
SolidEdge model, as was the estimated mass. Whilst the constants used were reasonably
close to the physical values, a system identication as described in Section 11.2.3 would
result in a superior model upon which to design a controller.
57
Chapter 6. Control System 6.2. State Space Control
For preliminary testing the equations of the mathematical model are used as the plant.
For the controller to work the values of all states must be fed back into the controller.
Not all of the states of the model can be measured by the IMU. Hence an observer is
required in the controller to estimate those states that are not measured.
6.2.3 Observer Design
To begin with, an observer with full-rank feedback (to observe all states) gain matrix
was developed to estimate the states. Initially the feedback matrix was determined using
pole placement, however the resulting observer matrix was unable to be calculated by
Matlab. An optimal observer was attempted but similar issues were encountered during
testing in Simulink. A reduced order observer was developed in an attempt to remedy
these problems. To develop a reduced order observer it is necessary to partition the states
into those x
m
which can be measured and those x
u
which must be estimated (Hansen and
Snyder, 1996). This resulting state equation is shown in Equation 6.8.
x
m
x
u
A
mm
A
mu
A
um
A
uu
x
m
x
u
B
m
B
u
u (6.8)
An observer matrix L was created to estimate the states that are not measured. This
is implemented as in Section 6.4. In the nal controller the estim command is used in
Matlab to create a state space system to represent the whole observer.
Figure 6.4: Reduced Order Observer Implementation Cazzolato (2005c)
58
6.2. State Space Control Chapter 6. Control System
6.2.4 Simulink Model
A Simulink model of the desired controller complete with estimator was adapted from
the state space controller provided by Dr. Ben Cazzolato for the Quanser 3DOF Hover
Platform. The VR Model Block was added to this Simulink model and a reduced order
observer version was also created. The gain and observer matrices created by the controller
m-le can be implemented in such a Simulink block diagram of a state space controller.
For preliminary testing the equations of the mathematical model were used in a state
space Simulink block as the plant, with a gain block containing the state output matrix,
converting the output of the state space block to the correct vector.
Figure 6.5: Simulink State Space Model
For tethered testing the state space block was replaced with links to the DS-1104 boards
representing the outputs from the controller and the inputs from the IMU. Figure 6.6
shows the layout of the controller for testing, including a block to determine vertical
velocity as the return input for Z velocity.
6.2.5 Microcontroller Implementation
In order to convert the complete controller from a set of gain and observer matrices to
a form able to be implemented on a microcontroller, a state space model of the whole
system was created in Matlab. This was done by creating state space models for each
59
Chapter 6. Control System 6.2. State Space Control
Figure 6.6: Simulink Model with Observer and Connections from IMU and to dSPACE
of the augmented states, estimator, set-point inputs and controller gains. These blocks
were appended into a single state space model. The connect command was then used
to connect the various components of the model in the same manner as the Simulink
block model. Separate output states were added for the control signals of the voltages
and motor angles of the model so that they could be monitored. This process results in a
state space model that can be discretised and diagonalised. The resulting set of matrices
can more easily be converted to C-code for use in the microcontroller.
60
Chapter 7
Implementation of Control
7.1 Signals, Hardware and Software
In order to provide some insight into the way the control system was integrated, the
components are discussed briey.
7.1.1 Control Signals
Control signals are the method by which dierent components of the control system
transfer information between each other. The two types of control signals used in this
project are Remote Control (RC) Pulse Width Modulation (PWM) and asynchronous
serial communications using the RS-232 standard.
7.1.1.1 RC Pulse Width Modulation
Pulse Width Modulation (PWM) is a technique commonly used to represent an analogue
signal using digital circuitry. It involves the switching on and o of a digital output at a
xed frequency (switching frequency f
s
), but with varying times of either on or o. The
ratio of on-time to the total period (T =
1
f
s
) is called the duty cycle (d). Some examples
of a PWM signal are shown in Figure 7.1.
RC equipment such as servo motors and electronic speed controllers typically use PWM
signals to represent the control input. As opposed to standard PWM signals where the
signal value is dependant upon the duty-cycle, RC equipment use the actual pulse-width
(in seconds) to represent the signal. An RC PWM signal is usually bound between a 750 s
61
Chapter 7. Implementation of Control 7.1. Signals, Hardware and Software
Figure 7.1: Example PWM Signals
and 2250 s pulse width, with 1500 s generally being accepted as the centre-point, as
indicated in Figure 7.2. The RC PWM signals usually operate fairly independently of the
PWM switching frequency, with the accepted range being between 20 Hzand 200 Hz.
Figure 7.2: RC PWM and Servo Motor Example
7.1.1.2 Asynchronous Serial Communications
Many devices communicate using an asynchronous serial communications port, ones in
this project include the IMU (mentioned previously), the PicoPic, dSPACE DS-1104 and
MiniDRAGON+ (all mentioned later). Several standards for this exist, including the
commonly known RS-232 and RS-485 standards. The standard used in this project
62
7.1. Signals, Hardware and Software Chapter 7. Implementation of Control
was RS-232 which will be discussed briey, but a full description of the standard is
unwarranted.
The RS-232 standard includes many features, such as hardware ow control and
handshaking, but which are not usually used in practice. The connections of interest are
the transmit (Tx), receive (Rx) and ground (GND) lines. The standard also recommends
several connector types, commonly the DB-9 (or D-subminiature 9-pin) type. The
standard pinouts for these connectors, as well as the ones on the MiniDRAGON+ are
shown in Figure 7.3.
Figure 7.3: RS-232 Connectors and Pinouts used in this Project
7.1.2 Control Hardware
The control hardware is the hardware used to run the control system or assist in its
implementation.
7.1.2.1 dSPACE DS-1104
The dSPACE DS-1104 rapid prototyping platform is a real-time control target that is
extensively used in the construction and testing of control systems. The DS-1104 is an
expansion card that sits on the host computers PCI bus and contains its own PowerPC
CPU and a Texas Instruments (TI) Digital Signal Processor (DSP). Matlab Simulink
models are compiled using a cross-C compiler and loaded to the DS-1104 platform. Using
63
Chapter 7. Implementation of Control 7.1. Signals, Hardware and Software
the dSPACE software ControlDesk, variables and outputs from the Simulink model are
accessible via a Graphical User Interface (GUI). A dSPACE DS-1104 breakout board is
shown in Figure 7.4.
The DS-1104 hardware has eight Analogue to Digital (A/D) converters, eight Digital
the Analogue (D/A) converters, four PWM outputs, one asynchronous serial port (either
RS-232 or RS-422/485), two encoder readers as well as a host of other inputs and outputs.
Figure 7.4: dSPACE Breakout Board
7.1.2.2 MiniDRAGON+
The microcontroller chosen to run the embedded control system is the Motorola 68HCS12,
operating on a MiniDRAGON+ development board. The HCS12 is very exible and
powerful when compared to similar microcontrollers, featuring a plethora of inputs and
outputs. Some of these include two asynchronous serial communication ports, two 10-bit
analogue to digital converters (multiplexed to 16 channels), eight 8-bit PWM outputs, an
Enhanced Capture Timer (ECT) and a variety of congurable digital input/output pins.
A MiniDRAGON+ is shown in Figure 7.5.
Dr. Frank Wornle has developed a Real-Time MC9S12 Simulink Target, allowing Simulink
models to be compiled onto the MiniDRAGON+ in a similar fashion to the dSPACE
platform.
7.1.2.3 PicoPic
The PicoPic servo controller is a PIC microcontroller that has been designed and built
by PicoBytes to generate RC PWM signals. It has 20 PWM output channels, each with
a resolution of 1 s (giving approximately 1500 discrete output levels)(Picobytes inc.,
2003). It receives commands over its RS-232 asynchronous serial communications port
up to a rate of 115.2 kbaud, giving ample output bandwidth. The serial connection is
64
7.1. Signals, Hardware and Software Chapter 7. Implementation of Control
Figure 7.5: MiniDRAGON+ Development Board.
uni-directional, that is the PicoPic does not transmit any information it only receives it.
A PicoPic servo controller is shown in Figure 7.6.
Figure 7.6: PicoPic Servo Motor Controller.(Picobytes inc., 2003)
7.1.3 Control Software
The control software is the software used when designing, constructing and testing the
control system.
7.1.3.1 Matlab/Simulink
MathWorks Matlab (short for Matrix Laboratory) is a powerful mathematical program
that is commonly used not just for engineering, but many applications ranging from
nancial modelling to image processing. Due to its powerful and versatile control toolbox
it is commonly used in the design and analysis of control systems.
65
Chapter 7. Implementation of Control 7.2. Development Stage (Tethered)
Simulink is a software package that comes with Matlab and is commonly used in
the construction of control systems, particularly those that contain non-linearities,
discontinuities or complex systems. It also has facilities to compile these models to
a variety of platforms, including the aforementioned dSPACE DS-1104 and HCS12
platforms.
7.1.3.2 dSPACE ControlDesk
ControlDesk is the software that comes with the DS-1104 platform. It interacts with
the Simulink control system running on the DS-1104 hardware to allow the monitoring of
control signals, such as controller outputs, and allows the modication of control variables,
such as controller gains, on the y. When a USB joystick is attached to the host computer,
ControlDesk acts as an interface, forwarding any joystick commands to the DS-1104
platform.
ControlDesk combines all of these features with an easy to use Graphical User Interface
(GUI).
7.1.3.3 Metrowerks Codewarrior
Metrowerks Codewarrior is an Integrated Development Environment (IDE) for several
platforms including the Motorola HCS12 family of microcontrollers. It allows direct
programming of the MiniDRAGON+ development board in the C programming language.
7.2 Development Stage (Tethered)
The rst stage of implementation was to operate the aircraft while tethered to a frame.
This would allow safe operation of the aircraft while tuning the controller.
7.2.1 Hardware Conguration
The basic control hardware conguration of the model is shown in Figure7.7.
66
7.2. Development Stage (Tethered) Chapter 7. Implementation of Control
Figure 7.7: Tethered Conguration Hardware Layout
Figure 7.8: Tethered Conguration
67
Chapter 7. Implementation of Control 7.2. Development Stage (Tethered)
7.2.1.1 Control Platform
During tethered testing the control system was initially run on the dSPACE DS-1104
platform. A DS-1104 board is only capable of producing 4 PWM outputs. Since this
project required a minimum of 5 such outputs, one for each motor and one for each wing
arm servo motor, a second DS-1104 board was used in a master-slave conguration to
provide the additional PWM outputs. The two DS-1104 boards communicated with each
other via digital to analogue (D/A) and analogue to digital (A/D) ports. The PWM
signals were run along a BNC cable to the breakout board where they are terminated and
run along the main loom to the platform.
Problems arose with electrical noise from nearby equipment. The large length of the loom
made this problem signicant. The group was able to use the serial port of the secondary
DS-1104 board and a PicoPic servo controller to minimise the noise interfering with the
PWM signals.
7.2.1.2 Power Supply
The three motors (two main and single rear) were powered from a 12V deep-cycle sealed
lead acid (SLA) battery as shown in Figure 7.9. For safety reasons, a 100A circuit
breaker/isolator was installed to allow the team to cut the power should anything go
wrong and to help prevent damage in the case of a short circuit. It also allows the
complete isolation of power from the high-power components, allowing the team to work
on the model in safety, without the fear the motors will start up unexpectedly. The servos
and the IMU were powered using a bench power supply which allowed the group to easily
monitor and control the maximum current.
7.2.1.3 Signal Routing and Distribution
The control signals were routed through a breakout board which was developed by Jarrett
et al. (2004). Since the power to the motors came from the battery in the control room,
large gauge wires needed to be added to last years loom. The only other addition was
two thermocouple extension cables for monitoring the temperature of the motors as this
was identied as a potential problem. Figure 7.10 shows the breakout board located
at the host end. The ve PWM channels are on cables with BNC connectors. This is
convenient as one could easily connect a channel to a Cathode Ray Oscilloscope (CRO) to
troubleshoot the system. The IMU power and data connections are shown on the bottom
left of the picture.
68
7.2. Development Stage (Tethered) Chapter 7. Implementation of Control
Figure 7.9: Tethered Power Supply
Figure 7.10: Breakout Board
69
Chapter 7. Implementation of Control 7.2. Development Stage (Tethered)
As mentioned previously, there was the problem of electrical noise. The group were able
to overcome this without modifying the cable loom. For untethered conguration the
group had decided on using the PicoPic serial servo motor controller, as it was expected
the serial connection would be less sensitive to noise. Since the signal is uni-directional,
a pin to BNC cable connecting the transmit and ground pins of the dSPACE serial port
to the breakout board. This is shown in Figure 7.11.
Figure 7.11: Modied Conguration
Figure 7.12 shows the PicoPic mounted on the aircraft. The serial connection is located
on the right of the picture and the ve PWM connections are at the top of the device.
Figure 7.12: PicoPic Mounted to the Aircraft Frame
7.2.2 Software Conguration
While in its tethered conguration the model was ran open-loop, with proportional, PID
and State-Space control as described in Chapter 6. The results of this are discussed in
70
7.2. Development Stage (Tethered) Chapter 7. Implementation of Control
detail in Chapter 8.
7.2.2.1 Simulink
When implementing the control system through Simulink several specialized input/output
blocks were constructed to abstract the control system from the underlying hardware. The
abstracted Simulink model is shown in Figure 7.13.
Figure 7.13: Abstracted Simulink Model
The feedback block handles the serial communication protocol to the IMU, sending the
command byte and receiving the raw data from the IMU. This is then converted to
standard units, such as radians, and output from the block.
The output, or VTOL block receives the output from the control system as a series of
control outputs as standardised units, for example motor angles in radians. This data is
scaled and oset to correspond with the appropriate raw output and sent to the digital to
analogue converters in order to send it to the slave DS-1104 board. For reasons of safety
a software emergency stop (or Estop) has been programmed into this block that latches
all outputs to zero in the event of an emergency. The workings of the VTOL block are
shown in Figure 7.14.
7.2.2.2 ControlDesk
Dierent ControlDesk layouts were required for each of the controller types being run.
The open-loop layout provided direct access to the output signals, the PID controller
layout had control of the setpoints and access to the controller gains, while the State-
Space controller layout only provided access to the setpoints. Figure 7.15 shows the
71
Chapter 7. Implementation of Control 7.2. Development Stage (Tethered)
Figure 7.14: VTOL Control Block
ControlDesk layout used during the tuning of the PID controller. It provides access to
all of the controller gains, the control output values, the input values provided by the
joystick and the IMU feedback.
Figure 7.15: ControlDesk Layout for the PID Controller
72
7.3. Semi-Tethered Conguration Chapter 7. Implementation of Control
7.3 Semi-Tethered Conguration
When the issue regarding the pivot not being located at the centre of mass was identied,
as discussed in Section 10.6, it was decided to test the aircraft while semi-tethered. The
aircraft was removed from the gimble, but still powered by the power sources discussed
in Section 7.2.1. The large power cables acted as an anchor, preventing the model from
lifting too high or travelling too far.
The only signicant dierence between this conguration and that outlined in Section
7.2 is the replacement of the serial connections with the free2move bluetooth dongles,
shown in Figure 7.16. These dongles act as a wireless serial link and have an approximate
outdoor range of 100m.
Figure 7.16: free2move Bluetooth RS-232 Transmitter / Receiver
In order to replace to two serial connections with a single wireless link the semi-
unidirectional nature of the IMU and the PicoPic were exploited. Information was send
to the PicoPic (located on the aircraft) as before, since this is already a unidirectional
link. The IMU was placed into continuous mode, where it sends back information about
the aircrafts state as quickly as it can, and hence was only used uni-directionally. This
data-stream from the IMU was buered in the DS-1104 board and required analysis to
identify a packet, compute its checksum and store the previous correct result in the event
a checksum fails. This process was made dicult by the signals-based nature of Simulink.
73
Chapter 7. Implementation of Control 7.4. Fully Embedded Solution
7.4 Fully Embedded Solution
7.4.1 Embedded Hardware Design
The aircraft hardware layout in its fully untethered conguration is shown in Figure 7.17
Figure 7.17: Untethered Hardware Conguration
7.4.1.1 Control Platform
In the untethered conguration the control system was ported to the MiniDRAGON+
development board, as discussed further in Section 7.4.2. It received control setpoints
by measuring the pulse width of the PWM output from the RC transmitter/receiver
pair, shown in Figure 7.18. Feedback is received from the IMU via one of the serial
communications ports of the MiniDRAGON+.
Figure 7.18: RC Transmitter and Receiver
74
7.4. Fully Embedded Solution Chapter 7. Implementation of Control
It was decided to continue using the PicoPic to generate the RC PWM signals even
though the MiniDRAGON+ has the facilities to generate eight 8-bit PWM signals, or
four 16-bit PWM signals. This is because the PicoPic can generate a much higher
resolution output for the ve required PWM outputs (expected to be eight when the
aircraft achieves conventional ight). The 8-bit PWMs generated by the MiniDRAGON+
can describe a maximum of 256 discrete levels over the entire period. Given the
usable pulse width is restricted to between 750s and 2250s as outlined in Section
7.1.1.1, as a best case scenario with f
s
= 200Hz, the number of usable outputs is
(2250 750) 10
6
200 256 = 76.8. This was deemed too low compared with
the approximate 1500 usable output levels available when using the PicoPic (see Section
7.1.2.3).
7.4.1.2 Power Supply
Once fully untethered the main motors and the the control system were powered by
on-board Lithium Polymer (LiPo) batteries, as chosen in Section 4.3.4.
7.4.2 Embedded Software Design
After consultation with Dr. Frank Wornle it was decided that the embedded controller
would be programmed in C, using Metrowerks Codewarrior, as opposed to using Dr.
Wornles real-time embedded Simulink target. This decision was made because of the need
to use some of the hardware units on the microcontroller, as discussed later. Programming
in C also tends to be more ecient, exible and reliable than using Simulink and the real-
time target.
A brief overview of the operation of the embedded code can be seen in Figure 7.19. The
following describes the basic operation of the program. Refer to Appendix C for the
embedded code.
7.4.2.1 Main Program
The main program consists of a loop that does nothing. The function of the main program
is to simply waste time until an interrupt occurs, at which time the program jumps to
one of the interrupt service routines.
75
Chapter 7. Implementation of Control 7.4. Fully Embedded Solution
Figure 7.19: Embedded Code Operation
7.4.2.2 Timed Interrupt
The timed interrupt is an interrupt that occurs at a xed frequency, in this case exactly
40 Hz. The function of the timed interrupt is to ensure the control system runs at a
xed rate as is required when running a discrete control system. As soon as the interrupt
occurs the control system is started.
7.4.2.3 Control System
The control system executes outside of the timed interrupt, so that other interrupts
associated with the other modules can still occur. Once the control system begins
execution it reads in the buered data from the IMU on the rst serial port (SCI0)
and requests the next set of data from the IMU. The control system then copies the
setpoint data from the PWM capture block, and for safety reasons tests the state of the
landing gear switch on the RC radio. If this switch is o or the radio itself is o the
control system is stopped from executing and all outputs set to zero, this is to prevent the
accidental starting up of the motors while someone is working on the aircraft. Before the
actual control system will execute properly this switch needs to be on for two seconds.
The controller has been ported to C from the state-space model. This was done by
collecting all the state-space components together into one large state-space controller
using the connect command in Matlab, as discussed in Section 6.2.5. This connected
state-space controller was converted from the continuous s-plane to the discrete z-
plane using Matlabs c2d command. Finally the A matrix of the discrete state-space
controller was diagonalized using the canon command in Matlab, which diagonalizes
the state space model reducing it to a simpler series of multiplications and additions which
are easily implemented in C.
76
7.4. Fully Embedded Solution Chapter 7. Implementation of Control
Once the control outputs are calculated they are placed in a buer to be sent to the
PicoPic over the second serial port (SCI1).
7.4.2.4 PWM Capture
The PWM capture code makes use of the microcontrollers Enhanced Capture Timer
(ECT) hardware unit to accurately measure the PWM signal output from the RC receiver
while using as little processor time as possible. The ECT captures both the time when
the PWM signal goes high and the time when it goes low. It then generates an interrupt
where the two times are compared to calculate the input pulse width. This pulse width
is scales to a value between zero and one representing the control setpoint.
The ECT has a total of eight channels, one (channel 7) is reserved for the timed interrupt
and another (channel 5) is connected to the speaker of the MiniDRAGON+ and thus does
not operate properly, leaving six channels able to capture the PWM signals.
7.4.2.5 IMU Communications
Upon the request of the control system the IMU Communications block sends the one-byte
request for the next set of data to the IMU. When each byte is returned from the IMU an
interrupt occurs and this byte is buered. Once the entire data packet has been received
the raw data from the IMU is converted and scaled to standard units. The control system
requests this data once it starts executing.
7.4.2.6 PicoPic Communications
Once the control system has buered the data for sending to the PicoPic, the PicoPic
communications module converts the data to the appropriate format for the PicoPic and
begins transmitting. Given the relatively long time required to send this data compared
with the processors speed this process is interrupt driven. When a byte has been sent
an interrupt occurs and the next byte in the buer is sent. This signicantly reduces the
communications overhead as compared to the busy-waiting method of communication.
77
Chapter 8
Testing and Tuning
8.1 Initial Open Loop Testing
The group initially tested the model connected rigidly to the gimble. This allowed the
group to verify the mechanical and systems design. It revealed the aw in the integrity
of the wing arm/motor mount junction, discussed in detail in Section 10.3. A new motor
mount was designed and built to withstand greater loading conditions.
After strengthening and rebuilding, a thrust test was performed by placing a set of digital
scales under the whole assembly and measuring the reduction in force applied to the
scales. Using the 12V Sealed Lead Acid (SLA) battery, a 5 kg reduction in mass was
measured which corresponds to 49 N of lift. The maximum current and voltage drop were
measured using the Emeter, a device placed in series with the power supply to one of
the motors which records its voltage, current draw and speed. The Emeter is showed in
Figure 8.1. The maximum current draw of one of the primary motors was 33.3A under
maximum load, with a corresponding voltage of 11.3V. This results in a total power draw
of 375W each motor. This exercise was repeated when powered by the LiPo batteries
which yielded slightly over 30N, however this is dependant of the actual charge status of
the batteries.
If the motors were not adequately cooled there was the potential for damage. A
thermocouple was attached to the exterior of each motor which allowed the group to
monitor the surface temperature, as overheating was a concern. During normal operation
the surface temperature did not exceed 30
1 300 300
Landing Gear 1 30 30
Bluetooth Dongle 1 50 50
Total 3952
Estimated
85
Chapter 9. Constraint Analysis 9.3. Power Budget
9.3 Power Budget
The amount of power that the batteries can provide is a constraint. Given the specication
of a minimum of 3 minutes ight time it is important that the batteries are able to provide
full power to the motors for at least this period.
The current prototype contains four separate power circuits. The control circuit contains
all of the control components and is powered by a 7.4V 1800 mAh LiPo, as shown in Table
9.4. Each of the main motors are driven by two Tanic 2400mAh 11.1V LiPo batteries,
while the rear motor runs from its own Tanic TP730-2S. The power budgets for both of
these circuits are shown in Table 9.5.
Table 9.4: Control Circuit Power Budget
Component Current Draw (mA) Quantity Total
Servo Motors 130 6 780
PicoPic 14 1 14
MiniDRAGON+ 85 1 85
3DM-GX1 IMU 65 1 65
Bluetooth RS-232 Dongle 70 1 70
TOTAL (mA) 1014
Battery Capacity (mAh) Surge Current (A) Discharge Time (min)
7.4 V 1800 mAh LiPo 1800 12 106.5
Table 9.5: Motor Power Budgets
Motor Current
Draw (A)
Battery Battery
Capacity (mAh)
Battery
Surge
(A)
Discharge
Time (min)
Plettenberg @ 100% 31 2xTanic LiPo 4900 58 8.9
Plettenberg @ 75% 25 2xTanic LiPo 4900 58 11.76
Himax @ 100% 10 Tanic LiPo 2450 24 14.7
86
Chapter 10
Issues
10.1 IMU
There were a number of issues relating to the IMU. Initially the 3DM-G, an older variant
of the 3DM-GX1 described in Section 4.4.1, was to be used. The communications protocol
provided with this unit was in fact for the newer 3DM-GX1, and hence described several
modes of operation which were not available on the older 3DM-G. It was desired to use
one of these modes of operation for the project, and as such a lot of time was wasted
trying to get these modes to work which were not supported by the 3DM-G. The correct
manual was eventually sourced from the manufacturer, and the 3DM-G exchanged with
a 3DM-GX1 another project group who did not need these advanced modes were using.
One issue relating to the IMU that aected several groups, including Jarrett et al. (2004)
was the poor handling of twos-complement numbers by Matlab and Simulink. Twos
complement is the most popular method used in computer science to represent both
positive and negative values. Matlab and Simulink treat the pure binary data, such as
that read back from the IMU, as unsigned integers, with no simple conversion to twos
complement representation. The conversion had to be manually programmed in order to
obtain the correct values.
10.2 Sourcing of Equipment
The Plettenberg motors together with the two associated ESCs, the Himax motor, LiPo
batteries and charger were originally sourced from a Canadian distributor. The specialised
nature of the Plettenberg motors required purchasing by the distributor from Plettenberg
87
Chapter 10. Issues 10.3. Mechanical Failure
in Germany prior to delivery. However, the deadline specied for delivery was exceeded.
After unsuccessful attempts to contact the distributor, a decision was made to procure
the Plettenberg motors direct from the manufacturer in Germany and the remainder of
the goods from a local distributor. Although this further delayed the acquisition date, it
was a necessary decision based on the lack of communication and unknown arrival date of
goods from the Canadian distributor. As a result of this sourcing issue, the commissioning
of the model was delayed by approximately three weeks.
10.3 Mechanical Failure
10.3.1 Wing Arm Motor Mount
During the initial stages of design testing, a failure occurred at the junction of the motor
mount and the wing arm. This occurred in the course of preliminary motor quantitative
thrust analysis and was believed to be a direct result of inadequate design accelerated by
propeller imbalance.
Initially the motor mount was xed to the aluminium tubing of the wing by a 3 mm bolt
through the tube, 10mm from the end of the shaft. The size of the tubing was designed to
withstand loading associated with torquing from the servo motors and transverse bending
from lift and the weight of the assembly, in which case the design would have been
sucient. However, the moment generated by the small distance between the thrust
point and the motor mount was not considered, and coupled with the eccentric force
generated by the propeller imbalance caused the bolt tear-out shown in Figure 10.1.
The slight imbalance in the pusher propeller was rectied through a static balancing
process. The thickness of the aluminium tubing used for the wing arm was also increased
to 2mm. This had the complimentary eect of reducing transverse ex of the wing arms,
a previously noticed concern. Additionally, the distance of the bolt-hole from the shaft
end was increased to 30mm and was reinforced with a solid aluminium plug. The result
of these changes was a more rigid, durable and strengthened junction point between the
wing arm and motor mount, reducing the risk of failure.
10.3.2 Gearbox Shaft
During untethered testing several crashes stripped the plastic gears on the servo motor
horn. This caused the wing arm to slip with the motor at high power, sending the propeller
88
10.4. Wing Arm Bearings Chapter 10. Issues
Figure 10.1: Failure of shaft at Wing/Motor Mount junction
into the ground at full-speed. This resulted in a torsional shear failure of the gearbox
output shaft.
Mr. Steve Kloeden from the workshop managed to repair the broken part in time for
the exhibition, allowing us to demonstrate the propulsion system. However Mr. Kloeden
stressed that this is a short-term solution, and advised a new gearbox or motor/gearbox
assembly be purchased. The motor itself is undamaged and it is envisaged that it will be
used to power a ducted fan for another of Dr. Ben Cazzolatos nal year projects.
10.4 Wing Arm Bearings
The original bearings used to facilitate rotation of the wing arms were teon coated
dry-rubbing copper bearings embedded into opposite ends of a nylon block. With no
transverse loading these bearings operated at a satisfactory level. However, transverse
forces experienced by shaft during operation resulted in an unsatisfactory level of friction
between the shaft and bearings. Even with additional lubrication, the wing arms were not
able to rotate with desired freedom, eventually resulting in stripping of the servo motor
gears.
The dry rubbing bearings were subsequently replaced with needle roller bearings of the
same inner diameter and similar length. This combined with the purchasing of the more
robust servo motors described in Section 4.5.1 resulted in satisfactory wing-arm operation.
89
Chapter 10. Issues 10.5. Electrical Noise
10.5 Electrical Noise
Originally the PWM signals were generated by the two dSPACE DS-1104 boards and
transmitted to the aircraft through the entire length of the wiring loom. During
transmission the PWM signals were picking up electrical noise which caused erratic
behaviour of the servo motors and electronic speed controllers. This noise problem was
identied by measuring the PWM signal at the aircraft side of the loom using a Cathode
Ray Oscilloscope (CRO).
The PWM signals were replaced with a serial connection to the PicoPic servo controller
which was located on the aircraft. The serial connection proved to be more robust
against noise, eliminating the erratic behaviour of the servo motors and electronic speed
controllers.
10.6 Unmodelled Gimble Dynamics
Tuning of the control system was initially attempted while the model was attached to
the gimble. This had the eect of introducing unmodelled dynamics into the system.
The gimble pivot was located at a distance from the centre of mass of the model. This
introduced dynamics analogous to the inverted pendulum problem, in that the aircraft
was easiest to control when in it was approximately horizontal, but became harder to
control as the angle from the horizontal increased. Furthermore the restraint on the
maximum angle of the gimble restricted movement and introduced a spring eect such
that the model could bounce when it hit the extremities of its movement.
To counter this problem, smaller IMU cradle arms where fabricated so the position of
the gimble could be brought closer to the centre of mass of the aircraft. If the centre of
mass is brought to the position of the pivot, or even slightly below it the dynamics of the
aircraft would better represent the true untethered dynamics.
10.7 Weight of Model
During the construction phase various elements of the design were altered. A consequence
of these alterations was the mass of the model to increased signicantly over initial
estimates. Increasing the size of the motors and propellers relative to the initial design
subsequently required an increase in battery size and resulted in substantial weight gain.
The redesign of the wing-arms after failure also increased the mass of the model, with
90
10.7. Weight of Model Chapter 10. Issues
thicker aluminium tubing and plate used to strengthen the motor mounts. The mass
of electric cabling was also higher than expected. The nal measured mass was 4.4kg
including batteries and training undercarriage. The model was able to attain sucient
thrust to leave the ground when running on a sealed lead acid battery. However testing
on LiPo batteries has shown that it there may not be enough static thrust generated to
achieve lift-o.
91
Chapter 11
Discussion and Future Work
11.1 Summary of achievements
Whilst a stable hover was not achieved during the course of the project, there were still
a number of signicant achievements throughout the project.
11.1.1 Choice of platform
The rst major task in this project was the choice of which platform to base our design on.
A number of sources were discussed in the literature review in Chapter 2 and the reasons
against choosing the F-35 Joint Strike Fighter were detailed in Section 3.1. For the reasons
outlined in Section 2.2.2, the V-22 Osprey was noted to have some promising features
and subsequently was analysed in more detail. This change in platform necessitated the
abandoning of much of the work achieved by Jarrett et al. (2004).
11.1.2 Mechanical design
To develop a realistic working model of the system, a full solid model of the frame and
components was constructed in SolidEdge. The detailed frame drawings can be found in
Appendix A. The biggest constraint was keeping the weight down enough to ensure that
the thrust to weight ratio exceeded the chosen minimum of 1.5:1. Although the mechanical
design of the current system did not have the same vibration issues that Jarrett et al.
(2004) had to consider, the frame still needed to be structurally sound.
92
11.1. Summary of achievements Chapter 11. Discussion and Future Work
11.1.3 Component Selection and Procurement
Through the review of the mechanical system requirements as discussed in Section 4.3, the
components required to produce thrust, namely the batteries, motors and propellers, were
chosen and subsequently purchased. These components, whilst expensive, have enormous
potential for producing thrust. Furthermore these components have a high degree of
reuseability due to their quality, and thus will be used in future projects.
11.1.4 Mechanical Construction
The frame design was manufactured in the workshop and was assembled with all the
chosen components. The frame displayed a high degree of robustness and controllability,
provided the control system were suciently tuned. As such makes a solid control platform
for future development.
11.1.5 Mathematical Modelling
This project intended to implement a state space controller which required an accurate
model of the system dynamics. In Chapter 5 the mathematical model of the aircraft
whilst in hover was derived using force and moment balancing, motor/propeller response
properties and dierential equations of motion. In order to design a controller the non-
linear terms were approximated as linear about their operation points.
11.1.6 Controller Design and Tuning
In Chapter 6 both a PID and a state-space controller were designed. The state-
space controller was constructed using the derived mathematical model. Whilst it was
envisioned the PID controller would be tuned experimentally this did not occur due to
the events discussed in Chapter 8, where mechanical failure hampered controller tuning.
The state-space controller, on the other hand, was tuned using optimal control (LQR).
11.1.7 Control Implementation
Signicant achievements were accomplished in the implementation of the control system,
even though the control system itself was not suciently tuned.
93
Chapter 11. Discussion and Future Work 11.2. Future Tasks
During the control development, while the controller was run from the dSPACE DS-
1104 platform, several issues relating to the Inertial Measurement Unit (IMU) were
discovered for the rst time in a nal year project, despite its previous use, as discussed
in Section 10.1. Additionally through the use the PicoPic servo motor controller, a much
less expensive component than a dSPACE DS-1104 platform, and insight into to the
communications protocols used, the control system was implemented on a single DS-
1104 board. This frees an expensive DS-1104 board for use in other projects or teaching
practicals throughout the university year.
Given the requirement of an embedded controller and the use of standard RC equipment
for control, extensive work was undertaken in the integration of these components.
The MiniDRAGON+ development board was programmed and tested for reliable
operation and communication with all peripheral equipment, as discussed in Section 7.4.
Furthermore the state space controller was ported to the MiniDRAGON+ development
board using an ecient method that is quick and easy to reproduce if the controller
changes. It was tested and proven that the MiniDRAGON+ development board had
sucient processing power to execute this state space controller, including such features
as a reduced-order observer.
11.2 Future Tasks
11.2.1 Stable Hover
Given the large amount of work that has gone into this project it is envisioned that the
completion of all the project goals will only require minimal work. As such all of the
project members have expressed an interest in continuing the project past the ocial
completion date in order to get the aircraft to hover in a stable manner. Through the
modication of the gimble to eliminate the issue of the unmodelled dynamics discussed
in Section 10.6, it is expected that a suitable controller could be quickly developed. The
aircraft would then be tested untethered, in a similar method to that described in Section
8.3.
11.2.2 Real-Time Embedded Gain Updating
It is proposed to implement communications from the MiniDRAGON+ to the IMU and
PicoPic using a single serial communications port in a similar fashion to that implemented
on the dSPACE DS-1104 control board. This would free up the second port which could
94
11.2. Future Tasks Chapter 11. Discussion and Future Work
then be used to implement a protocol to update the controller gains in real-time, possibly
using the bluetooth dongles, in a similar fashion to that used by ControlDesk.
11.2.3 System Identication
While the mathematical model developed in Chapter 5 is quite detailed, many
approximations were required to linearise the model. Due to these approximations some
states of the model may be uncontrollable in practice. Dierent methods of linearising
the equations exist but may have similar issues. Should this be the case with the
model presented in Chapter 5, the Matlab System Identication toolkit facilitates the
evaluation of linear models of dynamic systems from input-output data. Designing the
controller using such a numerical system model is potentially more accurate. This will
allow a wider choice of control system as some techniques require an accurate model.
11.2.4 Reduced Precision Sensors
As one of the main objectives is to build a system which is aordable by model aircraft
enthusiasts, using a $2500 IMU is not practical. It is envisioned that more economically
viable rate gyroscopes will be used. Rate gyroscopes are prone to DC oset since they
must be integrated to determine the position. The eect of less precise information can
be simulated on the IMU by not utilising some of its advanced features, which will allow
the tuning of the existing control system to a point where it is suitable for use with rate
gyroscopes and hence more viable for the commercial market.
Rate gyroscopes output the angular velocity of the model, thus for control the signal must
be numerically integrated to obtain a value for angular position. Numerical integration
of discrete signals is prone to oset errors, thus it is likely the model will drift during
hover. These bias errors can be overcome by an operator using trim pots (trimming
potentiometers) to correct the signal, or the addition of a cheap horizon sensor.
11.2.5 Model Body
Eventually a V-22 Osprey body will be constructed around the frame. Using balsa wood
ribbing and depron skin the body can be made very light. The frame has been designed to
t inside a 1:15 model of the V-22 Osprey with minor modication. At this stage serious
consideration must be put into the size, shape and actuation of the traditional control
surfaces. For the purposes of realism a simple body was manufactured from cardboard
95
Chapter 11. Discussion and Future Work 11.2. Future Tasks
and shaped clear plastic. This covering enables a view of the inner model workings, whilst
giving a realistic impression of the nal design. The drawback associated with this design
is that it is purely aesthetic and cannot be used for active conditional control surfaces.
11.2.6 Conventional Flight
As a future project the model could be adapted for conventional ight. This will involve
the construction of traditional ight and control surfaces, such as wings, ailerons, rudders
and elevators and the adaption of the control system to allow a successful transition to
conventional ight. This has been the major challenge to enthusiasts who have attempted
to build model VTOL aircraft in the past.
96
References
Aireld Models (2005).
http://www.aireldmodels.com/information source/model aircraft engines/propellers.html.
Accessed 10/10/05.
Bell Agusta (2005). http://www.bellagusta.com/pdf/ba609 2004.pdf. Accessed 19/5/05.
Boeing (2005). http://www.boeing.com/rotorcraft/military/v22. Accessed 10/5/05.
Cazzolato, B. (2005a). 3 Degree of Freedom Hover Tutorial. The University of Adelaide.
Cazzolato, B. (2005b). Advanced Automatic Control Lecture Notes. The University of
Adelaide, Adelaide.
Cazzolato, B. (2005c). Automatic Control II Lecture Notes. The University of Adelaide,
Adelaide.
Chapman, L. (2005). http://www.geocities.com/v22chap. Accessed 15/3/05.
Dorf, R. and Bishop, R. (2001). Modern Control Systems. Prentice Hall, New Jersey,
9th edition.
Franklin, J. A. (2002). Dynamics, Control and Flying Qualities of V/STOL Aircraft.
AIAA.
Hamel, R. L. R. O. J., Tarek; Mahony (2002). Dynamic modelling and conguration
stabilization for an x4-yer. IFAC 15th Triennial World Congress, Barcelona, Spain.
Hansen, C. and Snyder, S. D. (1996). Active Control of Noise and Vibration. Spon Press.
HazelProp (2005). http://www.hartzellprop.com/engineering/engineering faqs.htm.
Accessed 19/9/05.
ICARE (2005). Personal correspondence. 28/7/05.
Jarrett, M., Ng, R., and Teske, T. (2004). Radio Controlled Vertical Take-O and
Landing Aircraft. The University of Adelaide, Adelaide.
97
References References
JSF (2005). http://www.jsf.mil/index.htm. Accessed 19/5/05.
McCormick, B. W. J. (1995). Aerodynamics, Aeronautics and Flight Mechanics.
Academic Press.
Mettler, B. (2003). Identication Modelling and Characteristics of Minature Rotorcraft.
Kluwer Academic Publishers.
Modelight (2005). http://www.modelight.com.au/jr propo rc control servos.htm.
Accessed 1/5/05.
Newman, T. (2005). Personal correspondence. 16/5/05.
Picobytes inc. (2003). PicoPIC User and Technical Manual.
Rogers, M. (1989). VTOL Military Aircraft. Haynes.
RS Automation (2005). http://www.rsaustralia.com. Accessed 1/6/05.
Schubeler (2005). http://www.schuebeler-jets.de. Accessed 16/3/05.
TiltRotorMech (2005). http://www.tiltrotormech.com/v22 models.htm. Accessesd
10/5/05.
WeMoTec (2005). http://www.wemotec.com/index e.html. Accessed 1/5/05.
Wikipedia (2005). http://en.wikipedia.org. Accessed 25/9/05.
Wilkins, P. S. (2001). The potential use of military tiltrotor aircraft for aeromedical
evacuation. ADF Health, 1:58 63.
Xiaofei-Wu, Ignatov, R., Muenst, G., Imaev, A., and Zhu, J.-J. (2002). A nonlinear
ight controller design for a ufo by trajectory linearization method, part 1, modelling.
Proceedings of the Thirty Fourth Southeastern Symposium on System Theory Cat,
No.02EX540.:97102.
98
Appendix A
CAD Drawings
Drawing Number Title
VTOL-05-001 VTOL-05 Frame
VTOL-05-002 Main Chassis
VTOL-05-003 Main Chassis Parts
VTOL-05-004 Assembled Wing Arm
VTOL-05-005 Assembled Wing Arm Parts
VTOL-05-006 IMU Cradle
VTOL-05-007 IMU Cradle Parts
VTOL-05-008 Motor Mount and Propeller Adapter
Please note all drawings were intended for printing to A3, hence some detail may be lost
when printed to A4.
99
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
a1078621 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-001.dft SCALE: WEIGHT: SHEET 1 OF 2
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
VTOL-05 Frame
zebb.prime@student.adelaide.edu.au
VTOL-05-001
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
a1078621 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-001.dft SCALE: WEIGHT: SHEET 2 OF 2
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
VTOL-05 Frame
zebb.prime@student.adelaide.edu.au
VTOL-05-001
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
1154
260
94
6
0
2
2
0
3
0
0
4
2
0
9
4
5
3
1
1
1
2
2
Item Number Document
Number
Title Quantity
1 VTOL-05-002 Main Chassis 1
2 VTOL-05-004 Assembled Wing Arm 2
3 VTOL-05-006 IMU Cradle 1
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
a1078621 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-002.dft SCALE: 1:5 WEIGHT: 279g+welds SHEET 1 OF 1
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
Main Chassis
zebb.prime@student.adelaide.edu.au
VTOL-05-002
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
265
420
106.5
A
DETAIL A
B
DETAIL B
ASSEMBLY NOTE:
PLEASE WELD ALL COMPONENTS AS APPROPRIATE
(Left)
7
8
13
12
11
10
6
2
3
5
4
1
9
Item Number Document
Number
Title Quantity
1 VTOL-05-003 Rear Servo Mount (for elevators
and rudder)
1
2 VTOL-05-003 Main Frame Front Strut 1
3 VTOL-05-003 Main Frame Left Strut 1
4 VTOL-05-003 Main Frame - Rear Cantilever
Arm
1
5 VTOL-05-003 Main Frame Right Strut 1
6 VTOL-05-003 Main Frame Back Strut 1
7 VTOL-05-003 Aileron Servo Mount 1
8 VTOL-05-003 Rear Ducted Fan Mount 1
9 VTOL-05-017 Connecting Bracket 1
10 VTOL-05-003 Connecting Bracket 1
11 VTOL-05-003 Arm holder 2
12 VTOL-05-003 Wing Servo Bracket (Right) 1
13 VTOL-05-003 Wing Servo Bracket 1
Flatten tube to
accept rear fan mount
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
a1078621 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-003.dft SCALE: - WEIGHT: - SHEET 1 OF 5
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
Main Chassis Parts
zebb.prime@student.adelaide.edu.au
VTOL-05-003
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
Jesse Sherwood
3
47
1
0
0
37
7
.
5
1
4
.
5
3
REAR SERVO MOUNT (FOR RUDDER AND ELEVATOR CONTROL)
QUANTITY: 1
SCALE: 1.5:1
MATERIAL: 3MM ALUMINIUM
1
4
8
.
5
4.5
O
4
.5
O
3.5
O
3
.5
3
6
.
5
2
4
6
.
5
1
7
3
.
5
4
2
0
20
MAIN FRAME - LEFT STRUT
QUANTITY: 1 SCALE: 1:2
MATERIAL: 20x12x1.5 UNEQUAL ANGLE ALUMINIUM
4
5
12
13
1.5 THICK
8x M3
13.5
2
3
O
3
4x
1
9
.
5
2
.
5
33.5
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
a1078621 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-003.dft SCALE: - WEIGHT: - SHEET 2 OF 5
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
Main Chassis Parts
zebb.prime@student.adelaide.edu.au
VTOL-05-003
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
Jesse Sherwood
1
7
3
.
5
3
8
3
.
5
3
6
.
5
4
2
0
O
3
.5
O
3
.5
4
5
13
20
1
4
8
.
5
4.5
12
1.5 THICK
MAIN FRAME - RIGHT STRUT
QUANTITY: 1 SCALE: 1:2
MATERIAL: 20x12x1.5 UNEQUAL ANGLE ALUMINIUM
9
4
4
5
20
1
2
1.5
O
4
.5
4
7
4
7
4.5
MAIN FRAME - FRONT STRUT
QUANTITY: 1
SCALE: 1:1
MATERIAL: 20x12x1.5 UNEQUAL ANGLE ALUMINIUM
9
4
1
0
4
2
4
2
20
1
2
1.5
4
5
M2
2
.
5
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
a1078621 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-005.dft SCALE: - WEIGHT: - SHEET 2 OF 2
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
Assembled Wing Arm Parts
zebb.prime@student.adelaide.edu.au
VTOL-05-005
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
ACRYLIC ARM BEARING BLOCK
QUANTITY: 2
SCALE: 1:1
MATERIAL: ACRYLIC
NOTES: 1 FOR EACH WING ARM
RECESSES MACHINED TO FIT STANDARD
ID16x16 ROLLER BEARINGS
35
3
0
O
2
0
O
2
2
5
5
5
5
16 28 16
60
1
0
1
0
4xM3
O
2
6
O
16
.2
5
4
5
1
0
.
5
2
.
5
4
.5
4xM3
1
0
WING ARM MOTOR MOUNT
QUANTITY: 2
SCALE: 2:1
MATERIAL: ALUMINIUM
NOTES: 1 FOR EACH WING ARM
O
1
2
O
2
6
1
0
3
0
4
0
1
0
.
5
2
.
5
4xO3
WING ARM PLUG
QUANTITY: 2
SCALE: 2:1
MATERIAL: ALUMINIUM
NOTES: 1 FOR EACH WING ARM
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
a1078621 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-006.dft SCALE: 1:2 WEIGHT: 126g+welds SHEET 1 OF 1
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
IMU Cradle
zebb.prime@student.adelaide.edu.au
VTOL-05-006
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
BOTTOM ONLY
BOTTOM ONLY
AS APPROPRIATE
AS APPROPRIATE
AS APPROPRIATE
AS APPROPRIATE
240
9
4
7
6
.
5
5
6.5
NOTES:
ALL PARTS EXCEPT GIMBLE EXTENDER TO BE WELDED ON AS APPROPRIATE/SHOWN
5
1
3
2
4
Item Number Document
Number
Title Quantity
1 VTOL-05-007 IMU Cradle Strut - Back 1
2 VTOL-05-007 IMU Cradle - Right Strut 1
3 VTOL-05-007 IMU Cradle - Left Strut 1
4 VTOL-05-007 IMU Cradle upright 4
5 VTOL-05-007 Gimble Extender 1
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
Jesse Sherwood 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-007.dft SCALE: - WEIGHT: - SHEET 1 OF 2
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
IMU Cradle Parts
jesse.sherwood@student.adelaide.edu.au
VTOL-05-007
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
4
5
4
7
9
4
O
6
.5
20
1
2
1.5
IMU CRADLE - REAR STRUT
QUANTITY: 1
SCALE: 1:1
MATERIAL: 20x12x1.5 UNEQUAL ANGLE ALUMINIUM
2
4
0
4
5
3
2
1
5
6
20
1
2
1.5
IMU CRADLE - LEFT STRUT
QUANTITY: 1
SCALE: 1:2
MATERIAL: 20x12x1.5 UNEQUAL ANGLE ALUMINIUM
20
1
2
1.5
2
4
0
3
2
1
5
6
8.25
5.5
4
5
8.25
5.5
IMU CRADLE - RIGHT STRUT
QUANTITY: 1
SCALE: 1:2
MATERIAL: 20x12x1.5 UNEQUAL ANGLE ALUMINIUM
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
Jesse Sherwood 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-007.dft SCALE: - WEIGHT: - SHEET 2 OF 2
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
IMU Cradle Parts
jesse.sherwood@student.adelaide.edu.au
VTOL-05-007
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
O
1
0
O
7
.6
7
5
IMU CRADLE - UPRIGHT
QUANTITY: 4
SCALE: 2:1
MATERIAL: STANDARD OD 10MM ALUMINIUM TUBE
O
1
0
1
0
5
0
1
0
M6
M6
GIMBLE EXTENDER
QUANTITY: 1
SCALE: 2:1
MATERIAL: STEEL
NOTES: CONFIRM BOTTOM THREAD SIZE BEFORE
SUMBISSION
GIMBLE-IMU MOUNT
QUANTITY: 1
SCALE 1:1
MATERIAL: 3mm ALUMINIUM
NOTES: DISTANCE BETWEEN HOLES IS IMPORTANT
76
O
4
.5
2
x
2
5
O
6
.
5
94
1
2
0
A
p
p
r
o
x
25 Approx
36 Approx 22 Approx
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
a1078621 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-008.dft SCALE: WEIGHT: SHEET 1 OF 2
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
Motor Mount and Propeller Adapter
zebb.prime@student.adelaide.edu.au
VTOL-05-008
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
O
1
8
4xO3.5
1
8
5
0
3
20 23
46
3
2
13
1
3
40
7
5
1
0
.
5
3
0
4
0
.
5
10.5 9.5
3
3
3
5
0
50
PLETTENBERG MOTOR MOUNT
QUANTITY: 2
SCALE: 1:1
MATERIAL: ALUMINIUM
NOTE: TO BE WELDED TOGETHER FROM 3MM ALUMINIUM
APC PROPELLER ADAPTER
QUANTITY: 2
SCALE: 2:1
MATERIAL: STEEL
NOTE: PARTS ON THE FOLLOWING PAGE
5
1
2
4
3
Item Number Document
Number
Title Quantity
1 VTOL-05-008 Propeller Adapter Shaft 1
2 VTOL-05-008 Propeller Adapter Lower Collar 1
3 ------------ APC 20"x10" Glass Filled Nylon
Propeller
1
4 VTOL-05-008 Propeller Adapter Upper Collar 1
5 ------------ M8 Fibre Lock Nut 1
DRAWN
CHECKED
ENG APPR
MGR APPR
ALL DIMENSIONS IN MILLIMETERS
UNLESS OTHERWISE SPECIFIED
a1078621 27/10/05
TITLE
SIZE
A3
DWG NO REV
FILE NAME: VTOL-05-008.dft SCALE: WEIGHT: SHEET 2 OF 2
REVISION HISTORY
REV DESCRIPTION DATE APPROVED
CONTACT
Motor Mount and Propeller Adapter
zebb.prime@student.adelaide.edu.au
VTOL-05-008
1
ALL TOLERANCES +/- 0.5MM OR +/- 1
UNLESS OTHERWISE SPECIFIED
O
4
4
O
2
8
.2
O
17.8
O
8
1
.
5
5
.
3
O
2
5
O
1
5
.9
O
8
1
.
5
3
.
4
M8
O
1
4
4
M
6 O
2
3
6
3
4
0
1
7
4
M
PROPELLER ADAPTER SHAFT
QUANTITY: 2
SCALE: 2:1
MATERIAL: STEEL
NOTE: ONE FOR EACH MOTOR
PROPELLER ADAPTER LOWER COLLAR
QUANTITY: 2
SCALE: 2:1
MATERIAL: STEEL
NOTE: ONE FOR EACH MOTOR
PROPELLER ADAPTER UPPER COLLAR
QUANTITY: 2
SCALE: 2:1
MATERIAL: STEEL
NOTE: ONE FOR EACH MOTOR
Appendix B
Simulink Code
100
% This file will build a state model of the 2005 RC VTOL (Osprey).
% The file was adapted from Ben Cazzolato's state model template.
clc
close all
clear all
disp('Mass of motors and fans')
mf = 0.4; % mass of each front motor/prop (kg)
mb = 0.1; % mass o rear motor/fan (kg)
disp('Total mass')
Mp = 4; %Mass of plane (kg)
%disp('Length of fuselage (m)')
l1 = .05;
l2 = .8;
l3 = .5;
% Will need to work these out somehow
%disp('Moment of intertia for a single motor/fan')
J = mf;
Jre = mb;
%disp('Moments of inertia about each axis')
Jy = 0.25934; %calculated on solid edge
Jp = 0.094625;
Jr = 0.19712;
% prop weighs 0.0433lbs = 195g.
Jpr = 2.55e-3; % moment of inertia of prop, see p31 of allans book
disp('Motor/Fan Force and Torque constants')
% some of these constants are not in use currently as they have been
% replaced by experimentally determined values
Vhov = 8; % Voltage supplied to front motors for hover
kD = .004; % drag constant of props (assumed from prop calc)
kt = .1901; % torque constant of motor (mN.m/A) (published on website)
kB = 0; % torque constant of rear motor (Nm/A)
keb = kB;
Ra = .29; % armature resistance (ohms)
CT = 0.0828; %thrust coefficient for propeller 20-10 estimated propcalc
kl = 0.7; % coefficient of lift for props
klrear = 0.5; % coefficient of lift for rear fan
ke = kt; %back emf constant = torque const in SI units
Kmp = ((.1901)^2/0.56 + 0.008*3000/60); %(bm + kt*ke/Ra + kD*theta_0_dot);% was 0.06;
Kd = 0; % kD*theta_0_dot*kt/(Ra*Kmp); % Nm per volt Front Props (not measured)
Kdr = 0; % Nm per volt Rear Prop/Fan (not measured)
%Kp = kl*theta_0_dot*kt/(Ra*Kmp);
% From Thrust Testing
thr = 2.5*9.81; % from full power thrust test on 12V battery 49N for both props;
Kp = thr/10; % N x volt Front Props;
Kr = .15/10; % N per volt Rear Prop/Fan;
Pd = l1*Kp/Jp;
Rd = l3*Kp/Jr;
Zd = Kp/Mp;
%_______________________________________________
disp('Define the uncoupled model')
disp('States : [y, y_dot, p, p_dot, r, r_dot, theta_L_dot,theta_R_dot, X, X_dot, Z, Z_dot]')
% Angles are in radians
% p = pitch
% r = roll
% y = yaw
% theta_L = angular position of left prop
% theta_R = angular position of right prop
% X = translation along X axis
% Y = translation along Y axis
% Z = translation along Z axis
disp('State Matrix')
Am=[ 0 0 0 0 0 0 0 0 % * y_dot
0 0 0 0 1 0 0 0 % * p
0 0 0 0 0 1 0 0 % * r
0 0 0 0 0 0 Zd Zd % * Z_dot
0 0 0 0 0 0 -Pd -Pd % * p_dot
0 0 0 0 0 0 -Rd Rd % * r_dot
0 0 0 0 0 0 -Kmp/Jpr 0 % * theta_L_dot
0 0 0 0 0 0 0 -Kmp/Jpr ] % * theta_R_dot
disp('State input matrix')
disp('Command states are: [Dl, Dr, Db, phi_L, phi_R]')
% Vl Vr Vb phi L phi R
Bm=[ Kd -Kd Kdr l3*Kp*Vhov/Jy -l3*Kp*Vhov/Jy % = y_ddot
0 0 0 0 0 % = p_dot
0 0 0 0 0 % = r_dot
0 0 -Kr/Mp 0 0 % = Z_ddot
0 0 l2*Kr/Jp 0 0 % = p_ddot
0 0 0 0 0 % = r_ddot
kt/(Ra*Jpr) 0 0 0 0 % = theta_L_ddot
0 kt/(Ra*Jpr) 0 0 0 ] % = theta_R_ddot
%State output vector
% y p r X Z
Cm = [1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0 ];
%Feedforward term
Dm = [0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0];
disp(' ');disp(' ');
osprey_model = ss(Am,Bm,Cm,Dm);
Statenames = str2mat('y_dot', 'p','r', 'Z_dot', 'p_dot', 'r_dot', 'theta_L_dot', 'theta_R_dot')
set(osprey_model,'StateName',Statenames);
set(osprey_model,'InputName',{'D_{left}'; 'D_{right}'; 'D_{back}'; 'Phi_{left}';...
'Phi_{right}'},'OutputName',{'yaw'; 'pitch'; 'roll'; 'Z_trans'})
disp(' ');disp(' ');
disp('Now add the augmented states');
disp('States : [y_dot, p, r, Z_dot , p_dot, r_dot, theta_L_dot,...
theta_R_dot, alpha, beta, gamma, zeta, eta]');
% State Matrix
A_augmented = [Am, zeros(8,4); Cm, zeros(4,4)];
% State input matrix
B_augmented = [ Bm; zeros(4,5)];
% Also define an alternative input vector to allow us to input the desired
% setpoints
B_setpoint = zeros(12,4);B_setpoint(9,1)=-1;B_setpoint(10,2)=-1; B_setpoint(11,3)=-1;
B_setpoint(12,4)=-1;% Augmented state input vector for 4 augmented states
% B_aug = [B,B2]
% State output vector
C_augmented = [Cm, zeros(4,4)];
% Feedforward term
D_augmented = Dm;
osprey_augmented = ss(A_augmented,B_augmented,C_augmented,D_augmented);
Statenames = str2mat('y_dot', 'p','r','Z_dot', 'p_dot', 'r_dot', 'theta_L_dot',...
'theta_R_dot', 'alpha', 'beta', 'gamma', 'zeta');;
set(osprey_augmented,'StateName',Statenames);
set(osprey_augmented,'InputName',{'D_{left}'; 'D_{right}'; 'D_{back}'; 'Phi_{left}';...
'Phi_{right}'},'OutputName',{'yaw'; 'pitch'; 'roll'; 'Z_trans'});
osprey_augmented;
%%
%disp('The open poles are')
damp(Am);
step(osprey_model)
title('Open Loop Step Response')
% Check controllability
Co = ctrb(osprey_model);
cond(Co);
% Check observability
Ob = obsv(osprey_model);
cond(Ob);
unco = length(Am)-rank(Co); % number of uncontrollable states
unob = length(Am)-rank(Ob); % number of unobservable states
%_____________________________________________________________
disp('Now design the controller')
disp('State weighting matrix')
q = diag([100 100 100 100 1 1 1 1 200 200 200 200])
disp('Effort penalty matrix')
r = diag([2 2 2 50 50])
% The controller gains
K = lqr(A_augmented,B_augmented,q,r);
Km = K(:,1:8) % These are the usual feedback gains
Ki = K(:,9:12) % These are the feedback gains for the augmented states
% The closed loop system with full state feedback is
C_extra = [Cm;-Km]; % Augment the output so we can see the motor drive voltages.
osprey_model_full = ss(Am-Bm*Km,Bm,C_extra,0);
Statenames = str2mat('y_dot', 'p','r', 'Z_dot', 'p_dot', 'r_dot', 'theta_L_dot', 'theta_R_dot');
set(osprey_model_full,'StateName',Statenames);
set(osprey_model_full,...
'InputName',{'D_{left}'; 'D_{right}'; 'D_{back}'; 'Phi_{left}'; 'Phi_{right}'}, ...
'OutputName',{'yaw'; 'pitch'; 'roll'; 'Z_trans'; 'D_{left}'; 'D_{right}'; 'D_{back}';...
'Phi_{left}'; 'Phi_{right}'});
% Plot the closed loop step response
figure
step(osprey_model_full)
title('Closed loop step response with full state feedback');
% The closed loop augmented system with full state feedback and command following is
C_extra = [C_augmented;-K]; % Augment the output so we can see the motor drive voltages.
osprey_augmented_full = ss(A_augmented-B_augmented*K,B_setpoint,C_extra,0);
Statenames = str2mat('y_dot','p','r', 'Z_dot', 'p_dot', 'r_dot', 'theta_L_dot',...
'theta_R_dot', 'alpha', 'beta', 'gamma', 'zeta');
set(osprey_augmented_full,'StateName',Statenames);
set(osprey_augmented_full,...
'InputName',{'Yaw Command'; 'Pitch Command'; 'Roll Command';'Z Trans Command'}, ...
'OutputName',{'yaw'; 'pitch'; 'roll';'Z_trans';'D_{right}';'D_{left}'; 'D_{back}';'Phi_{left}'; 'Phi_
{right}'});
osprey_augmented_full;
% % Plot the closed loop step response
figure
step(osprey_augmented_full)
title('Augmented system closed loop step response with full state feedback and command following')
%% Reduced Order Observer
% Splits A and B matrices into required form for Reduced Order Observer
for i = 1:4
for j = 1:4
Aaa(i,j) = Am(i,j);
Ba(i,j) = Bm(i,j);
end
end
for i = 5:8
for j = 1:4
Aba(i-4,j) = Am(i,j);
Bb(i-4,j) = Bm(i,j);
end
end
for i = 1:4
for j = 5:8
Aab(i,j-4) = Am(i,j);
end
end
for i = 5:8
for j = 5:8
Abb(i-4,j-4) = Am(i,j);
end
end
Qob = diag([1 1 1 1]); % Q matrix for kalman filter
Rob = diag([1 1 1 1]); % R matrix for Kalman filter
G = lqr(Abb',Aab',Qob,Rob); % Determine observer gains
L = transpose(G);
L_red = L;
%computes state matrices for reduced order observer to allow for a state
%space block to be used in Simulink model
Ar = Abb - L*Aab;
Br = [(Aba- L*Aaa + Abb*L - L*Aab*L) (Bb - L*Ba)];
Cr = eye(4);
Dr = [L zeros(4,5)];
%% Full Rank Observer (used in estim command below)
P = pole(ss(Am-Bm*Km,Bm,Cm,Dm));
disp('Place observer poles at 10 times the controller poles')
P_ob = 10*P;
disp('Now work out observer gains')
L_transpose = place(transpose(Am),transpose(Cm),P_ob);
L_full = transpose(L_transpose);
disp('Now build the full estimator (not reduced) using the "estim" command')
% EST = ESTIM(SYS,L,SENSORS,KNOWN)
% The system is "plant", the estimator gains are "L"
% The sensors specify which outputs (y) are known, which in this case
% is the first four states
% The known refers to which inputs (u) to the plant are known.
%
% First determine the number of inputs and outputs from the plant
[Nstates,Nin] = size(Bm)
[Nout,Nstates] = size(Cm)
SENSORS = [1:Nout]
KNOWN = [1:Nin]
system_estim = estim(osprey_model,L,SENSORS,KNOWN)
plant_estim = estim(osprey_model,L)
Statenames = str2mat( 'y_dot_est', 'p_est', 'r_est',...
'Z_dot_est','p_dot_est','r_dot_est','theta_L_dot_est', 'theta_R_dot_est')
set(system_estim,'StateName',Statenames)
set(system_estim,
'InputName',{'V_{left}'; 'V_{right}'; 'V_{back}'; 'Phi_{left}'; 'Phi_{right}';...
'Yaw_des'; 'Pitch_des'; 'Roll_des';'Z_des'},...
'OutputName',{'Yaw_est'; 'Pitch_est'; 'Roll_est';'Z_est'; 'y_dot_est';...
'p_est';'r_est';'Z_dot_est';'p_dot_est'; 'r_dot_est';'theta_L_dot_est'; 'theta_R_dot_est'})
%%
%
disp('*******************')
disp('Design a regulator ')
disp('*******************')
% Look at the regulated plant - For checking final system
disp('The regulator is')
osprey_model_reg = reg(osprey_model,Km,L)
disp('The regulated system is')
osprey_model_regulated = feedback(osprey_model,-osprey_model_reg)
figure
step(osprey_model_regulated)
title('Step response with regulator')
%%
%
disp('************************************************************************')
disp('Now build all the subcomponents to make the model with integral tracking')
disp('************************************************************************')
disp('*******************************************')
disp('Build a state space model of the controller')
disp('*******************************************')
system_controller = ss([],[],[],-Km); % This is simply a feed forward term
Statenames = str2mat( 'y_dot', 'r', 'p', 'Z_dot','p_dot','r_dot','theta_L_dot','theta_R_dot')
set(system_controller,...
'InputName',{ 'y_dot_in','p_in','r_in','Z_dot_in',
'p_dot_in','r_dot_in','theta_L_dot_in','theta_R_dot_in'},...
'OutputName',{'Vcont_{left}'; 'Vcont_{right}'; 'Vcont_{back}'; 'Phi_cont_{left}'; 'Phi_cont_
{right}'});
system_controller
disp('******************************************************')
disp('Build a state space model of only the augmented states')
disp('******************************************************')
% This is an integrator (on the input) for each state, with input weighting equal to the control gains
calculated earlier
system_aug = ss(zeros(5),Ki,eye(5),0);
Statenames = str2mat('alpha', 'gamma','beta','epsi','kappa')
set(system_aug,'StateName',Statenames)
set(system_aug,...
'InputName',{'Yaw Error'; 'Pitch Error';'Roll Error';'Z Error'},...
'OutputName',{'Integral Vl error'; 'Integral Vr error'; 'Integral Vb error';...
'Integral phi L error';'Integral phi R error'})
system_aug
%%
disp('**********************************************')
disp('Build a state space model of the command input')
disp('**********************************************')
% This is the only way to have four inputs into the augmented states
system_input = ss([],[],[],eye(4));
set(system_input,'InputName',{'Yaw SP', 'Pitch SP','Roll SP','Z SP'},'OutputName',{'Pitch SP', 'Yaw SP',
'Roll SP','Z SP'});
system_input
system_plant = osprey_model;
disp('********************************************************************************************')
disp('Append the plant, the estimator, the controller, the augmented states and the command inputs')
disp('********************************************************************************************')
system_complete_temp = append(system_plant, system_estim, system_aug, system_controller, system_input)
goutput = get(system_complete_temp,'OutputName');
ginput = get(system_complete_temp,'InputName');
disp('*********************************************************************************************')
disp('Connect the plant, the estimator, the controller, the augmented states and the command inputs')
disp('*********************************************************************************************')
%% Connect all the appropriate inputs and outputs of the subsystems
% The connection from the plant output into the estimator
con1 = [11, 1, 0; 12, 2, 0; 13, 3, 0; 14, 4, 0];
% The connection from the control gain and augmented states to the estimator
con2 = [6, 22, 17; 7, 23, 18; 8, 24, 19 ; 9, 25, 20 ; 10, 26, 21];
% The connection from the control gain and augmented states to the plant input
con3 = [1, 22, 17; 2, 23, 18; 3, 24, 19 ; 4, 25, 20 ; 5, 26, 21];
% The connection from the ref gain and plant output into the augmented states
con4 = [15, 27, -1; 16, 28, -2; 17, 29,-3 ; 18, 30, -4;];
% The connection from the state estimates to the controller
con5 = [ 19, 9, 0; 20 , 10, 0; 21, 11, 0; 22, 12, 0; 23, 13, 0; 24 , 14, 0; 25, 15, 0; 26, 16, 0];
CON = [con1;con2;con3;con4;con5];
INPUTS = [27,28,29,30]; % The inputs to the system are the four setpoints
OUTPUTS = [1,2,3,4]; % The outputs from the system are
system_complete = connect(system_complete_temp,CON,INPUTS,OUTPUTS);
C_extra = [system_complete.c;zeros(5,8), -Km, eye(5)]; % Add some additional outputs to see the
motor control voltage
D_extra = [0];
system_complete = ss(system_complete.a, system_complete.b, C_extra, D_extra);
set(system_complete,...
'InputName',{'Yaw SP', 'Pitch SP', 'Roll SP', 'Z SP'}, ...
'OutputName',{'Yaw'; 'Pitch'; 'Roll'; 'Z';'VL control';'VR control';'VB control';'PhiL control';'PhiR
control'})
Statenames = get(system_complete_temp,'StateName');
set(system_complete,'StateName',Statenames)
system_complete
figure
step(system_complete)
title('Augmented System step response using an estimator with command following')
Appendix C
Embedded Controller Code
101
/* ------ Metrowerks Codewarrior Project: P:\Code\miniDRAGON_SS -------- */
/* -----------------------------------------------------------------------------------------------
File: main.c
----------------------------------------------------------------------------------------------- */
#include <mc9s12dp256.h> /* derivative information */
#include "pll.h" /* defines _BUSCLOCK, sets bus frequency to _BUSCLOCK MHz */
#include "timer.h"
#include "ControlSystem.h"
void main(void) {
/* set system clock frequency to _BUSCLOCK MHz (24 or 4) */
PLL_Init();
/* Initialize the timer unit */
timer_Init();
/* Initialize the control system */
controlSystem_Init();
/* forever - check if the control system is ready for execution */
for(;;){
if( controlSystemFlag == 0x01 ){
controlSystemFlag = 0x00;
controlSystem();
}
}
}
/* -----------------------------------------------------------------------------------------------
File: isr_vectors.c
----------------------------------------------------------------------------------------------- */
extern void near _Startup(void); /* Startup routine */
/* declarations of interrupt service routines */
//extern __interrupt void SCI1_RX_isr(void);
//extern __interrupt void RTI_isr(void);
#include "timer.h"
#include "PicoPicCommInt.h"
#include "IMUComms.h"
#pragma CODE_SEG __NEAR_SEG NON_BANKED
/* Interrupt section for this module. Placement will be in NON_BANKED area. */
__interrupt void UnimplementedISR(void) {
/* Unimplemented ISRs trap.*/
asm BGND;
}
typedef void (*near tIsrFunc)(void);
const tIsrFunc _vect[] @0xFF80 = { /* Interrupt table */
UnimplementedISR, /* vector 63 : (reserved) */
UnimplementedISR, /* vector 62 : (reserved) */
UnimplementedISR, /* vector 61 : (reserved) */
UnimplementedISR, /* vector 60 : (reserved) */
UnimplementedISR, /* vector 59 : (reserved) */
UnimplementedISR, /* vector 58 : (reserved) */
UnimplementedISR, /* vector 57 : PWM emergency shutdown */
UnimplementedISR, /* vector 56 : PORT P */
UnimplementedISR, /* vector 55 : MSCAN4 - transmit */
UnimplementedISR, /* vector 54 : MSCAN4 - receive */
UnimplementedISR, /* vector 53 : MSCAN4 - errors */
UnimplementedISR, /* vector 52 : MSCAN4 - wakeup */
UnimplementedISR, /* vector 51 : MSCAN3 - transmit */
UnimplementedISR, /* vector 50 : MSCAN3 - receive */
UnimplementedISR, /* vector 49 : MSCAN3 - errors */
UnimplementedISR, /* vector 48 : MSCAN3 - wakeup */
UnimplementedISR, /* vector 47 : MSCAN2 - transmit */
UnimplementedISR, /* vector 46 : MSCAN2 - receive */
UnimplementedISR, /* vector 45 : MSCAN2 - errors */
UnimplementedISR, /* vector 44 : MSCAN2 - wakeup */
UnimplementedISR, /* vector 43 : MSCAN1 - transmit */
UnimplementedISR, /* vector 42 : MSCAN1 - receive */
UnimplementedISR, /* vector 41 : MSCAN1 - errors */
UnimplementedISR, /* vector 40 : MSCAN1 - wakeup */
UnimplementedISR, /* vector 39 : MSCAN0 - transmit */
UnimplementedISR, /* vector 38 : MSCAN0 - receive */
UnimplementedISR, /* vector 37 : MSCAN0 - errors */
UnimplementedISR, /* vector 36 : MSCAN0 - wakeup */
UnimplementedISR, /* vector 35 : FLASH */
UnimplementedISR, /* vector 34 : EEPROM */
UnimplementedISR, /* vector 33 : SPI2 */
UnimplementedISR, /* vector 32 : SPI1 */
UnimplementedISR, /* vector 31 : IIC bus */
UnimplementedISR, /* vector 30 : DLC */
UnimplementedISR, /* vector 29 : SCME */
UnimplementedISR, /* vector 28 : CRG lock */
UnimplementedISR, /* vector 27 : Pulse accumulator B overflow */
UnimplementedISR, /* vector 26 : Modulus down counter underflow */
UnimplementedISR, /* vector 25 : PORT H */
UnimplementedISR, /* vector 24 : PORT J */
UnimplementedISR, /* vector 23 : ATD1 */
UnimplementedISR, /* vector 22 : ATD0 */
SCI1_TDRE_ISR, /* vector 21 : SCI1 (TIE, TCIE, RIE, ILIE) */
SCI0_RIE_ISR, /* vector 20 : SCI0 (TIE, TCIE, RIE, ILIE) */
UnimplementedISR, /* vector 19 : SPI0 */
UnimplementedISR, /* vector 18 : Pulse accumulator input edge */
UnimplementedISR, /* vector 17 : Pulse accumulator A overflow */
UnimplementedISR, /* vector 16 : Timer Overflow (TOF) */
TOC7_ISR, /* vector 15 : Timer channel 7 */
TIC6_ISR, /* vector 14 : Timer channel 6 */
TIC5_ISR, /* vector 13 : Timer channel 5 */
TIC4_ISR, /* vector 12 : Timer channel 4 */
TIC3_ISR, /* vector 11 : Timer channel 3 */
TIC2_ISR, /* vector 10 : Timer channel 2 */
TIC1_ISR, /* vector 09 : Timer channel 1 */
TIC0_ISR, /* vector 08 : Timer channel 0 */
UnimplementedISR, /* vector 07 : Real-Time Interrupt (RTI) */
UnimplementedISR, /* vector 06 : IRQ */
UnimplementedISR, /* vector 05 : XIRQ */
UnimplementedISR, /* vector 04 : SWI */
UnimplementedISR, /* vector 03 : Unimplemented Instruction trap */
UnimplementedISR, /* vector 02 : COP failure reset*/
UnimplementedISR, /* vector 01 : Clock monitor fail reset */
_Startup /* vector 00 : Reset vector */
};
/* -----------------------------------------------------------------------------------------------
File: pll.h
----------------------------------------------------------------------------------------------- */
/*************************PLL.h****************************
* boosts the CPU clock to 48 MHz *
* *
* Created by Theodore Deden on 20 January 2004. *
* Modified by Theodore Deden on 9 February 2004. *
* Last Modified by Jonathan Valvano 2/9/04. *
* *
* Distributed underthe provisions of the GNU GPL ver 2 *
* Copying, redistributing, modifying is encouraged. *
* *
**********************************************************/
// modified to define _BUSCLOCK
// PLL now running at 48 MHz to be consistent with HCS12 Serial Monitor
// fw-07-04
#ifndef _PPL_H_
#define _PLL_H_
/* Define the desired bus clock frequency:
no PLL (crystal) -> SYSCLOCK = 4 MHz -> BUSCLOCK = 2 MHz
PLL on -> SYSCLOCK = 48 MHz -> BUSCLOCK = 24 MHz
This is used by sci0.c and/or sci1.c to determine the baud rate divider */
#define _BUSCLOCK 24
//********* PLL_Init ****************
// Set PLL clock to 48 MHz, and switch 9S12 to run at this rate
// Inputs: none
// Outputs: none
// Errors: will hang if PLL does not stabilize
void PLL_Init(void);
#endif /* _PLL_H_ */
/* -----------------------------------------------------------------------------------------------
File: pll.c
----------------------------------------------------------------------------------------------- */
/*************************PLL.C***************************
* boosts the CPU clock to 48 MHz *
* *
* Created by Theodore Deden on 20 January 2004. *
* Modified by Theodore Deden on 9 February 2004. *
* Last Modified by Jonathan Valvano 2/16/04. *
* *
* Distributed underthe provisions of the GNU GPL ver 2 *
* Copying, redistributing, modifying is encouraged. *
* *
*********************************************************/
// modified to make PLL_Init depend on _BUSCLOCK (defined in pll.h)
// PLL now running at 48 MHz to be consistent with HCS12 Serial Monitor
// fw-07-04
#include <hidef.h> /* common defines and macros */
#include <mc9s12dp256.h> /* derivative information */
#include "pll.h" /* macro _BUSCLOCK */
//********* PLL_Init ****************
// Set PLL clock to 48 MHz, and switch 9S12 to run at this rate
// Inputs: none
// Outputs: none
// Errors: will hang if PLL does not stabilize
void PLL_Init(void){
/* ensure we're running the controller at an appropriate clock speed */
#if (_BUSCLOCK != 24 && _BUSCLOCK != 16)
#error pll.h: _BUSCLOCK has to be set to 16 (MHz) or 24 (MHz)
#endif
/* set PLL clock speed */
#if _BUSCLOCK == 24
SYNR = 0x02; // PLLOSC = 48 MHz
REFDV = 0x01;
#else
SYNR = 0x00; // PLLOSC = 32 MHz
REFDV = 0x00;
#endif
/* PLLCLK = 2 * OSCCLK * (SYNR + 1) / (REFDV + 1)
Values above give PLLCLK of 48 MHz with 4 MHz crystal.
(OSCCLK is Crystal Clock Frequency) */
CLKSEL = 0x00;
/*Meaning for CLKSEL:
Bit 7: PLLSEL = 0 Keep using OSCCLK until we are ready to switch to PLLCLK
Bit 6: PSTP = 0 Do not need to go to Pseudo-Stop Mode
Bit 5: SYSWAI = 0 In wait mode system clocks stop.
But 4: ROAWAI = 0 Do not reduce oscillator amplitude in wait mode.
Bit 3: PLLWAI = 0 Do not turn off PLL in wait mode
Bit 2: CWAI = 0 Do not stop the core during wait mode
Bit 1: RTIWAI = 0 Do not stop the RTI in wait mode
Bit 0: COPWAI = 0 Do not stop the COP in wait mode
*/
PLLCTL = 0xD1;
/*Meaning for PLLCTL:
Bit 7: CME = 1; Clock monitor enable - reset if bad clock when set
Bit 6: PLLON = 1; PLL On bit
Bit 5: AUTO = 0; No automatic control of bandwidth, manual through ACQ
But 4: ACQ = 1; 1 for high bandwidth filter (acquisition); 0 for low (tracking)
Bit 3: (Not Used by 9s12c32)
Bit 2: PRE = 0; RTI stops during Pseudo Stop Mode
Bit 1: PCE = 0; COP diabled during Pseudo STOP mode
Bit 0: SCME = 1; Crystal Clock Failure -> Self Clock mode NOT reset.
*/
while((CRGFLG&0x08) == 0){ // Wait for PLLCLK to stabilize.
}
CLKSEL_PLLSEL = 1; // Switch to PLL clock
}
/* -----------------------------------------------------------------------------------------------
File: timer.h
----------------------------------------------------------------------------------------------- */
extern char controlSystemFlag; // Flag to indicate start control system
void timer_Init( void ); // Initialize the timer module
extern float PWM_Capture_Ch0; // PWM input variables, range: 0-1
extern float PWM_Capture_Ch1;
extern float PWM_Capture_Ch2;
extern float PWM_Capture_Ch3;
extern float PWM_Capture_Ch4;
extern float PWM_Capture_Ch5;
extern float PWM_Capture_Ch6;
__interrupt void TOC7_ISR( void ); // Interrupt Service Routines for timer channels.
__interrupt void TIC6_ISR( void );
__interrupt void TIC5_ISR( void );
__interrupt void TIC4_ISR( void );
__interrupt void TIC3_ISR( void );
__interrupt void TIC2_ISR( void );
__interrupt void TIC1_ISR( void );
__interrupt void TIC0_ISR( void );
/* -----------------------------------------------------------------------------------------------
File: timer.c
----------------------------------------------------------------------------------------------- */
/**
* \file
* Code to control the ECT timer module. Channel 7 causes
* 40Hz Interrupts and Channels 0-6 capture PWM inputs. Channels
* 0-3 are pins 9-12 (miniDRAGON+) and Channels 4-6 are pins
* 15-17 (miniDRAGON+).
* The PWM signal received from the R700 receiver normally varies between
* 1.1ms and 1,9ms, hence the PWM is configured for this.
*
* \bugs Channel 5 doesn't work. This is because the channel is connected
* to the speaker and a capaciter. This can be fixed by breaking
* the J15 connection on the bottom of the board.
*
*
* \author Zebb Prime
* \date 19/7/05
* \version 1.0 beta
*/
#include <mc9s12dp256.h> // Derivative information
// Constants that define the operation of the PWM and the timed interrupts.
#define timerOffset 37500 // Timer offset for 40Hz interupts
#define lowCount 1650 // #Clock cycles for 1.1ms
#define highCount 2850 // #Clock cycles for 1.9ms
#define validCount 3000 // If greater than this ignore the value.
#define fullPeriodThreshold 3500 // Threshold for low pwm
#define pwmInputScale 1200.0 // Input resolution, highCount - lowCount
#define pwmInputPeriod 33000 // Clock cycles per pwm input period
// Flag to begin control system computation
char controlSystemFlag;
// Variables containing the captured PWM signals. Vary from 0 to 1.
float PWM_Capture_Ch0;
float PWM_Capture_Ch1;
float PWM_Capture_Ch2;
float PWM_Capture_Ch3;
float PWM_Capture_Ch4;
float PWM_Capture_Ch5;
float PWM_Capture_Ch6;
// Holding variables for the channels without buffered registers.
unsigned short first_Ch4;
unsigned short first_Ch5;
unsigned short first_Ch6;
char PWM_Capture_flags;
// Variable to reduce period to 1s for flashing the LED.
char timerDivider;
/**
* \brief Initializes the ECT timer module.
*
* Sets up channel 7 for 40Hz interrupts and channels 0-6 for
* PWM capture. The PWM signals saturate at 1.1ms and 1.9ms.
*
* \author Zebb Prime
* \date 19/7/05
*/
void timer_Init( void ){
asm sei
TIOS = 0x80; // Ch7 = OC, Ch0-6 = IC
TCTL1 = 0x3F; // Disconnect pin 7
OC7M = 0x00; // Don't affect any linked input pins
TCTL3 = 0xFF; // Detect on all edges
TCTL4 = 0xFF; // Detect on all edges
ICOVW = 0xFF; // Only write to registers when they're empty
ICSYS = 0x0A; // TFMOD, BUFEN
TSCR2 = 0x0C; // PR = 32, reset on successful OC
TC7 = timerOffset; // Offset for 40Hz interrupts
TIE = 0xFF; // Enable all interrupts
TSCR1 = 0x80; // Enable Timer
DDRB = 0xFF; // Port B is output
DDRH = 0xFF; // Port H is output
PWM_Capture_Ch0 = 0.5;
PWM_Capture_Ch1 = 0.5;
PWM_Capture_Ch2 = 0.5;
PWM_Capture_Ch3 = 0.5;
PWM_Capture_Ch4 = 0.5;
PWM_Capture_Ch5 = 0.5;
PWM_Capture_Ch6 = 0.5;
PWM_Capture_flags = 0x00;
controlSystemFlag = 0x00; // Initially don't start computation
TFLG1 = 0xFF; // Clear all interrupt flags
asm cli // Enable interrupts
}
/**
* \brief 40Hz interrupt routine.
*
* Toggles bottom LED of 7seg display at 1Hz, also sets flag
* to mark the beginning of the control system.
*
* \author Zebb Prime
* \date 19/7/05
*/
__interrupt void TOC7_ISR( void ){
if( timerDivider < 20 ){
timerDivider ++;
}else{
timerDivider = 0;
PTH ^= 0x08; // Toggle PortH bit3
}
controlSystemFlag = 0x01; // Set flag
TFLG1 = 0x80; // Clear interrupt flag
}
/**
* \brief Interrupt service routine for Channel 0 PWM capture
*
* Channel 0 has a buffered holding register. Using this we only need
* to interrupt once 2 edges have been caught (catches both rising and
* falling edges). Determines if it has caught a rising then falling or
* falling then rising edge by testing the time between them. Using this
* it offsets and scales the input to between 0 (1.1ms) and 1 (1.9ms).
* Can detect a maximum of 1200 discrete PWM input levels.
*
* \author Zebb Prime
* \date 19/7/05
*/
__interrupt void TIC0_ISR( void ){
unsigned short first;
unsigned short last;
PTH |= 0x02; // Beginning of paylod
first = TC0H; // Read from registers
last = TC0;
if( last > first ){ // Calculate difference between edges
last -= first;
}else{
last = (first - last) + timerOffset;
}
if( last > fullPeriodThreshold ){// Detect if PWM high or low
last = pwmInputPeriod - last;
}
if( last > validCount ){ // If data is greater than the threshold, ignore it.
PTH &= 0xFD; // End of payload
TFLG1 = 0x01; // Clear interrupt flag
return;
}
if( last < lowCount ){ // Test for lower limit
PWM_Capture_Ch0 = 0.0;
PTH &= 0xFD; // End of payload
TFLG1 = 0x01; // Clear interrupt flag
return;
}
if( last > highCount ){ // Test for upper limit
PWM_Capture_Ch0 = 1.0;
TFLG1 = 0x01; // Clear interrupt flag
PTH &= 0xFD; // End of Payload
return;
}
last = last - lowCount; // Offset
PWM_Capture_Ch0 = ((float)last)/pwmInputScale;
PTH &= 0xFD; // End of payload
TFLG1 = 0x01; // Clear interrupt flag
}
/**
* \brief Interrupt service routine for Channel 1 PWM capture
*
* Channel 1 has a buffered holding register. Using this we only need
* to interrupt once 2 edges have been caught (catches both rising and
* falling edges). Determines if it has caught a rising then falling or
* falling then rising edge by testing the time between them. Using this
* it offsets and scales the input to between 0 (1.1ms) and 1 (1.9ms).
* Can detect a maximum of 1200 discrete PWM input levels.
*
* \author Zebb Prime
* \date 19/7/05
*/
__interrupt void TIC1_ISR( void ){
unsigned short first;
unsigned short last;
PTH |= 0x02; // Beginning of paylod
first = TC1H; // Read from registers
last = TC1;
if( last > first ){ // Calculate difference between edges
last -= first;
}else{
last = (first - last) + timerOffset;
}
if( last > fullPeriodThreshold ){ // Detect if PWM high or low
last = pwmInputPeriod - last;
}
if( last > validCount ){ // If data is greater than the threshold, ignore it.
PTH &= 0xFD; // End of payload
TFLG1 = 0x02; // Clear interrupt flag
return;
}
if( last < lowCount ){ // Test for lower limit
PWM_Capture_Ch1 = 0.0;
PTH &= 0xFD; // End of payload
TFLG1 = 0x02; // Clear interrupt flag
return;
}
if( last > highCount ){ // Test for upper limit
PWM_Capture_Ch1 = 1.0;
TFLG1 = 0x02; // Clear interrupt flag
PTH &= 0xFD; // End of Payload
return;
}
last = last - lowCount; // Offset
PWM_Capture_Ch1 = ((float)last)/pwmInputScale;
PTH &= 0xFD; // End of payload
TFLG1 = 0x02; // Clear interrupt flag
}
/**
* \brief Interrupt service routine for Channel 2 PWM capture
*
* Channel 2 has a buffered holding register. Using this we only need
* to interrupt once 2 edges have been caught (catches both rising and
* falling edges). Determines if it has caught a rising then falling or
* falling then rising edge by testing the time between them. Using this
* it offsets and scales the input to between 0 (1.1ms) and 1 (1.9ms).
* Can detect a maximum of 1200 discrete PWM input levels.
*
* \author Zebb Prime
* \date 19/7/05
*/
__interrupt void TIC2_ISR( void ){
unsigned short first;
unsigned short last;
PTH |= 0x02; // Beginning of paylod
first = TC2H; // Read from registers
last = TC2;
if( last > first ){ // Calculate difference between edges
last -= first;
}else{
last = (first - last) + timerOffset;
}
if( last > fullPeriodThreshold ){ // Detect if PWM high or low
last = pwmInputPeriod - last;
}
if( last > validCount ){ // If data is greater than the threshold, ignore it.
PTH &= 0xFD; // End of payload
TFLG1 = 0x04; // Clear interrupt flag
return;
}
if( last < lowCount ){ // Test for lower limit
PWM_Capture_Ch2 = 0.0;
PTH &= 0xFD; // End of payload
TFLG1 = 0x04; // Clear interrupt flag
return;
}
if( last > highCount ){ // Test for upper limit
PWM_Capture_Ch2 = 1.0;
TFLG1 = 0x04; // Clear interrupt flag
PTH &= 0xFD; // End of Payload
return;
}
last = last - lowCount; // Offset
PWM_Capture_Ch2 = ((float)last)/pwmInputScale;
PTH &= 0xFD; // End of payload
TFLG1 = 0x04; // Clear interrupt flag
}
/**
* \brief Interrupt service routine for Channel 3 PWM capture
*
* Channel 3 has a buffered holding register. Using this we only need
* to interrupt once 2 edges have been caught (catches both rising and
* falling edges). Determines if it has caught a rising then falling or
* falling then rising edge by testing the time between them. Using this
* it offsets and scales the input to between 0 (1.1ms) and 1 (1.9ms).
* Can detect a maximum of 1200 discrete PWM input levels.
*
* \author Zebb Prime
* \date 19/7/05
*/
__interrupt void TIC3_ISR( void ){
unsigned short first;
unsigned short last;
PTH |= 0x02; // Beginning of paylod
first = TC3H; // Read from registers
last = TC3;
if( last > first ){ // Calculate difference between edges
last -= first;
}else{
last = (first - last) + timerOffset;
}
if( last > fullPeriodThreshold ){ // Detect if PWM high or low
last = pwmInputPeriod - last;
}
if( last > validCount ){ // If data is greater than the threshold, ignore it.
PTH &= 0xFD; // End of payload
TFLG1 = 0x08; // Clear interrupt flag
return;
}
if( last < lowCount ){ // Test for lower limit
PWM_Capture_Ch3 = 0.0;
PTH &= 0xFD; // End of payload
TFLG1 = 0x08; // Clear interrupt flag
return;
}
if( last > highCount ){ // Test for upper limit
PWM_Capture_Ch3 = 1.0;
TFLG1 = 0x08; // Clear interrupt flag
PTH &= 0xFD; // End of Payload
return;
}
last = last - lowCount; // Offset
PWM_Capture_Ch3 = ((float)last)/pwmInputScale;
PTH &= 0xFD; // End of payload
TFLG1 = 0x08; // Clear interrupt flag
}
/**
* \brief Interrupt service routine for Channel 4 PWM capture
*
* Channel 4 does not have a buffered holding register like channels 0-3.
* Hence we need to interrupt on every edge. On first edge it stores the
* interrupt time and sets a flag. On the second edge it computes the PWM
* input. Determines if it has caught a rising then falling or
* falling then rising edge by testing the time between them. Using this
* it offsets and scales the input to between 0 (1.1ms) and 1 (1.9ms).
* Can detect a maximum of 1200 discrete PWM input levels.
*
* \author Zebb Prime
* \date 19/7/05
*/
__interrupt void TIC4_ISR( void ){
unsigned short last;
PTH |= 0x02; // Beginning of Payload
if((PWM_Capture_flags & 0x10)==0){ // Capture first time
first_Ch4 = TC4;
PWM_Capture_flags |= 0x10; // Set flag
TFLG1 = 0x10; // Clear Interrupt flag
PTH &= 0xFD; // End of Payload
}else{ // Capture second time
last = TC4;
PWM_Capture_flags &= 0xEF; // Clear flag
if( last > first_Ch4 ){ // Calculate difference between edges
last -= first_Ch4;
}else{
last = (first_Ch4 - last) + timerOffset;
}
if( last > fullPeriodThreshold ){ // Detect if PWM high or low
last = pwmInputPeriod - last;
}
if( last > validCount ){ // If data is greater than the threshold, ignore it.
PTH &= 0xFD; // End of payload
TFLG1 = 0x10; // Clear interrupt flag
return;
}
if( last < lowCount ){ // Test for lower limit
PWM_Capture_Ch4 = 0.0;
PTH &= 0xFD; // End of payload
TFLG1 = 0x10; // Clear interrupt flag
return;
}
if( last > highCount ){ // Test for upper limit
PWM_Capture_Ch4 = 1.0;
TFLG1 = 0x10; // Clear interrupt flag
PTH &= 0xFD; // End of Payload
return;
}
last = last - lowCount; // Offset
PWM_Capture_Ch4 = ((float)last)/pwmInputScale;
PTH &= 0xFD; // End of payload
TFLG1 = 0x10; // Clear interrupt flag
}
}
/**
* \brief Interrupt service routine for Channel 5 PWM capture
*
* Channel 5 does not have a buffered holding register like channels 0-3.
* Hence we need to interrupt on every edge. On first edge it stores the
* interrupt time and sets a flag. On the second edge it computes the PWM
* input. Determines if it has caught a rising then falling or
* falling then rising edge by testing the time between them. Using this
* it offsets and scales the input to between 0 (1.1ms) and 1 (1.9ms).
* Can detect a maximum of 1200 discrete PWM input levels.
*
* \bugs Doesn't work due to the issues outlined in bug report at the top of
* the file.
*
* \author Zebb Prime
* \date 19/7/05
*/
__interrupt void TIC5_ISR( void ){
unsigned short last;
PTH |= 0x02; // Beginning of Payload
if((PWM_Capture_flags & 0x20)==0){ // Capture first time
first_Ch5 = TC5;
PWM_Capture_flags |= 0x20; // Set flag
TFLG1 = 0x20; // Clear Interrupt flag
PTH &= 0xFD; // End of Payload
}else{ // Capture second time
last = TC5;
PWM_Capture_flags &= 0xDF; // Clear flag
if( last > first_Ch5 ){ // Calculate difference between edges
last -= first_Ch5;
}else{
last = (first_Ch5 - last) + timerOffset;
}
if( last > fullPeriodThreshold ){ // Detect if PWM high or low
last = pwmInputPeriod - last;
}
if( last > validCount ){ // If data is greater than the threshold, ignore it.
PTH &= 0xFD; // End of payload
TFLG1 = 0x20; // Clear interrupt flag
return;
}
if( last < lowCount ){ // Test for lower limit
PWM_Capture_Ch5 = 0.0;
PTH &= 0xFD; // End of payload
TFLG1 = 0x20; // Clear interrupt flag
return;
}
if( last > highCount ){ // Test for upper limit
PWM_Capture_Ch5 = 1.0;
TFLG1 = 0x20; // Clear interrupt flag
PTH &= 0xFD; // End of Payload
return;
}
last = last - lowCount; // Offset
PWM_Capture_Ch5 = ((float)last)/pwmInputScale;
PTH &= 0xFD; // End of payload
TFLG1 = 0x20; // Clear interrupt flag
}
}
/**
* \brief Interrupt service routine for Channel 6 PWM capture
*
* Channel 6 does not have a buffered holding register like channels 0-3.
* Hence we need to interrupt on every edge. On first edge it stores the
* interrupt time and sets a flag. On the second edge it computes the PWM
* input. Determines if it has caught a rising then falling or
* falling then rising edge by testing the time between them. Using this
* it offsets and scales the input to between 0 (1.1ms) and 1 (1.9ms).
* Can detect a maximum of 1200 discrete PWM input levels.
*
* \author Zebb Prime
* \date 19/7/05
*/
__interrupt void TIC6_ISR( void ){
unsigned short last;
PTH |= 0x02; // Beginning of Payload
if((PWM_Capture_flags & 0x40)==0){ // Capture first time
first_Ch6 = TC6;
PWM_Capture_flags |= 0x40; // Set flag
TFLG1 = 0x40; // Clear Interrupt flag
PTH &= 0xFD; // End of Payload
}else{ // Capture second time
last = TC6;
PWM_Capture_flags &= 0xBF; // Clear flag
if( last > first_Ch6 ){ // Calculate difference between edges
last -= first_Ch6;
}else{
last = (first_Ch6 - last) + timerOffset;
}
if( last > fullPeriodThreshold ){ // Detect if PWM high or low
last = pwmInputPeriod - last;
}
if( last > validCount ){ // If data is greater than the threshold, ignore it.
PTH &= 0xFD; // End of payload
TFLG1 = 0x40; // Clear interrupt flag
return;
}
if( last < lowCount ){ // Test for lower limit
PWM_Capture_Ch6 = 0.0;
PTH &= 0xFD; // End of payload
TFLG1 = 0x40; // Clear interrupt flag
return;
}
if( last > highCount ){ // Test for upper limit
PWM_Capture_Ch6 = 1.0;
TFLG1 = 0x40; // Clear interrupt flag
PTH &= 0xFD; // End of Payload
return;
}
last = last - lowCount; // Offset
PWM_Capture_Ch6 = ((float)last)/pwmInputScale;
PTH &= 0xFD; // End of payload
TFLG1 = 0x40; // Clear interrupt flag
}
}
/* -----------------------------------------------------------------------------------------------
File: SS_Coeff.h (Truncated for printing, please see file for all coefficients)
----------------------------------------------------------------------------------------------- */
/*
This is an automatically generated C header containing
the state-space coefficients for embedded implementation.
Matlab Script: ss_to_C(state_model,filename)
Filename: miniDragon_SS/sources/SS_Coeff.h
*/
const float A[21][21]= {
-9.1569272269e-001, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, -9.1569268446e-001, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, -3.8880428789e-001, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, -3.8880429515e-001, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 8.1703176158e-001...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, -1.5453544113e-001...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000, 0.0000000000e+000...
};
#define A_r 21
#define A_c 21
const float B[21][4]= {
3.6582688568e-013, 2.4467522904e-014, 3.1242486781e-014, -2.1705685760e-014,
1.6712711309e-013, 5.2834063705e-013, -1.2557649859e-013, -8.1983891956e-013,
1.9843779054e-012, 5.9900646127e+000, 2.2014237798e-007, -1.3504266527e+000,
-2.9010561451e-012, 1.5089742169e-007, 6.1617707053e+000, -3.4017976770e-008,
-2.4184664193e-011, -4.7056325828e-012, 1.3492266473e-012, 1.7220433282e-012,
-4.4849946680e-011, -1.4073711378e-011, 4.5062648469e-012, 3.1700405834e-012,
7.4181812052e-012, -1.8413170676e-012, 1.1911860740e-012, 3.3944339450e-014,
3.3737575024e-011, 2.1871351392e-011, -9.4595802845e-012, -5.0029395807e-012,
3.7938084548e-011, 2.7250524993e-011, -6.5493908201e-012, -4.8949575126e-012,
-4.6764788929e-011, 2.6509138572e-011, 5.2382893392e-011, -1.1272323060e-012,
-1.3783742617e-011, 6.1147145472e-011, 7.0997845059e-002, -8.2123923013e-012,
3.7013896008e-011, -3.7372361300e-011, -2.7746898269e+001, 3.7811686665e-012,
-2.1586936395e+000, 1.7292502007e-012, -5.5748089934e-014, -2.0138870928e-013,
-2.3222524122e+000, -1.5280042564e-012, 1.0041674945e-013, 3.4836853354e-014,
-2.2717536008e-011, 1.5838285949e-001, 5.6269623357e-012, 2.8203040294e-001,
1.3437569820e-011, 2.7135180414e+001, 1.3139954975e-011, -6.8533579834e-001,
5.7031990974e-012, 9.2537772449e-011, 2.2784283437e+001, -7.1467867754e-013,
-9.1060348650e-013, 1.6393862198e-002, -1.0137053021e-012, 1.0561911880e+001,
1.3310443365e-011, -1.3336306705e-001, 1.0280626427e-011, 1.0930577444e+001,
-2.3104715970e-012, -2.2614016329e+001, 8.2612501756e-012, 2.9346513625e-001,
2.1921292290e-014, -1.8582181118e-015, -6.0355819202e-015, 3.2943424657e-015
};
#define B_r 21
#define B_c 4
const float C[9][21]= {
-1.5135710425e-009, -5.0000998413e-011, 2.8280210190e-020, -1.7387059327e-020, 8.6650829691e-008..
1.2538929729e-016, 2.4449164424e-007, -1.8707062049e-005, -5.0650824380e-004, -8.2050340264e-017..
8.5468421435e-004, -3.5955196304e-017, -4.3783564211e-016, 4.2501851266e-015, 3.0349521701e-017...
-7.9623063711e-005, -1.3054349330e-004, 1.1832256217e-016, 1.7468585945e-004, -1.7021630967e-004..
6.8601559232e-005, 1.6517375709e-005, -4.7059613017e-005, -1.7105528226e-006, 3.0658896706e-005...
6.8601559232e-005, 1.6517375709e-005, 4.7059613017e-005, -1.7105528223e-006, 3.0658896705e-005...
-2.0895429305e-003, 1.6922006100e-004, 7.2704763060e-015, -4.3194157336e-004, 2.2771334703e-002...
-4.9376122033e-016, -9.1493967213e-016, 3.7769139042e-017, 4.8777088403e-016, -4.5010575369e-016..
1.1450331826e-005, -8.0359465268e-006, 4.9955754429e-006, 4.6401473120e-018, 3.8328293839e-017...
};
#define C_r 9
#define C_c 21
const float D[9][4]= {
5.1054167768e-005, -5.9863029349e-019, -6.1332346957e-019, 1.4606183962e-019,
3.0196506168e-024, 1.1141134508e-007, -6.1612654539e-019, 6.2663331226e-009,
2.9511260106e-024, -5.0774104049e-018, 5.1120242753e-007, 1.2394756926e-018,
-2.9847545536e-022, -6.3630467674e-006, 1.3033869983e-019, 1.3318683848e-006,
-1.4440332303e-018, -2.6648620966e-002, -2.7118402241e-002, 6.0801804810e-003,
-1.1309289964e-018, -2.6648620966e-002, 2.7118402241e-002, 6.0801804810e-003,
-8.2208294403e-018, 2.7308393981e-002, -2.7622221347e-015, 1.2169653467e-001,
1.7491888561e-002, 1.7610189069e-018, -2.9154543622e-018, 3.0797889565e-018,
-1.7491888561e-002, -1.7610189069e-018, 2.9154543622e-018, -3.0797889565e-018
};
#define D_r 9
#define D_c 4
#define state_length 21
#define input_length 4
#define output_length 9
/* -----------------------------------------------------------------------------------------------
File: ControlSystem.h
----------------------------------------------------------------------------------------------- */
void controlSystem_Init( void ); // Initialize the control system
void controlSystem( void ); // Run the control system
/* -----------------------------------------------------------------------------------------------
File: ControlSystem.c
----------------------------------------------------------------------------------------------- */
/**
* \file
* Control system computation. Occurs outside an interrupt as there are a large
* number of interrupts that need to occur while the control system computation
* is taking place. Note the state-space controller hasn't been tested. It is
* recommended that this take place!
*
*
* \author Zebb Prime
* \date 22/7/05
* \version 1.0 alpha
*/
#include <mc9s12dp256.h> // Derivative information
#include <math.h>
#include "timer.h"
#include "PicoPicCommInt.h"
#include "IMUComms.h"
#include "SS_Coeff.h"
#define pi 3.141592564
void SSmatrixMult(float *X, float *Y, float *result, int X_r, int X_c);
char active; // Control System active flag.
char counter; // count until control system starts
float current_states[ state_length ];
float next_states[ state_length ];
float inputs[ input_length ];
float outputs[ output_length ];
float Z_d;
/**
* \brief Initialize the control system.
*
* Initializes the SCI1 module for communications to PicoPic and
* the SCI0 module for the IMU. Also clears all of the state variables.
*
* \author Zebb Prime
* \date 22/7/05
*/
void controlSystem_Init( void ){
int ii;
PicoPicCommInt_Init();
IMUComms_Init();
active = 0;
counter = 80; // 2 second delay
DDRB = 0xff; // Port B is output
for(ii=0; ii<state_length; ii++){ // Clear States
current_states[ ii ] = 0.0;
next_states[ ii ] = 0.0;
Z_d = 0.0;
}
}
/**
* \brief Computes the control system.
*
* For safety the remote control landing gear switch (PWM Capture Channel 4) must
* be on for at least two seconds before the control system will start.
* Computes the connected state space model of the controller through matrix
* multiplication.
*
* \author Zebb Prime
* \date 5/10/05
*/
void controlSystem( void ){
int ii;
float temp_states[ state_length ];
PTH |= 0x01; // Beginning of payload
IMUComms_Update(); // Update the IMU data.
// If the switch is off, then stop the control system.
if( PWM_Capture_Ch4 < 0.9 ){
counter = 81;
active = 0;
PORTB &= 0x7F; // Turn off PortB.7 (Pin 31 - LED)
}
if( active == 0 ){ // If the control system is off
PicoPicCommInt_Send( 0, 1); // All signals to 0
PicoPicCommInt_Send( 0, 2);
PicoPicCommInt_Send( 0.709677419, 4);
PicoPicCommInt_Send( 0.29032258, 5);
PicoPicCommInt_Send( 0, 7);
// Decrement count.
counter --;
if( counter == 0 ){ // If the switch has been on for two
active = 1; // seconds, start the controller and reset the states.
for(ii=0; ii<state_length; ii++){
current_states[ ii ] = 0.0;
next_states[ ii ] = 0.0;
Z_d = 0.0;
}
}
}else{
PORTB |= 0x80; // Turn on PortB.7 (Pin 31 - LED)
/* State Space Control Implementation */
// update state vectors
for(ii=0; ii<state_length; ii++){
current_states[ ii ] = next_states[ ii ];
}
Z_d += (scaledOutput[ 6 ] + 9.81)*0.025; // Integrate Z acceleration
// Calculate controller inputs (setpoints - feedback)
inputs[0] = (PWM_Capture_Ch3+0.5)*pi - scaledOutput[ 2 ]; // Yaw = Yaw_SP - Yaw_FB
inputs[1] = (PWM_Capture_Ch2+0.5)*pi/12 - scaledOutput[ 1 ]; // Pitch = Pitch_SP - Pitch_FB
inputs[2] = (PWM_Capture_Ch1+0.5)*pi/12 - scaledOutput[ 0 ]; // Roll = Roll_SP - Roll_FB
inputs[4] = (PWM_Capture_Ch0+0.5) - Z_d; // Z_d = Z_d_SP - Z_d_FB
SSmatrixMult(&A,¤t_states,&temp_states,A_r,A_c); // A*x
SSmatrixMult(&B,&inputs,&next_states,B_r,B_c); // B*u
for(ii=0; ii<state_length; ii++){ // x_n = A*x + B*u
next_states[ii] += temp_states[ii];
}
SSmatrixMult(&C,¤t_states,&temp_states,C_r,C_c); // C*x
SSmatrixMult(&D,&inputs,&outputs,D_r,D_c); // D*u
for(ii=0; ii<output_length; ii++){ // y = C*x + D*u
outputs[ii] += temp_states[ii];
}
PicoPicCommInt_Send( outputs[4]/10, 1); // Send the left motor speed
PicoPicCommInt_Send( outputs[5]/10, 2); // Send the right motor speed
PicoPicCommInt_Send( 0.36965019*outputs[7]+0.709677419, 4); // Send the left servo position
PicoPicCommInt_Send( -0.36965019*outputs[8]+0.29032258, 5); // Send the right servo position
PicoPicCommInt_Send( outputs[6]/10, 7); // Send the rear motor speed
}
PTH &= 0xFE; // End of payload
}
/**
* \brief Performs State-Space matrix multiplication (matrix * vector).
*
* \param X: first matrix for multiplication
* \param Y: second matrix for multiplication
* \param result: matrix to house the result (please make sure the size is correct)
* \param X_r: number of rows of X
* \param X_c: number of columns of X
*
* \author Zebb Prime
* \date 24/10/05
*/
void SSmatrixMult(float *X, float *Y, float *result, int X_r, int X_c){
int ii, jj, kk;
float temp;
// Matrix * Vector multiplication
kk=0;
for( ii=0; ii<X_r; ii++ ){
temp = 0;
for( jj=0; jj<X_c; jj++){
temp += *(X+kk) * *(Y+jj);
kk ++;
}
*(result + ii) = temp;
}
}
/* -----------------------------------------------------------------------------------------------
File: IMUComms.h
----------------------------------------------------------------------------------------------- */
#define GSEAARV // Defined mode
#define BAUD_115200 // Defined baud rate
void IMUComms_Init( void ); // Prototypes
char IMUComms_Update( void );
__interrupt void SCI0_RIE_ISR( void );
// Available modes
#ifdef RSO
#define outputLength 9
#endif
#ifdef GSV
#define outputLength 9
#endif
#ifdef IV
#define outputLength 9
#endif
#ifdef IQ
#define outputLength 4
#endif
#ifdef GSQ
#define outputLength 4
#endif
#ifdef IOM
#define outputLength 9
#endif
#ifdef GSO
#define outputLength 9
#endif
#ifdef GSQV
#define outputLength 13
#endif
#ifdef IEA
#define outputLength 3
#endif
#ifdef GSEA
#define outputLength 3
#endif
#ifdef GSEARV
#define outputLength 6
#endif
#ifdef GSEAARV
#define outputLength 9
#endif
extern float scaledOutput[ outputLength ];
/* -----------------------------------------------------------------------------------------------
File: IMUComms.c
----------------------------------------------------------------------------------------------- */
/**
* \file
* \brief Communications to the 3DM-GX1 IMU using interrupts over SCI0
*
* data bits = 8, stop = 1, parity = none, baud - see header
* Communicates to the 3DM-GX1 IMU using receiver interrupts. Mode is selectable
* by declaring the acronym in the header file IMUComms.h.
*
* \author Zebb Prime
* \date 8/9/05
* \version 1.0
*/
#include <mc9s12dp256.h> /* derivative information */
#include <math.h> /* Math libraries */
#include "IMUComms.h"
#define pi 3.141592653
#define RDRF 0x20 // Receive Data Register Full Bit
#define TDRE 0x80 // Transmit Data Register Empty Bit
#define bufferLength (outputLength*2+5)
char ReadBuffer[ bufferLength ]; // Not a ringbuffer.
char bufferIndex;
float scaledOutput[ outputLength ];
// Raw sensor output
#ifdef RSO
#define commandByte 0x01
const float scalingValues[ outputLength ] = { 5.0/65536.0, 5.0/65536.0, 5.0/65536.0,
5.0/65536.0, 5.0/65536.0, 5.0/65536.0,
5.0/65536.0, 5.0/65536.0, 5.0/65536.0
};
#endif
// Gyro stabilised vectors
#ifdef GSV
#define commandByte 0x02
#define magGainScale 4000.0
#define accelGainScale 7000.0
#define gyroGainScale 8500.0
const float scalingValues[ outputLength ] = {
magGainScale/32768000.0, magGainScale/32768000.0, magGainScale/32768000.0,
accelGainScale/32768000.0, accelGainScale/32768000.0, accelGainScale/32768000.0,
gyroGainScale/32768000.0, gyroGainScale/32768000.0, gyroGainScale/32768000.0
};
#endif
// Instantaneous vectors
#ifdef IV
#define commandByte 0x03
#define magGainScale 2000.0
#define accelGainScale 7000.0
#define gyroGainScale 8500.0
const float scalingValues[ outputLength ] = {
magGainScale/32768000.0, magGainScale/32768000.0, magGainScale/32768000.0,
accelGainScale/32768000.0, accelGainScale/32768000.0, accelGainScale/32768000.0,
gyroGainScale/32768000.0, gyroGainScale/32768000.0, gyroGainScale/32768000.0
};
#endif
// Instantaneous Quaternion
#ifdef IQ
#define commandByte 0x04
const float scalingValues[ outputLength ] = { 1.0/8192.0, 1.0/8192.0, 1.0/8192.0, 1.0/8192.0
};
#endif
// Gyro Stabilised Quaternion
#ifdef GSQ
#define commandByte 0x05
const float scalingValues[ outputLength ] = { 1.0/8192.0, 1.0/8192.0, 1.0/8192.0, 1.0/8192.0
};
#endif
// Instantaneous Orientation Matrix
#ifdef IOM
#define commandByte 0x0A
const float scalingValues[ outputLength ] = { 1.0/8192.0, 1.0/8192.0, 1.0/8192.0, 1.0/8192.0,
1.0/8192.0, 1.0/8192.0, 1.0/8192.0, 1.0/8192.0,
1.0/8192.0, 1.0/8192.0, 1.0/8192.0, 1.0/8192.0
};
#endif
// Gyro Stabilised Oriantation Matrix
#ifdef GSO
#define commandByte 0x0B
const float scalingValues[ outputLength ] = { 1.0/8192.0, 1.0/8192.0, 1.0/8192.0, 1.0/8192.0,
1.0/8192.0, 1.0/8192.0, 1.0/8192.0, 1.0/8192.0,
1.0/8192.0, 1.0/8192.0, 1.0/8192.0, 1.0/8192.0
};
#endif
// Gyro Stabilised Quaternion and Vectors
#ifdef GSQV
#define commandByte 0x0C
#define magGainScale 2000.0
#define accelGainScale 7000.0
#define gyroGainScale 8500.0
const float scalingValues[ outputLength ] = {
1.0/8192.0, 1.0/8192.0, 1.0/8192.0, 1.0/8192.0,
magGainScale/32768000.0, magGainScale/32768000.0, magGainScale/32768000.0,
accelGainScale/32768000.0, accelGainScale/32768000.0, accelGainScale/32768000.0,
gyroGainScale/32768000.0, gyroGainScale/32768000.0, gyroGainScale/32768000.0
};
#endif
// Instantaneous Euler Angles (rad)
#ifdef IEA
#define commandByte 0x0D
const float scalingValues[ outputLength ] = { 2.0*pi/65536.0, 2.0*pi/65536.0, 2.0*pi/65536.0
};
#endif
// Gyro Stabilised Euler Angles (rad)
#ifdef GSEA
#define commandByte 0x0E
const float scalingValues[ outputLength ] = { 2.0*pi/65536.0, 2.0*pi/65536.0, 2.0*pi/65536.0
};
#endif
// Gyro Stabilised Euler Angles (rad) and Rate Vector (rad/s)
#ifdef GSEARV
#define commandByte 0x30
#define gyroGainScale 8500.0
const float scalingValues[ outputLength ] = {
2.0*pi/65536.0, 2.0*pi/65536.0, 2.0*pi/65536.0,
gyroGainScale/32768000.0, gyroGainScale/32768000.0, gyroGainScale/32768000.0
};
#endif
// Gyro Stabilised Euler Angles (rad) and Acceleration (g) and Rate Vectors (rad/s).
#ifdef GSEAARV
#define commandByte 0x31
#define accelGainScale 7000.0
#define gyroGainScale 8500.0
const float scalingValues[ outputLength ] = {
2.0*pi/65536.0, 2.0*pi/65536.0, 2.0*pi/65536.0,
accelGainScale/32768000.0, accelGainScale/32768000.0, accelGainScale/32768000.0,
gyroGainScale/32768000.0, gyroGainScale/32768000.0, gyroGainScale/32768000.0
};
#endif
/**
* \brief Initialize SCI0 for communications to the 3DM-GX1 IMU
*
* Sets the communication parameters such as baud, data bits and parity.
* Communications are two-way so both transmitter and receiver are enabled.
* Interrupts are enabled for receive register full, however command packets
* are one byte so polling is sufficient for sending.
*
* \author Zebb Prime
* \date 28/7/05
*/
void IMUComms_Init( void ){
char i;
asm sei
#ifdef BAUD_115200 // Set up baud rate
SCI0BDH=0;
SCI0BDL=13;
#endif
#ifdef BAUD_38400
SCI0BDH=0;
SCI0BDL=39;
#endif
#ifdef BAUD_19200
SCI0BDH=0;
SCI0BDL=78
#endif
SCI0CR1=0x00; // data = 8, stop = 1, parity = none
SCI0CR2=0x2C; // RIE,TE,RE
bufferIndex = 0; // Reset Buffer Index
for( i=0; i<outputLength; i++ ){ // Clear output values
scaledOutput[i] = 0.0;
}
asm cli // enable interrupts
}
/**
* \brief Updates that data in the holding variables, requests the next lot of data from the
* IMU
*
* Calculates the checksum to make sure the packet is valid, if so the results are converted
* to floating point values and normalized, then placed in the holding variables. It then
* sends a request to the IMU for the next data packet. This implies that the data will
* always be Ts behind at worst.
*
* \return valid: 1 if data in variables is valid, 0 if not.
* \author Zebb Prime
* \date 28/7/05
*/
char IMUComms_Update( void ){
char i;
short temps;
float tempf;
if( (SCI0SR1 & RDRF) != 0 ){
temps = SCI0DRL;
}
for(i=0; i<outputLength; i++){
temps = ReadBuffer[ (i*2+1) ] << 8; // Data MSB
temps += ReadBuffer[ (i*2+2) ]; // Data LSB
tempf = (float)temps; // convert to floating point
tempf *= scalingValues[i]; // scale
scaledOutput[i] = tempf; // store
}
if(bufferIndex == bufferLength) i = 0x01;
else i = 0x00;
bufferIndex = 0; // reset the buffer index
while((SCI0SR1 & TDRE) == 0){}; // When Tx ready
SCI0DRL = commandByte; // Send request for next byte
return i;
}
/**
* \brief miniDRAGON+ to 3DM-GX1 over SCI0 received data interrupt service routine
*
* Adds the received data to the buffer. The buffer must be big enough to hold all of the
* input data. If the buffer is full the byte is ignored.
*
* \author Zebb Prime
* \date 28/7/05
*/
__interrupt void SCI0_RIE_ISR( void ){
char temp;
if( bufferIndex == bufferLength ){ // if buffer is full discard the byte
while((SCI0SR1 & RDRF) == 0){};
temp = SCI0DRL;
return;
}
while((SCI0SR1 & RDRF) == 0){}; // Test to see if data is present
ReadBuffer[ bufferIndex ] = SCI0DRL; // Place the data in the buffer
bufferIndex ++;
}
/* -----------------------------------------------------------------------------------------------
File: PicoPicCommInt.h
----------------------------------------------------------------------------------------------- */
void PicoPicCommInt_Init( void ); // Initialize SCI1 to PicoPic
void PicoPicCommInt_Send( float position, char port ); // Send a position setpoint to PicoPic
__interrupt void SCI1_TDRE_ISR( void ); // SCI1 TDRE interrupt service routine
/* -----------------------------------------------------------------------------------------------
File: PicoPicCommInt.c
----------------------------------------------------------------------------------------------- */
/**
* \file
* \brief Communications to the PicoPic using SCI1 with interrupts.
*
* baud = 115200, data bits = 8, parity = none.
* Even though the baud is set at the maximum for the PicoPic there
* was still significant latency when communicating using polling
* (~0.5 ms per channel) which is too much considering there is only
* 25ms available per control system cycle (40Hz). Hence using interrupts
* the polling overhead is removed freeing MCU time for other computation
* while still transferring data to the PicoPic as fast as possible.
*
* Utilizes a ring-buffer to store data. There is no buffer overflow check
* so if the communications starts doing crazy stuff try increasing the
* bufferLength parameter. As indicated below the current maximum buffer
* length is 255 (using 8-bit indexes), to increase this change SCI1Buffer
* and SCI1Sent to unsigned short or unsigned int (16-bit: max length 65535).
*
* \author Zebb Prime
* \data 19/7/05
* \version 1.0
*/
#include <mc9s12dp256.h> /* derivative information */
#define TDRE 0x80 // Transmit Data Register Empty
#define bufferLength 100 // Max 255 unless change pointers to short
char SCI1RingBuffer[ bufferLength ]; // Ringbuffer variables
char SCI1Buffer;
char SCI1Sent;
/**
* \brief Initialize SCI1 for communications to the PicoPic
*
* Sets the communication parameters such as baud, data bits and parity.
* Communications are one way so it only enables the transmitter. Interrupts
* aren't enabled until the buffer is non-empty.
*
* \author Zebb Prime
* \date 19/7/05
*/
void PicoPicCommInt_Init( void ){
char i;
SCI1BDH=0; // baud = 115200
SCI1BDL=13;
SCI1CR1=0x00; // No parity
SCI1CR2=0x08; // TIE,Enable Transmitter
for(i=0; i < bufferLength; i++ ){ // Clear buffer
SCI1RingBuffer[i] = 0;
}
SCI1Buffer = 0;
SCI1Sent = 0;
asm cli; // Global enable Interrupts
}
/**
* \brief Sends a position to the PicoPic.
*
* Scales the input to values recognisable by the PicoPic, then
* places the data into the ring-buffer. If the buffer was empty at the
* beginning of the call it starts the transmission by enabling the interrupts.
*
* \param position: float - value between 0 and 1 indicating the desired position
* of the servo. If <0 or >1 saturates to 0 or 1.
* \param port: char (byte) - servo port to send the position to (1 - 20)
*
* \author Zebb Prime
* \date 19/7/05
*/
void PicoPicCommInt_Send( float position, char port ){
short setpoint;
char data;
char flag; // Flag if buffer is empty
if( SCI1Buffer == SCI1Sent ) flag = 1;
else flag = 0;
setpoint = (short)(1500.0*position); // Scale for PicoPic
setpoint += 750; // Offset for PicoPic
if(setpoint > 2135){ // Position Saturation
setpoint = 2135;
}else if( setpoint < 750 ){
setpoint = 750;
}
SCI1RingBuffer[ SCI1Buffer ] = 120; // Put PicoPic address in buffer
SCI1Buffer ++;
if( SCI1Buffer == bufferLength ) SCI1Buffer = 0;
SCI1RingBuffer[ SCI1Buffer ] = port; // Put servo port in buffer
SCI1Buffer ++;
if( SCI1Buffer == bufferLength ) SCI1Buffer = 0;
data = (char)(setpoint/256); // Put upper position byte in buffer
SCI1RingBuffer[ SCI1Buffer ] = data;
SCI1Buffer ++;
if( SCI1Buffer == bufferLength ) SCI1Buffer = 0;
data = (char)(setpoint%256);
SCI1RingBuffer[ SCI1Buffer ] = data; // Put lower position byte in buffer
SCI1Buffer ++;
if( SCI1Buffer == bufferLength ) SCI1Buffer = 0;
SCI1RingBuffer[ SCI1Buffer ] = 0; // Put a 0 in the buffer
SCI1Buffer ++;
if( SCI1Buffer == bufferLength ) SCI1Buffer = 0;
if(flag == 1){ // If the buffer is initially empty.
SCI1CR2 = 0x88; // Enable the interrupts
}
}
/**
* \brief SCI1 to PicoPic Transmission Data Register Empty (TDRE) interrupt
* service routine.
*
* Tests if the ring-buffer is empty. If it is the interrupts are disabled,
* otherwise it places the next byte in the transmission register to send
* to the PicoPic.
*
* \author Zebb Prime
* \date 19/7/05
*/
__interrupt void SCI1_TDRE_ISR( void ){
PTH |= 0x40; // Turn on the Tx LED.
if( SCI1Buffer == SCI1Sent ){ // If nothing to send
PTH &= 0xBF; // Turn off Tx LED
SCI1CR2 = 0x08; // Turn off the interrupts
return;
}
while((SCI1SR1 & TDRE) == 0){}; // Read SCI1SR1 (needed before transmission)
SCI1DRL = SCI1RingBuffer[ SCI1Sent ]; // Place next byte in register
SCI1Sent ++; // Update ring-buffer
if(SCI1Sent == bufferLength) SCI1Sent = 0;
PTH &= 0xBF; // Turn off Tx LED
}