Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

ECE5881/6881 Real Time System Design

Pendulum Design Exercise

0 Aim

To develop a real time system to sense the motion of a pendulum and  reproduce the same motion with a DC motor driving a pointer.  The following learning objectives will be achieved by completing this design exercise:

1.   Develop and practise real time embedded system design, testing and debugging techniques.

2.   Understand the trade-off between hardware and software implementations in a real time embedded system by studying a software hardware co-design            problem.

3.   Interpret timing information from a sensor and its relationship to a physical system.

4.   Design modules that respond to sensor changes within hard deadlines.

5.   Use Mathematical modelling of a physical system to guide real time design and implementation.

6.   Design a PID motor controller with PWM output to produce desired motions in real time.

1 Equipment

•   Altera Quartus/ NIOS II development software

•   DE2- 115 FPGA Development Board

•   Pendulum mechanical system with:

o Free swinging pendulum with variable position weight

o Light beam retro reflective sensor

o Slotted asymmetric mask mounted on the end of the pendulum

o Co-axial DC motor with quadrature optical shaft encoder

•   Interface Electronics with a 12 V plug pack power supply and sensor/motor connections.

Photo Above of New Kit Yellow circled numbers: 1: 12V power connector; 2:      ribbon cable connector for DE2- 115 board; 3: combined motor gearbox and encoder; 4: 3D printed beam sensor mask; 5: 3D printed 45 degree constrained pivot for          pendulum; 6: pendulum clip for safe transporting.

2 Risk Assessment

There is the unlikely risk that the pendulum may strike a user or other people in the lab.  For this reason, the following precautions must be observed:

1.   Ensure that the equipment is positioned away from people and in the centre of the bench with the swinging pendulum on the far side of the user.

2.   Ensure that the pendulum constraint is present and working – this is a fishing  line in the old red kit and 3D printed plastic barrier in the new kit, labelled 5   above.  It must prevent the pendulum swinging more than 45 degrees from the bottom rest position.  The limit restricts the energy of the swing and prevents  the pendulum becoming unbalanced due to large swing excursions.

3.   Keep hands and face clear of the bottom of the pendulum when it is operating.

4.   Do not use the pendulum if the clear disk with red line is damaged or fractured since this may have sharp edges.

3 Background and Preliminary Work

Pendulum motion is a well understood behaviour that can be simply modelled            mathematically.  For small angles of deviation of the pendulum from its rest position, the motion approximates simple harmonic motion.  Simple harmonic motion is          characterised by an acceleration being proportional to the displacement.

Derive the equations of motion for a pendulum of length to a point mass and       small angle from rest of . Start by showing that the force component acting               perpendicular to the pendulum (that is acting in the positive direction of angle) is        − sin ≈ − for small angles where is the acceleration due to gravity.     Use this result to find a 2nd order differential equation in and check that a sinusoidal solution exists with amplitude , period and phase angle .  Find the period of this sinusoidal solution in terms of and . What is the maximum speed of the                 pendulum?  Given the maximum speed and period, find the maximum amplitude of the angle.  These equations allow you to characterise the pendulum motion given        measurements of its period, direction and speed.

In practice some energy is lost on each cycle due to friction in the pendulum bearing and air resistance.  The amplitude of the swinging pendulum therefore decreases      gradually.  However sufficient accuracy can be obtained for our purposes if we         assume there are no losses over each half period of motion and update the motion     estimate at the end of each half cycle.

A light beam is mounted at the bottom of the pendulum path as shown in the photos    above.  The beam shines onto the corner cube reflector on the other side of the             swinging pendulum and the corner cube returns the beam in the opposite direction to   its arrival. The beam sensor output is a logic signal that is 1 when the beam is detected and 0 when the beam is blocked.   A mask shape shown below is used to cut the beam in a particular pattern.  What is the purpose of this mask shape?

10 mm

10 mm

20 mm

4 Method

4.0 Setting up and Testing the Equipment.

1. Connect:

•   the ribbon cable to the JP5 (GPIO) connector

•   12V power supply ensure power is OFF when making connections.

2. Power the DE2- 115 board before the interface board.

3. Power the Interface 12V supply.  The red and orange interface box LEDs and the beam sensor LED should then be illuminated.  The orange beam sensor LED       should turn on when the red visible beam is unobstructed.

