THIS METHOD IS ONLY TESTED WITH CORTEX M3 and M4 SERIES MICROCONTROLLERS. FOR MORE EFFECTIVE AND UNIVERSAL METHOD PLEASE VISIT THE VIDEO HERE
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.
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.
The following is the result I got by toggling the pin at 10us, 100us and 1000us respectively.
You can buy me a
coffee sensor 🙂
download the CODE below