hcsr04 = {}
function hcsr04.init(trig_pin, echo_pin, average)
local self = {}
self.trig_pin = trig_pin or 7
self.echo_pin = echo_pin or 6
self.average = average or 3
gpio.mode(self.trig_pin, gpio.OUTPUT)
gpio.mode(self.echo_pin, gpio.INT)
self.time_start = 0
self.time_end = 0
self.dist = {}
self.count = 0
function self.echo_int(level)
if level == 1 then
self.time_start = tmr.now()
gpio.trig(self.echo_pin, "down")
else
self.time_end = tmr.now()
end
end
function self.trigger()
self.time_start = 0
self.time_end = 0
-- register echo interrupt
gpio.trig(self.echo_pin, "up", self.echo_int)
-- start trigger
gpio.write(self.trig_pin, gpio.HIGH)
-- end trigger impuls after 100us
tmr.delay(20)
gpio.write(self.trig_pin, gpio.LOW)
-- start the watchdog
tmr.alarm(2,100,tmr.ALARM_SINGLE, function ()
if (self.time_end - self.time_start) < 0 then
self.dist = -1
print("measurement failed - " .. self.count)
else
self.count = self.count + 1
self.dist[self.count] = (self.time_end - self.time_start) / 5800
if (self.count < self.average) then
self.trigger()
else
local dist = 0
for loop, value in ipairs(self.dist) do
dist = dist + value
end
dist = dist / self.count
print("distance: " .. dist)
end
end
end)
end
return self
end
The problem is that it seems the trigger signal is not send properly or the interrupt is not fired. Unfortunately I do not have a scope to figure out which one is the issue. When resetting the nodeMCU, the measurement works fine. Afterwards, however, the measurement fails (usually on the very first iteration). It fails because the interrupt (registered on the ECHO pin) isn't fired.
Any ideas what could be the problem here?
---
HC-SR04 background:
One needs to send a pulse on the TRIGGER pin (at least 10us) to trigger the measurement. The measured distance is given back by the impulse length on the ECHO pin.