Test the equipment by using Quartus to download to the DE2- 115 board the PendulumTest.sof file provided on the Moodle site. The following functions and displays are then available:

KEY[0] press for a reset

SW[9:0] is the signed 10 bit binary input to the PWM motor control HEX3-HEX0 displays SW[9:0] in decimal.

LEDG[0] is the Hbridge_PWM

LEDG[1] is the Hbridge_InB

LEDG[2] is the Hbridge_InA

LEDG[5] = beam;

LEDG[6] = enA;

LEDG[7] = enB;

HEX7-HEX4 displays encoder angle count from reset

where the encoder 1200 counts per revolution.

Test that the encoder counts in both directions without losing steps – you can apply a reset with KEY[0] when the red disk line points downwards as a reference.

Test the motor drives in both directions using positive and negative binary SW values. SW[9] is the sign bit. Start with SW[9:0] all being 0, and change SW[8:0] to test         forward motion. Disconnect pendulum power, change SW[9:0] to all being 1, and       then reconnect pendulum power. Then change SW[8:0] to test reverse motion.

Check that the beam sensor is working by observing the status LEDs on the receiver as the pendulum moves slowly past.

4.1 Software Encoder Interface

The aim of this section is to accumulate and display the encoder shaft angle of the motor from the A and B outputs of the incremental encoder.  The operation of an incremental shaft encoder is described in the lectures.  Here are the detailed steps:

1.   Create a new Quartus Verilog project with a NIOS-II processor and SOPC modules.  Parallel port modules should be included that are configured as:

Encoder: Inputs A and B from the encoder that generate an interrupt on   both rising and falling edges (use one 2 bit port for both A and B encoder signals),

•   outputs for the HEX displays for the angle and

•   input from a KEY pushbutton to reset the encoder angle

•   inputs from the SW switches for selecting angle units for display see 4 below.

Microseconds: 32 bit input port and

TimerControl: 3 bit output port (for signals ext_in, rst_interrupt_timer_in and rst_ext_timer_in) for use by the module InterruptLatencyEventTiming that measures ISR and software latency see the discussion within the file InterruptLatencyEventTiming.v and below on this page.

•   JTAG UART

•   On-chip memory - select the RAM mode, 32-bit data width, and a size of 400kB

•   Interval timer for a 1 msec real time interrupt.

2.   Ensure you allocate pins appropriately – see Appendix A at the end of these notes.

3.   Create a new NIOS-II IDE uCOS-II Hello World project.

4.   Write a single interrupt service routine (ISR) to handle the changes in encoder A and B signals that updates an angle counter variable.

5.   Display the angle counter with sign on HEX 7 that displays in 1200 counts per revolution or degrees depending on a SW input.

Time     the     interrupt     latency     using     the     microsecond     counter     module InterruptLatencyEventTiming.v provided on Moodle.   To measure interrupt latency:

1.   Ensure your 2 bit Encoder parallel port is configured to generate interrupts on both rising and falling edges of the encoder signals.

2.   Using Verilog, connect the 32 bit module port microseconds to the parallel port Microseconds.

3.   As a once off initialisation before the ISR is linked to the interrupt, issue a rst_interrupt_timer_in=1 then 0 via the TimerControl parallel port.

4.   At the end of the ISR, read the Microseconds parallel port to obtain the latest interrupt latency and then send a 1, 0 to rst_interrupt_timer_in to prime the timer for the next interrupt latency measurement.

5.   See comments within InterruptLatencyEventTiming.v for more details.

Questions:

Estimate the maximum  speed that the  shaft  can rotate with your  software interface.  Compare this with the specification of maximum speed in the data sheet on the unit webpage for the shaft encoder.

Max speed of rotation achievable =  ………………………………… (RPM)

4.2 HDL Encoder Interface

Achieve the same functionality as in the previous section except replace the ISR with a Verilog HDL design discussed in lectures and clocked at 50 MHz.  The output of the Verilog Encoder module should be a 32-bit signed angle counter that is interfaced to the NIOS processor with a synchronous PIO module.

Questions:

Estimate the maximum speed achievable for this hardware solution and again compare this with the encoder data sheet.

Max speed of rotation achievable =  … …………………………… (RPM)

