【发布时间】: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)
结束
【问题讨论】: