cancel
Showing results for 
Search instead for 
Did you mean: 

HC-SR04 issue w/ NUCLEO-L432KC

lazerwild165
Associate

I am trying to interface the HC-SR04 sensor to the NUCLEO-L432KC board. Here are the connections:
VCC -> 5V
GND -> GND
TRIG -> A0
ECHO -> A1
Despite not getting any errors, I am consistently getting the value of 0 as the distance. I suspect the issue lies with the timing but I'm unable to pinpoint it. Would appreciate any help!

Here's the main function:

int main(void)

{

/* USER CODE BEGIN 1 */

 

/* USER CODE END 1 */

 

/* MCU Configuration--------------------------------------------------------*/

 

/* Reset of all peripherals, Initializes the Flash interface and the Systick. */

HAL_Init();

 

/* USER CODE BEGIN Init */

 

/* USER CODE END Init */

 

/* Configure the system clock */

SystemClock_Config();

 

/* USER CODE BEGIN SysInit */

 

/* USER CODE END SysInit */

 

/* Initialize all configured peripherals */

MX_GPIO_Init();

MX_USART2_UART_Init();

MX_TIM1_Init();

/* USER CODE BEGIN 2 */

HAL_TIM_Base_Start(&htim1);

HAL_GPIO_WritePin(TRIG_PORT, TRIG_PIN, GPIO_PIN_RESET); // pull the TRIG pin low

/* USER CODE END 2 */

 

/* Infinite loop */

/* USER CODE BEGIN WHILE */

while (1)

{

HAL_GPIO_WritePin(TRIG_PORT, TRIG_PIN, GPIO_PIN_SET); // pull the TRIG pin HIGH

__HAL_TIM_SET_COUNTER(&htim1, 0);

while (__HAL_TIM_GET_COUNTER (&htim1) < 100); // wait for 100 us

HAL_GPIO_WritePin(TRIG_PORT, TRIG_PIN, GPIO_PIN_RESET); // pull the TRIG pin low

 

pMillis = HAL_GetTick(); // used this to avoid infinite while loop (for timeout)

// wait for the echo pin to go high

while (!(HAL_GPIO_ReadPin (ECHO_PORT, ECHO_PIN)) && pMillis + 10 > HAL_GetTick());

Value1 = __HAL_TIM_GET_COUNTER (&htim1);

 

pMillis = HAL_GetTick(); // used this to avoid infinite while loop (for timeout)

// wait for the echo pin to go low

while ((HAL_GPIO_ReadPin (ECHO_PORT, ECHO_PIN)) && pMillis + 50 > HAL_GetTick());

Value2 = __HAL_TIM_GET_COUNTER (&htim1);

 

Distance = (Value2 - Value1)* 0.034/2;

char buffer[20];

sprintf(buffer, "Distance: %d cm\r\n", Distance);

HAL_UART_Transmit(&huart2, (uint8_t*)buffer, strlen(buffer), HAL_MAX_DELAY);

 

HAL_Delay(50);

/* USER CODE END WHILE */

 

/* USER CODE BEGIN 3 */

}

/* USER CODE END 3 */

}

1 REPLY 1
RhSilicon
Lead

:eyes::backhand_index_pointing_right:https://www.google.com/search?q=HC-SR04+stm32