0% found this document useful (0 votes)
19 views324 pages

@15 - 8051 Advanced - IV - Data Converters Sensors and Controllers

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views324 pages

@15 - 8051 Advanced - IV - Data Converters Sensors and Controllers

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 324

ADC and DAC, Sensor Interfacing

Digital Representation of Analog Signals

Digitization: Amplitude and time quantization


32

28

24

20

16
Discrete digital signal
12

8 Continuous analog signal


4

0
0 1 2 3 4 5 6 7 8 9 10
Time (s)
A/D and D/A Conversion
1023
32 Digital Analog
Input DAC Output
28 896

24 768
zoomed in
20 640

16 512
Discrete digital signal
12 384

8 Continuous analog signal 256


Analog Digital
Input ADC Outputs
4 128

0 0
0 1 2 3 4 5 6 7 8 9 10 0 1 2 3
Time (s) Analog signal (volts)
Nyquist Theorem
• A bandlimited analog signal that has been sampled can be perfectly
reconstructed from an infinite sequence of samples if the sampling rate
fsample exceeds 2fmax samples per second, where fmax is the highest frequency
in the original signal.
– If the analog signal does contain frequency components larger than
(1/2)fsample, then there will be an aliasing error.
– Aliasing is when the digital signal appears to have a different frequency
than the original analog signal.

• Valvano Postulate: If fmax is the largest frequency component of the analog


signal, then you must sample more than ten times f max in order for the
reconstructed digital samples to look like the original signal when plotted
on a voltage versus time graph.
Sampling
• 100Hz signal sampled at 1600Hz
Sampled Data Sampled Data 2.5 FFT Magnitude
3
T rue Data
2.0
2

Voltage (V)
1 1.5
Voltage (V)

0 1.0
0 2 4 6 8 10
-1 0.5

-2 0.0

-3 0.0 0.2 0.4 0.6 0.8 1.0


Time (ms)
Frequency (kHz)
Sampling
 A signal with DC, 100Hz and 400Hz sampled at 1600Hz

Sampled Data Sampled Data 2.5 FFT Magnitude


3
T rue Data
2 2.0

Voltage (V)
1 1.5
Voltage (V)

0 1.0
0 2 4 6 8 10
-1 0.5

-2 0.0

-3 0.0 0.2 0.4 0.6 0.8 1.0


Time (ms)
Frequency (kHz)
Sampling
 1500Hz signal sampled at 1600Hz

Sampled Data Sampled Data 2.5 FFT Magnitude


3
T rue Data
2 2.0

Voltage (V)
1 1.5
Voltage (V)

0 1.0
0 2 4 6 8 10
-1 0.5

-2 0.0
-3 0.0 0.2 0.4 0.6 0.8 1.0
Time (ms)
Frequency (kHz)
Analog-to-Digital Converter Precision
• Quantitative DAS performance
– range (rx)
– resolution (Δx)
– precision (nx in alternatives)
– frequencies of interest (fmin to fmax)
– repeatability (σ of repeated measurements, same conditions)
– reproducibility (σ of repeated measurements, different conditions)

• Observable x(t) is sensed via transducer as signal y(t)


– assume a relation, y = f(x)
– range of x is rx and range of y is ry
– precision of x and y is nx and ny respectively
– resolution of x and y is Dx and Dy respectively
• and Dx = rx/nx
Analog-to-Digital Converter Precision
• The output of the transducer is related to the input
such that:
– Dy = min{f(x + Dx) – f(x)} for all x in rx
– and ny = ry/Dy
• Consider y = x2 with 0 £ x £ 1
– then 0 £ y £ 1
• If Dx = 0.01, Dx = rx/nx = 1/0.01 = 100
– log2(100) ~ 7 bits
• Dy = min{(x + 0.01)2 – x2} = 0.0001
– ny = ry/Dy = 1/10-4 = 104;
– log2(104) ~ 15 bits
Time/Sample Jitter
• Definition of time-jitter, δt:
– Let nΔt be the time a task is scheduled to be run and tn
the time the task is actually run
– Then δtn= tn – nΔt
• Real time systems with periodic tasks, must have an
upper bound, k, on the time-jitter
– -k ≤ δtn ≤ +k for all n
Delayed Service
• Consequences
– Nyquist’s theorem no longer holds
• requires constant sampling interval
– data acquisition and control systems operate using
incorrect calculated values
• consider derivative dx/dt = ((x(t)-x(t-Δt))/Δt
– errors in signal generation
• the sound is distorted
• the picture is blurry
Measurement Accuracy
• Resolution: Limiting factors
100 measurements with
– Transducer noise Position = P1
100 measurements with
P Position= P1+P
– Electrical noise pdf
– ADC precision
– Software errors Measurement Output

• Accuracy: Limiting factors


– Resolution
– Calibration
– Transducer stability
n
1
Average accuracy (with units of x) =
n
 x
i 0
ti  xmi
Fixed-Point Revisited
• Why:
express non-integer values
no floating point hardware support (want it to run fast)

• When:
range of values is known value  integer • 
range of values is small

• How:
1) variable integer, called I.
may be signed or unsigned
may be 8, 16 or 32 bits (precision)
2) fixed constant, called  (resolution)
value is fixed, and can not be changed
not stored in memory
specify this fixed content using comments
Fixed-Point Numbers
• The value of the fixed-point number:
Fixed-point number  I•
Smallest value = Imin • D, where Imin is the smallest integer
Largest value = Imax • D, where Imax is the largest integer

• Decimal fixed-point, =10m


Decimal fixed-point number = I • 10m
Nice for human input/output

• Binary fixed-point, =2m


Binary fixed-point number = I • 2m
Easier for computers to perform calculations
Fixed-Point Math Example

Consider the following calculation.


C = 2**R
The variables C, and R are integers
2p ≈ 6.283
C = (6283*R)/1000
Fixed-Point Math Example
Calculate the volume of a cylinder
V = *R2 * L
The variables are fixed-point
R = I*2-4 cm L = J*2-4 cm
V = K*2-8 cm3 2p ≈ 201*2-5
K = (201*I*I*J)>>9
Fixed-Point ADC
Vin (V) N I (10 mV) LCD
Analog in Digital out Variable part
0 0 0 0.00
0.003 1 0 0.00
1.5 512 150 1.50
2.25 768 225 2.25
3 1023 300 3.00

=0.01 V
Vin = 3•N/1024 how ADC works
Vin = I • 0.01 definition of fixed point
I = (3•100*N)/1024 substitution
I = (75•N)/256 simplify
I = (75•N+128)/256 round to closest integer
I = (m•N+512)/1024+b calibrate to get m and b
Lab 8 Calibration
Position Analog input ADC sample Correct Fixed-point Measured Fixed-point Output
0.00 cm 0.000 2 0 11
0.40 cm 0.653 224 400 380
0.80 cm 1.408 479 800 803
1.20 cm 2.119 721 1200 1205
1.60 cm 2.815 958 1600 1599

n
1
n
 x
i 0
ti  xmi
Digital ↔ Analog Conversion

Digital in voltage and in time

fs = 1/Dt
Signal has frequencies 0 to ½ fs
DAC Performance
• Resolution, range, precision
• Maximum sampling frequency
• Monotonicity
– Input increase causes output increase (always)

nonlinear nonmonotonic
Vout Vout

Ideal Ideal

Digital Input Digital Input


DAC Performance
• The DAC precision is the number of distinguishable DAC
outputs (e.g., 4096 alternatives, 12 bits).
• The DAC range is the maximum and minimum DAC output
(0 to 3.3V).
• The DAC resolution is the smallest distinguishable change in
output. (3.3V/4096 =1.2 mV)
Range(volts) = Precision(alternatives) •
Resolution(volts)
• The DAC is monotonic if the output change always the same
sign
• The DAC accuracy is (Actual – Ideal) / Ideal
– 12-bit DAC
Ideal Vout = 3V * (n/4095)
Conversion from Digital to Analog
• Range 1023
Digital Analog
Input DAC Output
– 0 to 3.3V 896

• Resolution 768
zoomed in
– 3.3V/15 = 0.22V 640

• Precision 512

– 4 bits 384

– 16 alternative 256
Analog Digital
ADC
• Speed 128 Input Outputs

• Monotonic 0
0 1 2 3
Analog signal (volts)
ADC0804 (National Semicond.)
ADC0808/0809: Multi-(Analog)-Channel
• 8 analog input lines
– Selected by 3-bit, internally share 1 ADC
– Conceptually, analog multiplexor on input
– ALE latches the address
• 8-bit output port
– Similar to the single-channel ADC
Pin interface and timing diagram
Schematic for ADC0809
Digital vs Analog Ground
Code example
PID Motor Control Using ADC0809
Sensing Robot Arm Position Using Resistive Potentiometer
Electret Microphone Interface
• Current Electret Condenser Microphones (Record sound)
Digital Thermometer with MCU
• LM35 has an operating range of -55 to 150OC, giving 10.0 mV/OC. The
amplifier gain of the signal conditioning circuit is calculated by dividing the
span of output voltage of the amplifier (i.e., 5V) by the span of the sensor
output (i.e. 127.5x10mV = 1.275 mV for the temperature measurement
range 0-127.5OC) => the amplifier gain is 5/1.275 = 3.921.
Digital Thermometer with MCU
• Any MCU with ADC can be used to interface to the output of the
conditioning circuit. For example, a built-in 8 bit ACD with 0-5 range is used.
• As the sensor itself is calibrated to give 10.0mV/ OC, it will be easier if we
adjust the amplifier gain and ADC resolution. Let us calibrate the signal
conditioning for 0-127.5OC and setup the ADC to obtain the resolution of
0.5OC. We can put the binary point to the right of the seven MSBs. The ADC
output range will be 0000 000.0 to 1111 111.1. Note that if we truncate this
fraction, then we get only 1OC resolution giving a range of 0-127OC. If we use
this binary number as it is, the resolution will be 0.5 OC, the temperature
range will be 00.0-127.5OC (see tables 13.5 for details).
RTD/Thermocouple: XTR103
RTD/Thermocouple: XTR101
Analog Proximity Sensors
• Maxbotix LV-EZ0 Ultrasonic Range Finder

• Sharp GP2Y0A21YK Infrared Proximity Sensor


• QRD1114 infrared emitter / Phototransistor combo
Maxbotix LV-EZ0 Ultrasonic Range Finder
• It is an ultrasonic range finder meaning that it uses a projected sound and measures
how long it takes for the sound to bounce off of an object and come back. The
sound is ultrasonic so it can not be heard.
• Hooking it up
– Hooking up the LV-EZ0 up is very easy, just connect the “AN” pin to an ADC.
• What it is good/bad for
– The LV-EZ0′s range is really dependent on the size of the object – About 8ft for something the
size of a finger, to over 20ft for something the size of a piece of paper. The best part is that
the output is linear, so something that is 6ft way will output half that of something 12 ft away.
– LV-EZ0 has a 1 inch resolution and a range of 0–254”, meaning you could track something
with 1” reliability over 254” of movement from the sensor. This sensor has trouble sensing
distances under 1ft, and the output can be pretty shaky especially when trying to sense
objects that are not perpendicular with the sensor.
• There are a few different versions of this sensor with various beam widths. A
narrow beam is better when you only want to know about objects directly in front
of the sensor, and wide is better if you need to know if anything is near. Maxbotix
also offers a more precise line (XL Series) that has 1cm accuracy, longer distance,
and better noise suppression (makes the read out less shaky)
Using ADC for IR-Distance Sensors
• Ping))) distance sensor
– There is one SIG pin used for both output and input.
– You will need 5V to power Ping)))
– Use a five volt tolerance pin to interface the Ping))).
• Measurement sequence:
– 0) disable interrupts
– 1) make the SIG pin an output;
– 2) issue a 5 μs output pulse (causing a sound pulse);
– 3) switch the SIG pin to back to an input;
– 4) enable interrupts
– 5) measure the time until the echo is received
• Busy-wait if foreground task
• Interrupt synchronization if background task.

