First, let's demonstrate the correct implementation method. We won't show the problematci syntax examples.
void HCSR04_Configuration(void){
GPIO_InitTypeDef gpioConfiguration;
TIM_TimeBaseInitTypeDef timerConfig;
// Enable GPIO peripheral clocks
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
// Enable timer clock
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE);
// Configure Echo pin as input
gpioConfiguration.GPIO_Pin = GPIO_Pin_4;
gpioConfiguration.GPIO_Mode = GPIO_Mode_IN;
gpioConfiguration.GPIO_OType = GPIO_OType_PP;
gpioConfiguration.GPIO_Speed = GPIO_Speed_25MHz;
gpioConfiguration.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &gpioConfiguration);
// Configure Trigger pin as output
gpioConfiguration.GPIO_Pin = GPIO_Pin_7;
gpioConfiguration.GPIO_Mode = GPIO_Mode_OUT;
gpioConfiguration.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB, &gpioConfiguration);
// Timer configuration
timerConfig.TIM_Prescaler = 84 - 1; // 84MHz/84 = 1MHz
timerConfig.TIM_Period = 50000 - 1;
timerConfig.TIM_CounterMode = TIM_CounterMode_Up; // Up counting
timerConfig.TIM_ClockDivision = TIM_CKD_DIV1; // Clock division
// Initialize timer with ARR and PSC values
TIM_TimeBaseInit(TIM6, &timerConfig);
// Disable timer initially
TIM_Cmd(TIM6, DISABLE);
}
int Calculate_Distance(void){
int pulseWidth = 0, distance = 0, timeout = 0;
// Generate trigger pulse
GPIOB->BSRRH = GPIO_Pin_7; // Set trigger pin low
delay_us(8);
GPIOB->BSRRL = GPIO_Pin_7; // Set trigger pin high
delay_us(20);
GPIOB->BSRRH = GPIO_Pin_7; // Set trigger pin low
// Reset timer counter
TIM6->CNT = 0;
// Wait for echo signal to go high
printf("Waiting for echo start\r\n");
while(!(GPIOA->IDR & GPIO_Pin_4)){
// Optional: Add timeout handling here
}
// Start timer measurement
TIM_Cmd(TIM6, ENABLE);
printf("Measuring pulse width\r\n");
timeout = 0;
// Wait for echo signal to go low
while(GPIOA->IDR & GPIO_Pin_4){
// Optional: Add timeout handling here
}
printf("Pulse measurement complete\r\n");
// Read timer counter value
pulseWidth = TIM6->CNT;
// Stop timer
TIM_Cmd(TIM6, DISABLE);
// Calculate distance (speed of sound = 340m/s)
distance = pulseWidth / 58;
return distance;
}<br></br><br></br>
int main(void){ int measuredDistance = 0;```
<div><div> // Ultrasonic distance measurement</div><div> static uint16_t counter;</div><div> if(counter++ % (2 * 1000) == 0)</div><div> measuredDistance = Calculate_Distance();</div></div>```
}
Common issues with ultrasonic sensor getting stuck:
Stuck waiting for echo signal<br></br>Issue 1: Sensor hangs immediately on first measurement<br></br>Cause 1: Incorrect GPIO pin mode configuration<br></br>Solution: Ensure the trigger pin is configured as output mode and the echo pin as input mode
Issue 2: First measurement works, but subsequent measurements hang
Cause 2: Processing speed is too fast, causing timing synchrnoization issues
Soultion 2: Add appropriate delay intervals between measurement cycles