Arduino Core for STM32  1.0
HardwareTimer Class Reference

Handle timers in interrupt mode really easy using this class.
In table below, you can see methods sections. More...

#include <HardwareTimer.h>

Collaboration diagram for HardwareTimer:

Public Member Functions

 HardwareTimer (TIM_HandleTypeDef &tim)
 Hardware timer constructor. More...
 
 HardwareTimer (TIM_TypeDef *instance)
 Hardware timer constructor. More...
 
 ~HardwareTimer ()
 Class destructor. More...
 
bool instanceExists (void)
 Checks if timer instance really exists and is based on real timer. More...
 
bool init (void)
 Initialize timer instance. More...
 
bool isInitDone (void)
 Checks if timer was initialized. More...
 
void deInit (void)
 Deinitialization of timer. More...
 
bool supportsSelectionCounterMode ()
 Setup methods Those methods have to be called before init(void) method to apply settings. More...
 
bool setCounterMode (uint32_t mode)
 Sets timer Counter Mode. More...
 
uint32_t getCounterMode (void)
 Gets timer Counter Mode. More...
 
TimerSettings setInterval_ns (uint64_t interval_ns)
 Easiest settings methods applied in real time. More...
 
TimerSettings setInterval (uint64_t interval_ms)
 Calculates period and prescaler and clock division from set interval. More...
 
uint64_t getInterval (void)
 Calculates interval from period, prescaler and timer clock division. More...
 
uint64_t getInterval_ns (void)
 Calculates interval from period, prescaler and timer clock division. More...
 
uint16_t getPrescaler (void)
 Basic settings methods applied in real time Those setting methods can be called every time, changes made by those methods are done in real time. More...
 
void setPrescaler (uint16_t factor)
 Sets prescaler that was set. More...
 
uint32_t getPeriod ()
 Gets period that was set. More...
 
void setPeriod (uint32_t val)
 Sets period that was set. More...
 
uint32_t getCount (void)
 Gets current value in counter register. More...
 
void setCount (uint32_t val)
 Sets new value to counter register. More...
 
void unlockSettings ()
 Advanced settings methods applied in real time Those setting methods can be called every time, changes made by those methods are done in real time. More...
 
void lockSettings ()
 Locks settings registers. More...
 
bool haveLockedSettings ()
 Checks if settings registers are locked. More...
 
void enableAutoReloadPreload (bool enable)
 When autoReloadPreload is enabled, timer is running and period was changed, the new value of period will be applied on counter reload. More...
 
bool isAutoReloadPreloadEnabled (void)
 Checks if autoReloadPreload is enabled. More...
 
bool is32BitTimer ()
 Checks if timer is 32bit or 16bit. More...
 
bool supportsClockDivision ()
 Checks if timer supports clock division. More...
 
bool setClockDivision (uint8_t division)
 Sets timer clock division. More...
 
uint8_t getClockDivision (void)
 Gets clock division value. More...
 
uint32_t getTimerClockFreq (void)
 Gets timer clock frequency before clock division. More...
 
uint32_t getDivTimerClockFreq (void)
 Gets timer clock frequency after clock division. More...
 
void pause (void)
 Timer control functions Those methods can be called just after init(void) method. More...
 
void stop (void)
 Stops timer. More...
 
bool resume (void)
 Resumes timer. More...
 
bool start (void)
 Starts timer. More...
 
TimerState state (void)
 Checks timer state. More...
 
void setCallback (void(*PeriodElapsedCallback_)())
 Sets callback function, that is called when timer period elapsed (interrupt). More...
 
uint8_t availableChannelsCount ()
 Get count of available channels. More...
 
TIM_HandleTypeDef & getHAL_TIM_Struct ()
 Returns timer structure, that is used for handling timer. More...
 

Static Public Member Functions

static void handleCallback (TIM_TypeDef *instance)
 Expert methods Those methods you probably don't need to call in basic timer operation. More...
 
static void handleCallback (uint32_t timerIndex)
 Handles callback function. More...
 
