tkt-3500 microcontroller systems › kurssit › 3500 › s09 › lec › 3500...#4/64 brown-out and...
TRANSCRIPT
TKT-3500
Microcontroller
systems
Lec 4 – Timers and other peripherals,
pulse-width modulation
Ville Kaseva
Department of Computer Systems
Tampere University of Technology
Fall 2009
#2/64
Sources
Original slides by Erno Salminen
Robert Reese, Microprocessors: From Assembly
to C with the PIC18Fxx2, Charles River Media,
2005
PIC18F8722 Family Data Sheet, Microchip
Technology Inc.
Tim Wilmshurst, Designing Embedded Systems
with PIC Microcontrollers – Principles and
applications, Elsevier, 2007.
Wikipedia
TotalPhase Knowledge Base - Article 10045
#3/64
Contents
Integrated peripherals of PIC18
Timers
Structure
Usage
Accuracy
Co-operation with capture/compare/PWM module
Pulse-width modulation (PWM)
Short notes about motor control
#4/64
Brown-out and hi/low voltage detectors
10-bit AD-converter
Two enhanced USART modules (RS-232 or RS-485)
Two master synchr. serial port modules (I2C+ SPI)
Two 8-bit and three 16-bit timers
Six capture/comparator/PWM modules
Digital IO
General-purpose, bidirectional pins
User can select the direction: input/output
Can be used for parallel communication and for controlling
external devices
data bus
PIC18LF8722
integrated
peripherals
#5/64
Brown-out reset (BOR)
Resets microcontroller when voltage is too low
Power lines (wires) have some resistance R
CPU draws current I and hence Vdd = Vs – RI
Current I depends on internal activity of CPU
With large current I, the Vdd drops too much
Logic gets slower resulting in malfunction
Mem write may corrupt mem contents, better reset the
CPU
CPU
Vdd
R > 0+-
Vs
I
voltage
time
Vs
Vdd
Achtung! Reset der
CPU!
V > 0
#6/64
BOR (2)
Vdd is allowed to drop momentarily,
i.e. for a duration less than threshold time
theshold TBOR is, for example, 200 us
To detect BOR,
Reset POR to ’1’ immediately after any POR event
Read both status bits BOR and POR (power-on reset)
BOR==0 and POR==1 is indication of brown-out reset
#7/64
High-Low voltage detect (HLVD)
Informs when voltage is too high/low
Interrupt flag is set
Programmable circuit
User sets
Trip point (voltage level)
Direction (rising/falling)
Controlled shut-down can be performed before
voltage drops critically low
data bus
#8/64
HLVD structure and low-Vdd detection
each node
forms one
trip point
select one
trip point
comparator:
trip point vs. ref voltage
Battery
Start shut-
down if Vdd
drops here
Minimum valid
Vdd
Time
margin
for
shut-
down
Voltage direction
magnitude
brown-out
reset
enable
#9/64
HLVD operation
internal ref.
voltage stable
Low voltage
detect
High voltage
detect
#10/64
HLVD cntd.
When the module is enabled, the HLVD comparator and voltage divider are enabled and will consume static current To decrease the current requirements, the HLVD
circuitry may only need to be enabled for short periods where the voltage is checked
After doing the check, the HLVD module may be disabled
For example, the HLVD module could be periodically enabled to detect Universal Serial Bus (USB) attach or detach High-voltage detect when device uses, say 3.3V
and receives 5V from USB
#11/64
data bus
Analog input/output
Analog-to-digital conversion (ADC)
Requires own reference voltage inputs
10-bit conversion means 1024 distinct signal levels
16 channels, at sample rate ~1 Mhz
Depends on microcontrollers clock frequency
Discussed in more detail in lecture 9
t
v
analog
signal
digital
signal
1
1
2
3
4
5
6
7
8
2 3 4 5 6 7 8 9 10 11 12
#12/64
Serial ports
2*EUSART (Enchanced Universal
Synchronous Asynchronous Receiver
Transmitter)
Module for eg. RS-232 or RS-485 transmissions
Lecture 3
2xMSSP (Master Synchronous Serial Port)
i2c and SPI in the same port
Covered in lectures 3+5data bus
#13/64
Timers, Watchdog, real-time clock
Timers1. Measuring duration of tasks and waveforms of input signals
2. Generating timed events and output signals
3. Counting input events
Usually several 8-bit and 16-bit timers, 5 in PIC18
The input clock may be selected
Watchdog timer (WDT) Special purpose: reset the CPU unless regularly taken care off
A program gone mad (stuck in infite loop etc) cannot service WDT and CPU will get rebooted
Real-time clock Timer for implementing ”wall clock” or calendar functionality
Needs special power (battery) to keep the timedata bus
#14/64
(Enhanced) Capture/Compare/PWM
data bus
Enhanced Capture/Compare/PWM (ECCPx)
Capture Timer value is saved when event (rise, fall) is happened in
the corresponding capture pin
Compare Compares register value to the timer value. When they are
same wanted event occurs
PWM Module for creating Pulse Width Modulation signals
ECCP includes eg. user selectable polarity etc.
Structure of timers
#16/64
Timer basics
Timer is a counter
usually count upwards
when enabled, counter_r <= counter+1;
The values are also called timer ticks
Easily converted to wall-clock time when the period
of tick is known
In PIC, the counters are 8-bit and 16-bits wide
The value ranges are [0,255] and [0, 65535] ticks
new value
counter_r++
Counter
enableLoad
enableclk
counter
#17/64
Timer basics (2)
Longest delay obtained directly is 2n * (1/f)
Assume f=40 MHz
8-bit: 28 * (1/40) = 255 * 25ns = 6.372 us
16-bit: : 216 * 25 ns = 1638.4 us = 1.6384 ms
Rather short time!
use lower frequency by scaling down the CPU clk
max delay becomes 2n * (1/(f/i))
Scale-factor is typically power of 2
#18/64
clk/2
Clock divider
Simple chain of D flip-flops can divide the frequency
Each stage by 2, together by 2stages
DFFs do not use the same clock!
Each stage increases the phase difference between
clk/i and clk
Must synchronize the clocks
clk
...
clk/4 clk/8
#19/64
clk
synchronizer
Clock divider – with synchronization
...
clk/2 clk/4 clk/8
clk
syn
hcro
niz
ed, d
ivid
ed
clo
cks
#20/64
PIC’s timers
PIC18 has 5 timers
both 8-bit and 16-bit
all have readable register(s) for current value
all have writable register(s) to set the new value
all can generate interrupts
Block diagram of Timer0
operating in 8-bit mode
Clock
Selection
Instruction
clock
Clock Edge
Selection
Pre-scaler
setting
Pre-scaler
assignment
Value
register++
#21/64
PIC’s timers
Minor differences in their usage
generate interrupt when
a) overflow occurs
b) value is equal to match register
which clocks can be used
what kind of frequency scaling is allowed
some can be automatically reset due to special
event trigger
Timer2 allows optional use as the shift clock for
the MSSPx module
#22/64
Timer1 and 3 subsystems
16-bit susbsystems with identical capabilities
Two 8-bit registers for value
input pin for
on-chip osc.
input for ext.
clk/output pin of
on-chip osc.
TMR1L
May be reset by CCP
module
Timer1
oscillator
#23/64
Timer1
Can act in three modes1) Timer – incremented on every instruction cycle
2,3) Synchronous/Asynchronous Counter – incremented on every edge of external clk or Timer1 oscillator
Reading from TMR1L (lower byte) will update the value of TMR1Hbuffer
User gets all the 16-bits accurately
Otherwise, TMR1H could have been incremented before it is read and hence become invalid
Writing 1. Write the new high byte first into buffer
2. Write the TMR1L – this will update also the counter’s high byte from the buffer
Both bytes are written at the same time
#24/64
Timer1 Oscillator
An on-chip crystal oscillator circuit between pins T1OSI (in) and T1OSO (amplifier output)
Can be used as CPU’s clk source
Low-power circuit rated for 32.768 kHz crystal Continue to run during all power-managed modes
Often used for implementing real-time clk (RTC) Preload 16-bit counter with 32K = 215 so that the
overflow at 64K will occur with 1 second interval
In ISR, increment the counter variables for seconds, minutes, hours and so on
Asynchronous mode is more accurate
#25/64
Timer1 Oscillator (2)
Enabling the amplifier improves noise immunity but increases power
Low-power nature makes the oscillator sensitive to rapidly changing signals in close proximity Oscillator circuit must be located very close to MCU
No circuit should pass within the oscillator circuit boundaries other than VSS or VDD
If a high-speed circuit must be located near the Timer1 oscillator, a grounded guard ring around the oscillator circuit may be helpful
Fig. External components for
oscillator
Capacitor values 27pF are a starting point Check the specs of your
crystal/resonator
Higher C increases the stability but also the start-up time
#26/64
Timer2
Always clocked with instruction cycle clock
8-bit counter with both pre- and post scalers
Compares when counter reaches value of period register PR2
Matches are ”post-scaled” before generating an
interrupt
#27/64
Timer2 (2)
Counter is reset after each match
Interrupt period becomestTMR2_IF_per = ((tosc * 4) * PRE) * PR2) * POST (10.1)
Common usage of (any) timer is periodic interrupt generation to accomplish certain action at fixed time intervals tTMR2_IF_per
PR2 has largest range of the 3 adjustable parameters, solving it from (10.1) and rounding to integer gives
PR2 = -1
tTMR2_IF_per
((tosc * 4) * PRE) * POST
#28/64
Timer2 (2)
Again, rounding
causes errors in
timing
Similar to baud
rate generation
This is still way
better than
implementing
delay with
dummy SW loop
Usage of timers and
capture/compare/PWM
modules
#30/64
Shape of things to come in this lecture
Example use cases
1. Time keeping
2. Switch debounce
3. Pulse width measurement
4. Square wave generation
5. (Infrared decoding omitted, see the book)
Accuracy considerations and usage of CCP
modules
Intertwined into examples
Pulse-width modulation (PWM)
#31/64
Example1: Time keeping - ISR
Two seconds have
passed when overflow
occurs
Variable secs is also a semaphore
#32/64
Ex1: main
Terminal SW on PC:
#33/64
Example2: switch debounce
Earlier example used SW delay to implement switch debounce
Here, Timer2 is configured to generate periodic interrupts 5 interrupts with ~6 ms period yield appropriate delay
24ms – 30 ms, since timer’s start value is unknown when INT2 happens!
1
2
4
3 Wait until RB2 high and then 30 ms more
#34/64
Ex2: Switch debounce – main()
1
#35/64
Ex2: Switch debounce - ISR
{ }
{
}
2
3
4
#36/64
Ex3: Pulse width measurement
Basic version of measuring time between two
external events (fall/rise of signal)
#37/64
...
Ex3: Pulse width measurement (2)
Pulse width = TMR0 * (tOSC * 4 * PRE)
Accuracy defined by tOSC and PRE
There are few problems, however
1. Timer is reset and read in ISR and entering ISR
takes many cycles
2. What happens if Timer overflows?
RB0/INT0
time
...
...Timer0 w/ PRE=1
latencyISRlatencyISRreset timer
get timer
value
TMR0
0Timer0 w/ PRE=4
12 3
4
#38/64
Ex3: min/max pulse widths
Let’s calculate minimum and maximum pulse
widths that can be measured
Pulse width = TMR0 * (tOSC * 4 * PRE)
Assume tOSC = (1/40 MHz) = 25 ns and PRE=1
Maximum: set TMR0=216-1
wpulse,max = 65535 * (25 ns * 4 * 1) = 6 553 500 ns =
6.6 ms
Minimum: set TMR0=1
wpulse,min = 1 * (25 ns * 4 * 1) = 100 ns
This is also the resolution – the minimum
difference between pulses that can be observed
#39/64
Ex3: min/max pulse widths
Changing interrupt sensitivity from falling to rising edge requires several instructions
Min pulse width must be larger than 100 ns = 1 instrcution cycle
We could increase prescaler:
For example with PRE=256
min pulse becomes 256*100 ns = 25.6 us
max pulse becomes 256*6.6 ms = 1.68 s
Increasing the prescaler extends maximum pulse width
but reduces precision
#40/64
Ex3: min/max pulse widths
Still, previous example is accurate enough for
human-interface such as button
Too inaccurate for sqaure-wave measurement in the
range of ten to hundreds of kHz
Moreover,
the time from falling edge to timer reset is not included
the time after rising edge to timer read is included
These times are likely the almost the same if
interrupts are always enabled
No matter which scheme, you should analyze the
limitations
Next we discuss using CCP modules to enahnce
pulse measurement
#41/64
(Enhanced) Capture/Compare/PWM
Two Capture/Compare/PWM (CCP) modules
Three Enhanced Capture/Compare/PWM (ECCP) modules: One, two or four PWM outputs per ECCP
Enhancements: Selectable polarity, Programmable dead time, Auto-Shutdown and Auto-Restart, Half-Bridge and Full-Bridge Output modes
Enhanced modes are not considered on this course
User can of course select which timer is the source
#42/64
Capture/Compare/PWM operation
1. Event (edge) occurs in CCCP4
2. Interrupt flag is set
3. Timer value is stored into register
Benefit: value is captured immediately and
not after interrupt latency
#43/64
Enhanced Ex3: pulse width with capture
Measured pulse is now fed into pin CCP1
Capture module reads the value of Timer1
There’s no interrupt latency prior to reading
Note that timer is not reset at any point
It is always in operation
We calculate the difference between tic samples
#44/64
EEx3: handling timer overflows
In no overflow occurs (short pulse), the
difference between captured values defines
the pulse width directly
In general case, we must record how many
overflows occurs between captures
#45/64
EEx3: ISR
#46/64
EEX1: main
#47/64
Capture/Compare/PWM operation
1. Timer value matches the value of compare register
2. Interrupt flag is set
3. Event (edge) is generated into CCP4 Driven high/low, toggled, driven latched value
4. Special event trigger notifies other modules, e.g. to start AD converter or to reset the base timer
Benefit: event is generated immediately and not after interrupt latency
#48/64
Capture/Compare/PWM operation (2)
Periodic interrupt generation
In simple time keeping code, the timer
overflowed once every 2 seconds
To update secs variable every second
load CCPR1 register with 0x8000 = 32K
use special event register to reset Timer1 on
match
trigger interrupt with flag CCP1IF instead of
overflow
increment secs varibale by 1 instead of 2
#49/64
EEX3: main
Very small
changes to
dummy version
#50/64
Ex4: Square wave generation with compare
mode
1. Let timer run for half period of the desired
square wave
2. Toggle (invert) the output signal’s value
Done automagically by CCP!
#51/64
Ex4: approach a) for ISR
Action: Reset timer to zero and wait for new match
Not too complicated but slightly wrong anyway
Reset takes just few cycles but they decrease the wave freq anyway
desired wave
real wave
#52/64
Ex4: approach a) for ISR
Modify the compare register
Increment it by half period (HPERIOD)
Never alter Timer1
#53/64
Ex4: about false match
Approach b) updates the high byte of compare
register before lower
Why?
First match value 0x010A
Next match value 0x20B5
Updates in wrong order (i.e. lower byte first)
Avoids false match if half period is at least 256
0x010A 0x010B 0x010C
01 0A
Timer1
Compare reg
Calculating new value and
updating take a while
0x10B4 0x10B5
20 B501 B5
0x010D ...time
1 2Match + interrupt
01 B5
False match when compare reg
is in ”intermediate” state. oops3
#54/64
Pulse Width Modulation (PWM)
Pulse width modulation is technique that
varies the duty cycle of a square wave
signal while keeping the period fixed
Duty cycle refers to time when signal is ’1’
Duty cycle defines the average current
delivered to external device
Example usages
brightness of a led
controlling a motor
”poor man’s” digital-to-analog conversion
#55/64
PWM as DAC
Shown RC network does low-pass filtering for signal.
since PIC’s output pin can source only few milliamps.
#56/64
PWM as DAC (2)
External operational amplifier (’opari’)
provides large current drive capability than
PIC’s output
Series resistor + parallel capacitor slows
down the changes in signal level
Low-pass filtering - only the low frequency
component are let pass
Larger the time constant (RC product), lower
the cut-off frequency
RC defines the amount of ripple – voltage
variation
#57/64
Capture/Compare/PWM operation
CCP module has built-in capability for
constructing PWM modulated signals
Period register
defines the period
This register sets the
duty cycle
Next duty cycle is
written here to avoid
glitches
When duty cycle
ends, new val is
loaded from low reg
into hi reg
#58/64
PWM for LED
#59/64
PWM for DC motor
PWM regulates the current through power-
FET
Diode protects FET against voltage spikes
due large inductance of a motor
FET is voltage-controlled, practically no current flows into gate
#60/64
H-bridge for DC motor
Motor’s rotation direction depends on the direction of electrical current
FETs in opposite corners conduct at the same time
Pulse ratio defines the direction
The longer PWM phase defines directions
Motor keeps rotating but slows down during the other phase
50%- 50% keeps the motor still
Current I when
PWM signal is ’1’
#61/64
#62/64
Servo motor
A servo motor does revolve freely but
between two extreme positions
Here they are marked as
CW - clock-wise
CCW -counter clk-wisemid
CWCCW
#63/64
clock-wise
counter-
clock-wise
#64/64
Conclusions
Timers are integral part of most
microcontroller applications
Timers are used for
Measure external events (pulse-width, frequency)
Trigger timed actions (task execution, wave
generation, wakeup)
Pulse-width modulation
PIC has capture-compare-PWM modules that
increases the accuracy and convenience of
these tasks