E8-7ESP8266Beginner

ESP8266 RGB LED Color Picker on the Web: Pick a Color on Your Phone and a NodeMCU Shows It at Once

Pick a color in your phone's browser and the RGB LED shows it. The NodeMCU V3 joins your home Wi-Fi and serves a page with a color picker. Every color is a mix of red, green and blue; the board sets the brightness of three pins with PWM. Every new color sends the board a small request and the page never reloads. The code is written for a common cathode LED; a common anode one needs a single line changed. The ESP8266 only joins 2.4 GHz networks.

0.0(0)
ESP8266 RGB LED Color Picker on the Web: Pick a Color on Your Phone and a NodeMCU Shows It at Once
The step after dimming a single LED: running three brightness values at once and mixing any color you like. You see that a color code is really three numbers and how the board splits that code and hands it to three outputs. You also learn the difference between common cathode and common anode and how the code adapts to it. The same method drives night lights, ambient lighting, status lights and LED strips from a phone.

Video

Circuit Diagram

ESP8266 RGB LED Color Picker on the Web: Pick a Color on Your Phone and a NodeMCU Shows It at Once - Circuit Diagram

Source Code

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   ESP8266 RGB LED Color Picker on the Web: Pick a Color on Your Phone and a NodeMCU Shows It at Once
4// ─────────────────────────────────────────
5// The NodeMCU joins your home Wi-Fi and serves a page with a color picker.
6// Open the board's IP address in the browser of a phone on the same
7// network and pick a color: the RGB LED shows it. Every color is a mix of
8// red, green and blue; the board sets the three brightness values with
9// PWM.
10//
11// Pins:
12//   D7 (GPIO13) -> 220 ohm resistor -> RGB LED red leg
13//   D6 (GPIO12) -> 220 ohm resistor -> RGB LED green leg
14//   D5 (GPIO14) -> 220 ohm resistor -> RGB LED blue leg
15//   GND         -> RGB LED long leg (common cathode)
16
17#include <ESP8266WiFi.h>
18#include <ESP8266WebServer.h>
19
20// ============ WI-FI NETWORK ============
21// Write the name and password of your own network inside the quotes. The ESP8266 only joins 2.4 GHz
22// networks.
23const char *const WIFI_SSID = "YOUR_WIFI_NAME";
24const char *const WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
25const unsigned long WIFI_HINT_MS = 20000; // Time until the hint (ms)
26
27// ============ PINS ============
28// D3, D4 and D8 have a special job while the board starts; the three colors use the spare pins D5,
29// D6 and D7.
30const uint8_t PIN_RED = D7;               // GPIO13
31const uint8_t PIN_GREEN = D6;             // GPIO12
32const uint8_t PIN_BLUE = D5;              // GPIO14
33
34// ============ RGB LED TYPE ============
35// Common cathode: the long leg goes to GND, keep false. Common anode: the long leg goes to 3V,
36// write true and the code turns every value upside down (0 is full brightness, 255 is off).
37const bool COMMON_ANODE = false;
38// The top PWM value. Core 3.x counts to 255 by default, older cores to 1023; setup fixes the range
39// so the code works the same on both.
40const int PWM_MAX = 255;
41
42// ============ PAGE TEXTS ============
43const char TEXT_TITLE[] = "Color Picker";
44const char TEXT_NOT_FOUND[] = "Page not found";
45
46// ============ WEB PAGE ============
47// The fixed top of the page: UTF-8 encoding, a phone-friendly width and the looks (CSS).
48const char PAGE_HEAD[] = R"rawliteral(<!DOCTYPE html><html><head><meta charset="utf-8">
49<meta name="viewport" content="width=device-width,initial-scale=1"><title>ESP8266</title>
50<style>
51body{margin:0;padding:28px 20px;background:#0f172a;color:#f8fafc;font-family:sans-serif;
52text-align:center}
53h1{font-size:26px;margin:0 0 28px}
54input{width:220px;height:220px;padding:0;border:0;border-radius:24px;background:none}
55p{font-size:40px;font-weight:bold;margin:24px 0 0;font-family:monospace}
56</style></head><body>)rawliteral";
57
58// The script of the page: every new color shows its code and asks the board for /set?c=RRGGBB.
59// While one request is on its way it only remembers the newest color and sends it next, so the
60// board is never flooded.
61const char PAGE_SCRIPT[] = R"rawliteral(<script>
62var busy=false,next='';
63function send(v){
64document.getElementById('p').textContent=v;
65if(busy){next=v;return}
66busy=true;
67fetch('/set?c='+v.substring(1)).then(done,done);
68}
69function done(){busy=false;if(next){var v=next;next='';send(v)}}
70</script></body></html>)rawliteral";
71
72ESP8266WebServer server(80);              // Port 80: the web default
73long color = 0;                           // 0xRRGGBB
74bool wifiUp = false;
75bool hintDone = false;
76
77// Writes one color channel (0-255). A common anode LED lights while the pin is LOW, so its value is
78// turned upside down.
79void writeChannel(uint8_t pin, int level) {
80  analogWrite(pin, COMMON_ANODE ? PWM_MAX - level : level);
81}
82
83// The color as text for the page and the Serial port, for example #ff8800.
84String colorCode() {
85  char text[8];
86  snprintf(text, sizeof(text), "#%06lx", color);
87  return String(text);
88}
89
90// Splits the color into red, green and blue (0-255 each) and writes the three pins.
91void setColor(long value) {
92  color = value & 0xFFFFFF;
93  writeChannel(PIN_RED, (color >> 16) & 0xFF);
94  writeChannel(PIN_GREEN, (color >> 8) & 0xFF);
95  writeChannel(PIN_BLUE, color & 0xFF);
96  Serial.print("Color: ");
97  Serial.println(colorCode());
98}
99
100// Builds the page for the current color and sends it to the browser: the color picker and the color
101// code.
102void sendPage() {
103  String html = PAGE_HEAD;
104  html += "<h1>";
105  html += TEXT_TITLE;
106  html += "</h1><input type=\"color\" value=\"";
107  html += colorCode();
108  html += "\" oninput=\"send(this.value)\"><p id=\"p\">";
109  html += colorCode();
110  html += "</p>";
111  html += PAGE_SCRIPT;
112  // The browser must not keep a copy of the page; every tap has to reach the board.
113  server.sendHeader("Cache-Control", "no-store");
114  server.send(200, "text/html; charset=utf-8", html);
115}
116
117// Every address has its own function; it runs when the browser asks for that address.
118void handleRoot() {
119  sendPage();
120}
121
122// The color picker asks for this address: c is the new color as six hex digits. The answer is just
123// the color code, the page stays where it is.
124void handleSet() {
125  if (server.hasArg("c")) {
126    setColor(strtol(server.arg("c").c_str(), nullptr, 16));
127  }
128  server.sendHeader("Cache-Control", "no-store");
129  server.send(200, "text/plain", colorCode());
130}
131
132void handleNotFound() {
133  server.send(404, "text/plain; charset=utf-8", TEXT_NOT_FOUND);
134}
135
136// Watches the connection: prints the IP address once connected and reports a drop. The ESP8266
137// rejoins a lost network by itself.
138void checkWifi() {
139  bool up = WiFi.status() == WL_CONNECTED;
140  if (up && !wifiUp) {
141    hintDone = true;
142    Serial.println("Wi-Fi connected");
143    Serial.print("Open in your browser: ");
144    Serial.print("http://");
145    Serial.println(WiFi.localIP());
146  } else if (!up && wifiUp) {
147    Serial.println("Wi-Fi lost. Reconnecting");
148  }
149  wifiUp = up;
150
151  if (!up && !hintDone && millis() > WIFI_HINT_MS) {
152    hintDone = true;
153    Serial.println("Could not join the Wi-Fi");
154    Serial.println("Check the network name and password");
155    Serial.println("The ESP8266 only sees 2.4 GHz networks");
156  }
157}
158
159void setup() {
160  Serial.begin(115200);
161  pinMode(PIN_RED, OUTPUT);
162  pinMode(PIN_GREEN, OUTPUT);
163  pinMode(PIN_BLUE, OUTPUT);
164  analogWriteRange(PWM_MAX);
165  writeChannel(PIN_RED, 0);               // Start with the LED off
166  writeChannel(PIN_GREEN, 0);
167  writeChannel(PIN_BLUE, 0);
168  Serial.println();
169  Serial.println("Web RGB color picker");
170  if (strncmp(WIFI_SSID, "YOUR_", 5) == 0) {
171    Serial.println("Put your Wi-Fi name and password in the code");
172  }
173  Serial.println("Connecting to Wi-Fi");
174  // The board opens no network of its own, it joins yours
175  WiFi.mode(WIFI_STA);
176  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
177
178  server.on("/", handleRoot);
179  server.on("/set", handleSet);
180  server.onNotFound(handleNotFound);
181  server.begin();
182}
183
184// loop never waits: a long delay would freeze the page and can drop the Wi-Fi.
185void loop() {
186  checkWifi();
187  server.handleClient();                  // Handles a waiting request
188}
189

FAQ

What does a color code like #ff8800 mean?

The code is a six digit hex number in three parts: the first two digits are red, the middle two are green and the last two are blue. Each part runs from 00 to ff, that is 0 to 255. ff8800 means full red, half green and no blue: orange. The code splits these three numbers and writes each one to its own pin as PWM.

What is the difference between common cathode and common anode?

An RGB LED holds three LEDs that share one leg: the longest one. With a common cathode that leg goes to GND and a color lights when its pin is HIGH. With a common anode it goes to 3V and the logic flips: 0 is full brightness and 255 is off. Set the COMMON_ANODE line to true and every value is turned upside down for you; in the wiring only the long leg moves.

Why does my color look a little different on the LED?

The three LEDs inside are not equally bright: green and blue often look stronger than red, so white can turn bluish and yellow greenish. On top of that the eye does not see brightness in a straight line. For a more even color you can put a piece of white paper or a ping pong ball over the LED to mix the light.

Why does the color picker react late on some phones?

The picker is drawn by the browser, not by the page. Some browsers report all the time while you drag your finger and the LED follows at once; others only report when you confirm the choice and the LED changes then. Either way the page does not reload and the last color you pick reaches the board.