simple_uart.lua 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. --[[
  2. @module simple_uart
  3. @summary 简易串口功能模块
  4. @version 1.0
  5. @date 2025.09.23
  6. @author 魏健强
  7. @usage
  8. 本demo演示的核心功能为:
  9. 1.开启串口,配置波特率等参数;
  10. 2.设置接收回调函数
  11. 3.定时向串口发送数据
  12. ]]
  13. local uartid = 1 -- 根据实际设备选取不同的uartid
  14. local function uart_send()
  15. -- 循环两秒向串口发一次数据
  16. while true do
  17. sys.wait(2000)
  18. uart.write(uartid, "test data.")
  19. end
  20. end
  21. local function uart_send_cb(id)
  22. log.info("uart", id , "数据发送完成回调")
  23. end
  24. local function uart_cb(id, len)
  25. local s = ""
  26. repeat
  27. s = uart.read(id, 128) -- 读取缓冲区中的数据,这里设置的一次读最多128字节
  28. if #s > 0 then -- #s 是取字符串的长度
  29. -- 关于收发hex值,请查阅 https://doc.openluat.com/article/583
  30. log.info("uart", "receive", id, #s, s)
  31. -- log.info("uart", "receive", id, #s, s:toHex()) --如果传输二进制/十六进制数据, 部分字符不可见, 不代表没收到
  32. end
  33. until s == ""
  34. end
  35. --初始化
  36. uart.setup(
  37. uartid,--串口id
  38. 115200,--波特率
  39. 8,--数据位
  40. 1--停止位
  41. )
  42. -- 收取数据会触发回调, 这里的"receive" 是固定值
  43. uart.on(uartid, "receive", uart_cb)
  44. -- 发送数据完成会触发回调, 这里的"sent" 是固定值
  45. uart.on(uartid, "sent", uart_send_cb)
  46. sys.taskInit(uart_send)