HC-SR04 and STM32

Ultrasonic ranging module HC - SR04 provides 2cm - 400cm non-contact measurement function, the ranging accuracy can reach to 3mm. The modules includes ultrasonic transmitters, receiver and control circuit.
Today in this tutorial we are going to learn How to interface HC-SR04 Ultrasonic sensor module with STM32.




WORKING


Working of hcsr04 is pretty simple and straight.
The module emits an ultrasound at 40 KHz which, after reflecting from obstacle, bounces back to the module. By using the travel time and the speed of the sound, we can calculate the distance between the sensor and the obstacle.


HOW TO


According to the datasheet of hc-sr04, the following is required to be done :-
  • Keep the pin HIGH for at least 10us
  • The Module will now send 8 cycle burst of ultrasound at 40 kHz and detect whether there is a pulse signal back
  • IF the signal returns, module will output a HIGH PULSE whose width will be proportional to the range of the object.
  • Distance can be calculated by using the following formula :- range = high level time * velocity (340m/s) / 2
  • We can also use uS / 58 = Distance in cm or uS / 148 = distance in inch
  • It is recommended to wait for at least 60ms before starting the operation again.

CONNECTION


CODE

uint32_t local_time, sensor_time;
uint32_t distance;

uint32_t hcsr04_read (void)
{
 local_time=0;
 HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);  // pull the TRIG pin HIGH
 delay(2);  // wait for 2 us


 HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET);  // pull the TRIG pin HIGH
 delay(10);  // wait for 10 us
 HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);  // pull the TRIG pin low

 // read the time for which the pin is high

 while (!(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_4)));  // wait for the ECHO pin to go high
 while (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_4))    // while the pin is high
  {
  local_time++;   // measure time for which the pin is high
  delay (1);
  }
 return local_time;
}
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
   sensor_time = hcsr04_read();
   distance  = sensor_time * .034/2;


   HAL_Delay(200);
  }


You can Download code at the end of the post

RESULT














HC-SR04 and STM32 HC-SR04 and STM32 Reviewed by Controllerstech on October 30, 2019 Rating: 5

2 comments:

  1. Thank you so much... I noticed a lot of people using Timers, what is your opinion on that?.... I think this is much easier..

    ReplyDelete
  2. Timer is more accurate... Another things to wonder is if the response is not received successfully. Will the code stack in the loop?

    ReplyDelete

Powered by Blogger.