I am trying to get the NodeMCU ESP8266 dev board to work with an HC SR04 Ultrasonic Sensor. I keep getting a reading of "0", which is not the reality.
I have the ground and 5v pins of the sensor hooked up to a 5v source, and the Echo and Trigger pins on GPIO pin 4 and 5. In theory, everything should be working, but I just keep getting "0". Perhaps there is something wrong with my code? See below:
import machine
import sys
import time
time.sleep(1) #Just for everything to settle down
while 1:
pinTrigger = machine.Pin(5, machine.Pin.OUT) #defining the pins
pinEcho = machine.Pin(4, machine.Pin.IN) #defining the pins
pinTrigger.high()
time.sleep(0.00001)
pinTrigger.low()
time.sleep(0.5)
start = time.time()
stop = time.time()
while pinEcho ==0:
start = time.time() #Starting the time when sending out the signal
while pinTrigger ==1:
stop = time.time() #Stopping the time when the signal comes back
elapsed = stop-start #working out the time.
distance = elapsed * 34000 #multiply by speed of sound to get distance
distance = distance / 2 #divide by 2 becuase it was there and back
print ("Distance : %.1f" % distance)
sys.exit()
Please help.