usb_uart.lua 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. --[[
  2. @module usb_uart
  3. @summary USB虚拟串口功能模块
  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 = uart.VUART_0 -- 使用USB虚拟串口,固定id
  14. local function uart_send()
  15. local data =
  16. {
  17. host = "abcdefg.com",
  18. port = "1883",
  19. clientID = "c88885",
  20. username = "user",
  21. password = "123456",
  22. ca_self = {ssl=false},
  23. }
  24. local jsondata = json.encode(data)
  25. -- 循环每两秒向串口发一次数据
  26. while true do
  27. sys.wait(2000)
  28. uart.write(uartid, jsondata)
  29. end
  30. end
  31. local function uart_send_cb(id)
  32. log.info("uart", id , "数据发送完成回调")
  33. end
  34. local function uart_cb(id, len)
  35. local s = ""
  36. repeat
  37. s = uart.read(id, 128) -- 读取缓冲区中的数据,这里设置的一次读最多128字节
  38. if #s > 0 then -- #s 是取字符串的长度
  39. -- 关于收发hex值,请查阅 https://doc.openluat.com/article/583
  40. log.info("uart", "receive", id, #s, s)
  41. -- log.info("uart", "receive", id, #s, s:toHex()) --如果传输二进制/十六进制数据, 部分字符不可见, 不代表没收到
  42. end
  43. until s == ""
  44. end
  45. --初始化
  46. uart.setup(
  47. uartid,--串口id
  48. 115200,--波特率
  49. 8,--数据位
  50. 1--停止位
  51. )
  52. -- 收取数据会触发回调, 这里的"receive" 是固定值
  53. uart.on(uartid, "receive", uart_cb)
  54. -- 发送数据完成会触发回调, 这里的"sent" 是固定值
  55. uart.on(uartid, "sent", uart_send_cb)
  56. sys.taskInit(uart_send)