irsend.lua 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. -- luacheck: push no unused
  14. local NEC_PULSE_US = 1000000 / 38000
  15. local NEC_HDR_MARK = 9000
  16. local NEC_HDR_SPACE = 4500
  17. local NEC_BIT_MARK = 560
  18. local NEC_ONE_SPACE = 1600
  19. local NEC_ZERO_SPACE = 560
  20. local NEC_RPT_SPACE = 2250
  21. -- luacheck: pop
  22. -- cache
  23. local gpio, bit = gpio, bit
  24. local mode, write = gpio.mode, gpio.write
  25. local waitus = tmr.delay
  26. local isset = bit.isset
  27. -- NB: poorman 38kHz PWM with 1/3 duty. Touch with care! )
  28. local carrier = function(pin, c)
  29. c = c / NEC_PULSE_US
  30. while c > 0 do
  31. write(pin, 1)
  32. write(pin, 0)
  33. c = c + 0
  34. c = c + 0
  35. c = c + 0
  36. c = c + 0
  37. c = c + 0
  38. c = c + 0
  39. c = c * 1
  40. c = c * 1
  41. c = c * 1
  42. c = c - 1
  43. end
  44. end
  45. -- tsop signal simulator
  46. local pull = function(pin, c)
  47. write(pin, 0)
  48. waitus(c)
  49. write(pin, 1)
  50. end
  51. -- NB: tsop mode allows to directly connect pin
  52. -- inplace of TSOP input
  53. local nec = function(pin, code, tsop)
  54. local pulse = tsop and pull or carrier
  55. -- setup transmitter
  56. mode(pin, 1)
  57. write(pin, tsop and 1 or 0)
  58. -- header
  59. pulse(pin, NEC_HDR_MARK)
  60. waitus(NEC_HDR_SPACE)
  61. -- sequence, lsb first
  62. for i = 31, 0, -1 do
  63. pulse(pin, NEC_BIT_MARK)
  64. waitus(isset(code, i) and NEC_ONE_SPACE or NEC_ZERO_SPACE)
  65. end
  66. -- trailer
  67. pulse(pin, NEC_BIT_MARK)
  68. -- done transmitter
  69. --mode(pin, 0, tsop and 1 or 0)
  70. end
  71. -- expose
  72. M = {
  73. nec = nec,
  74. }
  75. end
  76. return M