adc_rgb.lua 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. --
  2. -- Light sensor on adc0(A0), RGB LED connected to gpio12(D6) Green, gpio13(D7) Blue & gpio15(D8) Red.
  3. -- This works out of the box on the typical ESP8266 evaluation boards with Battery Holder
  4. --
  5. -- It uses the input from the sensor to drive a "rainbow" effect on the RGB LED
  6. -- Includes a very "pseudoSin" function
  7. --
  8. -- Required C Modules: adc, tmr, pwm
  9. local redLed, greenLed, blueLed = 8, 6, 7
  10. local function setRGB(r,g,b)
  11. pwm.setduty(redLed, r)
  12. pwm.setduty(greenLed, g)
  13. pwm.setduty(blueLed, b)
  14. end
  15. -- this is perhaps the lightest weight sin function in existence
  16. -- Given an integer from 0..128, 0..512 approximating 256 + 256 * sin(idx*Pi/256)
  17. -- This is first order square approximation of sin, it's accurate around 0 and any multiple of 128 (Pi/2),
  18. -- 92% accurate at 64 (Pi/4).
  19. local function pseudoSin(idx)
  20. idx = idx % 128
  21. local lookUp = 32 - idx % 64
  22. local val = 256 - (lookUp * lookUp) / 4
  23. if (idx > 64) then
  24. val = - val;
  25. end
  26. return 256+val
  27. end
  28. do
  29. pwm.setup(redLed, 500, 512)
  30. pwm.setup(greenLed,500, 512)
  31. pwm.setup(blueLed, 500, 512)
  32. pwm.start(redLed)
  33. pwm.start(greenLed)
  34. pwm.start(blueLed)
  35. tmr.create():alarm(20, tmr.ALARM_AUTO, function()
  36. local idx = 3 * adc.read(0) / 2
  37. local r = pseudoSin(idx)
  38. local g = pseudoSin(idx + 43) -- ~1/3rd of 128
  39. local b = pseudoSin(idx + 85) -- ~2/3rd of 128
  40. setRGB(r,g,b)
  41. end)
  42. end