I am using hcsr04 ultrasonic sensor to measure distance. While the NodeMCU is running the official firmware from Github, the sensor works fine. However, when the NodeMCU is flashed with customized firmware from https://nodemcu-build.com/, then the sensor does not work. I used the same code for both. I am sure I have selected all the necessary modules. I have no idea what the problem is. Code is attached below. Thanks for your help!
time_start = 0
time_end = 0
trig = 8
echo = 7
gpio.mode(trig, gpio.OUTPUT)
gpio.mode(echo, gpio.INT)
function echo_cb(level)
if level == 1 then
time_start = tmr.now()
gpio.trig(echo, "down", echo_cb)
else
time_end = tmr.now()
end
end
function measure()
gpio.trig(echo, "up", echo_cb) -- Echo pin at rising edge, call echo_cb
gpio.write(trig, gpio.HIGH) -- trig low
tmr.delay(100)
gpio.write(trig, gpio.LOW) -- trig high
tmr.delay(100000) -- delay 10ms
if (time_end - time_start) < 0 then
return -1
end
return (time_end - time_start) / 58
end
distance = measure()
print("Distance: " .. distance .. " cm")