0

I'm programming STM32F103C6, and I'm using Keil Microvision with Proteus Professional 8, I have problem with reading value from HC SR04 Ultrasonic sensor in LCD(LM016L), the code is below

#define TRIG_PIN GPIO_PIN_9
#define TRIG_PORT GPIOA
#define ECHO_PIN GPIO_PIN_8
#define ECHO_PORT GPIOA
uint32_t pMillis;
uint32_t Value1 = 0;
uint32_t Value2 = 0;
uint16_t Distance  = 0;  // cm
uint16_t temp  = 50;  
/* USER CODE END PV */

  /* 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 */
    lcd_init();
  char buffer[24];
  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) < 10);  // wait for 10 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;

        sprintf(buffer, "%u\n", Distance);
lcd_puts(0,0, (int8_t*)(buffer));
        HAL_Delay(50);
  }
}

I think I got some value 10* -300, does anyone has idea how to read it or another code

artless noise
  • 21,212
  • 6
  • 68
  • 105
e Res
  • 101
  • 1
  • 10
  • Just guessing here, but if your loop waiting for ECHO to go high times out, you carry on regardless, and then "wait" for it to go low again. Of course, it is already low, since it never went high. So you get a time that is zero (or nearly zero), and a distance to match. Would recommend aborting the reading if there is a timeout. – pmacfarlane Dec 17 '22 at 22:42

0 Answers0