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. https://ruturajn.hashnode.dev/interfacing-an-ultrasonic-sensor-with-the-stm32f407-discovery-board-using-bare-metal-programming
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
TIM2_us_Delay(10);
GPIOA->BSRR |= 0x00000020;//PA5 set to High
TIM2_us_Delay(10);
GPIOA->BSRR |= 0x00200000;// Make PA5 low again
while(GPIOA->IDR & (1<<6)){
data++;
}
if(data > 0){
time = data*(0.0625*0.000001);
dist = ((time*340)/2)*100;
}
data = 0;
TIM2_us_Delay(4);
}
int main(void){
RCC->CFGR |= 0<<10;
HCSR04_Init();
GPIOA->BSRR = 0x00000000;
while(1){
HCSR04_Read();
}
return 0;
}
