main.lua 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 uart_id = 1
  14. local uartid = 2 -- 根据实际设备选取不同的uartid
  15. local _uart485Pin = 18
  16. gpio.setup(_uart485Pin, 0, nil, nil, 4)
  17. -- --gpio.setup(18, 0, nil, nil, 4)
  18. --初始化
  19. -- 485自动切换, 选取GPIO10作为收发转换脚
  20. uart.setup(uart_id, 9600, 8, 1, uart.NONE)
  21. uart.setup(uartid, 9600, 8, 1, uart.NONE, uart.LSB, 1024, _uart485Pin, 0, 2000)
  22. -- uart.setup(uartid, 9600, 8, 1, uart.NONE)
  23. --循环发数据
  24. sys.timerLoopStart(uart.write,1000, uart_id, "test")
  25. sys.timerLoopStart(uart.write,1000, uartid, "test")
  26. -- 收取数据会触发回调, 这里的"receive" 是固定值
  27. sys.taskInit(function ()
  28. uart.on(uart_id, "receive", function(id, len)
  29. -- if uart_id ~= id then
  30. -- return
  31. -- end
  32. local s = ""
  33. repeat
  34. -- s = uart.read(id, 1024)
  35. s = uart.read(id, len)
  36. if #s > 0 then -- #s 是取字符串的长度
  37. -- 如果传输二进制/十六进制数据, 部分字符不可见, 不代表没收到
  38. -- 关于收发hex值,请查阅 https://doc.openluat.com/article/583
  39. log.info("uart", "receive", id, #s, s)
  40. -- log.info("uart", "receive", id, #s, s:toHex())
  41. end
  42. if #s == len then
  43. break
  44. end
  45. until s == ""
  46. end)
  47. end)
  48. sys.taskInit(function ()
  49. uart.on(uartid, "receive", function(id, len)
  50. -- if uartid ~= id then
  51. -- return
  52. -- end
  53. local s = ""
  54. repeat
  55. -- s = uart.read(id, 1024)
  56. s = uart.read(id, len)
  57. if #s > 0 then -- #s 是取字符串的长度
  58. -- 如果传输二进制/十六进制数据, 部分字符不可见, 不代表没收到
  59. -- 关于收发hex值,请查阅 https://doc.openluat.com/article/583
  60. log.info("uart", "receive", id, #s, s)
  61. -- log.info("uart", "receive", id, #s, s:toHex())
  62. end
  63. if #s == len then
  64. break
  65. end
  66. until s == ""
  67. end)
  68. end)
  69. -- 并非所有设备都支持sent事件
  70. uart.on(uart_id, "sent", function(id)
  71. log.info("uart", "sent", id)
  72. end)
  73. uart.on(uartid, "sent", function(id)
  74. log.info("uart", "sent", id)
  75. end)
  76. -- sys.taskInit(function()
  77. -- while 1 do
  78. -- sys.wait(500)
  79. -- end
  80. -- end)
  81. -- 用户代码已结束---------------------------------------------
  82. -- 结尾总是这一句
  83. sys.run()
  84. -- sys.run()之后后面不要加任何语句!!!!!