Timer, Delay and Last_ticks

the clock on your robot

Authors

Dicaprio Cheung

Timer

uint32_t HAL_GetTick(void);
  • The HAL_GetTick function is the main thing to use for timing control in software. It counts up by one every millisecond(ms). So, it returns the time (in ms) since you turned on the mainboard.

Delay

void HAL_Delay(uint32_t Delay);
  • The HAL_Delay function stops the program for Delay milliseconds(ms). We seldom use this because it stops everything from working during the delay. (i.e. it won't check if the button is pressed during the delay) Instead, we will use the technique below to achieve the delay functionality.

Last Ticks

Fundamental Program Structure Example: Do something every XXX ms

int main(void)
{
    // Initialize Everything Here, this is like setup() in Arduino
    HAL_Init();
    SystemClock_Config();
    MX_GPIO_Init();     //Initialize most GPIOs on board
    MX_DMA_Init();      //Initialize DMA

    // the following is like loop() in Arduino also
    //Run code in an infinite loop: this is like loop() in Arduino
    while (1) {
      static uint32_t last_ticks = 0;	//This variable keeps its stored value through every iteration
        //Everything inside this if-statements gets called every 100ms
      if((HAL_GetTick() - last_ticks) >= 100){
            // do something every 100 ms
          last_ticks = HAL_GetTick();
      }
      
      static uint32_t last_ticks2 = 0;	//This variable keeps its stored value through every iteration
        //Everything inside this if-statements gets called every 60ms
      if((HAL_GetTick() - last_ticks2) >= 60){
            // do another thing every 60 ms
          last_ticks2 = HAL_GetTick();
      }
    }
}

In the example above, we do something every 100 ms and another thing every 60 ms. Since they are only an if-statement, there won't be any while loops/ for loops that prevent the other tasks from doing their tasks.

but if you write it using delay:

while(1){
    //do something (task1)
    HAL_Delay(100);
    //do another thing (task2)
    HAL_Delay(60);
}

This doesn't work as task1 need to wait for 100+60 ms before it can execute again and task2 also need to wait for 60+100 ms before it can execute again. This is not what we want.

You might say you can carefully design the delay time such that it delays accurately:

T1, T2, delay 60, T2, delay 40, T1, delay 20, T2, delay 60, T2, delay 20, T1, delay 40, T2, delay 60

However, you will have to write many different tasks(>10) for the mainboard to do in many different intervals. it is nearly impossible for you to design a delay pattern for that many tasks accurately. It is also difficult to add, remove, or modify the interval if you write using delay.

So, PLEASE USE LAST_TICKS INSTEAD OF DELAY IN YOUR PROGRAM!!!

Last updated