【问题标题】:uart.on("data", ... not firing withoug "\r\n" (0x0d 0x0a)uart.on("data", ... 没有触发"\r\n" (0x0d 0x0a)
【发布时间】:2016-12-29 22:40:33
【问题描述】:

我目前正在 lua 中为 NodeMCU 固件编写室内空气质量传感器(CO2 和颗粒物)的驱动程序。

传感器通过备用 UART 引脚 GPIO13/15 连接。在发出测量命令时,ESP 切换 uart.alt(1) 并注册 uart.on("data", 9, ...) 函数,以便在接收到九个字节后触发。我已经用两个连接到本机和备用 UART 引脚的 ch340 对此进行了测试。 如果我手动输入数据并添加 \r\n (0d 0a),则值的读数很好。

但是,我使用的传感器在其回复末尾没有 \r\n - 如何更改我的代码以在收到 9 个字节后读出 UART 缓冲区?

function MHZ19:measure(callback)
-- timeout and restore UART
tmr.alarm(self.timer, self.timeout*1000, 0,
function()
    uart.alt(0)
    uart.setup(0, 115200, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
    uart.on('data')
    print("Timed out. Restored UART.")
    callback(nil)
end)

uart.on('data', 9,
    function(data)
        -- unregister uart.on callback
        uart.on('data')
        tmr.stop(self.timer)
        uart.alt(0)
        uart.setup(0, 115200, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
        -- First two bytes are control bytes 0xFF && 0x86
        local a,b = string.byte(data,1,2)
        if (a==tonumber('FF',16)) and (b==tonumber('86',16)) then
            local high,low = string.byte(data,3,4)
            local co2value = high * 256 + low
            callback(co2value)
        else
            callback(nil)
        end
    end)

    uart.alt(self.altUart)
    uart.setup(0, 9600, 8, uart.PARITY_NONE, uart.STOPBITS_1, 0)

    -- Send request sequence to get value (refer to datasheet)
    -- send: FF 01 86 00 00 00 00 00 79
    -- receive: FF 86 02 E8 42 04 2B 1C 03
    uart.write(0, 0xff, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79)

结束

【问题讨论】:

    标签: lua esp8266 nodemcu


    【解决方案1】:

    根据NodeMCU Documentationuart.on() 命令接受可选参数[run_input]。 如果此参数设置为 1,解释器将等待 '\r' 或 '\n' 然后运行命令。 将此参数设置为 0 并设置要接收的字节数,在检索到指定的字节数时调用回调函数。

    这解决了我的问题。

    【讨论】:

    • 嗨,弗拉德,当然 - 至于上面提到的函数,它用于通过 UART 向 CO2 传感器写入命令,然后等待传感器的应答。只需将第二个参数放入 uart.on (在这种情况下,在 '... end, ' 之后的 '0' uart.on('data', 9, function(data) print(data) end, 0)
    • 我没看错吧,功能前必须有模块介绍,即local MHZ19 = {timer = 1, timeout = 1, altUart = 0},用法是MHZ19 = require("MHZ19")?您将哪个 nodemcu 开发板引脚连接到 tr/rx?谢谢!
    • 是的,你没看错。您可以查看 nodemcu 存储库中的 lua-module 示例。对于引脚分配,uart 模块的 nodemcu 文档描述了替代 gpios。我认为它们是 14 和 15,但我不知道 nodemcu 板的哪些引脚可以转换为。
    猜你喜欢
    • 2016-01-17
    • 2021-05-20
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多