static uint32_t getTimerIndex (TIM_TypeDef *instance)
 Gets timer instance index, that is used in methods/attributes: handleCallback(TIM_TypeDef* instance), handleCallback(uint32_t timerIndex), getTimerInstances(), availableTimers[] when enabled. More...
 
static HardwareTimer ** getTimerInstances ()
 Gets array of all created timers instances (just from this class, not timer structure). More...
 
static uint8_t getAvailableTimersCount ()
 Gets available timer instances count. More...
 

Public Attributes

uint32_t setIntervalItLimit = 25
 Maximum iterations limit for interval calculation, that is done in method setInterval(). More...
 

Protected Member Functions

uint64_t CalculateTime_ns (uint32_t prescaler, uint32_t period, uint32_t timerFreq, uint8_t clockDiv)
 Calculates interval from period and prescaler and clock division. More...
 
uint64_t CalculateTime_ms (uint32_t prescaler, uint32_t period, uint32_t timerFreq, uint8_t clockDiv)
 Calculates interval from period and prescaler and clock division. More...
 
TimerSettings CalculateTimer (uint64_t ticks, uint32_t maxPrescaler, uint64_t maxPeriod, uint32_t minPeriod, uint32_t timerFreq, bool divEnabled, uint32_t maxIterations=UINT32_MAX)
 Calculates prescaler, period and timer clock division. More...
 
void addThisToInstArr ()
 Writes new class instance to array of all timer instances. More...
 
void removeThisFromInstArr ()
 Removes this instance from instances array. More...
 

Protected Attributes

TIM_HandleTypeDef createdTim
 We need this structure when calling HardwareTimer(TIM_TypeDef* instance) constructor, because we have to create new timer structure (TIM_HandleTypeDef). More...
 
TIM_HandleTypeDef & _tim = createdTim
 Timer structure (which include timer instance) that we will use to handle timer. More...
 
bool initDone = false
 This flag is true when init(void) method was successfully called. More...
 
void(* TIMPeriodElapsedCallback )() = NULL
 Pointer to callback function, that is called on timer interrupt(overflow or underflow event). More...
 

Static Protected Attributes

static HardwareTimerinstances []
 Array of all created timers instances (just from this class, not timer structure). More...
 
static uint8_t availableTimersCount
 Available timer instances count. More...
 

Detailed Description

Constructor & Destructor Documentation

◆ HardwareTimer() [1/2]

HardwareTimer::HardwareTimer ( TIM_HandleTypeDef &  tim)

Hardware timer constructor.

To check if timer exists and can be used call an instanceExists() method. This constructor ACCEPT timer settings done in .ioc file.

Parameters
timHal timer structure (e.g. htim1, htim2,...)

◆ HardwareTimer() [2/2]

HardwareTimer::HardwareTimer ( TIM_TypeDef *  instance)

Hardware timer constructor.

To check if timer exists and can be used call an instanceExists() method. This constructor IGNORE timer settings done in .ioc file.

Parameters
timHal timer instance (e.g. TIM1, TIM2,...)

◆ ~HardwareTimer()

HardwareTimer::~HardwareTimer ( )

Class destructor.

Member Function Documentation

◆ instanceExists()

bool HardwareTimer::instanceExists ( void  )

Checks if timer instance really exists and is based on real timer.

Returns
Returns true when timer exists.

◆ init()

bool HardwareTimer::init ( void  )

Initialize timer instance.

Before initialization can be called some methods to change default settings. It also enables timer clock and interrupt.

Note
To temporary sleep timers use deInit method and to wake it up use init(void) method. It will restore all settings, so you do not need to set nothing again.
Returns
Returns true when initialization was successful.

◆ isInitDone()

bool HardwareTimer::isInitDone ( void  )

Checks if timer was initialized.

Returns
Returns true when timer was initialized yet.

◆ deInit()

void HardwareTimer::deInit ( void  )

Deinitialization of timer.

Interrupts and timer clocks will be disabled.

