main.lua 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "usb_uart"
  3. VERSION = "1.0.0"
  4. -- 引入必要的库文件(lua编写), 内部库不需要require
  5. sys = require("sys")
  6. _G.sysplus = require("sysplus")
  7. --[[
  8. 注意: 若使用普通串口调试功能, 需要以下条件之一才能收到数据
  9. 1. 把DTR设置为高电平
  10. 2. 先发送一次数据
  11. ]]
  12. log.info("main", "usb uart demo")
  13. local uartid = uart.VUART_0 -- USB虚拟串口的固定id
  14. --初始化
  15. local result = uart.setup(
  16. uartid,--串口id
  17. 115200,--波特率,其实无所谓, 纯虚拟串口
  18. 8,--数据位
  19. 1--停止位
  20. )
  21. -- 收取数据会触发回调, 这里的"receive" 是固定值
  22. uart.on(uartid, "receive", function(id, len)
  23. local s = ""
  24. repeat
  25. -- s = uart.read(id, 1024)
  26. s = uart.read(id, len)
  27. if s and #s > 0 then -- #s 是取字符串的长度
  28. -- 如果传输二进制/十六进制数据, 部分字符不可见, 不代表没收到
  29. -- 关于收发hex值,请查阅 https://doc.openluat.com/article/583
  30. log.info("uart", "receive", id, #s, s)
  31. uart.write(uart.VUART_0, s)
  32. -- log.info("uart", "receive", id, #s, s:toHex())
  33. end
  34. until s == ""
  35. end)
  36. local tx_buff = zbuff.create(24)
  37. tx_buff:set(0, 0x31)
  38. -- 并非所有设备都支持sent事件
  39. uart.on(uartid, "sent", function(id)
  40. log.info("uart", "sent", id)
  41. end)
  42. sys.taskInit(function()
  43. while 1 do
  44. -- uart.write(uart.VUART_0, "hello test usb-uart\r\n")
  45. uart.tx(uart.VUART_0, tx_buff,0, tx_buff:len())
  46. sys.wait(1000)
  47. end
  48. end)
  49. -- 用户代码已结束---------------------------------------------
  50. -- 结尾总是这一句
  51. sys.run()
  52. -- sys.run()之后后面不要加任何语句!!!!!