This project create us-delay with timer
Made with STM32CubeMX with STM32CubeIDE Toolchain
Selected microcontroller is STM32F4xx
and HAL library has been used. (for other microcontrollers, just repalce library)
Clock configured 168MHz with PLL (maximum for my microcontroller,you can use any clock-rate):
TIM1 settings:
Just set clock source, internal clock
PSC set at 167 ((Used-Clock/1,000,000)-1) and counter period at maximum Value.
Algorithm is so simple:
First start the timer (in this code, Timer 1),
HAL_TIM_Base_Start(&htim1);
Then reset CNT value,
htim1.Instance->CNT=0;
And wait for CNT to reach us(input) value (with while).
while(htim1.Instance->CNT < us);
In main function, toggle GPIOE port, pin 15 every 20 micro-second and result:
Result was not exactly 20us because HAL-library functions have a delay itself and if it was very large, you can calibre it manually:
For example if we want 40us delay and every time we got ~42 us, write this code before the while:
us -= 2;
Also you can library to make us-delay with HAL-library functions delay rather than Timer.
For example, write this code and monitor the delay and calibre it with changing the value
to make one us delay :
void us_delay(int us){
value = 10000;
delay = us * value;
for(int i;i < delay;i++);
}