main.lua 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "uart_irq"
  3. VERSION = "1.0.0"
  4. log.info("main", PROJECT, VERSION)
  5. -- 引入必要的库文件(lua编写), 内部库不需要require
  6. sys = require("sys")
  7. if wdt then
  8. --添加硬狗防止程序卡死,在支持的设备上启用这个功能
  9. wdt.init(9000)--初始化watchdog设置为9s
  10. sys.timerLoopStart(wdt.feed, 3000)--3s喂一次狗
  11. end
  12. log.info("main", "uart demo")
  13. local uartid = 1 -- 根据实际设备选取不同的uartid
  14. --初始化
  15. local result = uart.setup(
  16. uartid,--串口id
  17. 115200,--波特率
  18. 8,--数据位
  19. 1--停止位
  20. )
  21. --循环发数据
  22. sys.timerLoopStart(uart.write,1000, uartid, "test")
  23. -- 收取数据会触发回调, 这里的"receive" 是固定值
  24. uart.on(uartid, "receive", function(id, len)
  25. local s = ""
  26. repeat
  27. -- 如果是air302, len不可信, 传1024
  28. -- s = uart.read(id, 1024)
  29. s = uart.read(id, len)
  30. if #s > 0 then -- #s 是取字符串的长度
  31. -- 如果传输二进制/十六进制数据, 部分字符不可见, 不代表没收到
  32. -- 关于收发hex值,请查阅 https://doc.openluat.com/article/583
  33. log.info("uart", "receive", id, #s, s)
  34. -- log.info("uart", "receive", id, #s, s:toHex())
  35. end
  36. if #s == len then
  37. break
  38. end
  39. until s == ""
  40. end)
  41. -- 并非所有设备都支持sent事件
  42. uart.on(uartid, "sent", function(id)
  43. log.info("uart", "sent", id)
  44. end)
  45. -- sys.taskInit(function()
  46. -- while 1 do
  47. -- sys.wait(500)
  48. -- end
  49. -- end)
  50. -- 用户代码已结束---------------------------------------------
  51. -- 结尾总是这一句
  52. sys.run()
  53. -- sys.run()之后后面不要加任何语句!!!!!