nodemcu + esp8266 + hc-sr04 - tmr.now() 的差异不正确。

我已经开始使用ESP8266上的NodeMCU。我用HC-SR04(用于距离测量的超声波传感器)连接了ESP。HC-SR04需要在trig引脚上接收10us的高状态。之后,HC会发送echo引脚的高状态。来自echo引脚的高状态的时间可能不同(取决于距离)。时间以微秒计算。问题在于来自echo引脚的时间不正确(在我看来)。我不确定,但这是有可能吗?来自NodeMCU的tmr并不如应该那样精确吗?为什么每个循环中的时间之间存在如此大的差异?

我的代码,以下是代码中的时间打印:

gpio.write(3,gpio.LOW)
gpio.mode(3,gpio.OUTPUT)

gpio.write(4,gpio.LOW)
gpio.mode(4,gpio.INT)

time=0
flag=0
i=1

function startDis(level)
    time=tmr.now()
end

function endDis(level)
    time=tmr.now()-time
    flag=0
end

function trigger()
    gpio.write(3,gpio.HIGH)
    tmr.delay(10)
    gpio.write(3,gpio.LOW)
    flag=1
end

gpio.trig(4,'up',startDis)
gpio.trig(4,'down',endDis)

//---------此部分已更改--------

while i<10 do
    if flag==0 then
        trigger()
    end
    tmr.delay(1000000)
    print(time)
    i=i+1
end

//--------------- TO ------------

tmr.alarm(0,2000,1,function()
    print(time)
    print(i)
    if flag==0 then
        trigger()
    end
    i=i+1
    if i==10 then tmr.stop(0) end
end)

代码打印:

0
440184038
1999856
442183990
4000221
444184055
6000175
446184287
7999686

感谢指引和解决方案。

点赞
用户1142045
用户1142045

Petre,我会把它作为答案来回答,因为它不适合快速评论。:(

你需要阅读FAQ中关于整个SDK如何安排任务的其他讨论。你在代码中假设这样的事情发生:

<每2毫秒>
print(time)
print(i)
if flag==0 then
gpio.write(3,gpio.HIGH)
time=tmr.now()
tmr.delay(10)
gpio.write(3,gpio.LOW)
time=tmr.now()-time
flag=0
flag=1
执 行 完 成
i=i+1
if i==10 then tmr.stop(0) end

实际上发生的情况更接近于:

<每2毫秒任务开始>
print(time)
print(i)
if flag==0 then
gpio.write(3,gpio.HIGH)
<H/W interupts calls low level GPIO which books up callback>
time=tmr.now()
tmr.delay(10)
<H/W interupts calls low level GPIO which books down callback>
gpio.write(3,gpio.LOW)
flag=1
执 行 完 成
i=i+1
if i==10 then tmr.stop(0) end
<任务结束>
<可能运行TCP和其他任务>
<up trigger发送>
time=tmr.now()
<任务结束>
<可能运行TCP和其他任务>
<down trigger发送>
time=tmr.now()-time
flag=0
<任务结束>

Esp8266 SDK不是真正的实时操作系统;它是事件驱动的。你的思维方式需要重新调整。

以这种方式使用 tmr.delay() 是正确的,但你需要硬件测试工具,如示波器或逻辑分析仪,来检查实际延迟时间,因为你需要加上处理Lua指令的时间。甚至放置tmr.now()调用内联也可以。

触发器的真正用途是,当你连接到传感器(例如机械开关检测器)时,避免了需要轮询它的必要性。

2015-09-09 21:48:02