Microsecond delay in STM32

HAL_Delay is able to provide minimum 1ms delay but when it comes to microsecond, there isn’t any predefined function to create 1us delay. In this tutorial, I am going to show you how to create 1 microsecond delay in STM32. The process will be same for all the STM32 devices, you need to make a minor change though.

CHECK OUT THE VIDEO BELOW




WHY Delay in MicroSeconds

Delay in microseconds is needed in order to interface some sensors for eg- DHT11/22. These sensors contains only one PIN for the data transfer and data is transferred bidirectionally. They need precise timing in order to work. For eg- To initialize DHT22, microcontroller need to pull the data pin low for 500us and than pull high for 40us. After that DHT22 start transmitting it’s response by pulling the line low for 80us followed by pulling high for 80us.
After searching a lot on the internet, finally I got the code which works. I don’t remember where I got it from so if someone knows the writer, do let me know in the comments below. I will give the credits for the work.
I will show the working on the oscilloscope, You can check the  RESULTS tab for more details. I am using STM32F103C8 cortex M3 microcontroller but the process is same for other STM32 devices

How to setup

This project contains a header file (dwt_stm32_delay.h) and a c file (dwt_stm32_delay.c). We need to include it in the main project. I am using keil and the process is described below:
First setup the project from the CubeMx and right click the Application/User and select add existing files to group

add both files in the project

Next we have to include the path in the project so follow along




Now include the location of the folder, where the files are copied

As you can see above that the folder is included in the path
Next you have to include dwt_stm32_delay.h in the main file by using #include “dwt_stm32_delay.h” and build the project. Now you will be able to see the *.h and *.c file in the list.
NOTE:-  Inside dwt_stm32_delay.h, change the #include”*.h” file according to your microcontroller.
You can use DWT_Delay_Init (); to initialize the delay and DWT_Delay_us (microseconds) for the delay in us.

CODE

#include "main.h"
#include "stm32f1xx_hal.h"
#include "dwt_stm32_delay.h"

int main(void)
{
  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init();
  DWT_Delay_Init ();
  while (1)
  {
 HAL_GPIO_TogglePin (GPIOA, GPIO_PIN_1);
 DWT_Delay_us (10);
  }
}

RESULT :-
PIN TOGGLES AFTER 10US

PIN TOGGLES AFTER 100 us

PIN TOGGLES AFTER 1000us

Microsecond delay in STM32 Microsecond delay in STM32 Reviewed by Controllerstech on February 17, 2018 Rating: 5

No comments:

Powered by Blogger.