Unable to find the distance using HC-SR04 ultrasonic sensor

493 views Asked by At

I am trying to find the distance to a nearby object using an HC SR04 ultrasonic sensor. I followed the tutorial from the below link:

HC-SR04 Ultrasonic Range Sensor on the Raspberry Pi

I replicated all the instructions as given. I ran into a problem when trying to run the code.

import RPi.GPIO as GPIO
import time

# Setting the GPIO pins mode
GPIO.setmode(GPIO.BCM)

# Setting the pin values
TRIG = 23
ECHO = 24

# Assigning the pins to GPIO
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

# Allowing the sensor to settle down
GPIO.output(TRIG, False)
print('Waiting for thr sensor to settle down!!')
time.sleep(2)

# Sending a trigger pulse of 10 micro seconds duration
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)

# Starting the measurement process
pulse_start = 0
pulse_end = 0

# Checking for the last timestamp at which the ECHO is OFF
while GPIO.input(ECHO) == 0:
    print('Running ECHO = 0 loop')
    pulse_start = time.time()

print('Pulse start: ',pulse_start)

# Checking for the last timestamp at which the ECHO is ON
while GPIO.input(ECHO) == 1:
    print('Running ECHO = 1 loop')
    pulse_end = time.time()

print('Pulse end: ',pulse_end)

# Calculating the pulse duration
pulse_duration = pulse_end - pulse_start

# Distance Calc
distance = round((343/2)*pulse_duration,2)
print('Distance: ', distance, 'm')

# Cleaning up the pins
GPIO.cleanup()

The code doesn't seem to enter the first while loop where the ECHO pin is being checked for low signal. This is giving me a problem in calculating the distance. The output from the above code is as follows:

Code Output

Can anyone point out what the problem could be?

0

There are 0 answers