main.lua 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. PROJECT = "candemo"
  2. VERSION = "1.0.0"
  3. sys = require("sys")
  4. log.style(1)
  5. local SELF_TEST_FLAG = true --自测模式标识,写true就进行自收自发模式,写false就进行正常收发模式
  6. local node_a = true -- A节点写true, B节点写false
  7. local can_id = 0
  8. local rx_id
  9. local tx_id
  10. local stb_pin = 28 -- stb引脚根据实际情况写,不用的话,也可以不写
  11. if node_a then -- A/B节点区分,互相传输测试
  12. rx_id = 0x12345678
  13. tx_id = 0x12345677
  14. else
  15. rx_id = 0x12345677
  16. tx_id = 0x12345678
  17. end
  18. local test_cnt = 0
  19. local tx_buf = zbuff.create(8)
  20. local function can_cb(id, cb_type, param)
  21. if cb_type == can.CB_MSG then
  22. log.info("有新的消息")
  23. local succ, id, id_type, rtr, data = can.rx(id)
  24. while succ do
  25. log.info(mcu.x32(id), #data, data:toHex())
  26. succ, id, id_type, rtr, data = can.rx(id)
  27. end
  28. end
  29. if cb_type == can.CB_TX then
  30. if param then
  31. log.info("发送成功")
  32. else
  33. log.info("发送失败")
  34. end
  35. end
  36. if cb_type == can.CB_ERR then
  37. log.info("CAN错误码", mcu.x32(param))
  38. end
  39. if cb_type == can.CB_STATE then
  40. log.info("CAN新状态", param)
  41. end
  42. end
  43. local function can_tx_test(data)
  44. if node_a then
  45. log.info("node a tx")
  46. else
  47. log.info("node b tx")
  48. end
  49. test_cnt = test_cnt + 1
  50. if test_cnt > 8 then
  51. test_cnt = 1
  52. end
  53. tx_buf:set(0,test_cnt)
  54. tx_buf:seek(test_cnt)
  55. can.tx(can_id, tx_id, can.EXT, false, true, tx_buf)
  56. end
  57. -- can.debug(true)
  58. gpio.setup(stb_pin,0)
  59. -- gpio.setup(stb_pin,1) -- 如果开发板上STB信号有逻辑取反,则要配置成输出高电平
  60. can.init(can_id, 128)
  61. can.on(can_id, can_cb)
  62. can.timing(can_id, 1000000, 6, 6, 4, 2)
  63. -- can.timing(can_id, 100000, 6, 6, 3, 2)
  64. if SELF_TEST_FLAG then
  65. can.node(can_id, tx_id, can.EXT) -- 测试模式下,允许接收的ID和发送ID一致才会有新数据提醒
  66. can.mode(can_id, can.MODE_TEST) -- 如果只是自身测试硬件好坏,可以用测试模式来验证,如果发送成功就OK
  67. else
  68. can.node(can_id, rx_id, can.EXT)
  69. can.mode(can_id, can.MODE_NORMAL) -- 一旦设置mode就开始正常工作了,此时不能再设置node,timing,filter等
  70. end
  71. sys.timerLoopStart(can_tx_test, 1000)
  72. sys.run()