Arduino Core for STM32  1.0
HardwareTimer.h
Go to the documentation of this file.
1 #ifndef _WIRISH_HARDWARETIMER_H_
2 #define _WIRISH_HARDWARETIMER_H_
3 
4 //Uncomment to use custom MSP init/deinit function
5 //#define HT_ENABLE_MSP_INIT_CB - DO NOT USE
6 
7 //Uncomment to enable array of available timers
8 //#define HT_ENABLE_ARR_AVAILABLE_TIMERS //enables array of available timers
9 
10 
22 #include "wirish.h"
23 
24 //Includes
25 #if defined(STM32F103xB)
26 //#include "stm32f1xx_hal.h"
27 #ifdef TIM5
28 #define CHECKTIM5 (_instance_) || (_instance_) == TIM5
29 #else
30 #define CHECKTIM5
31 #endif
32 #ifdef TIM6
33 #define CHECKTIM6 (_instance_) || (_instance_) == TIM6
34 #else
35 #define CHECKTIM6
36 #endif
37 #ifdef TIM7
38 #define CHECKTIM7 (_instance_) || (_instance_) == TIM7
39 #else
40 #define CHECKTIM7
41 #endif
42 #define IS_TIMER_INSTANCE_ON_APB1(_instance_) ((_instance_) == TIM2 \
43  || (_instance_) == TIM3 \
44  || (_instance_) == TIM4 \
45  CHECKTIM5 \
46  CHECKTIM6 \
47  CHECKTIM7)
48 #define IS_TIMER_INSTANCE_ON_APB2(_instance_) ((_instance_) == TIM1)
49 
50 #elif defined(STM32F031x6) || defined(STM32F070xB) || defined(STM32F070x6) || defined(STM32F030x6)
51 //#include "stm32f0xx_hal.h"
52 //all timers are connected to APB1
53 #ifdef HT_ENABLE_MSP_INIT_CB
54  #define TIM1_IRQn TIM1_CC_IRQn
55 #endif
56 #define IS_TIMER_INSTANCE_ON_APB1 IS_TIM_INSTANCE
57 
58 #elif defined(STM32L031xx)
59 //#include "stm32l0xx_hal.h"
60 #define IS_TIMER_INSTANCE_ON_APB1(_instance_) ((_instance_) == TIM2)
61 #define IS_TIMER_INSTANCE_ON_APB2(_instance_) ((_instance_) == TIM22 || (_instance_) == TIM21)
62 
63 #elif defined(STM32L432xx)
64 //#include "stm32l4xx_hal.h"
65 #define IS_TIMER_INSTANCE_ON_APB1(_instance_) ((_instance_) == TIM2 || (_instance_) == TIM6 || (_instance_) == TIM7)
66 #define IS_TIMER_INSTANCE_ON_APB2(_instance_) ((_instance_) == TIM1 || (_instance_) == TIM15 || (_instance_) == TIM16)
67 
68 #else
69 #error #error "Definitions for your MCU are not defined."
70 //Steps to add your MCU:
71 //1. add hal library - deprecated
72 //2. define which timer use what APB clock using MACROS: IS_TIMER_INSTANCE_ON_APB1, IS_TIMER_INSTANCE_ON_APB2, ...
73 //3. define correct name to IRQn, e.g.: #define TIM1_IRQn TIM1_CC_IRQn
74 #endif
75 
76 #if defined(HAL_TIM_MODULE_ENABLED) || defined(DOXYGEN_FORCED)
77 
78 #if !defined(min)
79 #define min(a,b) (((a)<b)?(a):(b))
80 #endif
81 #if !defined(max)
82 #define max(a,b) (((a)>b)?(a):(b))
83 #endif
84 #if !defined(abs)
85 #define abs(a) (((a)>=0)?(a):-(a))
86 #endif
87 
88 #define TIMER_16BIT_MAX_PRESCALER (0xFFFFUL)
89 #define TIMER_32BIT_MAX_PERIOD (0xFFFFFFFFUL)
90 #define TIMER_16BIT_MAX_PERIOD (0xFFFFUL)
91 
104  CTS_NONE = 0,
115 };
116 
122 #define CTS_IS_OK(state) ((state)>CTS_NONE)
123 
130  uint16_t prescaler = 0;
132  uint32_t period = 0;
134  uint8_t divider = 0;
137 
138  TimerSettings(uint16_t prescaler_, uint32_t period_, uint8_t div, CalculateTimerState state_) {
139  prescaler = prescaler_;
140  period = period_;
141  divider = div;
142  state = state_;
143  }
144 };
145 
159 };
160 
161 
212 
213 public:
214  //Constructors:
220  HardwareTimer(TIM_HandleTypeDef &tim);
221 
227  HardwareTimer(TIM_TypeDef* instance);
228 
229  //Destructor
233  ~HardwareTimer();
234 
235 
240  bool instanceExists(void);
241 
249  bool init(void);
250 
255  bool isInitDone(void);
256 
260  void deInit(void);
261 
262 
274 
288  bool setCounterMode(uint32_t mode);
289 
294  uint32_t getCounterMode(void);
295 
296  /*bool setChannel(uint8_t channel);
297  uint8_t getChannel(void);
298  bool setChannelMode(uint32_t mode); //- do not use now
299  uint32_t getChannelMode(void); //- do not use now
300  void setChannelOCPulse(uint16_t val); //- do not use now
301  uint16_t getChannelOCPulse(void); //- do not use now
302  void setChannelOtCPolarityHIGH(bool isHigh); //- do not use now
303  bool isChannelOtCPolarityHIGH(void); //- do not use now
304  void enableOCFastMode(bool enable); //- do not use now
305  bool isOCFastModeEnabled(void); //- do not use now*/
306 
307  /***/ //Setup methods END
308 
309 
310 
311 
325  TimerSettings setInterval_ns(uint64_t interval_ns);
326 
334  TimerSettings setInterval(uint64_t interval_ms);
335 
341  uint64_t getInterval(void);
342 
348  uint64_t getInterval_ns(void);
349 
350  /***/ //Easiest settings methods applied in real time END
351 
352 
363  uint16_t getPrescaler(void);
364 
369  void setPrescaler(uint16_t factor);
370 
377  uint32_t getPeriod();
378 
384  void setPeriod(uint32_t val);
385 
390  uint32_t getCount(void);
391 
395  void setCount(uint32_t val);
396 
397  /***/ //Basic settings methods applied in real time END
398 
399 
410  void unlockSettings();
411 
416  void lockSettings();
417 
422  bool haveLockedSettings();
423 
428  void enableAutoReloadPreload(bool enable);
429 
434  bool isAutoReloadPreloadEnabled(void);
435 
440  bool is32BitTimer();
441 
446  bool supportsClockDivision();
447 
453  bool setClockDivision(uint8_t division);
454 
459  uint8_t getClockDivision(void);
460 
465  uint32_t getTimerClockFreq(void);
466 
471  uint32_t getDivTimerClockFreq(void);
472 
473  /***/ //Advanced settings methods applied in real time END
474 
475 
485  void pause(void);
486 
490  void stop(void);
491 
496  bool resume(void);
497 
502  bool start(void);
503 
509  TimerState state(void);
510 
511  /***/ //Timer control functions END
512 
513 
518  void setCallback(void (* PeriodElapsedCallback_)());
519 
526 #ifdef HT_ENABLE_ARR_AVAILABLE_TIMERS
527 
530  const static TIM_TypeDef* availableTimers[];
531 #endif
532 
537  static inline void handleCallback(TIM_TypeDef* instance);
538 
544  static inline void handleCallback(uint32_t timerIndex);
545 
551  static uint32_t getTimerIndex(TIM_TypeDef* instance);
552 
557  static HardwareTimer** getTimerInstances(); //returns pointer to instances
558 
563  static uint8_t getAvailableTimersCount();
564 
569  uint8_t availableChannelsCount();
570 
575  TIM_HandleTypeDef& getHAL_TIM_Struct(){
576  return _tim;
577  }
578 
587  uint32_t setIntervalItLimit = 25;
588 
589  /***/ //Expert methods END
590 
591 
592 protected:
598  TIM_HandleTypeDef createdTim;
599 
603  TIM_HandleTypeDef &_tim = createdTim;
604 
605  //TIM_OC_InitTypeDef sConfigOC = {0}; //channel configuration
606 
611  bool initDone = false;
612 
622  uint64_t inline CalculateTime_ns(uint32_t prescaler, uint32_t period, uint32_t timerFreq, uint8_t clockDiv) {
623  uint64_t time = ((uint64_t)period + 1) * (((uint64_t)prescaler + 1) * 1000000000ULL) / timerFreq;
624  //if (time > UINT32_MAX) time = UINT32_MAX;
625  //if(clockDiv == 0) clockDiv = 1;
626  return time * clockDiv;
627  }
628 
638  uint64_t inline CalculateTime_ms(uint32_t prescaler, uint32_t period, uint32_t timerFreq, uint8_t clockDiv) {
639  uint64_t time = ((uint64_t)period + 1) * (((uint64_t)prescaler + 1) * 1000UL) / timerFreq;
640  //if (time > UINT32_MAX) time = UINT32_MAX;
641  //if(clockDiv == 0) clockDiv = 1;
642  return time * clockDiv;
643  }
644 
656  TimerSettings CalculateTimer(uint64_t ticks, uint32_t maxPrescaler, uint64_t maxPeriod, uint32_t minPeriod, uint32_t timerFreq, bool divEnabled, uint32_t maxIterations = UINT32_MAX);
657 
658 #ifdef HT_ENABLE_MSP_INIT_CB
659 
663  static void Base_MspInit_callback(TIM_HandleTypeDef* htim_oc);
664 
669  static void Base_MspDeInit_callback(TIM_HandleTypeDef* htim_oc);
670 #endif
671 
676  void addThisToInstArr();
677 
681  void removeThisFromInstArr();
682 
686  void (* TIMPeriodElapsedCallback)() = NULL;
687 
691  static HardwareTimer* instances[]; //There are stored pointers to all created instances of this class
692 
696  static uint8_t availableTimersCount;
697 };
698 
699 /*The timer peripherals can be classified as:
700 • Advanced-configuration timers like TIM1 and TIM8 among others.
701 • General-purpose configuration timers like TIM2 and TIM3 among others
702 • Lite-configuration timers like TIM9, TIM10, TIM12 and TIM16 among others
703 • Basic-configuration timers like TIM6 and TIM7 among others.*/
704 
705 #endif
706 #endif
HardwareTimer::_tim
TIM_HandleTypeDef & _tim
Timer structure (which include timer instance) that we will use to handle timer.
Definition: HardwareTimer.h:603
CalculateTimerState
CalculateTimerState
Enums of all possible calculation states of setTimer method.
Definition: HardwareTimer.h:96
HardwareTimer::haveLockedSettings
bool haveLockedSettings()
Checks if settings registers are locked.
HardwareTimer::isAutoReloadPreloadEnabled
bool isAutoReloadPreloadEnabled(void)
Checks if autoReloadPreload is enabled.
HardwareTimer::getTimerInstances
static HardwareTimer ** getTimerInstances()
Gets array of all created timers instances (just from this class, not timer structure).
HardwareTimer::getPrescaler
uint16_t getPrescaler(void)
Basic settings methods applied in real time Those setting methods can be called every time,...
TimerState
TimerState
This is enum of all possible timer states.
Definition: HardwareTimer.h:150
HardwareTimer::start
bool start(void)
Starts timer.
HardwareTimer::getTimerIndex
static uint32_t getTimerIndex(TIM_TypeDef *instance)
Gets timer instance index, that is used in methods/attributes: handleCallback(TIM_TypeDef* instance),...
HardwareTimer::enableAutoReloadPreload
void enableAutoReloadPreload(bool enable)
When autoReloadPreload is enabled, timer is running and period was changed, the new value of period w...
HardwareTimer::initDone
bool initDone
This flag is true when init(void) method was successfully called.
Definition: HardwareTimer.h:611
HardwareTimer::setIntervalItLimit
uint32_t setIntervalItLimit
Maximum iterations limit for interval calculation, that is done in method setInterval().
Definition: HardwareTimer.h:587
HardwareTimer::setClockDivision
bool setClockDivision(uint8_t division)
Sets timer clock division.
HardwareTimer::CalculateTimer
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.
HardwareTimer::resume
bool resume(void)
Resumes timer.
TS_RUNNING
@ TS_RUNNING
Timer is running.
Definition: HardwareTimer.h:152
TS_STOPPED
@ TS_STOPPED
Timer is stopped, counter register was restarted.
Definition: HardwareTimer.h:156
HardwareTimer::getPeriod
uint32_t getPeriod()
Gets period that was set.
HardwareTimer::availableTimersCount
static uint8_t availableTimersCount
Available timer instances count.
Definition: HardwareTimer.h:696
HardwareTimer::TIMPeriodElapsedCallback
void(* TIMPeriodElapsedCallback)()
Pointer to callback function, that is called on timer interrupt(overflow or underflow event).
Definition: HardwareTimer.h:686
HardwareTimer::availableChannelsCount
uint8_t availableChannelsCount()
Get count of available channels.
HardwareTimer::getClockDivision
uint8_t getClockDivision(void)
Gets clock division value.
TimerSettings::period
uint32_t period
Calculated period.
Definition: HardwareTimer.h:132
HardwareTimer::stop
void stop(void)
Stops timer.
HardwareTimer::setCallback
void setCallback(void(*PeriodElapsedCallback_)())
Sets callback function, that is called when timer period elapsed (interrupt).
CTS_OK_JUST_PERIOD
@ CTS_OK_JUST_PERIOD
Value was established just with period (prescaler value is 0)
Definition: HardwareTimer.h:106
HardwareTimer::instanceExists
bool instanceExists(void)
Checks if timer instance really exists and is based on real timer.
TimerSettings::TimerSettings
TimerSettings(uint16_t prescaler_, uint32_t period_, uint8_t div, CalculateTimerState state_)
Definition: HardwareTimer.h:138
CTS_TOO_HIGH_RESULT
@ CTS_TOO_HIGH_RESULT
Value (duration_100ns) is higher than maximum available time that can be set using this timer with cu...
Definition: HardwareTimer.h:100
CTS_NONE
@ CTS_NONE
Function was not called yet.
Definition: HardwareTimer.h:104
CTS_OK_ROUNDED_DOWN
@ CTS_OK_ROUNDED_DOWN
Value was established with the best possible accuracy, but is slightly lower than expected value.
Definition: HardwareTimer.h:114
HardwareTimer::setCounterMode
bool setCounterMode(uint32_t mode)
Sets timer Counter Mode.
HardwareTimer::lockSettings
void lockSettings()
Locks settings registers.
HardwareTimer::getInterval
uint64_t getInterval(void)
Calculates interval from period, prescaler and timer clock division.
HardwareTimer::getInterval_ns
uint64_t getInterval_ns(void)
Calculates interval from period, prescaler and timer clock division.
TimerSettings::prescaler
uint16_t prescaler
Calculated prescaler.
Definition: HardwareTimer.h:130
HardwareTimer::setPeriod
void setPeriod(uint32_t val)
Sets period that was set.
HardwareTimer::supportsSelectionCounterMode
bool supportsSelectionCounterMode()
Setup methods Those methods have to be called before init(void) method to apply settings.
HardwareTimer::getCounterMode
uint32_t getCounterMode(void)
Gets timer Counter Mode.
HardwareTimer::getAvailableTimersCount
static uint8_t getAvailableTimersCount()
Gets available timer instances count.
HardwareTimer::init
bool init(void)
Initialize timer instance.
HardwareTimer::getDivTimerClockFreq
uint32_t getDivTimerClockFreq(void)
Gets timer clock frequency after clock division.
TS_ERROR
@ TS_ERROR
There is some error with timer.
Definition: HardwareTimer.h:158
HardwareTimer::setPrescaler
void setPrescaler(uint16_t factor)
Sets prescaler that was set.
HardwareTimer::unlockSettings
void unlockSettings()
Advanced settings methods applied in real time Those setting methods can be called every time,...
TimerSettings::divider
uint8_t divider
Timer clock division.
Definition: HardwareTimer.h:134
HardwareTimer::setInterval_ns
TimerSettings setInterval_ns(uint64_t interval_ns)
Easiest settings methods applied in real time.
HardwareTimer::CalculateTime_ns
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.
Definition: HardwareTimer.h:622
HardwareTimer::deInit
void deInit(void)
Deinitialization of timer.
HardwareTimer::getHAL_TIM_Struct
TIM_HandleTypeDef & getHAL_TIM_Struct()
Returns timer structure, that is used for handling timer.
Definition: HardwareTimer.h:575
TS_PAUSED
@ TS_PAUSED
Timer is paused, counter register is unchanged.
Definition: HardwareTimer.h:154
wirish.h
This file contains basic (Arduino like) GPIO manipulation functions, delay, random,...
HardwareTimer::isInitDone
bool isInitDone(void)
Checks if timer was initialized.
HardwareTimer::HardwareTimer
HardwareTimer(TIM_HandleTypeDef &tim)
Hardware timer constructor.
HardwareTimer::createdTim
TIM_HandleTypeDef createdTim
We need this structure when calling HardwareTimer(TIM_TypeDef* instance) constructor,...
Definition: HardwareTimer.h:598
CTS_BAD_ARGUMENT
@ CTS_BAD_ARGUMENT
Check if values maxPrescaler, maxCounter, minPeriod are correct.
Definition: HardwareTimer.h:98
CTS_OK_JUST_PRESCALER
@ CTS_OK_JUST_PRESCALER
Value was established just with prescaler (period value is 0) - This should never happens when you ha...
Definition: HardwareTimer.h:108
HardwareTimer::handleCallback
static void handleCallback(TIM_TypeDef *instance)
Expert methods Those methods you probably don't need to call in basic timer operation.
TimerSettings::state
CalculateTimerState state
Calculation state.
Definition: HardwareTimer.h:136
HardwareTimer::getCount
uint32_t getCount(void)
Gets current value in counter register.
HardwareTimer::getTimerClockFreq
uint32_t getTimerClockFreq(void)
Gets timer clock frequency before clock division.
CTS_OK_BEST_ACCURACY
@ CTS_OK_BEST_ACCURACY
Value was established with the best possible accuracy.
Definition: HardwareTimer.h:110
HardwareTimer::setCount
void setCount(uint32_t val)
Sets new value to counter register.
HardwareTimer::removeThisFromInstArr
void removeThisFromInstArr()
Removes this instance from instances array.
TimerSettings
Structure, those data was calculated in setInterval method.
Definition: HardwareTimer.h:128
HardwareTimer::~HardwareTimer
~HardwareTimer()
Class destructor.
HardwareTimer::setInterval
TimerSettings setInterval(uint64_t interval_ms)
Calculates period and prescaler and clock division from set interval.
HardwareTimer::pause
void pause(void)
Timer control functions Those methods can be called just after init(void) method.
HardwareTimer::addThisToInstArr
void addThisToInstArr()
Writes new class instance to array of all timer instances.
HardwareTimer::is32BitTimer
bool is32BitTimer()
Checks if timer is 32bit or 16bit.
CTS_OK_ROUNDED_UP
@ CTS_OK_ROUNDED_UP
Value was established with the best possible accuracy, but is slightly higher than expected value.
Definition: HardwareTimer.h:112
CTS_TOO_LOW_RES
@ CTS_TOO_LOW_RES
Value (duration_100ns) is lower than minumum available time that can be set using this timer with cur...
Definition: HardwareTimer.h:102
HardwareTimer::instances
static HardwareTimer * instances[]
Array of all created timers instances (just from this class, not timer structure).
Definition: HardwareTimer.h:691
HardwareTimer::CalculateTime_ms
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.
Definition: HardwareTimer.h:638
HardwareTimer
Handle timers in interrupt mode really easy using this class. In table below, you can see methods se...
Definition: HardwareTimer.h:211
HardwareTimer::supportsClockDivision
bool supportsClockDivision()
Checks if timer supports clock division.
HardwareTimer::state
TimerState state(void)
Checks timer state.