main.lua 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. log.info("main", "usb uart demo")
  8. local uartid = uart.VUART_0 -- USB虚拟串口的固定id
  9. --初始化
  10. local result = uart.setup(
  11. uartid,--串口id
  12. 115200,--波特率
  13. 8,--数据位
  14. 1--停止位
  15. )
  16. -- 收取数据会触发回调, 这里的"receive" 是固定值
  17. uart.on(uartid, "receive", function(id, len)
  18. local s = ""
  19. repeat
  20. -- 如果是air302, len不可信, 传1024
  21. -- s = uart.read(id, 1024)
  22. s = uart.read(id, len)
  23. if s and #s > 0 then -- #s 是取字符串的长度
  24. -- 如果传输二进制/十六进制数据, 部分字符不可见, 不代表没收到
  25. -- 关于收发hex值,请查阅 https://doc.openluat.com/article/583
  26. log.info("uart", "receive", id, #s, s)
  27. uart.write(uart.VUART_0, s)
  28. -- log.info("uart", "receive", id, #s, s:toHex())
  29. end
  30. until s == ""
  31. end)
  32. local tx_buff = zbuff.create(4096)
  33. tx_buff:set(0, 0x31)
  34. -- 并非所有设备都支持sent事件
  35. uart.on(uartid, "sent", function(id)
  36. log.info("uart", "sent", id)
  37. end)
  38. sys.taskInit(function()
  39. while 1 do
  40. -- uart.write(uart.VUART_0, "hello test usb-uart\r\n")
  41. uart.tx(uart.VUART_0, tx_buff,0, tx_buff:len())
  42. sys.wait(1000)
  43. end
  44. end)
  45. -- 用户代码已结束---------------------------------------------
  46. -- 结尾总是这一句
  47. sys.run()
  48. -- sys.run()之后后面不要加任何语句!!!!!