rotary.lua 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. -- 旋转编码器
  2. -- 正反方向根据实际情况决定
  3. local rtos_bsp = rtos.bsp()
  4. function pinx() -- 根据不同开发板,给LED赋值不同的gpio引脚编号
  5. if rtos_bsp == "AIR105" then
  6. return pin.PC09, pin.PA10
  7. elseif string.find(rtos_bsp,"EC718") then -- Air780E开发板引脚
  8. return 12,13
  9. else
  10. log.info("main", "define led pin in main.lua")
  11. return 255,255
  12. end
  13. end
  14. local s1_pin, s2_pin = pinx()
  15. local pin_need = 1
  16. local s1_last = nil
  17. local s2_last = nil
  18. local s1_up = false
  19. local s2_up = false
  20. local s1_down = false
  21. local s2_down = false
  22. local _,us_tick = mcu.tick64()
  23. us_tick = us_tick * 1000 --低于1ms的当杂波去除,可以根据实际需要修改
  24. local function stage1()
  25. pin_need = 0
  26. -- log.info("wait down")
  27. ioqueue.exti(s1_pin, nil, gpio.FALLING, true)
  28. ioqueue.exti(s2_pin, nil, gpio.FALLING, true)
  29. end
  30. local function stage2()
  31. pin_need = 1
  32. -- log.info("wait up")
  33. ioqueue.exti(s1_pin, nil, gpio.RISING, true)
  34. ioqueue.exti(s2_pin, nil, gpio.RISING, true)
  35. s1_up,s2_up,s1_down,s2_down = false,false,false,false
  36. end
  37. local function s1_irq(val, tick)
  38. if gpio.get(s1_pin) ~= pin_need then return end
  39. if s1_last then
  40. local result,_ = mcu.dtick64(tick, s1_last, us_tick)
  41. if result then
  42. -- log.info("s1", mcu.dtick64(tick, s1_last))
  43. if pin_need > 0 then
  44. s1_up = true
  45. else
  46. s1_down = true
  47. end
  48. -- log.info("s1", s1_up, s1_down)
  49. else
  50. return
  51. end
  52. else
  53. -- log.info("s1")
  54. s1_up = true
  55. end
  56. if pin_need > 0 and s1_up and s2_up then
  57. stage1()
  58. end
  59. if s2_down then
  60. log.info("s2pin先检测到,右转+1")
  61. stage2()
  62. end
  63. s1_last = tick
  64. end
  65. local function s2_irq(val, tick)
  66. if gpio.get(s2_pin) ~= pin_need then return end
  67. if s2_last then
  68. local result,_ = mcu.dtick64(tick, s2_last, us_tick)
  69. if result then
  70. -- log.info("s2", mcu.dtick64(tick, s2_last))
  71. if pin_need > 0 then
  72. s2_up = true
  73. else
  74. s2_down = true
  75. end
  76. -- log.info("s2", s2_up, s2_down)
  77. else
  78. return
  79. end
  80. else
  81. -- log.info("s2")
  82. s2_check = true
  83. end
  84. if pin_need > 0 and s1_up and s2_up then
  85. stage1()
  86. end
  87. if s1_down then
  88. log.info("s1pin先检测到,左转+1")
  89. stage2()
  90. end
  91. s2_last = tick
  92. end
  93. sys.subscribe("IO_QUEUE_EXTI_" .. s1_pin, s1_irq)
  94. sys.subscribe("IO_QUEUE_EXTI_" .. s2_pin, s2_irq)
  95. function rotary_start()
  96. pin_need = 1
  97. ioqueue.exti(s1_pin, nil, gpio.RISING, true)
  98. ioqueue.exti(s2_pin, nil, gpio.RISING, true)
  99. -- sys.timerLoopStart(clear, 10000)
  100. end