I made this simple robot using LEGO and it uses a Raspberry Pi as the computer. The code I wrote was in Python and basically what it does is use the ultrasonic sensor to to measure distance. Here is the code:
import RPi.GPIO as g
import time as t
g.setmode(g.BCM)
g.setwarnings(False)
# trig is the pin on the sensor which will emit a very fast pulse
trig = 21
# echo is the pin which will recieve the pulse from the trig
echo = 20
g.setup(trig, g.OUT)
g.setup(echo, g.IN)
def distance(dur):
global dis
start = 0
end = 0
g.output(trig, False)
t.sleep(0.01)
g.output(trig, True)
t.sleep(0.00001)
g.output(False)
while g.input(echo) == 0:
start = t.time()
while g.input(echo) == 1:
start = t.time()
duration = end - start
dis = duration * 17150
dis = round(dis,2)
print "Distance: " + dis
t.sleep(dur)
while True:
# so the function is being called, and the time between outputs is 0.01 seconds so it is very
# fast and quickly showing on the screen. If the distance is less than 5, then the program
# will print out "Hi" to show that. s
distance(0.01)
if dis < 5:
print "Hi"
Pretty straightforward right? But you see, the code executes flawlessly, it shows the distance and when I put my hand near the sensor and the variable dis becomes less than 5, the program prints out "Hi"... UNTIL THIS:
Ultrasonic Sensor Distance Output Picture. You can see that the output stream just stalls. It literally stops and that is it. No error message, nothing. And the worst part about it is that it does this randomly. It could stall when it is just printing out the distance, it can stall when it is printing "Hi" but I did notice that it stalled a lot more frequently when it was printing "Hi" and it stalls after a random number of outputs. So the next thing I do is press ctrl+c to stop the program and this is what it looks like. I also forgot to mention that three ultrasonic sensors are hooked together as one and uses just GPIO 21 and GPIO 20. It still works though and even when they had their own separate pairs of pins they still had the same stalling problem so it does not make a difference.
If anyone has an idea as to what is causing this, I would be so happy because I spend hours trying to fix it.