Perform this measurement about 10 times per second.


• tIN is the time for the sound to travel to the object, reflect and travel back to
the sensor.
– tIN will be a pulse width measurement using input capture.
tIN = 2 d/ c
therefore : d=c* tIN/2,
c is the speed of sound.
HCSR04 Distance Sensor
• HCSR04 distance sensor
– There are two signals Trig output and Echo input.
• HCSR04 10 times a second
– 0) disable interrupts
– 1) issue a 10 μs Trig output pulse (causing a sound
pulse);
– 2) enable interrupts
– 3) measure the time until the echo is received
• Busy-wait if foreground task
• Interrupt synchronization if background task.
HCSR04 Distance Sensor
• tIN is the time for the sound to travel to the object, reflect and travel back
to the sensor.
• tIN will be a pulse width measurement using input capture.
tIN = 2 d/ c
therefore d=c* tIN/2, where c is the speed of sound.
• Perform this measurement about 10 times per second.
• You will need 5V to power Ping))) HCSR04
• Use a 5 volt tolerance pin to interface the Ping))) HCSR04.
Sharp GP2Y0A21YK IR Proximity Sensor
• It is an IR proximity Sensor. It shines a beam of IR light from an LED, and measures
the intensity of light that is bounced pack using a phototransistor.
• Hooking it up
– The sensor does not come wired, so I recommend buying the pigtail to connect to it. Connect this just as
seen in the illustration with the yellow wire to an analog input.
– Because the GP2Y0A21YK is sensing the intensity of its reflected IR light, the sensor outputs near 0V
when nothing is in front of it (approx. > 3ft), and ramps up as an object comes near.
• What it is good/bad for
– The GP2Y0A21YK is half the cost of the LV-EZ0, and incredibly simple to use, but there are a few downfalls
that make it unsuitable for sensing distance reliably. Unlike the LV-EZ0, its output is not linear, so using
this to read actual distance is difficult. Also because it is sensing IR, I have seen the output value thrown
off by a TV remote shined directly into it. And lastly, once an object comes within 4in of the GP2Y0A21YK,
the read values start to drop again down when an object is in contact with the sensor.
– If you just need a sensor so your robot does not to bump into walls, this should
work as a great low-cost solution.
• Other options
– Sharp does makes a few different versions of this sensor suitable for different
ranges (between 1.2in to 5ft).
• The code for any of the three sensors under consideration is incredibly
simple, and is exactly the same. All this does is read the value of ADC.
Using ADC for IR-Distance Sensors
• Sharp GP2Y0A21YK
– You will need 5V to power IR sensor
– Needs analog LPF
• Reduces noise
• Analog input protection
– Needs digital median filer
– Needs 10 μF or larger Vcc to GND cap for each sensor

• Calibration, fixed point d (0.01 cm)


QRD1114 IR Emitted / Phototransistor
• QRD1114 is 2 components, an IR transmitter, and a phototransistor, held together
in one package. This, like the GP2Y0A21YK, works by shining an IR light and seeing
how much of it bounces back. An object that is closer will bounce back more light
than one far away. The QRD1114 is only able to sense objects between 0 and 3cm
away.
• Hooking it up
– A little more complicated to hook up than the other two. It only requires two resistors,
(200-200ohm and a 4.7k – 5.6k ohm) to get it up and running.
• What it is good/bad for
– Not intended for determining exact distance, but for checking the proximity of objects under
3cm away. This sensor can also be used to detect white vs black surfaces because a white
surface will reflect more light than a black surface resulting in a higher reading. So, an array of these can
be used for line detection and following.
– Quite successfully used this sensor for detecting when an object passes over a track to trigger an event. In
fact, it is so fast at this detection, that properly setup, an object the size of your finger could be detected
passing over it at about 10 times the speed you can flick your finger.
– Unaware of the light’s source, it is susceptible to false positives (camera flashes, lamps, sun). Just make
sure you consider your environment before you use this as a mission critical component.
• Other options
– If you are looking at detecting lines alone, a better choice might be the QRE1113 specifically designed for
line sensing. If you are looking at sensing when an object passes by, and the object is small enough, you
might also consider Photo Interrupter. These are great for coin drop detection etc.
Further Applications with Proximity Sensors
• Just because these sensors are designed to check proximity,
don’t let your imagination be limited to that.
– The LV-EZ0 can accurately sense distance, and you can ascertain time
passed, so you can also find speed of an object. In fact I have used a
device that used 2 IR reflectance sensors and could track a marble at
80+ MPH passing by just by knowing the time and exact distance
between them.
• These are very simple devices, but don’t let that limit you to
simple ideas.
– What about a jacket that alerts you when someone approaches
behind you?
– Or dog door that only opens when the dog is near.
Sonar Range Finder
• Uses ultra-sound (not audible) to measure distance
• Time echo return
• Sound travels at approximately 343m/sec
– need at least a 34.3kHz timer for cm resolution
• One simple echo not enough
– many possible reflections
– want to take multiple readings for high accuracy
Polaroid 6500 Sonar Range Finder
• Commonly found on old Polaroid cameras, now a
frequently used part in mobile robots
• Transducer (gold disc)
– charged up to high voltage
and “snapped”
– disc stays sentisized so it
can detect echo (acts as
microphone)
• Controller board
– high-voltage circuitry
to prepare disc for
transmitting and then receiving
Polaroid 6500 Sonar Range Finder
• Only need to connect two pins to microcontroller
– INIT - start transmitting
– ECHO - return signal
• Some important information from data sheet
– INIT requires large
current (greater than
microcontroller can
provide – add external
buffer/amplifier)
– ECHO requires a
pull-up resistor (determine
current that needs to flow
into microcontroller pin
- size resistor so proper
voltage is on pin
Compass
• Four compass directions (each has three pins)
• One-hot/two-hot encoding
– one-hot for N, E, S, W
– two-hot for NE, SE, SW, NW
Compass
• Detecting a change in compass direction
– 4 bits change from 0001 to 0011 to 0010 to 0110 to 0100 …
– Always alternating between one bit on and two bits on
• Parity tree can detect difference between one and two bits
being asserted
– XOR tree of four bits (one TTL SSI package)
– Output must change at least once for every change in
orientation
– Use interrupts to detect changes
IR Proximity Detector
• Oscillator must be set to match detector
IR Frequency Modulation
Proximity Code
More Integrated Proximity Detector
• Always sending out IR
• Detector drives LED (guaranteed to match frequency)
Accelerometer
Accelerometer Output
• Analog output too susceptible to noise
• Digital output requires many pins for precision
• Use pulse-width modulation
• What about gravity?
Analog Devices ADXL202
• 2-axis accelerometer
– Set 0g at 50% duty-cycle
– Positive acceleration increases duty cycle
– Negative acceleration decreases duty cycle
– 12.5% per g in either direction
Typical Measurement for ADXL202
• Noisy data – all forces are aggregated by
accelerometer
• Sample trace at 250Hz
Typical Signal From ADXL202
• Cause interrupts at Ta, Tb, and Tc from X-axis output
• 1. Look for rising edge, reset counter: Ta = 0
• 2. Look for falling edge, record timer: Tb = positive duty cycle
• 3. Look for rising edge, record timer, reset counter: Tc = period
• Repeat from 2
• Same for Y-axis output (T2 is the same for both axes)
ADXL202: How to Handle Noise & Jitter?
• Average over time – smoothing
– Software filter – like switch debouncing
• Take several readings
– use average for Tb and Tc or their ratio
• Running average so that a reading is available at all
times
– e.g., update running average of 4 readings
current average = ¾ * current average + ¼ * new reading
• Take readings of both Tb and Tc to be extra careful
– Tc changes with temperature
– Usually can do Tc just once
Bulit-in Filter
• Filter capacitors limited noise frequency
– bandwidth limiting
ADXL202 Output
• Accelerometer duty cycle
varies with force
• 12.5% for each g
• RSET determines duration
of period
• At 1g duty-cycle will be
62.5% (37.5%)
ADXL202 Orientation
• Sensitivity (maximum duty cycle change per degree) is
highest when accelerometer is perpendicular to gravity
MAX 1112: Serial ADC
Configure MAX 1112: Send Control Byte
Connecting MAX 1112 to 8051
Load Cell
Load Cell: ADC Max 111
Linear Variable Differential Transformer (LVDT)
Linear Variable Differential Transformer (LVDT)
Linear Variable Differential Transformer (LVDT)
Digital - to- Analog (DAC) Conversion
Sine Wave Generation by PWM
(Sound Generation)
Sound Generation Schemes (A, AB Class)

Class AB push pull


Sound Generation Schemes (D Class)
• Class D amplifier uses PWM, switching
transistors, and a low-pass filter

• Despite the complexity involved, a


properly designed class D amplifier
offers the following benefits:
– Reduction in size and weight of the amplifier,
– Reduced power waste as heat dissipation and
hence smaller (or no) heat sinks,
– Reduction in cost due to smaller heat sink and
compact circuitry,
– Very high power conversion efficiency, usually
better than 90% above one quarter of the
amplifier's maximum power, and around 50% at
low power levels.
Serial DAC: TLV5616
Serial DAC: TLV5616
Serial DAC: TLV5616
• As with any SPI interface, there are basic interfacing issues to consider.
– 1. Word size. In this case we need to transmit 16 bits
– 2. Bit order. The TLV5616 requires the most significant bits first.
– 3. Clock phase, clock polarity. There are two issues to resolve. Since the
TLV5616 samples its serial input data on the rising edge of the clock, the SPI
must changes the data on the falling edge. CPOL=0 and CPHA=1 satisfy this
requirement. The second issue is which edge comes first the rise or the fall. In
this interface it probably doesn’t matter.
– 4. Bandwidth. We look at the timing specifications of the TLV5616.
Serial DAC: TLV5616
Serial DAC: MAX5353
Serial DAC: TLV5615
Serial DAC: TLV5615
Musical Notes

Note f T (milli s) t - ouput (micro s for 32 points)


C 523 1.91 59.75
B 494 2.02 63.26
b 466
B 2.15 67.06
A 440 2.27 71.02
b 415
A 2.41 75.30
G 392 2.55 79.72
b 370
G 2.70 84.46
F 349 2.87 89.54
E 330 3.03 94.70
b 311
E 3.22 100.48
D 294 3.40 106.29
b 277
D 3.61 112.82
C 262 3.82 119.27
Loudness and Pitch

Need software to create sounds. Frequency is the pitch


Sound
• Loudness and pitch (Need software to create sounds.
Frequency is the pitch)
– Controlled by amplitude and frequency

– Humans can hear from about 25 to 20,000 Hz.


– Middle A is 440 Hz
– Other notes on a keyboard are determined
• 440 * 2N/12, where N is no. of notes up or down from middle A.
– Middle C is 261.6 Hz.
– Music contains multiple harmonics
440 Hz Sound Generator
• Let’s generate a 440 Hz sound (assume Timer 20ns)
unsigned short I;
Interrupt period is 50000000/32/440 =
// 12-bit 32-element sine wave 3551 counts = 71ms
const unsigned short Wave[32]= {
2048,2438,2813,3159,3462,3711,3896,4010,4048,4010,3896,
3711,3462,3159,2813,2438,2048,1658,1283,937,634,385,
200,86,48,86,200,385,634,937,1283,1658};
//Periodic interrupt used to create the analog output waveform.
void TimerISR(void){
TIMER0_TAILR_R = 3551; // 71us
// acknowledge
TIMER0_ICR_R = TIMER_ICR_TATOCINT;
I = (I+1)&0x1F; // 0 to 31
DAC_Out(Wave[I]);
}
440 Hz Sound Generator
• Let’s generate a 440 Hz sound (assume Timer 20ns)

The waveform on the left uses a 4-bit DAC, while on one on the right uses a 12-bit DAC.

Experimental data of a 32-output 523 Hz sine-wave. Experimental data of a 256-output 523 Hz sine-wave.

Signal/noise ratio is 31 dB (3dB- -28dB) Signal/noise ratio is 49 dB (3dB- -46dB).


Figure 5.2. Voltage versus time data on top and the Fourier Transform (frequency spectrum dB versus kHz) of the data on the bottom.
How To Mix (2) Waves
• 1) Reduce range of each to 0 to 2047
• 2) Generate two output compare interrupts, one for each wave
• 3) Maintain two indices I0 and I1
• 4) Add the waveforms together
Tempo
330 Hz 330 Hz 523 Hz

0.5s 0.5s 1.0s


Figure: You can control the amplitude, frequency and duration of each note (not drawn to scale).

* tempo defines note duration


quarter note = 1 beat
120 beats/min => ½ s duration

* Design data structures for this information


Voltage versus time (the sin wave)
Set TAIL_R delays for each note in a scale (pitch)
TIMER0_TAILR_R = pt->Pitch;
Song table (voice, pitch, duration)
SysTick handles changing from one note to another

How to handle the pauses


1) enter the quiet times explicitly into the song table
2) create an envelop
Chord
• Two notes at the same time
– Superimposed waveforms
– 262 Hz (low C) and a 392 Hz (G)
Instrument Characteristics
period

Waveform shape of a trumpet sound

330 Hz 330 Hz 523 Hz

0.5s 0.5s 1.0s


Plucked string signal with envelope
(The amplitude of a plucked string drops exponentially in time)

Other things to add in structure


Instrument or voice (sine, trumpet)
Amplitude or loudness
Second note (harmony)
Envelope
440Hz sine wave output

97
Synthesizing Digital Music
• Recall Nyquist’s Sampling Theorem
– We can reproduce any bandlimited signal from its
samples if we sample correctly and at a frequency, fsam,
that is at least twice the highest frequency component of
the signal, fmax.
• Where do we get the samples?
– We could sample a series of musical tones
– We can compute the samples
Synthesizing Digital Music
• What is a musical tone?
– A sinusoid of a particular frequency
– Notes vary by twelfth root of 2 ~ 1.059
• What would the samples be?
– Fixed point numbers
• How do we generate a sinusoid?
– Output appropriate digital values via a resistor network that
effectively produces an pseudo-analog signal
• What about frequency?
– Employ a programmable timer to tell us when to output the
next value
Synthesizing Digital Music
• 440 Hz sine wave generated by 6-bit DAC

Frequency
spectrum
Music Generation (cont.)
• Objectives
– Employ LM3S to generate appropriately scaled digital
outputs at a specified frequency
• Three frequencies are required
• Frequencies are to be determined by switch settings
– Four digital outputs are are inputs to a resistor network
that serves as a digital-to-analog converter (DAC)
• Four output bits => 16 levels
Music Generation (cont.)
DAC hardware
Employ least significant four bits of a GPIO port
Arrange resistor network in 1, 2, 4, 8 sequence
Each port bit can assume digital levels of 0 and 5 V
Ports are current limited – max 8 mA

R3

R2

R1

R0
Music Generation (cont.)

• DAC software
– Interactions via device drivers
– Two device drivers required:

void DAC_INIT(void); // initializes the device


void DAC_OUT(unsigned char data); // transfers data to the device
(Device driver provides the functions associated with the
device but hides the detailed actions necessary to
implement the functions.)
Music Generation (cont.)
Interpretation of Data
• Note has three parameters
— Amplitude (loudness)
— Frequency (pitch)
— Duration
• Amplitude is a digitally approximated sinusoid
— Sinusoid varies between 0 and 5 volts
• Frequency is selected by switches
— Four states – stop, note_1, note_2, and note_3
• Duration is period switch(es) activated
4-bit Sinusoid Table
4-bit sin table
15
14
13
12
4-bit DAC output

11
10
9
8
7
6
5
4
3
2
1
0
0 1 2 3 4 5 6 7
theta (radians)

SinTab 8,9,11,12,13,14,14,15,15,15,14
14,13,12,11,9,8,7,5,4,3,2 32 value sinusoid
2,1,1,1,2,2,3,4,5,7
Sinusoid Waveform
Discrete Half-Period
2.5000

2.0000
1 + sin(x * Pi / 16)

1.5000
Series1
1.0000

0.5000

0.0000

11

13

15

17
1

9
Discrete Half-Period
obtained from previous half-period data

1.2000

1.0000
2 - sin(x * Pi / 16)
0.8000

0.6000 Series1

0.4000

0.2000

0.0000

11

13

15

17
1

9
The Two Discrete Half-Periods

2.5000

2.0000
1 + sin(x*Pi/16)

1.5000

1.0000

0.5000

0.0000
10

13

16

19

22

25

28

31
1

7
Some Relevant Numbers From Excel
X 1 + sin(x * Pi/16) 2 - sin(x * Pi/16) 8 * 1 + sin(x * Pi/16)
0 1.0000 1.0000 8
1 1.1951 0.8049 10
2 1.3827 0.6173 11
3 1.5556 0.4444 12
4 1.7071 0.2929 14
5 1.8315 0.1685 15
6 1.9239 0.0761 15
7 1.9808 0.0192 16
8 2.0000 0.0000 16
9 1.9808 0.0192 16
10 1.9239 0.0761 15
11 1.8315 0.1685 15
12 1.7071 0.2929 14
13 1.5556 0.4444 12
14 1.3827 0.6173 11
15 1.1951 0.8049 10
16 1.0000 1.0000 8
Four-bit Approximation

18
8 * {1 + sin(x * Pi / 16)

16
14
12
10
Series1
8
6
4
2
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
4-bit sinusoid table
4-bit sin table
15
14
13
12
4-bit DAC output

11
10
9
8
7
6
5
4
3
2
1
0
0 1 2 3 4 5 6 7
theta (radians)

SinTab 8,9,11,12,13,14,14,15,15,15,14
32 value sinusoid 14,13,12,11,9,8,7,5,4,3,2
2,1,1,1,2,2,3,4,5,7
112
Musical Notes
Note f T (ms) t - ouput (μs for 32 points)
C 523 1.91 59.75
B 494 2.02 63.26
b 466
B 2.15 67.06
A 440 2.27 71.02
b 415
A 2.41 75.30
G 392 2.55 79.72
b 370
G 2.70 84.46
F 349 2.87 89.54
E 330 3.03 94.70
b 311
E 3.22 100.48
D 294 3.40 106.29
b 277
D 3.61 112.82
C 262 3.82 119.27
Tone Generation
unsigned long I;
SysTick ISR
// 4-bit 32-element sine wave
const unsigned char wave[32]= {
8,9,11,12,13,14,14,15,15,15,14 Output one
value to DAC
14,13,12,11,9,8,7,5,4,3,2
2,1,1,1,2,2,3,4,5,7};

• For a 440Hz tone:


– assume a bus clock frequency of 50 MHz, SysTick count every 20ns
– each cycle of the 440 Hz sinusoid requires:
• (50*106 counts/s)/440 Hz = 113636.36 SysTick counts
– each cycle consists of 32 values each of duration:
• 113636.36 interrupt counts/32 values = 3551 SysTick counts/value
• DAC values change every 71.02 us
Lab 7 ISR SysTick ISR

• Each Systick interrupt Output one


value to DAC
– Output one value from the array to DAC
– Increment index to array (wrap back to zero)
• In main program
– If a switch is pressed set SysTick period (arm)
– If no switches are pressed then disarm
Other voices
// 6-bit 64-element bassoon wave Bassoon

const unsigned char Bassoon[64] = { 70


33,37,37,36,35,34,34,33,31,30,29, 60
30,33,43,58,63,52,31,13,4,5,10,16, 50
23,32,40,46,48,44,38,30,23,17,12,11, 40

15,23,32,40,42,39,32,26,23,23,24,25, 30
20
25,26,29,30,31,32,34,37,39,37,35,34,
10
34,34,33,31,30}; 0
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64

// 6-bit 64-element guitar wave


const unsigned char Guitar[64] = { Guitar

20,20,20,19,16,12,8,4,3,5,10,17, 60

26,33,38,41,42,40,36,29,21,13,9, 50

9,14,23,34,45,52,54,51,45,38,31, 40

26,23,21,20,20,20,22,25,27,29, 30

30,29,27,22,18,13,11,10,11,13,13, 20

13,13,13,14,16,18,20,20,20}; 10

0
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64
Data Acquisition System Design
Data Acquisition System Design
• Time quantizing - Nyquist theory
– Nyquist theory states that if the signal is sampled at fs, then the
digital samples only contain frequency components from 0 to ½fs.
– Conversely, if the analog signal does contain frequency components
larger than ½fs, then there will be an aliasing error. Aliasing is when
the digital signal appears to have a different frequency than the
original analog signal.
V(t) = A sin(2πft + φ)
– Nyquist theory says that if fs is strictly greater than twice f, then one
can determine A, f and φ from the digital samples. \
But if fs less than or equal to 2•f, then the apparent frequency, as
predicted by analyzing the digital samples, will be shifted to a
frequency between 0 and ½fs.
– Valvano Postulate: If fmax is the largest frequency component of the
analog signal, then you must sample more than ten times fmax in order
for the reconstructed digital samples to look like the original signal
when plotted on a voltage versus time graph.
Data Acquisition System Design
• Time quantizing - Nyquist theory (Con.)
– The choice of sampling rate, fs, is determined by the
maximum useful frequency contained in the signal.
fs > 2 fmax

– A low pass analog filter may be required to remove


frequency components above 0.5fs.
– Note: A digital filter can not be used to remove aliasing.
Data Acquisition System Design
Data Acquisition System Design
Data Acquisition System Design
• The data plotted in the next figure demonstrate the result that occurs
when we sample an input with multiple frequency components. This
original signal has three frequencies 0, 100 and 400 Hz. In particular,
V(t) = 0.25 + 2 sin(2π 100t) + 0.5 sin(2π 400t)
• Notice in the FFT that the information from all three components is
properly retained. This will be true for any input that has its highest
frequency component less than ½fs.
Data Acquisition System Design
• How Many Bits Does One Need for the ADC?
ADC Precision
• Quantitative DAS performance
– range (rx)
– resolution (Δx)
– precision (nx in alternatives)
– frequencies of interest (fmin to fmax)
– repeatability (σ of repeated measurements, same conditions)
– reproducibility (σ of repeated measurements, different conditions)

• Observable x(t) is sensed via transducer as signal y(t)


– assume a relation, y = f(x)
– range of x is rx and range of y is ry
– precision of x and y is nx and ny respectively
– resolution of x and y is Dx and Dy respectively
• and Dx = rx/nx
Data Acquisition System Design
• How Many Bits Does One Need for the ADC?
– Let the following describe the nonlinear system.
z = f(x)
– The required ADC precision, nz,
Δx = rx/nx
Δz = min {f(x+Δx)-f(x)} for all x in rx
Δz = Δx • ∂f/∂x for all x in rx
nz = rz/Δz
– If z=f(x) is linear, then nz = nx
– If z=f(x) is nonlinear, then nz > nx
Data Acquisition System Design
• Specifications for the Analog Signal Processing
– The analog signal processing is linear then
z = Gy + b
– Choose so the full scale range of the input signal x, maps
into the full scale range of the ADC.
• Another factor to consider is the electrical noise
– Let ez be the electrical noise referred to the ADC,
any ADC: Δz < ez would be wasteful
– E.g., range is 0 to +8V, noise at the ADC is 1mV
then any ADC bits beyond 13 would be wasteful.
Data Acquisition System Design
• Analog Filter
– Let the gain of the analog
filter be G3 = ⎢H3(s)⎢.
Then the system should pass,
with little error as seen by the
ADC, for signal frequencies
between fmin and fmax.
- To prevent aliasing => no
measurable signal above
0.5fs.
Data Acquisition System Design
• Ideal and practical filter responses
Data Acquisition System Design
• Time/Sample Jitter
– E.g. 1: data acquisition system, every Δt
• start the ADC, read the result, store in FIFO
Δt=1/fs
– E.g. 2: control system, every Δt
• read the sensors
• perform the digital control equations
• output to the actuators at a fixed rate
– E.g. 3: system that generates signals, every Δt
• output to the digital-to-analog converter (DAC)
– Definition of time-jitter, δt:
• Let nΔt be the time a task is scheduled to be run and tn the time the
task is actually run
• Then δtn= tn – nΔt
– For a real time systems with periodic tasks, we must have an
upper bound, k, on the time-jitter
Data Acquisition System Design
• Time/Sample Jitter
– For all three of the above examples it is more important
to control the time difference between periodic events
rather than the absolute time itself. Let Δtn be the actual
time difference between two executions of a software
task (e.g., starting the ADC). The desired time difference is
1/fs. For this situation, we define the time-jitter at sample
n to be:
δtn= Δtn - 1/fs
Again, we must be able to place an upper bound, k, on
the time-jitter.
-k ≤ δtn ≤ +k for all n
V(t) rather at V(t+δt)
Data Acquisition System Design
• Consequences of delayed service
– Nyquist’s theorem no longer holds
• requires constant sampling interval
– data acquisition and control systems operate using
incorrect calculated values
• consider derivative dx/dt = ((x(t)-x(t-Δt))/Δt
– errors in signal generation
• the sound is distorted
• the picture is blurry
Data Acquisition System Design
• How: Measurements of time-jitter
– A. Using a scope
– B. All the causes of jitter?
a. I=1, other ISR, critical sections removed by I=1
b. Currently executing instruction
void Timer0A_Handler(void){
PORTG0 ^= 0x01;
TIMER0_ICR_R = TIMER_ICR_TATOCINT;// acknowledge timer0A
Data = ADC_InSeq3(); // software start
}
Data Acquisition System Design
• How: Measurements of time-jitter
Data Acquisition System Design
• What factors limit measurement resolution?
– Transducer noise
– Electrical noise
– ADC precision
– Software errors
• What factors limit measurement accuracy?
– Resolution
– Calibration
– Transducer stability
Data Acquisition System: Example 1
• Data flow graph
Position Voltage Sample
0 to 3 cm 0 to +3V 0 to 1023
Sample
Position ADC ADC 0 to 1023
Sensor hardware driver
SysTick
ISR
SysTick
hardware Fixed-point
0 to 3.000
LCD LCD
display driver
Data Acquisition System: Example 1
• Call graph
SysTick
main
ISR

SysTick ADC LCD


init driver driver

SysTick ADC LCD


hardware hardware hardware
Temperature Data Acquisition System
• 1) Constraints
– Free stuff from Maxim, TI, or Analog Devices
– Murata NTSA0WF104F thermistor, 100 kΩ at 25 °C
– 10-bit ADC of the LM3S1968
– +3.3 V single power supply
• 2) Specifications (you can choose these as you wish)
– choose range T, e.g., 10 to 40 °C
– frequencies of interest, e.g., 0 to 10 Hz
– resolution, T, of at least 0.1 °C
– fixed-point of 0.01 °C
– numerical and graphical display
Temperature Data Acquisition System
• 3) Data flow graph
Temperature Data Acquisition System
• 4) Transducer design/specification
– Operates in the specified range
– Fast enough to pass the frequencies of interest
– Good sensitivity (dR/dT)
– Good selectivity (dR/dT > dR/dx, x is another input)
– Good stability (R vs T is constant over time)
– Interchangeability (R vs T is the same for all transducers)
– Linear (if it is monotonic, then the inverse function exists)
– Robust (pressure, vibrations, temperature, humidity)

– Two approaches to a nonlinear transducer


• Use an ADC with more bits and linearize it in software
• Linearize it with compensating nonlinear analog circuit
Temperature Data Acquisition System
• 5) Amplifier design
– Secondary conversion (bridge), resistance to voltage
– Specified temperature range, match to 0 to +3V ADC
– Fast enough to pass the frequencies of interest
– Impedance loading (Zin this stage > 2n * Zout previous stage)
– LPF at ½ fs to eliminate aliasing
– Electrical noise referred to ADC < ADC resolution
– Protect the ADC (limit range from 0 to +3V)
Input Capture: What?
• It is an edge trigger interrupt
– 1. An ISR is executed on the active edge of the external signal
– 2. Perform two rising edge input captures and subtract the two to get period
– 3. Perform a rising edge and then a falling edge capture and subtract the two
measurements to get pulse width
• Capture types
– Capture on rising
– Capture on falling
– Capture on both rising and falling (only for some special MCUs)

Optical Rotary
Two types of encoders: absolute and
Shaft Encoders
incremental encoders.
• In absolute encoders, the digital output
gives absolute position. Its problem is
that if not properly aligned, it gives
erroneous data; however, this may be
overcome by using gray codes =>
the maximum error could be 1 LSB.
• Incremental encoders provide the
relative position.
In Figure 13.2, the incremental encoder has more than one track, so that the direction
of rotation is also measured. Two sensors are located slightly apart on the outer track
generating outputs 'A' and 'B', respectively, and a third photo-sensor is located on the
inner track to detect the reference position, which would be a single pulse generated
in every rotation (while installing the encoder on the shaft, the reference position can
be fixed using this reference output.
• Typical resolution of an incremental encoder is 256 counts/revolution. Digital outputs
(pulses) are TTL compatible. It is normally recommended to use Schmitt triggered
inverters for each output signal. 5V at around 60mA is the maximum.
• Typical value of the maximum frequency of output is 120 KHz, which is very high rate.
Decoding Angular Position & Direction
Position Encoders with MCU
• MCU with interrupts sensitive to both rising and falling edges can
be used to decode the position and direction as in the figure.
• Depending upon the current and previous A and B bits, the
direction can be decoded. Note that after getting the valid
reference signal, the 2's complement position variable should be
cleared to indicate that this is a zero for reference position.
Angular Speed Measurement
Angular Speed Measurement with MCU
• In Figure 13.7, a simple variable reluctance sensor is used. The sensor consists of
a toothed rotor with equally spaced teeth and a magnet with a coil around it.
Each time an iron tooth passes near the magnet, it induces a small voltage in the
coil. Thus a pulse chain is generated at the output, which can be converted into
a clean square-wave by further conditioning or processing. A 20 teeth disk at
360 rpm speed will generate a 120 Hz square-wave.
• One solution is to use timer 1 to obtain the gating signal and timer 0 to count
the pulses while the gating signal is high.
• Figure 13.8 show the gating duration controlled by timer 1 overflow.
Odometry
• Odometry is a method to predict position from wheel rotations. We
assume the wheels do not slip along the ground.
• If one wheel moves but the other does not it will rotate about a single
contact point of the wheel to the ground.
• If one wheel moves more than the other, then there will be both a
motion and a rotation about a point somewhere along line defined by the
axle connecting the two wheels.
• We define the robot center of gravity (cog) as a point equidistant from
the pivot points. The robot position is defined as the (x,y) location and
the compass direction, or yaw angle θ, of the cog.
Odometry
• Constants
– Number of slots/rotation, n=32
– Wheel diameter, d = 886 (0.01cm)
– Wheelbase (distance between wheels), w = 1651 (0.01cm)
– Wheel circumference, c = πd = 2783 (0.01cm)
• Measurements
– LCount the number of slots of left wheel in Δt (in 349.5ms)
– RCount the number of slots of right wheel in Δt (in 349.5ms )
– At 150 RPM, there will be 28 counts in 349.5 ms . I.e., Counts vary
from -28 to +28 each Δt
Odometry: Simple Cases
Odometry
• Derivations
– Lr = LCount*c/n the arc distance traveled by the left wheel (0.01cm)
– Rr = RCount*c/n the arc distance traveled by the right wheel (0.01cm)
– Using similar triangles, we can find the new pivot point. Assuming Rr
and Lr are both positive and Rr>Lr, we get
L/Lr = (L+w)/Rr => L/Lr - L/Rr = w/Rr => … => L = w Lr/(Rr - Lr)
– Notice also the change in yaw, dθ, is the same angle as the sector
created by the change in axle. The change in angle is
dθ = Lr/L = Rr/(L+w)

c = circumference
n = number of slots per rotation
w = wheelbase
Odometry
• Derivations (Continued)
– We can divide the change in position into two components
– The exact calculation for position change is
dz = (L+w/2)*tan(dθ/2)
but if dθ is small, we can approximate
dz by the arc length.
dz = dθ/2*(L+w/2)

• Initialize
– We initialize the system by specifying the initial position and yaw.
(x,y,θ) (0.01cm, 0.01cm, 0.01 radians)
Odometry
• Calculations (run this periodically, measuring LCount RCount)
Lr = LCount*c/n (0.01cm)
Rr = RCount*c/n (0.01cm)
L = (w*Lr)/(Rr - Lr) (0.01cm)
dθ = (100*Lr)/L (0.01 radians)
dz = ((dθ/2)*(L+w/2))/100 (0.01cm) approximation
or dz = (tan(dθ/2)*(L+w/2))/100 (0.01cm) more accurate
x = x + dz*cos(θ) (0.01cm)
y = y+ dz*sin(θ) (0.01cm) first part of move
θ = θ + dθ (0.01 radians)
x = x + dz*cos(θ) (0.01cm)
y = y+ dz*sin(θ) (0.01cm) second part of move
Odometry
• Needs very accurate sensors
• Errors accumulate
• OK for relative travel from known position
– Periodic absolute knowledge of position
MCU Based Controllers
• On/Off Controllers
• PID Controllers
• Fuzzy Controllers
On/Off Controllers
• Simple
• Cheap
• Used In residential heating and domestic refrigerators
• Limited use in process control due to continuous
cycling of controlled variable  excessive wear
on control valve.
On/Off Controllers
• Synonyms:
“two-position” or “bang-bang” controllers.

Controller output has two possible values.


On/Off Controllers
• Practical case (dead band)
Proportional Action
Proportional Action

Proportional control action: u(t) = Kpe(t)


Kp: proportional gain

Controller transfer function:

C(s) = Kp

Advantage: small control signal for a small error signal


Disadvantage: steady state error

Behzad Samadi (Amirkabir University) Industrial Control 6 / 95


Proportional Action
• Steady state error occurs even if the process presents an
integrating dynamics, in case a constant load
disturbance occurs.
• Adding a bias (or reset) term:
u(t) = Kpe + ub
• The value of ub can be fixed or can be adjusted manually
until the steady state error is zero.
• Proportional Band (PB):
Integral Action
• Integral control action:
u(t) = Ki∫e(t)dt
• Ki : integral gain
• Controller transfer function:
C(s) = Kis
• Advantage: zero steady state error
• Disadvantage: integrator windup in the presence of
saturation
PI Controller
• Transfer function:

• Integral action is able to set automatically the value of ub.


• The integral action is also called automatic reset.
Derivative Action
• Derivative control action:
u(t) = Kdde(t)/dt
• Kd : derivative gain

• Controller transfer function:


C(s) = Kds
• Advantage: Derivative action is an instance of predictive
control.
• Disadvantage: Sensitive to the measurement noise in
the manipulated variable
Derivative Action
• Derivative action is an instance of predictive control.
• Taylor series expansion of the control error at time Td
ahead:

• A control law proportional to e(t + Td )

• Derivative action is also called anticipatory control, or


rate action, or pre-act.
What and Why PID?
• It is 3 term controller, based on knowledge of the present (P), of
the past (I) and of the future (D) to make a decision/action just
like human beings.
• It is old and simple, yet most popular and functions amazingly
well in most applications (90%)
– A “the simpler, the better” solution
• Often combined with logic, sequential functions, selectors, and
simple function blocks to build the complicated automation
systems
– Best used if uncertainties are not strong
– Attention to Parameter tuning/Wind-up
• PID control is used at lowest level;multivariablecontroller gives
the setpoints to the controllers at lower level.
Off-The-Shelf PID Controllers
Continuous PID Controllers
• There are three components of a proportional integral derivative controller.

– Let X(s), X*(s), E(s) be the Laplace transforms of the state variable x(t), desired state
variable x*(t), the error e(t).
– m is the DC gain and τ is its time constant.
– The transfer function of the motor is H(s) = m/(1+τ ⋅s)
– The overall gain of the control system is
X(s)/X*(s) = G(s)H(s)/(1+G(s)H(s))
PID Controller
• Transfer function:

• Time windows:
– Proportional action responds to current error.
– Integrator action responds to accumulated past error.
– Derivative action anticipated future error.
• Frequency band:
– Proportional action: all-band
– Integrator action: low pass
– Derivative action: high pass
169
Effects of Proportional, Integral and Derivative Action
• A proportional controller (Kp) reduces the rise time and reduces but never eliminates the
steady-state error (unless use the feed forward action).
– Increasing Kp makes the response more oscillatory
• An integral control (Ki) eliminates the steady-state error, but it may make the transient
response worse.
– Response creeps slowly for small Ki, but faster for larger Ki, but the system also becomes more oscillatory.
• A derivative control (Kd) increases stability of the system, reducing the overshoot, and
improving transient response (increase response speed).
– Damping decreases again when derivative time becomes too large, i.e. derivative action does not help if the prediction
time Td is too large.
– A drawback with derivative action is that an ideal derivative has very high gain for high frequency signals. This means
that high frequency measurement noise or signal of step change will generate large variations of the control signal =>
put rapidly changing signals of control effort on actuators, make them vibrate and worn out.

• Note that these correlations may not be exactly accurate, because Kp, Ki, and Kd are dependent on each other.
In fact, changing one of these variables can change the effect of the other two. For this reason, the table
should only be used as a reference when you are determining the values for Ki, Kp and Kd.
Effects of Proportional, Integral and Derivative Action

2008 Control Digital


Effects of Proportional, Integral and Derivative Action

2008 Control Digital


Effects of Proportional, Integral and Derivative Action

2008 Control Digital


PID Structures

174
PID Structures

175
PID Structures
• Series to ideal form conversion:

• Ideal to series form conversion: Only if Ti ≥ 4Td

176
Example: Incremental Control
Example: PI motor controller
Example: Integral Controller
• Let Error be the control variable
– 1) angle to wall
– 2) speed difference between wheels
– 3) distance to wall
• Run the controller
– 1) Faster than time constant of motor
– 2) No faster than sensor input rate
Controller Performance
• The response time is the delay after X* is changed for the
system to reach a new constant state.

• Steady state controller accuracy is defined as the average


difference between X* and X’.

• Overshoot is defined as the maximum positive error that


occurs when X* is increased.

• Similarly, undershoot is defined as the maximum negative


error that occurs when X* is decreased.
Perspective for Practical Implementation
• A “Naive” implementation of PID will actually not result in a good
controller. It is also necessary to consider:
– Noise filtering and high frequency roll-off
• (Often invisuably included in the commercial controllers)
– Set point weighting and 2 DOF
– Windup
– Tuning
– Computer implementation
Wash-out Filtering
• Differentiation is always sensitive to noise. This is clearly seen from the
transfer function D(s) = s.Td.Y which goes to infinity for large s.
• It is necessary to limit the high frequency gain of the derivative term, which
can be done using a wash-out filter:
– Maximum wash-out gain (f -> / s -> ) = - K.N;

• It can be interpreted as the ideal derivative (s.Td) filtered by a first-order


system with the time constant Td/N.
– Typical values of N are 8 to 20.
• The approximation acts as a derivative for low-frequency signal components
(the gain, however, is limited to KN) and as a constant gain for the high
frequency signals.
Wash-out Filtering
• A PID controller with the approximate derivative is

• This controller has constant gain


at high frequencies.
• Instead of filtering just the derivative it is also possible to use an ideal
controller and filter the measured signal.
• This can be achieved by additional low pass filtering of the control signal

where Tf is the filter time constant and n is the order of the filter.
– Tf is a compromise between filtering capacity and performance.
– The value of Tf can be coupled to the controller time constants in the same way as for the
derivative filter above.
– If the derivative time is used, Tf = Td/N is a suitable choice.
– If the controller is only PI, Tf = Ti/N may be suitable.
Wash-out Filtering
• If the 2nd filter is used, the PID controller is

• This structure has the advantage that we can develop the design methods
for an ideal PID controller and use an iterative design procedure.
• The controller is first designed for the process P(s). The design gives the
controller parameter Td.
• An ideal controller for the process
is then designed giving a new value of T d etc.
• Such a procedure will also give a clear picture of the trade-off between
performance and filtering
Other Modified Derivative Actions
Derivative action is the most difficult to tune, why?
Derivative action is the most difficult to tune, why?
Derivative action is the most difficult to tune, why?

188
Derivative action is the most difficult to tune, why?
• Consider the following process:
P(s) = 2 e−0.2s/(s + 1)
controlled by a PID controller in series form with Kp = 1
and Ti = 1.
• If Td = 0.01, GM=12.3dB, PM=68.2 deg.
• If Td = 0.05, GM=13.2dB, PM=72.7 deg.
• If Td = 0.5, the system stability is lost!
• In summary:
– Sensitive to noise
– Hard to tune (4 parameters)
Setpoint Weighting
• The normal PID controller leads to a system with error feedback because the
controller acts on the error. In this case, there could be a large initial peak of
the control signal, which is caused by the derivative of the reference signal.
The peak can be avoided by

• In this controller, proportional and derivative actions act on fractions β


(reference weights) and γ (setpoint weights) of the reference.
– Signal r is the feedforward of the reference added to improve the control systems response
to reference by changing the closed loop system zeros (not stability).
• Integral action has to act on the error to make sure that the error goes to
zero in steady state.
• The above controller has a structure with 2 DOF because the signal path
from y to u is different from that from r to u in forms of 2 difference transfer
functions.
Setpoint Weighting
• Figure 10.9 illustrates the effects of setpoint weighting on the step response. The
overshoot for reference changes is smallest for β = 0, which is the case where the
reference is only introduced in the integral term, and increases with increasing β.
Parameter β it typically in the range of 0 to 1 and γ is normally zero to avoid large
transients in the control signal when the reference is changed.

Control Digital
Wind-up
• Windup is such a phenomena caused by the interaction of integral action and
saturations.
– All actuators have limitations: a motor has limited speed, a valve cannot be more than fully opened
or fully closed, etc. Thus the control variable could reach the actuator limits. When this happens
the feedback loop is broken and the system runs as an open loop because the actuator will remain
at its limit independently of the process output. And the error signal that is driving the controller
cannot reduce. If a controller with integrating action is used, the error will continue to be
integrated => The change in the error signal have no effect upon the control signal . This means that
the integral term may become very large or, colloquially, it “winds up”. Because of the saturation
this growth is not fed through the system and hence the controller cannot supply a corrective
action. The growth in the integral block output is called ‘wind-up’ and is a problem because the
output of the integral block can become very large before the error sign changes. In such cases it is
then required that the error has opposite sign for a long period before things return to normal. The
consequence is that any controller with integral action may give large/long transients when the
actuator saturates. This can continue for a long time and cause the controller to behave badly.
• One way to stop this is to reset the output of the integrator to zero at periodic times. Most commercial
controllers will have an ‘integral reset’ feature for this or place limits on the integrator output directly
within the integrator block. This does not completely prevent wind-up, because it only influences the
integral part of controller output.
• The other way is to use anti-windup.
Wind-up
• Actuator saturation reduces a control system’s ability to
follow a command input;
• Actuator saturation degrades transience performance;
• Anti-windup mitigates the adverse effects of actuator saturation;
– Traditional way for the design of anti-windup gain is ad hoc.
– Direct methods to control design in the presence of actuator saturation
– Systematic ways to design anti-windup gains, with guarantee of stability
and performance.
Conditional Integration
• The integral term is limited to a predefined value.
• The integration is stopped when the error is greater
than a predefined threshold, namely, when the process
variable value is far from the setpoint value.
• The integration is stopped when the control variable
saturates
• The integration is stopped when the control variable
saturates and the control error and the control variable
have the same sign
– i.e., when ue > 0
Wind-up Example
• Figure 6.6 shows control of an integrating process with a PI controller and integrator
windup which is generated by a change in the reference value.
– Windup may also be caused by large disturbances or equipment malfunctions. It can also occur in many
other situations.
• The initial set point change is so large that the actuator saturates at the high limit.
The integral term increases initially because the error is positive; it reaches its
largest value at t = 10 when the error goes through 0. The output remains saturated
at this point because of the large value of the integral term. It does not leave the
saturation limit until the error has been negative for a sufficiently long time to let
the integral part come down to a small level.
• Control signal bounces between its limits several times. The net effect is a large
overshoot and a damped oscillation where the control signal flips from one extreme
to the other as in relay oscillation.
• The output finally comes so close to the set point that the actuator does not
saturate. The system then behaves linearly and settles.
Wind-up Example

Control Digital
Anti-Windup: Set-point Limitation
• Introduce limiters on the setpoint variations so that
the controller output never reaches the actuator limits.
• This frequently leads to conservative bounds and poor
performance.
• It does not avoid windup caused by disturbances.
Anti-Windup:
Incremental Algorithms
• In the early phases, integral action was integrated with the actuator by having a
motor drive the valve directly. In this case windup is handled automatically because
integration stops when the valve stops.
• When controllers were implemented by analog techniques, and later with
computers, many manufacturers used a configuration that was an analog of the old
mechanical design. This led to the so-called velocity algorithms.
– A velocity algorithm first computes the rate of change of the control signal which is then fed to an
integrator. In some cases this integrator is a motor directly connected to the actuator. In other cases the
integrator is implemented internally in the controller.
– With this approach it is easy to avoid windup by inhibiting integration whenever the output saturates.
This method is equivalent to back-calculation, which is described below.
– If the actuator output is not measured, a model that computes the saturated output can be used. It is
also easy to limit the rate of change of the control signal.
Anti-windup for Automatic Reset Configuration
Anti-Windup: Back-Calculation

200
Anti-Windup: Back-Calculation
PID with Tracking Input

202
Anti-Windup:
Back-Calculation and Tracking
• When the output saturates, the integral term is recomputed so that its new value
gives an output at the saturation limit.
– It is advantageous not to reset the integrator instantaneously but dynamically with a time
constant Tt.
• Figure 6.7 shows a block diagram of a PID controller with anti-windup based on
back-calculation using the actuator math model.
• The system has an extra feedback path generated by measuring the actual actuator
output, or the output of a mathematical model of the saturating actuator.

Control Digital
Anti-Windup:
Back-Calculation
• eS is zero when no saturation & extra feedback loop has no effect on system.
• When the actuator saturates, the signal e S ( 0) is feedback to the integrator
through the gain Tt.
– The normal feedback path around the process is broken because the process input remains
constant. There is, however, a feedback path around the integrator. e S ( 0) is fed back in a way to
reduce the input to the integrator until eS = 0. This reduces the controller output until it equals the
saturation limit and stops wind-up.
– Because of this, the integrator output is driven towards a value such that the integrator input
becomes zero (eS goes towards zero), this reduces the controller output until it equals the saturation
limit and stops, i.e. the controller output is kept close to the saturation limit.
– The controller output will then change as soon as the error changes sign and integral windup is
avoided.
– By increasing the value of the anti-wind-up gain it is possible to reduce the wind-up some more. Be
careful of a big anti-wind-up gain because stability can be influenced - try to use the smallest value
that gives a reasonable response.
Anti-Windup:
Back-Calculation
• The integrator input (= 0) is:

where ulim is the saturating value. It means that the signal v settles on a value slightly
outside the saturation limit and the control signal can react as soon as the error
changes time/sign. This prevents the integrator from winding up.
• The rate at which the controller output is reset is governed by the feedback gain
(called tracking gain), Kt =1/Tt, a large value of Kt give a short reset time. Kt can,
however, not be too large because measurement error can then cause an undesirable
reset.
Anti-Windup Example
Back Calculation
• In Fig. 6.8, the output of the integrator is quickly reset to a value such that
the controller output is at the saturation limit, and the integral has a
negative value during the initial phase when the actuator is saturated.
– This behavior is drastically different from that in Figure 6.6, where the integral has a positive
value during the initial transient.
– Also notice the drastic improvement in performance compared to the ordinary PI controller
used in Figure 6.6.
• The effect of changing the values of the tracking time constant (T t = 1/Kt) is
illustrated in Figure 6.9.
– Advantageous to choose a very small value of the time constant because the integrator is
then reset quickly.
– Some care must be exercised when introducing anti-windup in systems with derivative action.
If the time constant is chosen too small, spurious errors can cause saturation of the output,
which accidentally resets the integrator. The tracking time constant Tt should be larger than Td
and smaller than Ti. A rule of thumb, a reasonable compromise is to choose Kt ≈ 1/Ti for PI
control and as Tt ≈ sqrt(TiTd) for PID control.
Anti-Windup Example
Back Calculation
Anti-Windup Example
Back Calculation
Cruise Control Example
• Fig. 10.7a shows the wind-up.
– A car encounters a hill that is so steep (6◦) that the throttle saturates when the cruise
controller attempts to maintain speed.
– When encountering the slope at t = 5 the velocity decreases and the throttle increases to
generate more torque. The torque required is however so large that the throttle saturates.
– The error decreases slowly because the torque generated by the engine is just a little larger
than the torque required to compensate for the gravity. The error is large and the integral
continues to build up until the error reaches zero at time 30, but the controller output is still
much larger than the saturation limit and the actuator remains saturated. The integral term
starts to decrease and at time 45 and the velocity settles to quickly to the desired value.
– Notice that it takes considerable time before the controller output comes in the range where
it does not saturate resulting in a large overshoot.
• In Fig. 10.7b (Kt = 2), because of the feedback from the actuator model the
output of the integrator is quickly reset to a value such that the controller
output is at the saturation limit and the large overshoot is avoided.
Cruise control
• Tracking gain: Kt = 2
Controllers with a Tracking Mode

• A controller with back-calculation can be interpreted as having two modes:


– Normal control mode: when it operates like an ordinary controller
– Tracking mode: when the controller is tracking so that it matches given inputs and outputs.
– Mode switching is automatically done because tracking is automatically inhibited when the tracking signal
w is equal to the controller output. This can be used with great advantage when building up complex
systems with selectors and cascade control.

• Figure 6.10 shows a PID module with a tracking signal. The new input TR is called a
tracking signal because the controller output will follow this signal. Notice that
tracking is inhibited when w = v. Using the module the system shown in Figure 6.7
can be presented as shown in Figure 6.11.
Controllers with a Tracking Mode
Bumpless Transfer
Bumpless Transfer
Bumpless Transfer
Bumpless Transfer
Motor Parameter Determination
• 1) Step response of the motor to get time constant τ.

• 2) Plot speed in RPM versus duty cycle to get m


PID Controller Parameter Determination
Empirical method
• Start with just a proportional term (Kp).
– proportional controller will generate a smooth motor speed
– choose the sign of the term Kp so the system is stable.
– try different Kp constants until the response times are fast enough
• The next step is to add some integral term (Ki)
– a little at a time
– to improve the steady state controller accuracy
– without adversely affecting the response time.
– choose the sign of the term Ki so the system is stable.
– Don’t change both Kp and Ki at once.
• The last step is the derivative term (Kd)
– a little at a time
– reduce the overshoots/undershoots in the step response
– choose the sign of the term Kd so the overshoots/undershoots are reduced.
TRIAL AND ERROR TUNING METHOD
• Step1: With P-only controller
– Start with low Kc value and increase it until the response has a sustained
oscillation (continuous cycling) for a small set point or load change. (K cu)
– Set Kc = 0.5Kcu.
• Step2: Add I mode
– Decrease the reset time until sustained oscillation occurs.
– Set .
– If a further improvement is required, proceed to Step 3.
• Step3: Add D mode
– Increase the preact time until sustained oscillation occurs.
– Set .
(The sustained oscillation should not be cause by the controller saturation)
Ziegler-Nichols’ Tuning: Frequency Response Method
Ziegler-Nichols closed-loop tuning method (ultimate cycle method)
• The idea was to tune the controller based on the following idea:
– Make a simple experiment, extract some features of process dynamics from the experimental
data, and determine controller parameters from the features.
• One method is based on direct adjustment of the controller parameters.
– A controller is connected to the process, integral and derivative gain are set to zero and the
proportional gain is increased until the system starts to oscillate. The critical value of the
proportional gain Kc is observed together with the period of oscillation Tc. The controller
parameters are then given by Table 10.1.
– The values in the table were obtained based on many simulations and experiments on
processes that are normally encountered in process industry. There are many variations of
the method which are widely used in industry.

2008 Control Digital


Ziegler-Nichols’ Tuning: The Step Response Method
Ziegler-Nichols open-loop tuning method (process reaction method)
• It is based on determination of the open loop step response of the process, as
shown Figure 10.4a.
– The step response is measured by applying a step input to the process and recording the response.
– The response is scaled to correspond to a unit step input and characterized by parameters a and T del,
which are the intercepts of the steepest tangent of the step response with the coordinate axes.
– The parameter Tdel is an approximation of the time delay of the system and a/T del is the steepest slope of
the step response.
– Notice that it is not necessary to wait until steady state to find the parameters, it suffices to wait until the
response has had an inflection point.
• The controller parameters are given in Table 10.2. The parameters were obtained by
extensive simulation of a range of representative processes.

2008
PID Controller Design
Performance Criteria For PID Design
• Ensure that the closed loop system has desirable dynamic and steady-
state response characteristics.
• Ideally, we would like the closed-loop system to satisfy the following
performance criteria:
1. The closed-loop system must be stable.
2. The effects of disturbances are minimized, providing good disturbance
rejection.
3. Rapid, smooth responses to set-point changes are obtained, that is, good set-
point tracking.
4. Steady-state error (offset) is eliminated.
5. Excessive control action is avoided.
6. The control system is robust, that is, insensitive to changes in process
conditions and to inaccuracies in the process model.
PID Controller Design
• Trade-offs in control problems
– Set point tracking vs. disturbance rejection
– Robustness vs. performance
• In process industries, more than 97% of the regulatory controllers
are of the PID type.
• Most loops are actually under PI control (as a result of the large
number of flow loops).
• Pulp and paper industry over 2000 loops:
– Only 20% of loops worked well (i.e. less variability in the automatic mode
over the manual mode).
– 30% gave poor performance due to poor controller tuning.
– 30% gave poor performance due to control valve problems (e.g. control
valve stick-slip, dead band, backlash).
– 20% gave poor performance due to process and/or control system design
problems.
PID Controller Design
• Process industries:
– 30% of loops operated on manual mode.
– 20% of controllers used factory tuning.
– 30% gave poor performance due to sensor and control valve problems.
• Chemical process industry:
– Half of the control valves needed to be fixed (results of the Fisher diagnostic valve
package).
– Most poor tuning was due to control valve problems.
• Refining, chemicals, and pulp and paper industries over 26,000
controllers:
– Only 32% of loops were classified as excellent or acceptable.
– 32% of controllers were classified as fair or poor, which indicates unacceptably sluggish
or oscillatory responses.
– 36% of controllers were on open- loop, which implies that the controllers were either
in manual or virtually saturated.
– PID algorithms are used in vast majority of applications (97%). For the rare cases of
complex dynamics or significant dead time, other algorithms are used.
PID Design Methods
• PID controller settings can be determined by a number
of alternative techniques:
1.Direct Synthesis (DS) method
2. Internal Model Control (IMC) method
3. Controller tuning relations
4. Frequency response techniques
5. Computer simulation
6. On-line tuning after the control system is installed.
PID Controller Implementation
• Implementation methods:
– Pneumatic
– Hydraulic
– Electronic
– Digital
Implementation based Operational Amplifiers

Control Digital
Why digital PID?
• PID controllers have survived many changes in technology, from
mechanics and pneumatics (continuous) to microprocessors
(digital) via electronic tubes, transistors, integrated circuits.
• Microprocessor has had a dramatic influence on the PID
controller. Practically all PID controllers made today are based on
microprocessors.
– Provide additional features like automatic tuning, gain scheduling, and
continuous adaptation.
– Programmable, flexibility, easy digital integration,…
Digital Control System
Computer Implementation
Sampling
• When the controller is implemented in a computer, the analog inputs are
read and the outputs are set with a certain sampling period. This is a
drawback compared to the analog implementations, since the sampling
introduces dead-time in the control loop.
• When a digital computer is used to implement a control law, the ideal
sequence of operation is the following.
– Wait for clock interrupt
– Read analog input
– Compute control signal
– Set analog output
– Update controller variables
– Repeat

• Notice that an output is sent to the actuators as soon as it is available. The time
delay is minimized by making the calculations in Step 3 as short as possible and
performing all updates after the output is commanded.
Computer Implementation
Sampling
• With this implementation, the delay is minimized.
• If the analog input is read with a sampling period h, the average delay of the
measurement signal is h/2.
• The computation time is often short compared to the sampling period. This
means that the total delay is about h/2.
• However, most controllers and instrument systems do not organize the
calculation in this way. Therefore, the delays introduced because of the
sampling is often several sampling periods. ?????

2008 Control Digital


Computer Implementation
Aliasing - Prefiltering
• The sampling mechanism introduces some unexpected phenomena to be
considered in a good digital implementation of a PID controller.
• Consider a high frequency noise signal s(t) = cos(nωst ± ωt) where ws=2/h is the
sampling rate. At the sampling instants (t = k.h, k = 0,1,…,n):
s(t) = s(k.h) = cos(nωskh ± ωkh)= cos(2nk ± ωkh) = cos(ωkh) = sa(t)
With sa(t) = cos(ωt) is a low frequency signal.
• Thus s(t) and sa(t) have the same value at the sampling instants. And sa(t) is
called an alias of signal s(t). A consequence of the aliasing effect is that a high-
frequency disturbance s(t) after sampling may appear as a low-frequency signal
sa(t).
• In Figure 6.17, h is 1 s and the disturbance s(t) has a period of 6/5 s. After
sampling, s(t) appear as sa(t) with the low frequency fa = 1/6 Hz.

Control Digital
Computer Implementation
Aliasing - Prefiltering
• Because of sampling/aliasing, high frequency signals, which in analog controllers
normally are effectively eliminated by low-pass filtering, may appear as low-
frequency signals in the bandwidth of the sampled control system => disturb the
system adversely.
– To avoid this, an analog prefilter which effectively eliminates all signal components with
frequencies above half the sampling frequency should be introduced. Such a filter is called an anti-
aliasing filter.
– A second-order Butterworth filter is a common anti-aliasing filter. Higher-order filters are also used
in critical applications.
• The selection guide of the filter bandwidth (ωb)
– Assume we want the prefilter to attenuate signals by a factor of 16 at half the sampling frequency
(ωs), we need to design:
(ωs/2ωb)2 = 16 => ωb= ωs/8
i.e., the bandwidth is 1/8 of the sampling frequency f S & the prefilter significantly attenuate any
disturbance signals of the high frequency (above f S/2) accordingly.
– Notice that the dynamics of the prefilter is often significant. It should be accounted for in the
control design by combining it with the process dynamics.
Digital Control System
Approximating Continuous-Time Controllers

235
Approximating Continuous-Time Controllers
Discrete PID control
using Numerical Integration
Discrete PID control
using Numerical Integration

2008 Control Digital


Discrete PID control
using Numerical Integration

2008 Control Digital


Discrete PID control
using Numerical Integration

2008 Control Digital


Digital PID
Discrete PID control
using Numerical Integration

2008 Control Digital


Discrete PID control
using Numerical Integration

2008 Control Digital


Discrete PID control
using Numerical Integration

2008 Control Digital


Discrete PID control
using Numerical Integration

Control Digital
Digital PID
Digital PID: Inverse Response
• Inverse Response: When the initial response of a dynamic
system is in adirection opposite to the final outcome, it is
called an inverse response.
• Obtaining the effective delay (Half rule):
– Effective delay =True delay + inverse response time constant (s)
• + half of the largest neglected time constant
• + all smaller higher order time constants

• Time constant:
 = the largest time constant + 1/2 the second largest time constant
–  1 = the largest time constant,
–  2 = the second largest time constant + 1/2 the third largest time
constant
Digital PID: Inverse Response
Digital PID: Inverse Response
Example 1: PID Code
• Implement code for the following digital PID:
Example 1: PID Code Version 1
Example 1: PID Code Version 2
Example 1: PID Code with Anti-Windup
Example 2: PID Code

Antiwindup digital PID:

public class SimplePID


{ private double u,e,v,y;
Private double K,Ti,Td,Beta,Tr,N,h; private
double ad,bd;
private double D,I,yOld;
public SimplePID(double nK, double nTi, double NTd, double
nBeta, double nTr, double nN, double nh)
{ updateParameters(nK,nTi,nTd,nBeta,nTr,nN,nh);
}

Behzad Samadi (Amirkabir University) Industrial Control 92 / 95


Digital Control
Example 2: PID Code
Antiwindup digital PID:

public void updateParameters(double nK, double nTi, double NTd,


double nBeta, double nTr, double nN, double nh) {

K = nK; Ti = nTi; Td = nTd; Beta = nBeta;


Tr = nTr
N = nN;
h = nh;
ad = Td / (Td + N*h); bd =
K*ad*N;
}

Behzad Samadi (Amirkabir University) Industrial Control 93 / 95


Digital Control
Example 2: PID Code
Antiwindup digital PID:

public double calculateOutput(double yref, double newY) {


y = newY;
e = yref - y;
D = ad*D - bd*(y - yOld);
v = K*(Beta*yref - y) + I + D;
return v;
}
public void updateState(double u) {
I = I + (K*h/Ti)*e + (h/Tr)*(u - v);
yOld = y;
}
}

Behzad Samadi (Amirkabir University) Industrial Control 94 / 95


Digital Control
Example 2: PID Code
Antiwindup digital PID:
public class Regul extends Thread { private
SimplePID pid;
public Regul() { pid = new SimplePID(1,10,0,1,10,5,0.1); }
public void run() {
// Other stuff
while (true) {
y = getY();
yref = getYref():
u = pid.calculateOutput(yref,y);
u = limit(u);
setU(u);
pid.updateState(u); //
Timing Code
}}}
Behzad Samadi (Amirkabir University) Industrial Control 95 / 95
Example 3: PID in Cruise Control
• Tuning the parameters of a cruise-control system

258
Example 4: PID in Motor Control using RTOS
• Note: this example uses a different, integer-based, PID
implementation. As we discussed in ‘Hardware resource
implications’, integer-based solutions impose a lower CPU load
than floating-point equivalents.

Sch_Add_Task(Task_Name, Initial_Delay, Task_Interval);


260
Example 5: Forever Loop Based PID
Example 5: Forever Loop Based PID

262
Example 6: PID using PIC

263
Practical consideration in PID implementation

• What sample rate?


– One effective technique involves the measurement of the
system rise time tr:
fsample = 40/tr
Practical consideration in PID implementation
• Quantization:
– Due to limit of the number of bits in digital systems
– E.g., 0.36 can be exactly presented in 4-bit fractional number. 0.36 is
rounded/quantized to the closed quantization level (0.25), resulting in
quantization error 0.11
– Sources of quantization error: ADC resolution, arithmetic operations, …

• Overflow:
– Due to the range that the digital system can present
– E.g., can not present 1.25 as 4-bit fractional number
– Solutions: Use fixed-point representation/operations carefully or use
floating point co-processors (but costly)
Practical consideration in PID implementation
• Anti-Aliasing:
– Solutions: Use high sampling frequency or use pre-filters to remove high
frequency components of signals (noises)

• Computation delay
– Inherent delay in processing
• Actuation occurs later than expected
– Solutions: Need to characterize implementation delay to make sure it is
negligible
• Hardware delay is often easy to characterize
– Synchronous design
• Software delay is harder to predict
– Should organize code carefully so delay is predictable and minimized
– Write software with predictable timing behavior (be like hardware) using timer triggered
architecture or synchronous software language and/or RTOS
Practical consideration in PID implementation
• Hardware resource implications
– Implementation of a PID requires some floating-point or integer
mathematical operations. The precise load will vary with the
implementation used, but a typical implementation requires 4
multiplications, 3 additions and 2 subtractions. With floating-point
operations, this amounts to a total of approximately 2000 instructions
(using the Keil compiler, on an 8051 without hardware maths support). This
operation can be carried out every millisecond on a standard (12 osc /
instruction) 8051 running at 24 MHz, if there is no other CPU-intensive
processing to be done.
– A one-millisecond loop time is more than adequate for most control
applications, which typically require sample intervals of several hundred
milliseconds or longer.
– Of course, if you require higher performance, then many more modern
implementations of the 8051 microcontroller can provide this.
– Similarly, devices such as the Infineon 517 and 509, which have hardware
maths support, will also execute this code more rapidly, should this be
required.
Final words about PID
• PID is suitable for processes with almost monotone step responses provided
that requirements are not too stringent.
• PID control is not suitable for processes that are highly oscillatory or when
the requirements are extreme.
• PI has no phase advance. This means that PI will not work for systems which
have phase lag of 180’or more.
– The double integrator is a typical example. Controller with derivative action can provide
phase advance up to about 50’
– Simple processes can be characterized by the relative time delay τ introduced in the Ziegler-
Nichols tuning procedure. PI control is often satisfactory for processes that are lag dominated,
i.e. when τ close to one. Derivative action is typically beneficial for processes with small
relative delay τ
• The PID controller being linear is not suited for strongly nonlinear systems.
Excellent results can however be obtained by combining the PID controller
with gain scheduling. A particularly attractive feature is the use of auto-
tuning which drastically reduces the effort required to build up the gain
schedule.
Final words about PID
GUIDELINES FOR COMMON CONTROL LOOPS
• Flow and liquid pressure control
– Fast response with no time delay
– Usually with small high-frequency noise
– PI controller with intermediate controller gain
• Liquid level control
– Noisy due to splashing and turbulence
– High gain PI controller for integrating process
– Conservative setting for averaging control when it is used for damping the
fluctuation of the inlet stream
• Gas pressure control
– Usually fast and self regulating
– PI controller with small integral action (large reset time)
Final words about PID
GUIDELINES FOR COMMON CONTROL LOOPS
• Temperature control
– Wide variety of the process nature
– Usually slow response with time delay
– Use PID controller to speed up the response
• Composition control
– Similar to temperature control usually with larger noise and more time
delay
– Effectiveness of derivative action is limited
– Temperature and composition controls are the prime candidates for
advance control strategies due to its importance and difficulty of control
Future of PID
• Quite reasonable to predict that PID control will
continue to be used in the future.
– Feedback has had a revolutionary influence in practically all
areas where it has been used and will continue to do so.
– PI(D) control is perhaps the most basic form of feedback. It is
very effective and can be applied to a wide range of problems.
– The emerging features of automatic tuning have greatly
simplified the use of PID control. More knowledge about PID
control has been available for a long time. Unfortunately, it has
been buried in proprietary information of suppliers. There was a
strong resurgence in the interest in PID control over the last 15
years. Many publications have appeared and it is typical that
IFAC organized a workshop on PID control in the year 2000.
Future of PID
• The alternatives to PID control are:
– RST: Discrete-time linear MISO controllers.
– SFO: State feedback and observers.
– MPC: Model predictive control.
• Fuzzy control is often mentioned as an alternative to PID control, see Passino and
Yurkovich (1998).Most fuzzy controllers used in industry have the same structure
as incremental PI or PID controllers. The parameterization using rules and fuzzy
membership functions makes it easy to add nonlinearities, logic, and additional
input signals to the control law.
• The main advantages claimed by fuzzy control are that it is easy to use and that it
is nonlinear. Many of the comparisons between PID and fuzzy control made in the
literature are, however, very sloppy. A textbook PID with Ziegler–Nichols tuning is
typically used as a reference. Furthermore, if nonlinear behavior is desired gain
scheduling can be added to a PID controller. Many fuzzy controllers are also used
in a cascade structure using PID controllers at the lower level. An advantage of
fuzzy control is that very good software is available.
• Many fuzzy controllers are, however, used in a cascade structure using PID
controllers at the lower level.
Future of PID
• All control method alternatives offer potential improvements in the linear
behavior of the system. This is particularly useful when dealing with systems
having poorly damped oscillatory modes. It is, however, necessary to take
actuator saturation and windup into account. This is done very well for MPC
but it requires special consideration for RST and SFO, particularly in
combination with mode changes.
• The tuning problem is a major difficulty with all alternatives. Much work is
needed in order to develop appropriate tuning tools.
• The RST controller is beginning to appear in applications for motor drives. The
improvements in performance are particularly important for high performance
systems.
• Controllers based on state feedback and observers are used in special
applications where the cost of the modeling effort can be justified.
Future of PID
• MPC is typically used in supervisory mode with PID controllers at the base
level.
– Much of the improvement accredited to MPC in the process industry actually comes from the
improved tuning of the basic loops. The MPC does, however, offer drastic improvements in set
point responses for multivariable systems because of the coordination it provides.
– There are several interesting problems related to the integration of MPC and PID. Tuning of the
PID controller in the inner loop gives valuable modeling information for the MPC. Since the MPC
operates in a supervisory mode it can deal with slow interactions very well.
– The lower level PID loops still have to manage fast interactions.
• Another issue is the general philosophy of approaching design of a complex
system. Top–down approaches to system design will clearly favor SFO and
MPC. A bottom–up approach favors the use of simple building blocks such as
PID controllers. In this context, it is interesting to see how the PID controller
can be augmented. The set point response can be improved substantially by
exploiting a controller structure with two degrees of freedom
• Special considerations have to be given to a PID controller that will be used
effectively in this way. It is particularly important that the controller output is
available for feedforward in such a way that saturation and windup are
handled properly.
Future of PID
• More improvements can be made through proper use of
feedforward. Other possibilities are to add filters and blocks for
dealing with measurement noise and systems having oscillatory
modes.
• There are many good research problems in developing good
approaches to bottom up design techniques. The problem of
exploring system interactions is an important one.
• Even if the applications of other control strategies increase, PID
control will certainly continue to be used.
– When correctly used it is a very effective way of using feedback. Good results can
often be obtained if the performance requirements are not extreme. The PID
controller will also serve as a building block in more complex controllers. Most
DMC controllers in fact deliver set points to PID controllers. Good performance of
these PID controllers are essential. Much commissioning work for DMC control
actually consists of tuning up the underlying PID loops.
– There are also useful augmentations for PID control in the form of Smith
predictors, gain scheduling and filters for oscillatory systems.
Future of PID
• It is important to realize that there is a very wide range of control problems
and consequently also a need for a wide range of tuning techniques.
– There are already many tuning methods available, but a replacement of the Ziegler–Nichols
method is long overdue. It is very easy to demonstrate that any controller with reasonable
tuning will outperform a PID with Ziegler–Nichols tuning. Many strategies proposed can easily
be eliminated if they are compared with a well-tuned PID.
• Development of suitable software is another area that has to be developed.
PID control is quite under-developed in that respect compared, for example, to
fuzzy control. It would be highly desirable to have software so that persons
with a moderate knowledge can experiment with PID control. Tools for
modeling and methods for automatic tuning should be a part of such a
software.
• On the research side, it appears that the development of design methods for
PID control is approaching the point of diminishing returns. There are some
difficult problems that remain to be solved. For example, there is no
characterization of the processes where PID control is useful.
FLC: Fuzzy Membership Set
• A fuzzy membership set, a fuzzy variable and a fuzzy set
– A value/software variable specifying levels of truth
• E.g., Going too slow/Speed is ok/Going too fast
– Collection describes the entire system

• Examples for a speed control system


– TooSlow
– SpeedOK
– TooFast
– SlowingDown
– SpeedConstant
– SpeedingUp
Example of Fuzzy Membership Set
• Mobile Robot (Wall Hit Avoidance)
• Fuzzy membership sets:
– Too close to the right wall
– Distance to the right wall is ok
– Too far away from the right wall
– Too close to the left wall
– Distance to the left wall is ok
– Too far away from the left wall
– Open space to 30 degrees to the right
– Open space to straight ahead
– Open space to 30 degrees to the left
Example of Speed Controller
• The Desired state
– X* is the desired tach period = 9000 μs
• The Physical plant has real state variables
– X real/true state variable, actual tach period in μs
• The Data Acquisition System creates the estimated state variables
– X’: current estimated/measured tach period 7000 to 30000 μs.
• The Preprocessor may calculate relevant parameters called crisp inputs;
//E = X*-X’ the error in motor speed
E = 9000-Period; // 0=ok, positive=too fast
//D = X’(n)-X’(n-1) the change in tach speed
D = Period – Last; // 0=constant speed
Last = Period; // positive=slowing down
Fuzzy Approach
• Preprocessor
– Crisp inputs (variables with units)
• Fuzzification
– Input membership sets
• Fuzzy rules
– Output membership sets
• Defuzzification
– Crisp outputs (variables with units)
• Postprocessor and actuator output
Fuzzy Approach
Fuzzy Approach
• Preprocessor, crisp inputs
– E = X*-X’ error in motor period
– D = X’(n) – X’(n-1) acceleration
• Fuzzification: will convert crisp inputs into input fuzzy
membership sets
– Slow True if the motor is spinning too slow
– OK True if the motor is spinning at the proper speed
– Fast True if the motor is spinning too fast
– Up True if the motor speed is getting larger
– Constant True if the motor speed is remaining the same
– Down True if the motor speed is getting
smaller.
Fuzzification

(half true)

(half true)
Fuzzification
Fuzzy Rules
• The Fuzzy rules calculate output fuzzy membership
sets.

• These 7 rules can be illustrated in a table form.


If OK and Constant then Same
If OK and Up then Decrease
If Fast and Constant then Decrease
If Fast and Up then Decrease
If OK and Down then Increase
If Slow and Constant then Increase
If Slow and Down then Increase
Fuzzy Rules
Fuzzy Rules
Defuzzification
• Defuzzification will convert output sets into crisp outputs;
– Decrease True if the motor speed should be decreased
– Same True if the motor speed should remain the
same
– Increase True if the motor speed should be increased

(half true)
Defuzzification
• The Postprocessor modify crisp outputs into a more
convenient format;
dN (or dU)
• The Actuator System affects the Physical plant based
on these output.
N = N+dN (or U = U+dU)
• Control output N (or U)
• N (U): the duty cycle to motor interface, 100 to 9900
(0.01%)
Fuzzy Logic Controller
Controller Summary
• Incremental
– Simple
– Stable
– Slow response
• PID or PI
– Plant can be described using linear differential equations
– Theory, fast response
– Needs empirical tuning, depends on load
• Fuzzy logic: Maps human intuition into rules
– Execute faster
– Good when there is expert knowledge
– Maps intuition into rules
– Abstractive approach
– Needs empirical tuning
Noise & Noise Reduction
Types of Noise
• Broadband
– i.e., all frequencies, like white noise

• Certain specific frequencies


– e.g., 60 Hz EM field
Techniques To Measure Noise
• Digital voltmeter (DVM) in AC mode.
– calibrated voltmeter is most accurate quantitative method to measure noise.
• Analog oscilloscope.
– approximate the RMS noise amplitude by dividing the peak-to-peak noise by 8.
– line-trigger to see if the noise is 60 Hz

– Spectrum analyzer: Classifying noise by


measuring the amplitude versus frequency
Techniques To Reduce Noise
• 1) Reducing noise from the source
– enclose noisy sources in a grounded metal box
– filter noisy signals
– limit the rise/fall times of noisy signals.
– limiting the dI/dt in the coil.
– Limiting rise/fall times can reduce radiated noise.
• 2) limiting the coupling between the noise source and your instrument.
– Maximize the distance from source to instrument
– Cables with noisy signals should be twisted together,
– Cables should also be shielded.
– For high frequency signals, use coaxial
– Reduce the length of a cable
– Place the delicate electronics in a grounded case
– Optical or transformer isolation circuits
• 3) reduce noise at the receiver.
– bandwidth should be as small as possible.
– add frequency-reject digital filters
– use power supply decoupling capacitors on each
– twisted wires then Id1 should equal Id2.
– V1-V2 = Rs1.Id1 - Rs2.Id2.
Project: Mobile Robot
• Consider a robot with two sensors and two DC motors. The goal is to
design the robot so it follows the black line on the track.
Project: Mobile Robot
• Part a) Each sensor gives a voltage between 2 and 3V if it is positioned over the line on
the track, and the sensor gives a voltage between 3 and 4 V if it is not positioned over
the line. Design a hardware/software interface between the two sensors and the 6812.
Give chip numbers and resistor/capacitor values. Include both the hardware and the
software interface. Give the software ritual that initializes the interface. Design a
software function that returns 0 if both sensors are not on the line, 1 if just the left
sensor is on the line, 2 if just the right sensor is on the line and 3 if both sensors are on
the line. Style matters.
• Part b) Each motor requires +5 V at 2 A to turn. Your software needs to be able to
activate or deactivate each motor independently. The interface does not need to
support turning backward or to support PWM. Design a hardware/software interface
between the two motors and the 6812. Give chip numbers and
resistor/capacitor/diode values. Include both the hardware and the software interface.
Give the software ritual that initializes the interface. Design a software function that
accepts a 2-bit call by value parameter: 0 means stop both motors, 1 means activate
just the left motor (causing the robot to turn right), 2 means activate just the right
motor (causing the robot to turn left), 3 means activate both motors (causing the robot
to move forward). Style matters.
• Part c) Design a FSM to implement the line tracking. The 2-bit input comes from the
sensors (0,1,2,3) and the 2-bit output goes to the motors(0,1,2,3). The machine will be
run in the background using periodic interrupts. No software is required, just show the
FSM graph. Give descriptive names for the states.
Project: Mobile Robot Solution
• Part a) You could use a threshold detector (more expensive) or the ADC
to interface the sensor.
Project: Mobile Robot Solution
• Part b) Because of the 2A, I will use a MOSFET or a Darlington to switch
the current. N-channel devices are typically used to sink current (P-
channel devices for sourcing current).
Project: Mobile Robot Solution
• Output=1 to turn right, output=2 to turn left. Input=1 if right side is off
track, input=2 if left side is off track. If the car is on the track go straight. If
the car is off to the right, turn left. If the car is off to the left, turn right.
Run the algorithm about 10 times faster than the response time of the
motors.
• A finite state machine is needed to solve this problem in order to handle
the case where the car completely leaves the track (both sensors are off
the track.)
Project: Mobile Robot Solution
Project: Anti-Lock Brake System
• Rear wheel controller/anti-lock brake system
– Normal operation
• Regulate velocity of rear wheel
– Brake pressed
• Gradually increase amount of breaking
• If skidding (front wheel is moving much faster than rear wheel) then temporarily reduce
amount of breaking
• Inputs
– Brake pedal
– Front wheel speed
– Rear wheel speed
• Outputs
– Pulse-width modulation rear wheel velocity
– Pulse-width modulation brake on/off
Project: Anti-Lock Brake System
• Rear Wheel Controller /Anti-Lock Brake System
Project: Anti-Lock Brake System
• Basic I/O ports for brakes
– Check if brake pedal pressed – or interrupt
• brakePressed = read (brakePedalPort)
– Turn brake on/off
• write (brakePort, onOff)
– Move rear wheel
• write (rearWheel, onOff)
Project: Anti-Lock Brake System
• Polling vs. Interrupts
– Software must repeatedly check
• Brake pedal port
• How often?
• Need to make sure not to forget to do so (use timer)
– Use automatic detection capability of processor
• Connect brake pedal to input capture or external interrupt pin
• Interrupt on level change
• Interrupt handler for brake pedal
Project: Anti-Lock Brake System
• PWM for brakes
– To pump the brakes gradually increase the duty-cycle
(ton) until car stops
Project: Anti-Lock Brake System
• Brake pump setup
– Use timer to turn brake on and off
• Apply brake
• Set timer to interrupt after “on” time
• Disengage brake
• Set time to interrupt after “off” time
• Repeat
– How do we tell which interrupt is which?
Project: Anti-Lock Brake System
• Brake pump setup
– Change value of “on” time to change analog average
• average output = ( on + off ) / ( period )
– How do we decide on the period of the pulses?
– Using two timers
• One to set period (auto-reload)
• One to turn it off at the right duty cycle
Project: Anti-Lock Brake System
• Shaft encoders
– Need to determine the rear wheel velocity
• Use sensor to detect wheel moving
– Determine speed of a bicycle
• Attach baseball card so it pokes through spokes
• Number of spokes is known
• Count clicks per unit time to get velocity
– Baseball card sensor is a shaft encoder
Project: Anti-Lock Brake System
• Shaft encoder
– Instead of spokes we’ll use black and white segments
– Black segments absorb infrared light, white reflects
– Count pulses instead of clicks
Project: Anti-Lock Brake System
• IR reflective patterns
– How many segments should be used?
• More segments give finer resolution
• Fewer segments require less processing
• Tradeoff resolution and processing
Project: Anti-Lock Brake System
• Interfacing shaft encoders
– Use interrupt on GPIO pin
• Every interrupt, increment counter
– Use timer to set period for counting
• When timer interrupts, read GPIO pin counter
• velocity = counter ∗ “known distance per click” / “judiciously chosen period”
• Reset counter
– Pulse accumulator function
– Common function
– Some microcontrollers have this in a single peripheral device
– Basically a counter controlled by an outside signal
• Signal might enable counter to count at rate of internal clock – to measure time
• Signal might be the counter’s clock – to measure pulses
– ATmega16 has external clock source for timer/counter
Project: Anti-Lock Brake System
• General interfaces to MCU
– Microcontrollers come with built-in I/O devices
• Timers/counters
• GPIO
• ADC
• Etc.
– Sometimes we need more . . .
– Options
• Get a microcontroller with a different mix of I/O
• Get a microcontroller with expansion capability
– Parallel memory bus (address and data) exposed to the outside world
– Serial communication to the outside world
Project: Anti-Lock Brake System
• External PWM units
– Design a system to control a digital
– Solution: design a PWM unit
Project: Anti-Lock Brake System
• External PWM FSM Controller
Project: Anti-Lock Brake System
• External PWM software

You might also like