4.3 Motor Pulse Width Modulation (PWM) Interface

The aim in this section is to implement a hardware digital PWM module.  The module will require:

1. PWM_data_input - N bits representing a desired average motor voltage.

2. PWM_out - when 1 the H-bridge supplies full voltage to the motor, 0              otherwise.  The average motor voltage is arranged by the PWM module to be  proportional to PWM_data_input.  The duty cycle of PWM_out is equal to the PWM_data_input/2N for Part 1 below.

3.   The PWM output is synchronised to the PWM clock.  There are 2N clock         cycles in afundamental cycle of the PWM.  The PWM_out is high for the first PWM_input number of clock cycles and low for the remainder.  This can be     implemented with a binary counter and comparator and described in Verilog    with a single always block.

4.   Looking at the Fourier series produced by PWM_out, the lowest frequency     component is 1/(fundamental cycle) and is called thefundamentalfrequency.

5.   The fundamental frequency needs to be much higher than the motor response  frequencies for PWM to work well in practice.  The motor then behaves as if it receives an averaged voltage across the fundamental period.

6.   It is often possible to hear the fundamental frequency ofthe PWM drive  coming from a motor when it is within audible frequencies of20-20 kHz.

Example:

A 10 bit unsigned PWM_data_input we would need 210 = 1024 clock cycles to complete one fundamental cycle.  If the PWM_data_input is 50, the output is  asserted for 50 out of the 1024 clock cycles or approximately 5% of full           voltage.  A fundamental frequency of 10 kHz is well above the motor               dynamics in this project.

Questions:

What frequency should we update the Verilog PWM counter for a 10 kHz fundamental frequency and a 10 bit PWM_data_input?

PWM counter update frequency =   …………………… .  Hz

The PWM module will be implemented in hardware here since a software solution is impractical.  Why?

4.3.1 Unsigned PWM

Start  with  the  simple  unsigned  PWMunsigned  Verilog  module  template  below. Complete the module so that the counter count increments on system clock rising edges whenever the clock enable CE_in is 1. CE_in is to be defined by you so that CE_in=1 for one clock period every k clock periods and 0 the rest of the time.  This provides a mechanism to divide down the system clock rate whilst maintain the same system 50 MHz  clock.  A similar approach is taken with the microsecond counter” in the Real Time Scheduling Lab 3 where a CE was asserted once every 50 clock cycles of the 50 MHz system clock.

When the counter count is less than the PWM_data_input, PWM_out should be 1 otherwise 0.  It would be a good idea to only allow PWM_data_input to affect the PWM_out at the end of each PWM fundamental period rather than allowing it to change mid cycle and produce pulses that are not synchronised correctly.

Simulate your design in ModelSim to check that the timing is correct you may wish  to  reduce  the  PWM_IN_SIZE  parameter  to  4  to  limit  the  duration  of the simulations. There is a testbench file available on Moodle week 9.

It is highly recommended that you check the hardware synthesized from your Verilog

by compiling with Quartus and using the menu Tools->netlist viewers-> RTL view.   module PWMunsigned(clk_in, CE_in, synch_reset_in, PWM_data_input, PWM_out);

parameter PWM_IN_SIZE = 10;  // this is a constant that can be overridden when

// Instantiating this module

input

input [PWM_IN_SIZE- 1:0] output reg

reg [PWM_IN_SIZE- 1:0]

clk_in, CE_in, synch_reset_in;

// synch_reset_in must be synchronised to clk_in

PWM_data_input;

PWM_out;

// out=1 in proportion to magnitude of

// PWM_data_input/2**[PWM_IN_SIZE]

count;

// … other local signals declared here

always @(posedge clk_in)

if (synch_reset_in)

else if (CE_in) begin

end

endmodule

Use  a  simple  Quartus  Verilog  project  to  connect  the  SW[9:0]  switches  to  your PWM_data_input and LEDR outputs and design a CE_in so that the fundamental PWM frequency is close to 10 kHz for the 50 MHz clock. Drive the H-bridge logic lines with an appropriate pin assignment see Appendix A and the H-bridge data sheet on the unit webpage.  Test your design with different PWM inputs.

Show your demonstrator the PWM_out on a ModelSim simulation.

