在 Lua 中使用串口通讯需要使用到 luaserial 这个库。使用此库需要先安装,在 Windows 上可以使用 luarocks 安装,在 Linux 上可以使用 apt-get 安装。
安装完成后,可以使用以下代码打开串口:
local serial = require("luaserial")
local port = serial.open("/dev/ttyUSB0")
在打开串口后,可以使用以下代码来进行串口通讯:
-- 发送数据
port:write("hello")
-- 读取数据
local data = port:read(5) -- 读取5个字节的数据
注意,在读取数据时可能会因为缓冲区中没有足够的数据而阻塞。如果希望在没有数据时立即返回,可以使用 port:read(0) 这样的方式来读取缓冲区中的数据。
在使用完串口后,记得关闭串口:
port:close()
有关 luaserial 库的更多用法,可以参考其文档。