tkt-3500 microcontroller systems · tkt-3500 microcontroller systems ... #2/66 erno salminen - sep....
TRANSCRIPT
Erno Salminen - Sep. 2008
TKTTKT--3500 3500 Microcontroller Microcontroller systemssystemsLec Lec 55–– Timers and other peripherals, Timers and other peripherals, pulsepulse--width modulationwidth modulation
Erno SalminenErno Salminen
Department ofDepartment of Computer SystemsComputer SystemsTampere University of TechnologyTampere University of Technology
Fall 2008Fall 2008
Erno Salminen - Sep. 2008#2/66
SourcesSourcesRobert Reese, Microprocessors: From Assembly to C with the PIC18Fxx2, Charles River Media, 2005PIC18F8722 Family Data Sheet, Microchip Technology Inc.Tim Wilmshurst, Designing Embedded Systems with PIC Microcontrollers –Principles and applications, Elsevier, 2007.WikipediaTotalPhase Knowledge Base - Article 10045
Erno Salminen - Sep. 2008#3/66
ContentsContentsIntegrated peripherals of PIC18Timers
StructureUsageAccuracyCo-operation with capture/compare/PWM module
Pulse-width modulation (PWM)Short notes about motor control
Erno Salminen - Sep. 2008#4/66
Brown-out and hi/low voltage detectors10-bit AD-converterTwo enhanced USART modules (RS-232 or RS-485)
Two master synchr. serial port modules (I2C+ SPI)
Two 8-bit and three 16-bit timersSix capture/comparator/PWM modulesDigital IO
General-purpose, bidirectional pinsUser can select the direction: input/outputCan be used for parallel communication and for controlling external devices
data busPIC18LF8722 PIC18LF8722 integrated integrated peripheralsperipherals
Erno Salminen - Sep. 2008#5/66
Configuration bitsConfiguration bitsThe configuration bits select various device configurations
Oscillators, bus and mem modes, code protectionThey are either
programmed (read as ‘0’)left unprogrammed (read as ‘1’)
These bits are mapped starting at program memory location 300000h
configuration memory space (300000h-3FFFFFh) is beyond the user program memory spacecan only be accessed using table reads and table writes
Erno Salminen - Sep. 2008#6/66
Configuration bits (2)Configuration bits (2)Programming the Configuration registers is done in a manner similar to programming the Flash memory. 12 configuration and 2 devide ID registers
oscillator and clockbrown-out and power-upwatchdogCPU and bus modesmaster clear, timer+CCP
code protectionmiscellaneous
code protectionwrite protectionwrite protectiontable read protectiontable read protectiondevice id (read-only)
Configured properties
Erno Salminen - Sep. 2008#7/66
BrownBrown--out reset (BOR)out reset (BOR)Resets microcontroller when voltage is too lowPower lines (wires) have some resistance RCPU draws current I and hence Vdd = Vs – RI
Current I depends on internal activity of CPU
With large current I, the Vdd drops too muchLogic gets slower resulting in malfunctionMem write may corrupt mem contents, better reset the CPU
CPUCPU
Vdd
R > 0+-Vs
I
voltage
time
Vs
Vdd
Achtung! Reset der CPU!
V > 0
Erno Salminen - Sep. 2008#8/66
BOR (2)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 initializationRead both status bits BOR and POR (power-on reset)BOR==0 and POR==1 is quite reliable indication of brown-out reset
Erno Salminen - Sep. 2008#9/66
HighHigh--Low voltage detect (HLVD)Low voltage detect (HLVD)Informs when voltage is too high/low
Interrupt flag is set
Programmable circuitUser sets
Trip point (voltage level)Direction (rising/falling)
Controlled shut-down can be performed before voltage drops critically low
data bus
Erno Salminen - Sep. 2008#10/66
HLVD structure and lowHLVD structure and low--Vdd detectionVdd detection
each node forms one trip point
select one trip point
comparator:
trip point vs. ref voltage
Batte
ry
Start shut-down if Vdd drops here
Minimum valid Vdd
Time margin
for shut-down
Voltage direction magnitude
brown-out reset
enable
Erno Salminen - Sep. 2008#11/66
HLVD operationHLVD operation
internal ref. votlage stable
Erno Salminen - Sep. 2008#12/66
HLVD cntd.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 checkedAfter 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
Erno Salminen - Sep. 2008#13/66
data bus
Analog input/outputAnalog input/outputAnalog-to-digital conversion (ADC)
Requires own reference voltage inputs 10-bit conversion means 1024 distinct signal levels16 channels, at sample rate ~1 MhzDepends on microcontrollers clock frequency
Discussed in more detail in lecture 6 together with analog comparators
t
v
analog signal
digital signal
1
12345678
2 3 4 5 6 7 8 9 10 11 12
Erno Salminen - Sep. 2008#14/66
Serial portsSerial ports2*EUSART (Enchanced Universal Synchronous Asynchronous Receiver Transmitter)
Module for eg. RS-232 or RS-485 transmissionsLecture 3
2xMSSP (Master Synchronous Serial Port)i2c and SPI in the same port
Covered in lectures 3+4data bus
Erno Salminen - Sep. 2008#15/66
Timers, Watchdog, realTimers, Watchdog, real--time clocktime clockTimers1. Measuring duration of tasks and waveforms of input signals2. Generating timed events and output signals3. Counting input events
Usually several 8-bit and 16-bit timers, 5 in PIC18The input clock may be selected
Watchdog timer (WDT)Special purpose: reset the CPU unless regularly taken care offA program gone mad (stuck in infite loop etc) cannot service WDT and CPU will get rebooted
Real-time clockTimer for implementing ”wall clock” or calendar functionalityNeeds special power (battery) to keep the time
data bus
Erno Salminen - Sep. 2008#16/66
(Enhanced) Capture/Compare/PWM(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
CompareCompares register value to the timer value. When they are same wanted event occurs
PWMModule for creating Pulse Width Modulation signalsECCP includes eg. user selectable polarity etc.
Erno Salminen - Sep. 2008
Structure of timersStructure of timers
Erno Salminen - Sep. 2008#18/66
Timer basicsTimer basicsTimer is a counter
usually count upwardswhen enabled, counter_r <= counter +1;
The values are also called timer ticksEasily converted to wall-clock time when the period of tick is knownIn PIC, the counters are 8-bit and 16-bits wide
The value ranges are [0,255] and [0, 65535] ticks
new value
counter_r++
enwe clk
Erno Salminen - Sep. 2008#19/66
Timer basics (2)Timer basics (2)Longest delay obtained directly is 2n * (1/f)Assume f=40 MHz
8-bit: 28 * (1/40) = 255 * 25ns = 6.372 us16-bit: : 216 * 25 ns = 1638.4 us = 1.6384 ms
Rather short time!use lower frequency by scaling down the CPU clkmax delay becomes 2n * (1/(f/i))
Scale-factor is typically power of 2
Erno Salminen - Sep. 2008#20/66
clk/2
Clock dividerClock dividerSimple 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 clkMust synchronize the clocks
clk
...clk/4 clk/8
Erno Salminen - Sep. 2008#21/66
clk
synchronizer
Clock divider Clock divider –– with synchronizationwith synchronization
...clk/2 clk/4 clk/8
clk
synh
cron
ized
, div
ided
clo
cks
Erno Salminen - Sep. 2008#22/66
PICPIC’’s timerss timersPIC18 has 5 timers
both 8-bit and 16-bit all have readable register(s) for current valueall have writable register(s) to set the new valueall 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
++
Erno Salminen - Sep. 2008#23/66
PICPIC’’s timerss timersMinor differences in their usage
generate interrupt whena) overflow occursb) value is equal to match register
which clocks can be usedwhat kind of frequency scaling is allowedsome can be automatically reset due to special even trigger Timer2 allows optional use as the shift clock for the MSSPx module
Erno Salminen - Sep. 2008#24/66
Timer1 and 3 subsystemsTimer1 and 3 subsystems16-bit susbsystems with identical capabilities
Two 8-bit registers for valueAdditional clocking options possible
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
Erno Salminen - Sep. 2008#25/66
Timer1Timer1Can act in three modes1) Timer – incremented on every instruction cycle2,3) Synchronous/Asynchronous Counter – incremented on
every edge of external clk or Timer1 oscillatorReading from TMR1L (lower byte) will update the value of TMR1Hbuffer
User gets all the 16-bits accuratelyOtherwise, TMR1H would have been incremented before it is read and hence become invalid
Writing 1. Write the new high byte first into buffer2. Write the TMR1L – this will update also the counter’s high
byte from the bufferBoth bytes are written at the same time
Erno Salminen - Sep. 2008#26/66
Timer1 OscillatorTimer1 OscillatorAn on-chip crystal oscillator circuit between pins T1OSI (in) and T1OSO (amplifier output)Can be used as CPU’s clk sourceLow-power circuit rated for 32.768 kHz crystal
Continue to run during all power-managed modesOften 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 intervalIn ISR, increment the counter variables for seconds, minutes, hours and so onAsynchronous mode is more accurate
Erno Salminen - Sep. 2008#27/66
Timer1 Oscillator (2)Timer1 Oscillator (2)Enabling the amplifier improves noise immunity but increases powerLow-power nature makes the oscillator sensitive to rapidly changing signals in close proximity
Oscillator circuit must be located very close to CPU 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
Erno Salminen - Sep. 2008#28/66
Timer2Timer2Always clocked with instruction cycle clock8-bit counter with both pre- and post scalersCompares when counter reaches value of period register PR2
Matches are ”post-scaled” before generating an interrupt
Erno Salminen - Sep. 2008#29/66
Timer2 (2)Timer2 (2)Counter is reset after each matchInterrupt period becomes
tTMR2_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
Erno Salminen - Sep. 2008#30/66
Timer2 (2)Timer2 (2)Again, rounding causes errors in timing
Similar to baud rate generation
Alas! This is still way better than implementing delay with dummy SW loop
Erno Salminen - Sep. 2008
Usage of timers and Usage of timers and capture/compare/PWM capture/compare/PWM modulesmodules
Erno Salminen - Sep. 2008#32/66
Shape of things to come in this lectureShape of things to come in this lecture
Example use cases1. Time keeping2. Switch debounce3. Pulse width measurement4. Square wave generation5. (Infrared decoding omitted, see the book)Accuracy considerations and usage of CCP modules
Intertwined into examplesPulse-width modulation (PWM)
Erno Salminen - Sep. 2008#33/66
Example1: Time keeping Example1: Time keeping -- ISRISRTwo seconds have passed when overflow occurs
Variable secs is also a semaphore
Erno Salminen - Sep. 2008#34/66
Ex1: mainEx1: main
Terminal SW on PC:
Erno Salminen - Sep. 2008#35/66
Example2: switch debounceExample2: switch debounceEarlier example used SW delay to implement switch debounceHere, Timer2 is configured to generate periodic interrupts
5 interrupts with ~6 ms period yield appropriate delay24ms – 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
Erno Salminen - Sep. 2008#36/66
Ex2: Switch debounce Ex2: Switch debounce –– main()main()
1
Erno Salminen - Sep. 2008#37/66
Ex2: Switch debounce Ex2: Switch debounce -- ISRISR
{ }
{}
2
3
4
Erno Salminen - Sep. 2008#38/66
Ex3: Pulse width measurementEx3: Pulse width measurementBasic version of measuring time between two external events (fall/rise of signal)
Erno Salminen - Sep. 2008#39/66
...
Ex3: Pulse width measurement (2)Ex3: Pulse width measurement (2)Pulse width = TMR0 * (tOSC * 4 * PRE)Accuracy defined by tOSC and PREThere 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
latencyISR latencyISRreset timer
get timer value TMR0
0Timer0 w/ PRE=4
1 2 34
Erno Salminen - Sep. 2008#40/66
Ex3: min/max pulse widthsEx3: min/max pulse widthsLet’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=1Maximum: set TMR0=216-1
wpulse,max = 65535 * (25 ns * 4 * 1) = 6 553 500 ns = 6.6 ms
Minimum: set TMR0=1wpulse,min = 1 * (25 ns * 4 * 1) = 100 nsThis is also the resolution – the minimum difference between pulses that can be observed
Erno Salminen - Sep. 2008#41/66
Ex3: min/max pulse widthsEx3: min/max pulse widthsChanging interrupt sensitivity from falling to rising edge requires several instructionsMin pulse width must be larger than 100 ns = 1 instrcution cycleWe could increase prescaler: For example with PRE=256
min pulse becomes 256*100 ns = 25.6 usmax pulse becomes 256*6.6 ms = 1.68 s
Increasing the prescaler extends maximum pulse widthbut reduces precision
Erno Salminen - Sep. 2008#42/66
Ex3: min/max pulse widthsEx3: min/max pulse widthsStill, previous example is accurate enough for human-interface such as buttonToo inaccurate for sqaure-wave measurement in the range of ten to hundreds of kHzMoreover,
the time from falling edge to timer reset is not includedthe time after rising edge to timer read is included
These times are likely the almost the same if interrupts are always enabledNo matter which scheme you, analyze the limitationsNext we discuss using CCP modules to enahnce pulse measurement
Erno Salminen - Sep. 2008#43/66
(Enhanced) Capture/Compare/PWM(Enhanced) Capture/Compare/PWMTwo Capture/Compare/PWM (CCP) modulesThree Enhanced Capture/Compare/PWM (ECCP) modules:
One, two or four PWM outputs per ECCPEnhancements: Selectable polarity, Programmable dead time, Auto-Shutdown and Auto-Restart, Half-Bridge and Full-Bridge Output modesEnhanced modes are not considered on this course
User can of course select which timer is the source
Erno Salminen - Sep. 2008#44/66
Capture/Capture/Compare/PWMCompare/PWM operationoperation
1. Event (edge) occurs in CCCP42. Interrupt flag is set3. Timer value is stored into register
Benefit: value is captured immediately and not after interrupt latency
Erno Salminen - Sep. 2008#45/66
Enhanced Ex3: pulse width with captureEnhanced Ex3: pulse width with capture
Measured pulse is now fed into pin CCP1Capture module reads the value of Timer1There’s no interrupt latency prior to readingNote that timer is not reset at any point
It is always in operationWe calculate the difference between tic samples
Erno Salminen - Sep. 2008#46/66
EEx3: handling timer overflowsEEx3: handling timer overflowsIn no overflow occurs (short pulse), the difference between captured values defines the pulse width directlyIn general case, we must record how many overflows occurs between captures
Erno Salminen - Sep. 2008#47/66
EEx3: ISREEx3: ISR
Erno Salminen - Sep. 2008#48/66
EEX1: mainEEX1: main
Erno Salminen - Sep. 2008#49/66
CaptureCapture/Compare//Compare/PWMPWM operationoperation1. Timer value matches the value of compare register2. Interrupt flag is set3. Event (edge) is generated into CCP4
Driven high/low, toggled, driven latched value4. Special event trigger notifies other modules, e.g. to
start AD converter or to reset the base timerBenefit: event is generated immediately and not after interrupt latency
Erno Salminen - Sep. 2008#50/66
CaptureCapture/Compare//Compare/PWMPWM operation (2)operation (2)Periodic interrupt generationIn simple time keeping code, the timer overflowed once every 2 secondsTo update secs variable every second
load CCPR1 register with 0x8000 = 32Kuse special event register to reset Timer1 on matchtrigger interrupt with flag CCP1IF instead of overflowincrement secs varibale by 1 instead of 2
Erno Salminen - Sep. 2008#51/66
EEX3: mainEEX3: mainVery small changes to dummy version
Erno Salminen - Sep. 2008#52/66
Ex4: Square wave generation with compare Ex4: Square wave generation with compare modemode
1. Let timer run for half period of the desired square wave
2. Toggle (invert) the output signal’s valueDone automagically by CCP!
Erno Salminen - Sep. 2008#53/66
Ex4: approach a) for ISR Ex4: approach a) for ISR Action: Reset timer to zero and wait for new matchNot too complicated but slightly wrong anywayReset takes just few cycles but they decrease the wave freq anyway
desired wave
real wave
Erno Salminen - Sep. 2008#54/66
Ex4: approach a) for ISR Ex4: approach a) for ISR Modify the compare register
Increment it by half period (HPERIOD)Never alter Timer1
Erno Salminen - Sep. 2008#55/66
Ex4: about false matchEx4: about false matchApproach b) updates the high byte of compare register before lowerWhy?
First match value 0x010ANext match value 0x20B5Updates in wrong order (i.e. lower byte first)
Avoids false match if half period is at least 2560x010A 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. oops
3
Erno Salminen - Sep. 2008#56/66
Pulse Width Modulation (PWM)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 deviceExample usages
brightness of a ledcontrolling a motor”poor man’s” digital-to-analog conversion
Erno Salminen - Sep. 2008#57/66
PWM as DACPWM as DAC
Shown RC network does low-pass filtering for signal.
since PIC’s output pin can source only few milliamps.
Erno Salminen - Sep. 2008#58/66
PWM as DAC (2)PWM as DAC (2)External operational amplifier (’opari’) provides large current drive capability than PIC’s outputSeries 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
Erno Salminen - Sep. 2008#59/66
Capture/CompareCapture/Compare/PWM operation/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
Erno Salminen - Sep. 2008#60/66
PWM for LEDPWM for LED
Erno Salminen - Sep. 2008#61/66
PWM for DC motorPWM for DC motorPWM regulates the current through power-FETDiode protects FET against voltage spikes due large inductance of a motor
FET is voltage-controlled, practically no current flows into gate
Erno Salminen - Sep. 2008#62/66
HH--bridge for DC motorbridge for DC motorMotor’s rotation direction depends on the direction of electrical currentFETs in opposite corners conduct at the same timePulse ratio defines the direction
The longer PWM phase defines directionsMotor keeps rotating but slows down during the other phase50%- 50% keeps the motor still
Current I when PWM signal is ’1’
Erno Salminen - Sep. 2008#63/66
Erno Salminen - Sep. 2008#64/66
Servo motorServo motorA servo motor does revolve freely but between two extreme positionsHere they are marked as
CW - clock-wiseCCW -counter clk-wise
mid
CWCCW
Erno Salminen - Sep. 2008#65/66
clock-wise
counter-clock-wise
Erno Salminen - Sep. 2008#66/66
ConclusionsConclusionsTimers are integral part of most microcontroller applicationsTimers 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