I am programming in python the use of the supersonic sensor HY-SRF05 using a Raspberry Pi 3. The program does not give an error, but it does not show the distance when executed, if I remove the class and the methods and leave only the linear code , it works correctly but I require the use of methods for future work issues. I need to show the distance. My code is as follows:
import mysql.connector
import requests
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO_TRIGGER = 25
GPIO_ECHO = 7
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)
GPIO.setup(GPIO_ECHO,GPIO.IN)
GPIO.output(GPIO_TRIGGER,False)
class Execute:
def ObtenerDistancia(self):
temperature = 20
speedSound = 33100 + (0.6*temperature)
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)
GPIO.setup(GPIO_ECHO,GPIO.IN)
GPIO.output(GPIO_TRIGGER, False)
time.sleep(0.5)# Allow module to settle
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)# Wait 10us
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 * speedSound
distance = distance / 2
print("Distance : {0:5.1f}".format(distance))
GPIO.cleanup()
return distance
x = Execute()
xDis = x.ObtenerDistancia
while True:
print (xDis())
My "linear" code:
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO_TRIGGER = 23
GPIO_ECHO = 24
temperature = 20
speedSound = 33100 + (0.6*temperature)
print("Ultrasonic Measurement")
print("Speed of sound is",speedSound/100,"m/s at ",temperature,"deg")
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)
GPIO.setup(GPIO_ECHO,GPIO.IN)
GPIO.output(GPIO_TRIGGER, False)
time.sleep(0.5)# Allow module to settle
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)# Wait 10us
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 * speedSound
distance = distance / 2
print("Distance : {0:5.1f}".format(distance))
GPIO.cleanup()