- Sat Apr 30, 2016 10:37 am
#46554
Hi ,I'm trying to get a led blink with a hc sr04 ultrasonic sensor .The closer the object is the faster will the blink be but it seems like tmr.alarm won't work i've been trying to debug but it is quite frustrating here is my code if anyone can help out.
Code: Select allecho = 4
trig = 3
time_start = 0
time_end = 0
time_diff = 0
distance = 0
pin = 2
lighton = 1
function setup()
gpio.mode(echo,gpio.INT)
gpio.mode(trig,gpio.OUTPUT)
gpio.trig(echo,"up",rising_edge)
gpio.mode(pin,gpio.OUTPUT)
tmr.alarm(1,1000,1,function()
if lighton == 0 then
lighton = 1
gpio.write(pin,gpio.HIGH)
else
lighton = 0
gpio.write(pin,gpio.LOW)
end
end)
end
function falling_edge()
time_end = tmr.now()
gpio.trig(echo,"up",rising_edge)
time_diff = (time_end - time_start )
print("time diff:"..time_diff.."\n")
distance = time_diff / 58
print("distance is "..distance.."\n")
time_start = 0
time_end = 0
tmr.interval(1,distance * 20)
end
function rising_edge()
gpio.trig(echo,"down",falling_edge)
time_start = tmr.now()
end
setup()
while (1) do
gpio.write(trig,gpio.LOW)
tmr.delay(5)
gpio.write(trig,gpio.HIGH)
tmr.delay(10)
gpio.write(trig,gpio.LOW)
tmr.delay(1000000)
end