◆ supportsSelectionCounterMode()

bool HardwareTimer::supportsSelectionCounterMode ( )

Setup methods Those methods have to be called before init(void) method to apply settings.

Checks if timer supports selection of Counter Mode.

Returns
Returns true when timer supports selection of Counter Mode.

◆ setCounterMode()

bool HardwareTimer::setCounterMode ( uint32_t  mode)

Sets timer Counter Mode.

In every mode, interrupt is called when timer overflow or underflow.

Parameters
modeSelected Counter Mode
ModesExplanationIs default
TIM_COUNTERMODE_UPCounting starts incrementing in 0 and is reloaded in selected period.Default
TIM_COUNTERMODE_DOWNCounting starts decrementing in selected period and is reloaded in 0.
TIM_COUNTERMODE_CENTERALIGNED1The counter counts up and down alternatively.
Output compare interrupt flags of channels configured in output (CCxS=00 in TIMx_CCMRx register) are set only when the counter is counting down.
TIM_COUNTERMODE_CENTERALIGNED2The counter counts up and down alternatively.
Output compare interrupt flags of channels configured in output (CCxS=00 in TIMx_CCMRx register) are set only when the counter is counting up.
TIM_COUNTERMODE_CENTERALIGNED3The counter counts up and down alternatively.
Output compare interrupt flags of channels configured in output (CCxS=00 in TIMx_CCMRx register) are set both when the counter is counting up or down.
Returns
Returns true when timer counter mode was set successfully.

◆ getCounterMode()

uint32_t HardwareTimer::getCounterMode ( void  )

Gets timer Counter Mode.

Returns
Returns timer Counter Mode

◆ setInterval_ns()

TimerSettings HardwareTimer::setInterval_ns ( uint64_t  interval_ns)

Easiest settings methods applied in real time.

Those setting methods can be called every time, changes made by those methods are done in real time.

Calculates period and prescaler and clock division from set interval. This method can take a long time, especially at longer intervals. Period and prescaler is set only when macro CTS_IS_OK(status) returns true. When you change timer clock or timer clock division, you should to call this function again to recalculate parameters.

Note
At long intervals, this method can take a lot of time. We recommend to use it only in some setup code and try to not call it frequently.
Parameters
interval_nsInterval in nanoseconds, so minimal resolution is 1 ns. 1 second is then 1 000 000 000ULL. Maximum value depends from periphery bus frequency and timer type.
Returns
Returns structure with calculated parameters and calculation status.

◆ setInterval()

TimerSettings HardwareTimer::setInterval ( uint64_t  interval_ms)

Calculates period and prescaler and clock division from set interval.

This method can take a long time, especially at longer intervals. Period and prescaler is set only when macro CTS_IS_OK(status) returns true. When you change timer clock or timer clock division, you should to call this function again to recalculate parameters.

Note
At long intervals, this method can take a lot of time. We recommend to use it only in some setup code and try to not call it frequently.
Parameters
interval_msInterval in milliseconds, so minimal resolution is 1 ms. 1 second is then 1000. Maximum value depends from periphery bus frequency and timer type.
Returns
Returns structure with calculated parameters and calculation status.

◆ getInterval()

uint64_t HardwareTimer::getInterval ( void  )

Calculates interval from period, prescaler and timer clock division.

Note
When you change timer clock frequency or timer clock division, you should to calculate it again.
Returns
Returns calculated timer interval in milliseconds.

◆ getInterval_ns()

uint64_t HardwareTimer::getInterval_ns ( void  )

Calculates interval from period, prescaler and timer clock division.

Note
When you change timer clock frequency or timer clock division, you should to calculate it again.
Returns
Returns calculated timer interval in nanoseconds.

◆ getPrescaler()

uint16_t HardwareTimer::getPrescaler ( void  )

Basic settings methods applied in real time Those setting methods can be called every time, changes made by those methods are done in real time.

Gets prescaler that was set. Prescaler begins in 0 and maximum value is 65535. When prescaler 0 is set, counter is prescaled by 1, etc.

Returns
Returns prescaler that was set.

◆ setPrescaler()

void HardwareTimer::setPrescaler ( uint16_t  factor)

Sets prescaler that was set.

Prescaler begins in 0 and maximum value is 65535. When prescaler 0 is set, counter is prescaled by 1, etc. Keep this value as small as possible to achieve best accuracy.

◆ getPeriod()

uint32_t HardwareTimer::getPeriod ( )

Gets period that was set.

Period begins in 0 and maximum value is TIMER_16BIT_MAX_PERIOD for 16 bit timers and TIMER_32BIT_MAX_PERIOD for 32 bit timers. When period 0 is set, counting is restarted when reach 1, etc. Keep this value above 5 or more. This value should to be more than prescaler, to achieve best accuracy. Alternative names of period: overflow, autoreload. When autoReloadPreload is enabled and timer was started, then this value is applied after reloading(reseting) counter register.

Returns
Returns prescaler that was set.

◆ setPeriod()

void HardwareTimer::setPeriod ( uint32_t  val)

Sets period that was set.

Period begins in 0 and maximum value is TIMER_16BIT_MAX_PERIOD for 16 bit timers and TIMER_32BIT_MAX_PERIOD for 32 bit timers. When period 0 is set, counting is restarted when reach 1, etc. Keep this value above 5 or more. This value should to be more than prescaler, to achieve best accuracy.

Returns
Returns prescaler that was set.

◆ getCount()

uint32_t HardwareTimer::getCount ( void  )

Gets current value in counter register.

Returns
Returns current value in counter register.

◆ setCount()

void HardwareTimer::setCount ( uint32_t  val)

Sets new value to counter register.

◆ unlockSettings()

void HardwareTimer::unlockSettings ( )

Advanced settings methods applied in real time Those setting methods can be called every time, changes made by those methods are done in real time.

Unlocks settings registers. Settings registers are defaultly unlocked. Affected methods: setInterval(uint32_t interval), setPrescaler(uint16_t factor), setPeriod(uint16_t val), setCount(uint16_t val), setClockDivision(uint8_t division), enableAutoReloadPreload(bool enable)

◆ lockSettings()

void HardwareTimer::lockSettings ( )

Locks settings registers.

Affected methods: setInterval(uint32_t interval), setPrescaler(uint16_t factor), setPeriod(uint16_t val), setCount(uint16_t val), setClockDivision(uint8_t division), enableAutoReloadPreload(bool enable)

◆ haveLockedSettings()

bool HardwareTimer::haveLockedSettings ( )

Checks if settings registers are locked.

Returns
Returns true when settings registers are locked.

◆ enableAutoReloadPreload()

void HardwareTimer::enableAutoReloadPreload ( bool  enable)

When autoReloadPreload is enabled, timer is running and period was changed, the new value of period will be applied on counter reload.

Parameters
enableTrue to enable and false to disable autoReload preload. AutoReload preload is enabled by default.

◆ isAutoReloadPreloadEnabled()

bool HardwareTimer::isAutoReloadPreloadEnabled ( void  )

Checks if autoReloadPreload is enabled.

Returns
Returns true when autoReloadPreload is enabled.

◆ is32BitTimer()

bool HardwareTimer::is32BitTimer ( )

Checks if timer is 32bit or 16bit.

Returns
Returns true when timer supports 32-bits period value.

◆ supportsClockDivision()

bool HardwareTimer::supportsClockDivision ( )

Checks if timer supports clock division.

Returns
Returns true when timer supports clock division.

◆ setClockDivision()

bool HardwareTimer::setClockDivision ( uint8_t  division)

Sets timer clock division.

Division is set to 1 by default.

Parameters
divisionClock division. Possible values are: 1, 2, 4
Returns
Returns true when Clock division was set.

◆ getClockDivision()

uint8_t HardwareTimer::getClockDivision ( void  )

Gets clock division value.

Returns
Returns 0 - on error, 1,2,4 (clock division values) - on success

◆ getTimerClockFreq()

uint32_t HardwareTimer::getTimerClockFreq ( void  )

Gets timer clock frequency before clock division.

Returns
Returns timer clock frequency before clock division in Hz.

◆ getDivTimerClockFreq()

uint32_t HardwareTimer::getDivTimerClockFreq ( void  )

Gets timer clock frequency after clock division.

Returns
Returns timer clock frequency after clock division in Hz.

◆ pause()

void HardwareTimer::pause ( void  )

Timer control functions Those methods can be called just after init(void) method.

Pauses timer. Counter won't be reseted.

◆ stop()

void HardwareTimer::stop ( void  )

Stops timer.

Counter will be reseted.

◆ resume()

bool HardwareTimer::resume ( void  )

Resumes timer.

Counter will continue from last value in counter register.

Returns
Returns true when timer was resumed successfully

◆ start()

bool HardwareTimer::start ( void  )

Starts timer.

Counter will be reseted.

Returns
Returns true when timer was started successfully

◆ state()

TimerState HardwareTimer::state ( void  )

Checks timer state.

Returns
Returns timer state.
See also
TimerState

◆ setCallback()

void HardwareTimer::setCallback ( void(*)()  PeriodElapsedCallback_)

Sets callback function, that is called when timer period elapsed (interrupt).

Parameters
PeriodElapsedCallback_void function with no parameters, that will be called when timer period elapsed or NULL to ignore interrupt.

◆ handleCallback() [1/2]

static void HardwareTimer::handleCallback ( TIM_TypeDef *  instance)
inlinestatic

Expert methods Those methods you probably don't need to call in basic timer operation.

Handles callback function. This method have to be included in timer interrupt function.

Parameters
instanceTimer instance which callback function will be called. (values: TIM0, TIM1, TIM2, ...)

◆ handleCallback() [2/2]

static void HardwareTimer::handleCallback ( uint32_t  timerIndex)
inlinestatic

Handles callback function.

This method have to be included in timer interrupt function.

Note
This overload method is the fastest one.
Parameters
timerIndexTimer instance index which callback function will be called. (values: TIM0_INDEX, TIM1_INDEX, ...)

◆ getTimerIndex()

static uint32_t HardwareTimer::getTimerIndex ( TIM_TypeDef *  instance)
static

Gets timer instance index, that is used in methods/attributes: handleCallback(TIM_TypeDef* instance), handleCallback(uint32_t timerIndex), getTimerInstances(), availableTimers[] when enabled.

Parameters
instanceInstance of timer to get index of. (e.g. TIM1, TIM2, ...)
Returns
Returns index of timer instance that starts from 0. Timer instances that are not available in this chip are skipped.

◆ getTimerInstances()

static HardwareTimer** HardwareTimer::getTimerInstances ( )
static

Gets array of all created timers instances (just from this class, not timer structure).

Returns
Returns array of all created timers instances (just from this class, not timer structure).

◆ getAvailableTimersCount()

static uint8_t HardwareTimer::getAvailableTimersCount ( )
static

Gets available timer instances count.

Returns
Returns available timer instances count.

◆ availableChannelsCount()

uint8_t HardwareTimer::availableChannelsCount ( )

Get count of available channels.

Returns
Returns count of available channels.

◆ getHAL_TIM_Struct()

TIM_HandleTypeDef& HardwareTimer::getHAL_TIM_Struct ( )
inline

Returns timer structure, that is used for handling timer.

Returns
Returns timer structure, that is used for handling timer

◆ CalculateTime_ns()

uint64_t HardwareTimer::CalculateTime_ns ( uint32_t  prescaler,
uint32_t  period,
uint32_t  timerFreq,
uint8_t  clockDiv 
)
inlineprotected

Calculates interval from period and prescaler and clock division.