4.3.2 Signed PWM

Extend your design from Part 1 to a signed 2’s complement version, so that the motor can be driven in both directions.  Need a quick refresher on 2’s complement notation? The left most bit is the sign bit and is 1 for negative numbers.  See

http://en.wikipedia.org/wiki/Two's_complement

Note that you will need to find (in hardware) the magnitude of a 2’s complement binary number for comparison with the PWM counter. Here is a simple way to achieve this in Verilog:

wire [PWM_IN_SIZE-1:0] magn

= (data_in[PWM_IN_SIZE-1]? 1'b0-data_in : data_in);

Simulate and test your solution by driving the motor in both directions at different speeds. Show your demonstrator.

Questions:

Does your design achieve the full range of outputs from 0 to full scale? Is there an input where the H-bridge produces 0V?

Is there an input where the H-bridge produces the full positive voltage? Is there an input where the H-bridge produces the full negative voltage?

4.4 PID Implementation with a uCOS-II Task

A PID (Proportional Integral Differential) controller is commonly used to control DC motors. The input is an error defined as the difference between the desired and actual encoder positions for the motor shaft angle.  The aim of the PID controller is to reduce the  error  as  much  as possible  subject  to  the  dynamics  of the  DC  motor  and  its mechanical  load  via   appropriate  feedback  of  a  voltage  to  the  motor.     The implementation equation suitable for our application is

n

MotorVolt n = Kp En + Kd (En En1) + (128 + Ki Ej ) / 256 +128  / 256

Kp, Kd and Ki are the proportional, differential and integral gains respectively and En=desired angle encoder angle represents the error at time step n.

•   We are using fixed point integer representations for the gains and errors. Note that we have implemented rounding with the integer divisions by including 128 additions.   128 represents half of the 256 divisor, so represents adding ½ and truncating in other words rounding” .

•   The divisions by 256 indicate that we are storing 16 fractional bits for Ki and 8 fractional bits in Kp and Kd.

•   Integer multiplication, addition and subtraction can cause overflow.  Choose appropriate  numbers  of  bits  in  your  representations  to  avoid  multiplier overflows.    With  addition  and  subtraction,  check  for  overflow  and  apply saturation to the results of each addition or subtraction.  Overflow in addition and subtraction can be detected by looking at the sign bits of the operands and results alone.  For example, adding two positive integers with a negative result indicates overflow. If overflow/underflow occurs, the result should be set to the maximum/minimum   allowable  number   if  the   result   should  have  been positive/negative.   Also, the final conversion to a limited (say 10) number of motor voltage bits for the PWM module should be a saturating conversion rather than a simple truncation the sign must be preserved correctly in a saturating conversion.

Implement and test the PID controller in a single uCOS-II task that runs every  10 millisecond.  Here are some of the steps that need to be completed:

1.   Check that correct numerical results are obtained for corner test cases using printf statements or the debugger.

2.   Verify that numerical overflow is handled correctly by varying gains and injecting synthetic errors and checking that the output is well behaved.   Check largest gains and maximum/minimum positive/negative errors.

3.   Measure the execution time in microseconds of your PID calculation to ensure that the code does not overrun 10 millisecond (assuming a 100 Hz servo rate).

This can be done by using a microsecond timer similar to that was used in the RTSched Lab 3.

Your measured PID execution time = …………… ..   usec

4. Tune the gains of the PID controller by observing the step response of the system.   You should think about an interface that uses the SW as inputs to change the gains without re-compiling your program.  Start with increasing Kp with Ki and Kd both zero until significant overshoot occurs and the step time is short.  Adjust Kd to reduce overshoot. Adjust Ki to remove steady state error.

There is a good discussion in Wikipedia that is helpful:

http://en.wikipedia.org/wiki/PID_controller

5.   By using printf statements, record the step response of your tuned PID controller. That is, create a 90 degree step of 300 encoder counts in the desired position.  The desired position should be 0 for 2000 msec duration, 300 for a further 2000 msec duration and then 0 again for a final 2000 msec duration. Print the time, desired position and encoder position every 10 msec and plot these using Excel or Matlab for including in your final report. Be careful not to cause excessive delay in the PID loop when collecting this data – use only short printf outputs.  Ensure your PID loop is running exactly every 10 msec still - your results should show this. What is your step response time to reach and stay within 20% of the final target?   You should be able to achieve a step response in under 200 milliseconds with less than 20% overshoot and only a few encoder counts final error after 2000 msec of the step starting.

Questions:

In your report, discuss the choice of 10 milliseconds as your servo sample time of the PID controller.   Hint: what is the range of encoder counts between successive samples with a given the servo sample time?

How does this affect the derivative estimate in integer encoder counts per servo sample time?

What is your step response time to reach and stay within 20% of the final target?

4.5 Beam Sensor Interface

Connect the light beam sensor to a parallel port that generates interrupts on both edges. The beam ISR should update a record of the times in milliseconds and the values of the last n sensor readings.

Question:

What is the minimum choice for n?  …………………………………… .

The ISR should signal a semaphore. Wait on this semaphore in a task that process new data whenever the  light beam  sensor  changes.   The processing  of the time/value information from the beam sensor needs to reliably and robustly determine when the pendulum crosses the beam sensor, and determine the speed and direction of that crossing.  Beware that using a debugger may extend interrupt latency and corrupt the timing measurements. Shortprintf statements can be used judiciously. Test your sensor interpretation software with corner cases of pendulum behaviour:  namely small and large angle pendulum swings at different swing periods obtained by moving the mass to each end of the pendulum.

4.6 Motion Generation Mimicking the Pendulum

In this section integrate all the previous modules and generate a matched sinusoidal motion that mimics the swinging pendulum.  One approach worth considering is to use a velocity based trajectory generator module driven by a higher level motion generator – see Appendix B.

The purpose of the trajectory generator is to take a desired velocity from the motion generator and produce desired position outputs every PID  servo loop cycle.   The velocity can then be updated at a slower rate than the servo loop time.  You need to choose how this is implemented: Verilog or a uCOS-II task.  Document the factors that have determined your choice in your notes.

The  motion  generator  is  then  responsible  for  producing  velocity  commands  that approximate the perceived state of the pendulum.   In practice a quarter cycle of a sinusoidal motion is all that need be stored and around 10 waypoints can be used to approximate the sine function.  Associated with each waypoint can be a target time of arrival of the motor.  As time reaches each waypoint time, a new velocity command can be issued based on the current desired position and the target desired position at the end of the next waypoint.  Note that the PID controller provides the only feedback to the motor from the encoder this results in a clean, simple controller design.  Should you choose to use encoder readings at the motion generator level, you run the risk of creating an interacting complicated and potentially poorly controlled system.

Clearly the waypoints need to be updated when either the current times have expired or a new pendulum motion estimate arrives from the light beam sensor.  In your design extend the previous pendulum cycle so that smooth motion is maintained, even if the light beam data is late in arriving.

In your C code, do not use floating point variables or operations.  For example, the use of floating point trigonometry functions such as sine and cosine are unnecessary and excessively slow.  All of your code should be using fixed point integer variables for calculations with a fractional representation.  The number of fractional bits should be documented in your code.  Refer to your lecture notes on fixed point arithmetic.

Document the testing and results that you have performed. The demonstrators will have a standard test to check how well your implementation performs.  This is available to you as well as a quiz on the Moodle site.

5. Conclusion

This pendulum project has involved many levels of modelling and design of a real     time embedded system.  Hopefully you will have a much deeper understanding of the concepts that have been presented in lectures now!


Appendix A: Interface Electronics

The following circuitry is contained in the interface electronics

•   H-bridge electronics for driving the DC motor.

•   Opto isolation and level translation of the H-bridge logic inputs and outputs to be compatible with the DE2- 115 board 3.3 V DE2- 115 inputs and outputs.

•   Level translation of the Light Beam sensor and opto isolation.

•   Connections to the optical encoder.

•   Voltage regulators for the DC motor and optical encoder.

•   Protection circuits.

See the unit webpage for data sheets for the different components.

Two independent 12V power supplies should be connected to the Red (positive) and Black (negative) banana plugs.  One supply powers the motor and the other the        encoder and light beam sensor.  The motor supply is kept electrically isolated to       reduce noise coupling into the DE2- 115 board.

The ribbon cable should be connected to the GPIO header (marked JP5 on the DE2- 115 board).