uart.on("data", ... 不触发 withoug "\r\n" (0x0d 0x0a)

uart.on("data", ... not firing withoug "\r\n" (0x0d 0x0a)

我目前正在 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)

结束

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

这解决了我的问题。