Note
When you change timer clock frequency or timer clock division, you should to calculate it again.
Parameters
prescalerPrescaler.
periodPeriod.
timerFreqTimer frequency before division in Hz (without clock division included in frequency value).
clockDivClock division (Use values: 1,2,4).
Returns
Returns calculated interval in format nanoseconds, so 1 second is then 1 000 000 000ULL ns.

◆ CalculateTime_ms()

uint64_t HardwareTimer::CalculateTime_ms ( uint32_t  prescaler,
uint32_t  period,
uint32_t  timerFreq,
uint8_t  clockDiv 
)
inlineprotected

Calculates interval from period and prescaler and clock division.

Note
When you change timer clock frequency or timer clock division, you should to calculate it again.
Parameters
prescalerPrescaler.
periodPeriod.
timerFreqTimer frequency before division in Hz (without clock division included in frequency value).
clockDivClock division (Use values: 1,2,4).
Returns
Returns calculated interval in format milliseconds, so 1 second is then 1000 ms.

◆ CalculateTimer()

TimerSettings HardwareTimer::CalculateTimer ( uint64_t  ticks,
uint32_t  maxPrescaler,
uint64_t  maxPeriod,
uint32_t  minPeriod,
uint32_t  timerFreq,
bool  divEnabled,
uint32_t  maxIterations = UINT32_MAX 
)
protected

Calculates prescaler, period and timer clock division.

Parameters
ticksCount of timer clock ticks, that timer will be reloaded at. (ticks = duration[s] * timerFrequency[s])
maxPrescalerMax prescaler value (available value: TIMER_16BIT_MAX_PRESCALER)
maxPeriodMax period value (available values: TIMER_16BIT_MAX_PERIOD and TIMER_32BIT_MAX_PERIOD)
minPeriodMin period value to achieve better calculation accuracy (usually 5)
timerFreqTimer periphery bus frequency in Hz (without clock division included in frequency value)
divEnabledTrue if timer supports clock division
maxIterationsIterations limit. So higher value is, so better accuracy can be achieved, but it takes more time.
Returns
Returns structure with calculated parameters and calculation status.

◆ addThisToInstArr()

void HardwareTimer::addThisToInstArr ( )
protected

Writes new class instance to array of all timer instances.

We need to know all created instances to call period elapsed callback of right timer instance.

◆ removeThisFromInstArr()

void HardwareTimer::removeThisFromInstArr ( )
protected

Removes this instance from instances array.

Member Data Documentation

◆ setIntervalItLimit

uint32_t HardwareTimer::setIntervalItLimit = 25

Maximum iterations limit for interval calculation, that is done in method setInterval().

The higher this value is, the better accuracy you can get, but it can take a lot of time. According to estimates, maximum count of iterations, that you can get during calculation is 32 677, but this is real extreme and this value is in reality much lower.
Default limit value is 25 iterations. The worst accuracy it can achieve is 98% (on lower and upper limit with prime numbers) and average accuracy is around 99.99%.

◆ createdTim

TIM_HandleTypeDef HardwareTimer::createdTim
protected

We need this structure when calling HardwareTimer(TIM_TypeDef* instance) constructor, because we have to create new timer structure (TIM_HandleTypeDef).

We use this way to avoid dynamic allocation.

◆ _tim

TIM_HandleTypeDef& HardwareTimer::_tim = createdTim
protected

Timer structure (which include timer instance) that we will use to handle timer.

◆ initDone

bool HardwareTimer::initDone = false
protected

This flag is true when init(void) method was successfully called.

This flas can be set to false using deInit(void) method.

◆ TIMPeriodElapsedCallback

void(* HardwareTimer::TIMPeriodElapsedCallback) () = NULL
protected

Pointer to callback function, that is called on timer interrupt(overflow or underflow event).

◆ instances

HardwareTimer* HardwareTimer::instances[]
staticprotected

Array of all created timers instances (just from this class, not timer structure).

◆ availableTimersCount

uint8_t HardwareTimer::availableTimersCount
staticprotected

Available timer instances count.


The documentation for this class was generated from the following file: