main.lua 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "usb_uart"
  3. VERSION = "1.0.0"
  4. log.info("main", PROJECT, VERSION)
  5. -- 引入必要的库文件(lua编写), 内部库不需要require
  6. sys = require("sys")
  7. --[[
  8. 注意: 若使用普通串口调试功能, 需要以下条件之一才能收到数据
  9. 1. 把DTR设置为高电平
  10. 2. 先发送一次数据
  11. 参考用的上位机, 用py演示, 需要pyserial库
  12. import os, sys, serial.tools.list_ports, time
  13. for item in serial.tools.list_ports.comports():
  14. if not item.pid or not item.location :
  15. continue
  16. if item.vid == 0x19d1 and item.pid == 0x0001 and "x.6" in item.location :
  17. print(dir(item))
  18. print(item.name)
  19. with serial.Serial(item.name, 115200, timeout=1) as ser:
  20. while 1:
  21. data = ser.read(128)
  22. if data :
  23. print( str(time.time()) + ">> " + str(data))
  24. else :
  25. ser.write("Hi from PC".encode())
  26. ]]
  27. log.info("main", "usb uart demo")
  28. local uartid = uart.VUART_0 -- USB虚拟串口的固定id
  29. -- 2025年5月6日新增,虚拟UART对端(比如PC串口工具)打开和关闭通知
  30. sys.subscribe("VUART_STATE", function(vuart_id, state)
  31. log.info("vuart", vuart_id, "is connect", state)
  32. end)
  33. --初始化
  34. local result = uart.setup(
  35. uartid,--串口id
  36. 115200,--波特率,其实无所谓, 纯虚拟串口
  37. 8,--数据位
  38. 1--停止位
  39. )
  40. -- 收取数据会触发回调, 这里的"receive" 是固定值
  41. uart.on(uartid, "receive", function(id, len)
  42. local s = ""
  43. repeat
  44. -- s = uart.read(id, 1024)
  45. s = uart.read(id, len)
  46. if s and #s > 0 then -- #s 是取字符串的长度
  47. -- 如果传输二进制/十六进制数据, 部分字符不可见, 不代表没收到
  48. -- 关于收发hex值,请查阅 https://doc.openluat.com/article/583
  49. log.info("uart", "receive", id, #s, s)
  50. uart.write(uart.VUART_0, s)
  51. -- log.info("uart", "receive", id, #s, s:toHex())
  52. end
  53. until s == ""
  54. end)
  55. local tx_buff = zbuff.create(24)
  56. tx_buff:set(0, 0x31)
  57. -- 并非所有设备都支持sent事件
  58. uart.on(uartid, "sent", function(id)
  59. log.info("uart", "sent", id)
  60. end)
  61. sys.taskInit(function()
  62. while 1 do
  63. -- uart.write(uart.VUART_0, "hello test usb-uart\r\n")
  64. uart.tx(uart.VUART_0, tx_buff,0, tx_buff:len())
  65. sys.wait(1000)
  66. end
  67. end)
  68. -- 用户代码已结束---------------------------------------------
  69. -- 结尾总是这一句
  70. sys.run()
  71. -- sys.run()之后后面不要加任何语句!!!!!