TKT-3500 Microcontroller systems Lec 4 Timers and other peripherals, pulse-width modulation Ville Kaseva Department of Computer Systems Tampere University of Technology Fall 2010
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 #2/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 #3/64
PIC18LF8722 integrated peripherals data bus 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 #4/64
Brown-out reset (BOR) Vs + - 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 V > 0 R > 0 Vdd Logic gets slower resulting in malfunction Mem write may corrupt mem contents, better reset the CPU I CPU voltage Vs Vdd Achtung! Reset der CPU! time #5/64
BOR (2) Vdd is allowed to drop momentarily, i.e. for a duration less than threshold time theshold T BOR 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 #6/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 #7/64
Battery HLVD structure and low-vdd detection select one trip point Voltage direction magnitude Minimum valid Vdd each node forms one trip point Start shutdown if Vdd drops here comparator: trip point vs. ref voltage Time margin for shutdown brown-out reset enable #8/64
HLVD operation Low voltage detect High voltage detect internal ref. voltage stable #9/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 #10/64
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 v 8 7 6 5 analog signal digital signal data bus 4 3 2 1 1 2 3 4 5 6 7 8 9 10 11 12 t #11/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+5 data bus #12/64
Timers, Watchdog, real-time clock Timers 1. 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 time data bus #13/64
(Enhanced) Capture/Compare/PWM 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. data bus #14/64
Structure of timers
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 ++ counter counter_r new value #16/64 Load Counter clk enable enable
Timer basics (2) Longest delay obtained directly is 2 n * (1/f) Assume f=40 MHz 8-bit: 2 8 * (1/40) = 255 * 25ns = 6.372 us 16-bit: : 2 16 * 25 ns = 1638.4 us = 1.6384 ms Rather short time! use lower frequency by scaling down the CPU clk max delay becomes 2 n * (1/(f/i)) Scale-factor is typically power of 2 #17/64
Clock divider Simple chain of D flip-flops can divide the frequency Each stage by 2, together by 2 stages DFFs do not use the same clock! Each stage increases the phase difference between clk/i and clk Must synchronize the clocks... clk clk/2 clk/4 clk/8 #18/64
synhcronized, divided clocks Clock divider with synchronization... synchronizer clk clk/2 clk/4 clk/8 #19/64 clk
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 Instruction clock ++ Value register Clock Edge Selection Clock Selection Pre-scaler setting Block diagram of Timer0 operating in 8-bit mode Pre-scaler assignment #20/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 #21/64
Timer1 and 3 subsystems 16-bit susbsystems with identical capabilities Two 8-bit registers for value May be reset by CCP module TMR1L input for ext. clk/output pin of on-chip osc. input pin for on-chip osc. Timer1 oscillator #22/64
Timer1 Can act in three modes 1) 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 TMR1H buffer 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 #23/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 = 2 15 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 #24/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 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 Fig. External components for oscillator #25/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 #26/64
Timer2 (2) Counter is reset after each match Interrupt period becomes t TMR2_IF_per = ((t osc * 4) * PRE) * PR2) * POST (10.1) Common usage of (any) timer is periodic interrupt generation to accomplish certain action at fixed time intervals t TMR2_IF_per PR2 has largest range of the 3 adjustable parameters, solving it from (10.1) and rounding to integer gives t TMR2_IF_per PR2 = -1 ((t osc * 4) * PRE) * POST #27/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 #28/64
Usage of timers and capture/compare/pwm modules
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) #30/64
Example1: Time keeping - ISR Two seconds have passed when overflow occurs Variable secs is also a semaphore #31/64
Ex1: main Terminal SW on PC: #32/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 4 2 3 Wait until RB2 high and then 30 ms more #33/64
Ex2: Switch debounce main() 1 #34/64
Ex2: Switch debounce - ISR 2 3 } { { } 4 #35/64
Ex3: Pulse width measurement Basic version of measuring time between two external events (fall/rise of signal) #36/64
Ex3: Pulse width measurement (2) Pulse width = TMR0 * (t OSC * 4 * PRE) Accuracy defined by t OSC 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 Timer0 w/ PRE=1 1 latency ISR 2 3... reset timer... latency ISR 4 get timer value TMR0 Timer0 w/ PRE=4 0... time #37/64
Ex3: min/max pulse widths Let s calculate minimum and maximum pulse widths that can be measured Pulse width = TMR0 * (t OSC * 4 * PRE) Assume t OSC = (1/40 MHz) = 25 ns and PRE=1 Maximum: set TMR0=2 16-1 w pulse,max = 65535 * (25 ns * 4 * 1) = 6 553 500 ns = 6.6 ms Minimum: set TMR0=1 w pulse,min = 1 * (25 ns * 4 * 1) = 100 ns This is also the resolution the minimum difference between pulses that can be observed #38/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 #39/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 #40/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 #41/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 #42/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 #43/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 #44/64
EEx3: ISR #45/64
EEX1: main #46/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 #47/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 #48/64
EEX3: main Very small changes to dummy version #49/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! #50/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 #51/64
Ex4: approach a) for ISR Modify the compare register Increment it by half period (HPERIOD) Never alter Timer1 #52/64
Timer1 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 0x010D... 0x10B4 0x10B5 time Compare reg 01 0A 01 B5 01 B5 20 B5 1 2 Match + interrupt Calculating new value and updating take a while 3 False match when compare reg is in intermediate state. oops #53/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 #54/64
PWM as DAC since PIC s output pin can source only few milliamps. Shown RC network does low-pass filtering for signal. #55/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 #56/64
Capture/Compare/PWM operation Next duty cycle is written here to avoid glitches CCP module has built-in capability for constructing PWM modulated signals This register sets the duty cycle When duty cycle ends, new val is loaded from low reg into hi reg Period register defines the period #57/64
PWM for LED #58/64
PWM for DC motor PWM regulates the current through power- FET Diode protects FET against voltage spikes due large inductance of a motor #59/64 FET is voltage-controlled, practically no current flows into gate
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 #60/64
#61/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-wise mid CCW CW #62/64
clock-wise counterclock-wise #63/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 #64/64