On an Arduino it is easy to get an HC-SR04 ultrasonic sensor getting to work. However, on my STM32(F103C8T6) I get strange values.
I assumed I connect it correctly, since I get values on the trigger pin. I checked the voltage on the 5V pin going to VCC of the HC-SR04 is 4.87 V.
The following program I used (only most important parts and with generated comments removed):
// PA10 US1 Trigger
#define US1_Trigger_Port GPIOA
#define US1_Trigger_Pin GPIO_PIN_10
// PA9 US1 Echo
#define US1_Echo_Port GPIOA
#define US1_Echo_Pin GPIO_PIN_9
uint32_t us1_duration;
uint32_t us1_distance;
uint32_t raw_values[1024];
uint32_t n = 0;
And for the loop (default part, auto generated by CubeMX):
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_SPI1_Init();
MX_USART1_UART_Init();
MX_NVIC_Init();
while (1)
{
HAL_GPIO_WritePin(US1_Trigger_Port, US1_Trigger_Pin, SET);
HAL_Delay(10);
HAL_GPIO_WritePin(US1_Trigger_Port, US1_Trigger_Pin, RESET);
uint8_t state;
do
{
state = HAL_GPIO_ReadPin(US1_Echo_Port, US1_Echo_Pin);
} while (state == RESET);
uint32_t us1_start = HAL_GetTick();
do
{
state = HAL_GPIO_ReadPin(US1_Echo_Port, US1_Echo_Pin);
} while (state == SET);
uint32_t us1_end = HAL_GetTick();
us1_duration = us1_end - us1_start;
us1_distance = (us1_duration / 2) / 29.1; // cm (?)
raw_values[n] = us1_duration;
n++;
if (n == 1024)
{
break;
}
HAL_Delay(1000);
}
}
I put a breakpoint in the break statement to stop the program to check values. I moved my hand between 10 and 20 cm (4-8 inches) away from the sensor but the raw values I get are:
Name : raw_values
Details:{195, 196, 1, 1, 196, 1, 4, 1, 1, 1, 197, 0 <repeats 1013 times>}
Default:0x20001070 <raw_values>
Decimal:536875120
Hex:0x20001070
Binary:100000000000000001000001110000
Octal:04000010160
The raw values I expect would be in 10-20cm range (at least most of them), which would result according to the datasheet in raw values of 10 * 58 to 20 * 58 which is 580 to 1060. Especially not around 0's and not all same values around a certain value (this time 200).
The data sheet info I used can be found here: datasheet
Update I checked it with a logic analyzer, and noticed the high parts of the echo durations are less than 1 ms. I don't know why I still get values of 200 sometimes, maybe when there is no echo.