Message Boards Message Boards

0
|
3361 Views
|
0 Replies
|
0 Total Likes
View groups...
Share
Share this post:

ultrasonic sensor does not show correct distance?

Posted 8 years ago

I am doing a project using ultrasonic sensor with raspberry pi. whenever I am connecting the ground pin into my pi it shows distance which is also not correct.I have to hold the ground pin for distance but it is not showing correct distance either.Wiring, VCC is connected to 5V (PIN-2) , ground is connected to PIN-6, TRIG is PIN-23 and ECHO is PIN-24 Below is the code:

import time
import RPi.GPIO as GPIO


def measure():

  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 * 34300)/2

  return distance

def measure_average():

  distance1=measure()
  time.sleep(0.1)
  distance2=measure()
  time.sleep(0.1)
  distance3=measure()
  distance = distance1 + distance2 + distance3
  distance = distance / 3
  return distance

GPIO.setmode(GPIO.BCM)

GPIO_TRIGGER = 23
GPIO_ECHO    = 24

print "Ultrasonic Measurement"

GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo

GPIO.output(GPIO_TRIGGER, False)

try:

while True:

distance = measure_average()
print "Distance : %.1f" % distance
time.sleep(1)

except KeyboardInterrupt: GPIO.cleanup()

POSTED BY: Yagya maharshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract