I am trying to measure distance with HC-SR04 and Raspberry Pi A+ using Python on Raspbian. So here is how it is connected:
VCC - to the 5V Out from L289N motor driver
GND - to GND on the L298N motor driver
Trig - pin 12 (BOARD)
Echo - pin 22(BOARD) with 1K Ohm resistor
From the L298N Motor driver I measured ~4.8xx-4.9xx Volts so it should be enough to power the HC-SR04
I am using a 170 pin breadboard. I think I made a major mistake at the start, e.g connected pin 22 to Trig with the resistor and pin 12 to Echo. In the code I used(not mine, saw it on the net and wrote it manually) I had the pin 12 as OUT and pin 22 as IN and I tested it several times until I found out that wiring was wrong.
Here are 2 different python scripts I tried and both of them seem to stop at loops. With the one below I see the first print
and thats it, I have to kill with Ctrl+C
import time
import RPi.GPIO as gpio
gpio.setmode(gpio.BOARD)
trig = 12
echo = 22
gpio.setup(trig,gpio.OUT)
gpio.output(trig,0)
gpio.setup(echo,gpio.IN)
time.sleep(0.1)
print "Starting Measurement..."
gpio.output(trig,1)
time.sleep(0.00001)
gpio.output(trig,0)
while gpio.input(echo) == 0:
pass
start = time.time()
while gpio.input(echo) == 1:
pass
stop = time.time()
print (stop - start) * 17000
gpio.cleanup()
Here is the second piece of code(credits go to santdex on youtube)
import RPi.GPIO as gpio
import time
def distance(measure='cm'):
gpio.setmode(gpio.BOARD)
gpio.setup(12, gpio.OUT)
gpio.setup(22, gpio.IN)
gpio.output(12, False)
while gpio.input(22) == 0:
nosig = time.time()
while gpio.input(22) == 1:
sig = time.time()
tl = sig - nosig
if measure == 'cm':
distance = tl * 17000 #/ 0.000058
elif measure == 'in':
distance = tl / 0.000148
else:
print('improper choice of measurment: in or cm')
distance = None
gpio.cleanup()
return distance
print(distance('cm'))
Both of the scripts seem not working, but I do not know why. They seem to work for their inventors tough.
I do not know if I broke the sensor with wrong wiring and initial tests or if there is something else wrong. I hope someone could help. Thx in advance.
EDIT: So here are 2 images that should illustrate my wiring:
White goes to GND on L298N
Black to +5V on L298N
Purple(echo) to pin22
Grey to pin12
I am using 7 more pins to control 2 motors with PWM, but they are disconnected for now. Maybe I can try connecting the HC-SR04 to the Pi +5V and GND just to test it like that?
EDIT Just tested the sensor connected entirily to the Raspberry with the first script I posted and still it does not work. Wiring used only 1 resistor, e.g. GND to pin20 VCC to pin2 Echo to pin22 and Trig to pin 12. 1K Ohm resistor between Echo and pin22.