nizam
Posts: 15
Joined: Wed Jul 30, 2014 1:52 am

problems with HC-SR04 ultrasonic sensor

Thu Jul 31, 2014 1:55 am

hi,
im just a noob in robotics.
im doing a research on robotic and ultrasonic sensor. When using a hc-sr04 and connected to raspberry pi with 50ms and lower time.sleep, my data seems not very stable.
I want to use an infinite loop for my sensor..but i dun know how to use it using python..btw this is my copied code from someone`s page :(

Code: Select all

#!/usr/bin/python
import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

GPIO_TRIGGER = 23
GPIO_ECHO = 24

print "Ultrasonic Measurement"

GPIO.setup(GPIO_TRIGGER,GPIO.OUT)
GPIO.setup(GPIO_ECHO,GPIO.IN)     
try:

  while True:
    GPIO.output(GPIO_TRIGGER, False)
    time.sleep(0.05)
    GPIO.output(GPIO_TRIGGER, True)
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)
    start = time.time()
    while GPIO.input(GPIO_ECHO)==0:
      start = time.time()

    while GPIO.input(GPIO_ECHO)==1:
      stop = time.time()
    elapsed = stop-start
    distance = elapsed * 34000
    distance = distance / 2

    print "Distance : %.1f" % distance
except KeyboardInterupt:
    GPIO.cleanup()

User avatar
davef21370
Posts: 897
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Re: problems with HC-SR04 ultrasonic sensor

Sat Aug 02, 2014 3:07 pm

That is an infinite loop although it will try printing the distance about 200 times a second which isn't going to happen so you may want to add a sleep after the print.

Dave.
Apple say... Monkey do !!

nizam
Posts: 15
Joined: Wed Jul 30, 2014 1:52 am

Re: problems with HC-SR04 ultrasonic sensor

Sun Aug 03, 2014 11:51 pm

davef21370 wrote:That is an infinite loop although it will try printing the distance about 200 times a second which isn't going to happen so you may want to add a sleep after the print.

Dave.
thanks dave. I already put time.sleep(0.05) after print..but still it stop and give unstable reading. Thanks again for replying

Return to “Python”