Showing results for 
Search instead for 
Did you mean: 

Can't get correct values from HCSR-04 sensor


I have been trying to get values from an HCSR-04 sensor, but I only get garbage values. I debugged it and saw that my code doesn't clear the UIF flag of the TIM2 SR register. Could this be the cause of the garbage values? I tried the sensor with an Arduino, and it works normally. I have STM32F407G-DISC1 board. I copied this code from here it works for him but didn't worked for me. 

Here's my code:



#include "stm32f4xx.h"
#include <stdio.h>
#include <string.h>

void TIM2_us_Delay(uint32_t delay){
	RCC->APB1ENR |= 1;
	TIM2->ARR = (uint32_t)(delay/0.0625);
	TIM2->CNT = 0;
	TIM2->CR1 |= 1;

	while(!(TIM2->SR & (1<<0)));

	TIM2->SR = 0;

void HCSR04_Init(void) {
	RCC->AHB1ENR |= 1;
	//trig PA5
	GPIOA->MODER |= (1<<10);
	//echo PA6
	GPIOE->MODER &= ~(0x3<<12);

uint32_t data=0;
double time = 0, dist = 0;
void HCSR04_Read(){
	GPIOA->BSRR &= 0x00000000; //PA5 is low
	GPIOA->BSRR |= 0x00000020;//PA5 set to High
	GPIOA->BSRR |= 0x00200000;// Make PA5 low again

	while(GPIOA->IDR & (1<<6)){
	if(data > 0){
		time = data*(0.0625*0.000001);
		dist = ((time*340)/2)*100;
	data = 0;
int main(void){
	RCC->CFGR |= 0<<10;
	GPIOA->BSRR = 0x00000000;


	return 0;




ST Employee

Hello @xode ,

The problem you're experiencing with the HC-SR04 sensor and your STM32F407G-DISC1 board may indeed be linked to not properly handling of the TIM2 status register (SR). The update interrupt flag (UIF) in the TIM2 SR register could you try clearing it to avoid unexpected behavior. 

Not clearing this flag can lead to the microcontroller missing the actual event when the flag is set again, as it would still see the old status.

Also, ensure that your timer is configured correctly. This involves setting the prescaler and the auto-reload register correctly based on your clock settings.

I hope my answer has helped you. When your question is answered, please select this topic as solution that answered you, it will help others find that answer faster.

Thanks for your contribution.


I figured out that the whole problem was the calculations of the distance. It was not trash numbers it was just wrong calculations thanks for helping.