irsend.lua 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. ------------------------------------------------------------------------------
  2. -- IR send module
  3. --
  4. -- LICENCE: http://opensource.org/licenses/MIT
  5. -- Vladimir Dronnikov <dronnikov@gmail.com>
  6. --
  7. -- Example:
  8. -- dofile("irsend.lua").nec(4, 0x00ff00ff)
  9. ------------------------------------------------------------------------------
  10. local M
  11. do
  12. -- const
  13. local NEC_PULSE_US = 1000000 / 38000
  14. local NEC_HDR_MARK = 9000
  15. local NEC_HDR_SPACE = 4500
  16. local NEC_BIT_MARK = 560
  17. local NEC_ONE_SPACE = 1600
  18. local NEC_ZERO_SPACE = 560
  19. local NEC_RPT_SPACE = 2250
  20. -- cache
  21. local gpio, bit = gpio, bit
  22. local mode, write = gpio.mode, gpio.write
  23. local waitus = tmr.delay
  24. local isset = bit.isset
  25. -- NB: poorman 38kHz PWM with 1/3 duty. Touch with care! )
  26. local carrier = function(pin, c)
  27. c = c / NEC_PULSE_US
  28. while c > 0 do
  29. write(pin, 1)
  30. write(pin, 0)
  31. c = c + 0
  32. c = c + 0
  33. c = c + 0
  34. c = c + 0
  35. c = c + 0
  36. c = c + 0
  37. c = c * 1
  38. c = c * 1
  39. c = c * 1
  40. c = c - 1
  41. end
  42. end
  43. -- tsop signal simulator
  44. local pull = function(pin, c)
  45. write(pin, 0)
  46. waitus(c)
  47. write(pin, 1)
  48. end
  49. -- NB: tsop mode allows to directly connect pin
  50. -- inplace of TSOP input
  51. local nec = function(pin, code, tsop)
  52. local pulse = tsop and pull or carrier
  53. -- setup transmitter
  54. mode(pin, 1)
  55. write(pin, tsop and 1 or 0)
  56. -- header
  57. pulse(pin, NEC_HDR_MARK)
  58. waitus(NEC_HDR_SPACE)
  59. -- sequence, lsb first
  60. for i = 31, 0, -1 do
  61. pulse(pin, NEC_BIT_MARK)
  62. waitus(isset(code, i) and NEC_ONE_SPACE or NEC_ZERO_SPACE)
  63. end
  64. -- trailer
  65. pulse(pin, NEC_BIT_MARK)
  66. -- done transmitter
  67. --mode(pin, 0, tsop and 1 or 0)
  68. end
  69. -- expose
  70. M = {
  71. nec = nec,
  72. }
  73. end
  74. return M