adc_rgb.lua 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. --
  2. -- Light sensor on ADC(0), RGB LED connected to gpio12(6) Green, gpio13(7) Blue & gpio15(8) 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. function led(r,Sg,b)
  9. pwm.setduty(8,r)
  10. pwm.setduty(6,g)
  11. pwm.setduty(7,b)
  12. end
  13. -- this is perhaps the lightest weight sin function in existance
  14. -- Given an integer from 0..128, 0..512 appximating 256 + 256 * sin(idx*Pi/256)
  15. -- This is first order square approximation of sin, it's accurate around 0 and any multiple of 128 (Pi/2),
  16. -- 92% accurate at 64 (Pi/4).
  17. function pseudoSin (idx)
  18. idx = idx % 128
  19. lookUp = 32 - idx % 64
  20. val = 256 - (lookUp * lookUp) / 4
  21. if (idx > 64) then
  22. val = - val;
  23. end
  24. return 256+val
  25. end
  26. pwm.setup(6,500,512)
  27. pwm.setup(7,500,512)
  28. pwm.setup(8,500,512)
  29. pwm.start(6)
  30. pwm.start(7)
  31. pwm.start(8)
  32. tmr.alarm(1,20,1,function()
  33. idx = 3 * adc.read(0) / 2
  34. r = pseudoSin(idx)
  35. g = pseudoSin(idx + 43)
  36. b = pseudoSin(idx + 85)
  37. led(r,g,b)
  38. idx = (idx + 1) % 128
  39. end)