esp8266-house-led-rgb.ino 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /* Govee LED lights that were purcahsed from Amazon.com 100ft for 15USD.
  2. * 24Vdc 6 LED in series with current limiting resistor every 19.5".
  3. *
  4. * +----B----B----B----B----B----B----2K4-------------+
  5. * | |
  6. * 24Vdc ----+----R----R----R----R----R----R----2K4-----------------+
  7. * | | |
  8. * +----G----G----G----G----G----G----3K3---------------------+
  9. * | | | |
  10. * | | | |
  11. * | | | |
  12. * +---------+----B----B----B----B----B----B----2K4---+ | |
  13. * | | | |
  14. * +----R----R----R----R----R----R----2K4-------+ |
  15. * | | | |
  16. * +----G----G----G----G----G----G----3K3-----------+
  17. * | | | |
  18. * | control bus: blue red green
  19. * | | | |
  20. * ... ... ... ...
  21. *
  22. * We installed about 150ft so about 90 led circuits will need power. ESP8266 can
  23. * do 1KHz PWM so we can use 3 pins if we want. Another idea I had was to use lots
  24. * of pins to control 20mA LED driver ICs. With 15 pins one could make a circuit to
  25. * drive 32 levels of current to each color giving 32,768 colors. Each color would
  26. * have 5 npn controlling 1,2,4,8,16 LED drivers. One could then step through 0..620mA.
  27. *
  28. * Instead we will just use PWM to give us color control. We just need to calculate how
  29. * much current we want to send to our LED strip. Because each circuit runs in parallel
  30. * we need to determine how much current each branch will use. The current limiting
  31. * resistors means we can probably just use a fixed voltage supply. With a 48Vdc supply
  32. * at max brightness green will see 9mA, blue will see 12mA, and red will see 15mA. These
  33. * values are all pretty safe for the LED but the red would blow out a PN2222A with 1080mA.
  34. *
  35. * We should be careful about the inductance of the wire. Assuming 1/4mm diameter wire we
  36. * might have 47uH. We can use a diode on the collector of each color to send the spikes to
  37. * the +48Vdc rail. Each color will use an NPN-BJT, probably 3 parallel PN2222A with
  38. * ballast resitors, as buffers for the PWM signal from the esp8266.
  39. *
  40. * In the end I ended up using optoisolated pwm driving three power mosfets. This ended
  41. * up being a nuisance since the mosfet gates took forever to discharge resulting in
  42. * the LEDs staying lit when the esp8266 pulled the signal down. I did not really fix this
  43. * but I did add a few resistors on the gate to bleed off the gate charge. In effect the
  44. * max brightness is 0xfc instead of 0xff since the led does not turn off on 0xfd. But that
  45. * is not really a deal-breaker, just annoying.
  46. *
  47. * test using:
  48. * curl -X POST http://rain-gutter-rgb.lan.rome7.com/rgb -d "color=010101"
  49. */
  50. #include <ESP8266WiFi.h>
  51. #include <WiFiClient.h>
  52. #include <ESP8266WiFiMulti.h>
  53. #include <ESP8266mDNS.h>
  54. #include <ESP8266WebServer.h>
  55. ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'
  56. uint8_t hexStr[7] = "010101";
  57. /* 131 allows for frame count, 16 colors(3), 16 transistions(1), and a null terminator
  58. * the user provides the input as utf-8 encoded hexidecimal, we need twice
  59. * the storage space, but parsing is a little easier: 2 + (2 * (3 * 16 + 16)) + 1 = 131
  60. * [?] there are 16 transistions because there is an extra transition when we
  61. * reach the end an loop to the begining
  62. * [?] frame count allows user to have an animation that is not the maximum length,
  63. * as of this note, the max frame count is 0x0f, '0f' when using a
  64. */
  65. #define HOW_MANY_ANIMATION_FRAMES 16
  66. #define MAX_ANIMATE_FRAME_COUNT_LEN 2
  67. #define NULL_TERMINATOR_LEN 1
  68. #define FRAME_LEN (3 + 1)
  69. #define ANIMATE_BUFFER_LEN (MAX_ANIMATE_FRAME_COUNT_LEN + (2 * HOW_MANY_ANIMATION_FRAMES * FRAME_LEN) + NULL_TERMINATOR_LEN)
  70. #define MAX_ANIMATE_FRAME_COUNT ((ANIMATE_BUFFER_LEN - 2 - 1) / 8)
  71. uint8_t animateStr[ANIMATE_BUFFER_LEN];
  72. uint8_t animate = 0;
  73. uint8_t red = 1;
  74. uint8_t green = 1;
  75. uint8_t blue = 1;
  76. ESP8266WebServer server(80); // Create a webserver object that listens for HTTP request on port 80
  77. void handleRoot(); // function prototypes for HTTP handlers
  78. void handleLogin();
  79. void handleNotFound();
  80. void setup(void){
  81. Serial.begin(115200); // Start the Serial communication to send messages to the computer
  82. delay(10);
  83. Serial.println('\n');
  84. wifiMulti.addAP("n-phone-number-upstairs", "3103229909cedar"); // add Wi-Fi networks you want to connect to
  85. wifiMulti.addAP("n-phone-number", "3103229909cedar");
  86. Serial.println("Connecting ...");
  87. int i = 0;
  88. while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
  89. delay(250);
  90. Serial.print('.');
  91. }
  92. Serial.println('\n');
  93. Serial.print("Connected to ");
  94. Serial.println(WiFi.SSID()); // Tell us what network we're connected to
  95. Serial.print("IP address:\t");
  96. Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
  97. /*
  98. if (MDNS.begin("rain-gutter-rgb")) { // Start the mDNS responder for esp8266.local
  99. Serial.println("mDNS responder started");
  100. } else {
  101. Serial.println("Error setting up MDNS responder!");
  102. }
  103. */
  104. server.on("/", HTTP_GET, handleRoot); // Call the 'handleRoot' function when a client requests URI "/"
  105. //server.on("/login", HTTP_POST, handleLogin); // Call the 'handleLogin' function when a POST request is made to URI "/login"
  106. server.on("/rgb", HTTP_POST, handleRGB); // Call the 'handleRGB' function when a POST request is made to URI "/login"
  107. server.on("/dec", HTTP_GET, handleGetDec);
  108. server.on("/echo", HTTP_GET, handleEchoHex);
  109. server.on("/animate", HTTP_GET, handleAnimate);
  110. server.onNotFound(handleNotFound); // When a client requests an unknown URI (i.e. something other than "/"), call function "handleNotFound"
  111. server.begin(); // Actually start the server
  112. Serial.println("HTTP server started");
  113. /* esp8266 12-f breakout board has pins mapped a bit odd, and arduino esp8266 libs use GPIO pin number */
  114. #define PIN_5 14 /* GPIO_14 */
  115. #define PIN_6 12 /* GPIO_12 */
  116. #define PIN_7 13 /* GPIO_13 */
  117. //analogWriteFreq(1000);
  118. analogWriteFreq(250);
  119. // setup pins with a test pwm
  120. analogWrite(PIN_5, red);
  121. analogWrite(PIN_6, green);
  122. analogWrite(PIN_7, blue);
  123. }
  124. void loop(void){
  125. // keep track of where we are in the animation
  126. uint8_t frame = 0;
  127. uint8_t frameCount = 0;
  128. #define KEY_FRAMES 10
  129. #define MS_IN_ANIMATION_DELAY 250
  130. #define TEMPORAL_LENGTH (MS_IN_ANIMATION_DELAY / KEY_FRAMES)
  131. uint8_t redSubFrames[KEY_FRAMES];
  132. uint8_t greenSubFrames[KEY_FRAMES];
  133. uint8_t blueSubFrames[KEY_FRAMES];
  134. // keep track of where we are in the subframe
  135. uint8_t subframe = KEY_FRAMES;
  136. /* because subframes occur every quarter second and animation delays can be long (up to 64 seconds)
  137. * we need to guess what the next color should be for the next second based on where we are now
  138. */
  139. uint8_t animationDelayCounter = 0;
  140. uint16_t totalSubframes = 0;
  141. uint8_t frameAnimationDelay = 0;
  142. uint8_t frameStartRed = 0;
  143. uint8_t frameStartGreen = 0;
  144. uint8_t frameStartBlue = 0;
  145. uint8_t frameEndRed = 0;
  146. uint8_t frameEndGreen = 0;
  147. uint8_t frameEndBlue = 0;
  148. // tracking temporal length so that we do not run too fast or slow based on CPU frequency
  149. uint8_t delayCount = 0;
  150. while(true) {
  151. // listen for HTTP requests from clients
  152. server.handleClient();
  153. // check if we are supposed to animate
  154. if(0 == animate) break;
  155. /* we will transition several times a second (technically serveral times per animation delay)
  156. *
  157. * [?] this delay is not really necesarry, we just need a way to not run too fast
  158. *
  159. * [!] this delay also reduces power consumption of the esp8266 significantly
  160. * not something we want necessarily, but worth mentioning in case one questions
  161. * what the heck is happening
  162. */
  163. delay(1);
  164. if(delayCount++ < TEMPORAL_LENGTH) break;
  165. // do we have any subframes to animate?
  166. if(0 == subframe) {
  167. // reset the subframe counter
  168. subframe = KEY_FRAMES;
  169. // are we done with this frame?
  170. if(0 == animationDelayCounter) {
  171. // move to the next frame
  172. if(0 == frame) frame = (ANIMATE_BUFFER_LEN - 1) / 8;
  173. frame--;
  174. // get the next animation delay
  175. frameAnimationDelay = animationDelayCounter =
  176. // is this a stop frame
  177. if(0xff == frameAnimationDelay) { animate = 0; break; }
  178. // is this a loop frame
  179. if(0x00 == frameAnimationDelay) { frame = 0; continue; }
  180. // set our start and end frame colors
  181. frameStartRed = 0;
  182. frameStartGreen = 0;
  183. frameStartBlue = 0;
  184. frameEndRed = 0;
  185. frameEndGreen = 0;
  186. frameEndBlue = 0;
  187. }
  188. // using the start, stop, and animation delay counter, compute subframes
  189. // track progress through animation delay
  190. animationDelayCounter--;
  191. }
  192. // set color
  193. setColor(redSubFrames[subframe -1], greeenSubFrames[subframe -1], blueSubFrames[subframe -1])
  194. // track progress through subframes
  195. subframe--;
  196. }
  197. }
  198. void handleRoot() { // When URI / is requested, send a web page with a button to toggle the LED
  199. //server.send(200, "text/html", "<form action=\"/login\" method=\"POST\"><input type=\"text\" name=\"username\" placeholder=\"Username\"></br><input type=\"password\" name=\"password\" placeholder=\"Password\"></br><input type=\"submit\" value=\"Login\"></form><p>Try 'John Doe' and 'password123' ...</p>");
  200. server.send(200, "text/html", "rain-gutter-rgb http-post (hex values): /rgb color=\'RRGGBB\'");
  201. }
  202. void handleEchoHex() {
  203. // make sure null terminated, then send as string
  204. hexStr[6] = '\0';
  205. server.send(200, "text/html", (char*) hexStr);
  206. }
  207. void handleAnimate() {
  208. // turn on animate
  209. animate = 1;
  210. }
  211. void handleGetDec() {
  212. String hex = String("");
  213. server.send(200, "text/html", hex + red + "," + green + "," + blue + '\n');
  214. }
  215. void handleRGB() { // If a POST request is made to URI /login
  216. if( ! server.hasArg("color")) {
  217. server.send(400, "text/plain", "400: Invalid Request"); // The request is invalid, so send HTTP status 400
  218. return;
  219. }
  220. // turn of animate
  221. animate = 1;
  222. // kinda lame but parsing is not super easy here
  223. server.arg("color").getBytes(hexStr, 7);
  224. setColor(
  225. /* red */ (nibbler(hexStr[0]) << 4) + nibbler(hexStr[1]),
  226. /* green */ (nibbler(hexStr[2]) << 4) + nibbler(hexStr[3]),
  227. /* blue */ (nibbler(hexStr[4]) << 4) + nibbler(hexStr[5])
  228. )
  229. /*
  230. server.arg("color").substring(0, 2).toCharArray(hexStr, 2);
  231. r = hexStrToInt(hexStr);
  232. server.arg("color").substring(2, 4).toCharArray(hexStr, 2);
  233. g = hexStrToInt(hexStr);
  234. server.arg("color").substring(4, 6).toCharArray(hexStr, 2);
  235. b = hexStrToInt(hexStr);
  236. */
  237. String info = "degub r:";
  238. server.send(200, "text/html", info + red + " g:" + green + " b:" + blue + '\n');
  239. //server.send(200, "text/html", "okay");
  240. }
  241. void setColor(uint8_t r, uint8_t g, uint8_t b) {
  242. // store colors for API
  243. red = r;
  244. green = g;
  245. blue = b;
  246. analogWrite(PIN_5, red);
  247. analogWrite(PIN_6, green);
  248. analogWrite(PIN_7, blue);
  249. }
  250. // converts ASCII utf8 chars to integer values, [0..F], otherwise zero
  251. uint8_t nibbler(uint8_t v) {
  252. switch (v) {
  253. case 'f': case 'F': return 15;
  254. case 'e': case 'E': return 14;
  255. case 'd': case 'D': return 13;
  256. case 'c': case 'C': return 12;
  257. case 'b': case 'B': return 11;
  258. case 'a': case 'A': return 10;
  259. case '9': return 9;
  260. case '8': return 8;
  261. case '7': return 7;
  262. case '6': return 6;
  263. case '5': return 5;
  264. case '4': return 4;
  265. case '3': return 3;
  266. case '2': return 2;
  267. case '1': return 1;
  268. default: return 0;
  269. }
  270. }
  271. uint8_t hexStrToInt(char buf[]) {
  272. return (int) strtol(buf, 0, 16);
  273. }
  274. void handleLogin() { // If a POST request is made to URI /login
  275. if( ! server.hasArg("username") || ! server.hasArg("password")
  276. || server.arg("username") == NULL || server.arg("password") == NULL) { // If the POST request doesn't have username and password data
  277. server.send(400, "text/plain", "400: Invalid Request"); // The request is invalid, so send HTTP status 400
  278. return;
  279. }
  280. if(server.arg("username") == "John Doe" && server.arg("password") == "password123") { // If both the username and the password are correct
  281. server.send(200, "text/html", "<h1>Welcome, " + server.arg("username") + "!</h1><p>Login successful</p>");
  282. } else { // Username and password don't match
  283. server.send(401, "text/plain", "401: Unauthorized");
  284. }
  285. }
  286. void handleNotFound(){
  287. server.send(404, "text/plain", "404: Not found"); // Send HTTP status 404 (Not Found) when there's no handler for the URI in the request
  288. }