Pushbutton Event Handler: Part 2

Software Timer

In typical hardware timer use cases, you set up a timer with certain settings such as interval then assign a callback function that is called when the timer expires and let the function do certain task. You can instead write a timer callback function to call other callback functions, i.e. cascade the callback functions. This way, you can hook up multiple callback functions to a timer with arbitrary interval. Original timer now works as a base timer but the callback function works as a software timer.

Cortex-M processors have generic 1 millisecond timer called SysTick. Write a SysTick callback function that handles host of other callback functions with intervals of multiple of 1msec. For example, you can make the SysTick callback function call pushbutton state check routine every 300msec, as well as many other routines that are called at various intervals.

In STM32Cube framework, SysTick interrupt handler calls the function HAL_SYSTICK_IRQHandler (Warning: This was broken in the version 5.0.0 of STM32CubeMX. So you need to do it manually), which in turn calls HAL_SYSTICK_Callback function.

    1 /**
    2 * @brief This function handles System tick timer.
    3 */
    4 void SysTick_Handler(void)
    5 {
    6     /* USER CODE BEGIN SysTick_IRQn 0 */
    7 
    8     /* USER CODE END SysTick_IRQn 0 */
    9     HAL_IncTick();
   10     HAL_SYSTICK_IRQHandler();
   11     /* USER CODE BEGIN SysTick_IRQn 1 */
   12 
   13     /* USER CODE END SysTick_IRQn 1 */
   14 }

Thus it is a good place to put your software timer routine.

  355 /** SysTick callback function override.
  356  */
  357 void HAL_SYSTICK_Callback()
  358 {
  359     // UsrTimer_Routine will have 1msec resolution
  360     UsrTimer_Routine();
  361 }

Following example registers a function that toggles LED at every 100msec.

    1 void TestCallback()
    2 {
    3     HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
    4 }
    5 
    6 main()
    7 {
    8     // start software timer routine
    9     UsrTimer_Init();
   10 
   11     // register a callbackfunction with 100msec interval
   12     UsrTimer_Set(100, 0, TestCallback);

Software timer implemented in the sample project file support following functions

   43 /// Initialize all timers
   44 void UsrTimer_Init();
   45 /// Enable or disable main routine
   46 void UsrTimer_Enable(bool flag);
   47 /// Clear the timer
   48 void UsrTimer_Clear(uint32_t index);
   49 /// Pause the timer 
   50 void UsrTimer_Pause(uint32_t index);
   51 /// Resume the timer
   52 void UsrTimer_Resume(uint32_t index);
   53 /// Main timer routine
   54 void UsrTimer_Routine(void);
   55 /// Set a new timer with the callback function
   56 int UsrTimer_Set(uint32_t interval, uint32_t duration, usrtimer_callback f);

(source code)

Leave a comment