0% found this document useful (0 votes)
153 views16 pages

STM32 Timers Tutorial - Hardware Timers Explained

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

STM32 Timers Tutorial - Hardware Timers Explained

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Pet coro Lem sT™Ma2 Bases Setting Up STM Teolchaln| Getting Stared vith STH22 sTw22 HAL Library (6PI0 Tuts} 15PI0 Output Die Togale Pn PIO Input asd Pi) SSTM22 RCC Reset led STM22 delay. us (wr Time) STM22 daly. us Search The srwa2 || eseaz || arouino || pic || electronics Website STM32 Microcontrollers Tutoria‘ Categories Categories Select Category 2 Subscribe To Our Newsletter To Get All New Updates STM32 Timers Tutorial | Hardware Timers Explained Kodoa aad Previous Tutorial, Tutorial 12 Next Tutorial STM32 Timers Tutorial stva2 Course Heme Page 222? Pune) aE) In this tutorial, well be discussing the STM32 timers modules in STM32 rricrocontrolies. There aze different hardware timers in STM32 microcontrollers each ean operate in mutiple modes and perform so many tasks. Youll get to know these different harcware varias and thir application use eases. And wo start with the timer ‘mode inthis tutorial, other modes are to be discussed later on. UL seers caste coe elo ‘A Timer Module in its most basic form is a digital logic circuit that counts up every clock cycle. More functionalities are implemented in here to support the timer module so it can count up or down. tean have a Proscaler to divide the input clock frequeney by a selectable value It can also have eicuity for input capture, PWM signal generation, land much more as well seein this tutorial Lots consider a basic 16-38 timer Ike the one shown below. As a 18-BR time, Rea count from 0 up to 65535, Every clock cycle, the value ofthe timer is incremented by 1. And at you ean 2ee, the Feys ls not the frequency that fs incrementing the timer module. Butt gats divided by the Prescaler, then it gets fed to the timer. TUN, an TENT. TimeriCounter Register Foye PC D Basically. in timer mode, the TCNT register is incremented by 1 each clock cycle @ the folowing frequency (Feys/PSC). This means if the Feys Is BOMHe & PSC is 41:1024, the TONT gets incremented by 1 every 12.8ySee. Therefor, if you stat this, timer to count from 0 uni it reaches overfiow (at 65595), i wil Give you an interrupt Signal onee every 0.839 Second What if need to set up tis ter to give me an interupt signal ence per 1 second? I dont want this O.898Sec time interval in fact. Well, fr this reason, there exists a possible hardware feature caled preload register that forces the timer to count from any arbtvarty chosen value up tothe overfiow. So, you ne longer have to start counting from zero. Hence, any time interval can be obtained with a timer module, AA timer module can also operate in @ counter mode where the clock source is not knoum, its actualy an extemal signal. Mayoe from a push button, so the counter gets incremented every rising of fang edge from the button press. This mode can be advantageous in numerous applications as well discuss hereafter. But for now, consider the folowing diagram, I TNT: TimerCounter Register hu Lu h se tah & ‘Where you can see, the clock signal is now diven from the push button and gets tothe timer clock input through the Prescaler. And you ean capture the information of how many times the buton is pressed by simply ading the TCNT registers value, ‘or more introductory Information about Timers Modules & Timer Preloading STM32 Timers Hardware 'STMieroslectronies provides some sifferent versions or variants forthe haréware timer modules. STM92 microcontollers usually have a handful of each type, however, some parts may lack one or more of these hardware timers, So, in his section, Pt highight ‘those timer modules and thei’ min festures, block diagram, and! things ike that Just to give you an overview of the different avalable hardware timers in STMS2 ‘microcontroller. So, you can have a better understanding of which type fs in which kind of applicatons. Which in tum helps you better pick the right MCU part for your Project. 2.1 Basic Timers Modules The basic timers consist of a 16-bit auto-relosd counter driven by a programmable Prescaler. They may be used as generic tmers for time-base generation but they aso specificaly used to drive the digta-to-analog converter (OAC). In fact, the tenors tre interaly connected to the DAC and are able to ckive @ through their tigger ‘outputs, The timers are completely independent and do not share any resources, Basic timer block diagram Basie timer Features include, + 16-b8 auto reload up-counter + 16-58 programmable Prescaler used to divide (also ‘on the fy’) the counter lock frequency by any factor between 1 end 65596 *+ Synchronization ciruit to tigger the DAC + IntortuptOMA generation on the update event: counter overfion ‘The main block ofthe programmable imer isa 16-bit up-counter wth ts related auto reload register. The counter clock can be divided by a Prascaler. The counter, the auto-eload register, and the Prescaler register can be wiiten orread by software. This, Is tue even when the counter running. The tme-base unt inchides: + Counter Register (TIM_CNT) + Prosealer Register (TINbx PSC) + Auto Reload Register (TIM_ARR) ‘The auto-reload register is preloaded. The preload register Is accessed each time an aiternpt is made to write or read the auto-eload register. The contants of the preload register are transferred into the shedow register permanently of at each update event UEV, depending on the auto-reload preload anable bit (ARPE), In counter mode, the counter counts from 0 to the auto-eload value (contents of the TIN&ARR register), then restarts from 0 and generates a counter overflow event. An Update event can be generated at each counter overlow or by seting the UG bitin the TINtx_EGR register (by software or by using te slave mode contol 2.2 Low-Power Timers Modules ron we uuuany aoverapirens et power consumption reduction. Thanks to is diversity of clock sources, the LPTIM is able to keep cunning in all power mades except for Standby mode. Given ts eapabilty to run ‘oven wth no intemal clock souree, the LPTIM ean be used as a “Pulse Courter’ whieh ean be useful in some appctions. ‘Also, the LPTIM capability to wake up the system from low-power modes makes it suitable to realize “Tmeout functions’ with extremely low power consumption, The LLPTIM introduces a fexbe clock scheme that provides the needed functionaites end Performance while minimizing power consumption. Low-power tier block diagram for STMS2LASeedAbereASeeK46ee roy ——__ 2 ET ear SOFT 2 [eames FNAL] SS Paes hal oo Le “silos ee | a The Low Power Timers (LPTIM) Main Feature: + 16-bit up-counter + 9-bi Presealer with 8 possible cviding factors (1,24,8,10,92,04,128) + Selectable clock Ineomalelock sources: LSE, LSI, HSI16 or APB clock ~ External clock source over LPTIM input (working wah no LP oselistor runing, used by Pulse Counter eppcstion) TBbRARR auto-reload ragistor ‘16 bitcomoare register Contnous/One-shot mode Selectable sofvareharcvre input tigger Programmable Digtal Gitchfiter Configurable output: Puise, PWM Configurable 10 polarity Eneeder mode Repettion counter 2.3 General-Purpose Timers Modules ‘The general-purpose timers consist of a 16-bt autoreload counter diiven by a Programmable Prescaler. They may be used for a variety of purposes, including ‘measuring the puise lengths of input signals (input capture) or gonerting output waveforms (output compare and PWN). Pulse lengths and waveform periods can be ‘modulated from a few microseconds to several miliseconds using the timer Presealer and the RCC clock contoller Prascalets, The timers are completely independent and dort share any resources. Thay can be synchronized together as well \cenara-parpse ima block dagram General purpose TiMictier features incluse: ‘16:btup, down, upléown auto-eload counter ‘16:bt programmable Prescaler used to divide (also “on the fy’ the counter lock frequency by any factor between 1 and 65538, + Upto 4 independent channels for: Input capture = Ouiput compare = PWM generation (Eage- and Center-abgned modes) ~ One-pulse mode output + Synehvonization ekcut to contol the tmer with extemal signals and to Interconnect several ters. + lnterruptOMA generation on the following events: = Update: counter ovedlowtndertow, counter initabzation (by software ot internalextermal tigger) = Trigger event (counter star, stop, iniaization or count by intemalixternal = Output compere + Supports incremental (quadkature) encoder and alksensor citcutry for posttoning purpotes. *+ Trigger input for en external clock orcycle-by-cycle current management 2.4 Advanced-Control Timers Modules The advanced-contrl timers consist of @ 16-bit aulo-eload counter criven by a programmable Prescaler. It may be used for a varity of purposes, including measuring the pulse lengths of input signals (nput capture), or generating output waveforms (output compare, PWM, complementary PWM with dead-time inserton) Pulse lengths and waveform periods can be modulated from a few microseconds to several miliseconds using the tmer Prescaler and the RCC clock controler Prescalors. The advanced-control and general-purpose timers re completely independent and do not share any resources. They can be synchronized together as wel [Hal] Posten inciengsen oUt acini net Advanced-Contol Timers Features: s6-btup, down, upldown auto-eload counter, 16:be programmable Prescaler akowing diving (also “on the fy") the counter clock frequency either by any factor between 1 and 65536, Up to independent channels for = Input Capture = Ouput Compare = PWM generation (Edge and Center-aigned Moda} ~ One-pulse mode output Complementary outputs with programmable deac-ime ‘Syreonization cicut to contol the tmer with extemal signals and to interconnect several mers together. + Repettion counter to update the time cycles ofthe count, Breskinait to putthe tiers outout signals in a reset state or in a known stat. IntertspuOMA generation on the following events: = Update: counter overowndertiow, counter iialzaton (by sofware or internalextemal tigger) = Trigger event (counter start, stop, intiaization or count by intemalixternal tig = Input capture = Ouput compare Break input ‘+ Supports incremental (quadrature) encoder and hall-sensor circuitry for positoning purposes. *+ Trigger input for an external clock or cycle by-cycte current management 2.5 High-Resolution Timers Modules ‘The high-tesoluton timer can generate up to 10 digital signals with highly accurate ‘timings, It is prmanly intended to drive power conversion systems such as switeh- mode power supplies or lighting systems but can be of generalpupose usage, ‘whenever a very fine timing rsoluton is expected (up to 217pSec). For contol and montoring purposes, the tmer has also timing measure capabisties, and inks to built-in ADC and DAC converters. Last itfeatures a ightload management ‘mode ands abe to handle various fault schemes for safe shut-down purposes. High Resolution Timers (HRTIM) Features Include: + Highrresolition timing units ~217 ps resohiton, compensated against voltage and temperature variations ‘= Higivresoluton avaiable on all outputs, possibility to edhust dutycycle, ‘requeney and puise width in the tiggeredl ene-pulse mode ~ 6 16-08 timing unes (each one with an independent counter and 4 compare wmts) = 10 outputs that ean be controlled by any ting unt, upto 32 sebreset sources per channel Modular architecture to address either mutiple independent converters with 1 ‘r2 ewtehes or few large muit-evitch topologies Mutipe inks to buitn analog peripherals ~4 tiggers to ADC converters = 3 Wiggers to DAC converters = 3 comparators for analog signal conciioning Mutiple HRTIM instances can be synchronized with extemal synchronization Inputsourpute *+ Versatile output stage — Higtttesolution Deadtime insertion (down to 868 pSec) — Programmable output polity = Chopper mode Burst mode controller to handle ightioad operation synchronously on multiple converters + Tinterruptvectore, each one with up to 14 sources + 6 DMA requests with up to 14 sources, wth a burst mode for mutple registers update STM32 Timers Modes OF Operation ‘An STM2 timer modulo can operate in any of the folowing modes, however, you should not assume that a given timer does support all of these modes. Instead, youll have to check the datasheet to figure out which modes are supported by which timers. ‘As weve seen eavler, there are many groups of tmers which Include: General Purpose, LomPower, High-Resolution, Advanced-Contel timers. Each of which does ‘support a muliple ofthe following mocles, however, some timers do support most of ‘the operating modes. In this soction, well got just a brief description of each mode of operation. How it ‘works and what sort of applications It ts for. Each mode wil be discussed in-depth vith practical LAB experiments in fture tuterisls. But for today, well get into Timer Modlin sactiond and do Its LAB inthe next tutorial. Other modes wil be coming later on in ths series oftutorials 3.1 Timer Mode In timer mode, the timer module gets clocked fom an internal clock source with a known frequency. Hence the clocking frequency is knovmn, the overflow time can also be calevisted and controled by the preload register to get any arbitrarily chosen time interval. Each timer overflow the timer signals the CPU with an inteupt that indicates the end ofthe specified time interval ‘This mode of operation is usualy used to get a specific operation done each specific time interval And to achieve timing & sync between vatious tasks and events in the systom, Itean also replace delays in vaious situations for better system response. TUL Fos TENT. TimeriCounter Register wea (2) = 3.2 Counter Mode In counter mode, the timer module gets clocked fiom an external source (mer input pln}. So the timer counts up or down on each rising or fling edge of the external input ‘This mode is realy helpful in numerous stuations when you need to implement digtal counter without poling input pins or petiodicaly reading a GPIO or continuously interupt the CPU ifyoulve chosen te hook upto an EXTI pin You can setually monitor the counter value difference each time interval to tel how many pulses did occur or what was the frequency of IL Such @ mode can be advantageous in many situations tke this. And mote examples are to come in upcoming tora, Lio L TENT. TimerCounter Register oh Pe 2.3 PWM Mode In PWM mode, the timer module is clocked from an internal clock source and produces a digital waveform onthe output channel pin called the PWM signal By using output compare ragsters (OCR), the incrementing timers register value Is constantly compared against tis OCR register. When a match occurs the cutput pin state is finped uni the end of the petiod and the whole process is repeated, The timer in PWM made wil produce @ PWM signal a the specified frequency the user chose. The duty cyele is also programmatically contolled by its register. The PWM resolution is affected by the dested Fyn and other factors as well see in the dedicated tutorials for PWM ganeration. Vohage Se |! Duty Cycle: 10% 3.4 Advanced PWM Mode The sdvanced PWM signal generation refers to the hardware sbilty to contol more parameters and add some hardware cicuity fo support extra features forthe PWM. signal generation. Which includes: +The abity to produce a complementary PWM signa thats ypicay the same 2s ‘the PYM on the main channel but logicaly inverted (high potion becomes lw and vee versa. + The ably to bject deackime bend ia the PWM signal for motor driving sppleatons to prevent shootthvough curents thet result fom PWM signals everapping +The abity to perform auto-shutdown forthe PVM signal is also called “auto brake" which an mpotart feature fr safetseriical appieatons. + And the ably to phase-ajst the PIM signa, and much mor refered to as aevanced-PYiM consol All of tis is Here is an example for PWM channels with complementary waveform oufpu, with dead-band inserted, end phase-delay adjustment. typical control signal in halF-bridge mode, 3.5 Output Compare Mode In output compare mode, @ ter module contols an output waveform or indicates ‘when a petiod of tne has elapsed. When a match fs detected between the output ‘compare register (OCR) and the counter, the oulput compare function assigns the coresponcing output pin to a programmable valve defined by the output ‘compare mode defined by the programmer. ‘The output compare pin can be driven high, low, toggles its sate, or stay unchanged This is determined by the programmer as per the application requirements, This mode of operation can be extremely advantageous for generating tring signals an output tiving in many applications as well see in future tutorials Here is an example fora courting timer in output compare mode. Note when the output state is changed (toggled) and the value in the OCR (compare register TIM!_CCRI), ‘Output compare mode, togle on Ct 3.6 One-Pulse Mode COne-pulse mode (OPM) is a partcular case of the provious modes, It allows the counter to be sterted in response to a stimulus and to generate a pulse with a programmable length after a programmable dey. Stating the counter can be contrlled through the slave mode centroler. Generating the waveform ean be dene in output compare mode or PWM mode. ‘A pulse can be correcty generated only ifthe compare value Is ctferent from the counter inal value. Before stating (when the timer is waiting for the tigger), the configuration mast be CNT STWSEHALUDy Tut) STMGEPUM Phe SHreCimer STH apne Be Scenic «Erle Cod Fesutny Mearenent Exar 7 Fimerinparcaonre ose Share This Page With Your Network! Join Our +25,000 Newsletter Subscribers! Stay Updated With All Hew Content Releases You Also Get Occasional FREE Coupon Codes For Courses & Other Stuff a _) 2 badd Syste Embed Tur STME2 ARM, © sinszcore STlg2 Serial Communication With PC (TH UART To US TR92 Tine Inert HAL eagle Timer Mode LAB Pee NE Ce eee eee embeded software and hardware design, | work as an embexkled ee ee ea Ls) ere eee er ) eee re net eee ee eee ee ee a ee a ec ee ee en ee ee ees eae Leave a Comment Name* Notify me of new posts by email Categories Search The Website Resources Select: ategory Vo mt 0 Se eet eddec oe ps mation at a oe 1d more k ST Rezo te always chow your support by shasing eee or ok that Se You Can Support Me Through This Link Ee eee ee ee Se eke eee c ee ok: ee ee a ee eee eee

You might also like