Movatterモバイル変換


[0]ホーム

URL:


Skip to content
HOMEESP32ESP8266ESP32-CAMRASPBERRY PIMICROPYTHONRPi PICOARDUINOREVIEWS

ESP32/ESP8266 RGB LED Strip with Color Picker Web Server

In this project we’ll show you how to remotely control an RGB LED strip with an ESP8266 or an ESP32 board using a web server with a color picker.

ESP32 or ESP8266 RGB LED Strip with Color Picker Web Server

We’ll control a 5V RGB LED strip and the code will be written in Arduino IDE.

To better understand this project, there are a few tutorials that you may want to take a look first (this step is optional):

Watch the Video Tutorial

You can watch the video tutorial or keep reading this page for the written instructions.

Project Overview

Before getting started, let’s see how this project works:

How it works ESP32/ESP8266 RGB LED Strip with Color Picker Web Server
  • The ESP32/ESP8266 web server displays a color picker.
  • When you chose a color, your browser makes a request on a URL that contains the R, G, and B parameters of the selected color.
  • Your ESP32/ESP8266 receives the request and splits the value for each color parameter.
  • Then, it sends a PWM signal with the corresponding value to the GPIOs that are controlling the strip.

Parts Required

For this project you need the following parts:

You can use the preceding links or go directly toMakerAdvisor.com/tools to find all the parts for your projects at the best price!

Schematic

For this project, we’ll be using an RGB LED strip that can be powered with 5V.

5V RGB LED Strip

Note: there are other similar strips that require 12V to operate. You can still use them with the code provided, but you need a suitable power supply.

In this example, we’ll be powering the LED strip and the ESP32 or ESP8266 using the same 5V power supply.

ESP32 – schematic diagram

Follow the next schematic diagram to connect the strip to your ESP32.

ESP32 5V RGB LED Strip Schematic Circuit

ESP8266 – Schematic diagram

Follow the next schematic diagram to connect the strip to your ESP8266.

ESP8266 5V RGB LED Strip Schematic Circuit

NPN Transistors

In this circuit, we’re using the S8050 NPN transistor. However, depending on how many LEDs you have in your strip, you might need to use a NPN transistor that can handle more continuous current in the collector pin.

ESP32/ESP8266 RGB LED Strip Circuit and Schematic NPN transistor

To determine the max current used by your LED strip, you can measure the current consumption when all the LEDs are at maximum brightness (when the color is white).

Since we’re using 12 LEDs, the maximum current is approximately 630mA at full brightness in white color. So, we can use the S8050 NPN transistor that can handle up to 700mA.

ESP32/ESP8266 RGB LED Strip Circuit and Schematic NPN transistor

Note: your strip consumes the maximum current when you set white color (this is the same as setting all three colors to the maximum brightness). Setting other colors draws less current, so you’ll probably won’t have your strip using the maximum current.

ESP32 Code

We’ll program the ESP32 using Arduino IDE, so make sure you have the ESP32 add-on installed before proceeding:

After assembling the circuit, copy the following code to your Arduino IDE to program the ESP32.

/*********  Rui Santos  Complete project details at https://randomnerdtutorials.com  *********/// Load Wi-Fi library#include <WiFi.h>// Replace with your network credentialsconst char* ssid     = "REPLACE_WITH_YOUR_SSID";const char* password = "REPLACE_WITH_YOUR_PASSWORD";// Set web server port number to 80WiFiServer server(80);// Decode HTTP GET valueString redString = "0";String greenString = "0";String blueString = "0";int pos1 = 0;int pos2 = 0;int pos3 = 0;int pos4 = 0;// Variable to store the HTTP req  uestString header;// Red, green, and blue pins for PWM controlconst int redPin = 13;     // 13 corresponds to GPIO13const int greenPin = 12;   // 12 corresponds to GPIO12const int bluePin = 14;    // 14 corresponds to GPIO14// Setting PWM frequency, channels and bit resolutionconst int freq = 5000;const int redChannel = 0;const int greenChannel = 1;const int blueChannel = 2;// Bit resolution 2^8 = 256const int resolution = 8;// Current timeunsigned long currentTime = millis();// Previous timeunsigned long previousTime = 0; // Define timeout time in milliseconds (example: 2000ms = 2s)const long timeoutTime = 2000;void setup() {  Serial.begin(115200);  // configure LED PWM functionalitites  ledcAttachChannel(redPin, freq, resolution, redChannel);  ledcAttachChannel(greenPin, freq, resolution, greenChannel);  ledcAttachChannel(bluePin, freq, resolution, blueChannel);    // Connect to Wi-Fi network with SSID and password  Serial.print("Connecting to ");  Serial.println(ssid);  WiFi.begin(ssid, password);  while (WiFi.status() != WL_CONNECTED) {    delay(500);    Serial.print(".");  }  // Print local IP address and start web server  Serial.println("");  Serial.println("WiFi connected.");  Serial.println("IP address: ");  Serial.println(WiFi.localIP());  server.begin();}void loop(){  WiFiClient client = server.available();   // Listen for incoming clients  if (client) {                             // If a new client connects,    currentTime = millis();    previousTime = currentTime;    Serial.println("New Client.");          // print a message out in the serial port    String currentLine = "";                // make a String to hold incoming data from the client    while (client.connected() && currentTime - previousTime <= timeoutTime) {            // loop while the client's connected      currentTime = millis();      if (client.available()) {             // if there's bytes to read from the client,        char c = client.read();             // read a byte, then        Serial.write(c);                    // print it out the serial monitor        header += c;        if (c == '\n') {                    // if the byte is a newline character          // if the current line is blank, you got two newline characters in a row.          // that's the end of the client HTTP request, so send a response:          if (currentLine.length() == 0) {            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)            // and a content-type so the client knows what's coming, then a blank line:            client.println("HTTP/1.1 200 OK");            client.println("Content-type:text/html");            client.println("Connection: close");            client.println();                               // Display the HTML web page            client.println("<!DOCTYPE html><html>");            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");            client.println("<link rel=\"icon\" href=\"data:,\">");            client.println("<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\">");            client.println("<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js\"></script>");            client.println("</head><body><div class=\"container\"><div class=\"row\"><h1>ESP Color Picker</h1></div>");            client.println("<a class=\"btn btn-primary btn-lg\" href=\"#\" id=\"change_color\" role=\"button\">Change Color</a> ");            client.println("<input class=\"jscolor {onFineChange:'update(this)'}\" id=\"rgb\"></div>");            client.println("<script>function update(picker) {document.getElementById('rgb').innerHTML = Math.round(picker.rgb[0]) + ', ' +  Math.round(picker.rgb[1]) + ', ' + Math.round(picker.rgb[2]);");            client.println("document.getElementById(\"change_color\").href=\"?r\" + Math.round(picker.rgb[0]) + \"g\" +  Math.round(picker.rgb[1]) + \"b\" + Math.round(picker.rgb[2]) + \"&\";}</script></body></html>");            // The HTTP response ends with another blank line            client.println();            // Request sample: /?r201g32b255&            // Red = 201 | Green = 32 | Blue = 255            if(header.indexOf("GET /?r") >= 0) {              pos1 = header.indexOf('r');              pos2 = header.indexOf('g');              pos3 = header.indexOf('b');              pos4 = header.indexOf('&');              redString = header.substring(pos1+1, pos2);              greenString = header.substring(pos2+1, pos3);              blueString = header.substring(pos3+1, pos4);              /*Serial.println(redString.toInt());              Serial.println(greenString.toInt());              Serial.println(blueString.toInt());*/              ledcWrite(redPin, redString.toInt());              ledcWrite(greenPin, greenString.toInt());              ledcWrite(bluePin, blueString.toInt());            }            // Break out of the while loop            break;          } else { // if you got a newline, then clear currentLine            currentLine = "";          }        } else if (c != '\r') {  // if you got anything else but a carriage return character,          currentLine += c;      // add it to the end of the currentLine        }      }    }    // Clear the header variable    header = "";    // Close the connection    client.stop();    Serial.println("Client disconnected.");    Serial.println("");  }}

View raw code

Before uploading the code, don’t forget to insert your network credentials so that the ESP can connect to your local network.

const char* ssid     = "";const char* password = "";

If you’ve built aweb server with the ESP32 before, this code is not much different. It adds the color picker to the web page and decodes the request to control the strip color. So, we’ll just take a look at the relevant parts for this project.

ESP8266 Code

We’ll program the ESP8266 using the Arduino IDE. In order to upload code to your ESP8266, you need to install the ESP8266 add-on first, if you haven’t already (Install the ESP8266 Board in Arduino IDE).

After assembling the circuit, copy the following code to your Arduino IDE to program the ESP8266.

/*********  Rui Santos  Complete project details at https://randomnerdtutorials.com  *********/// Load Wi-Fi library#include <ESP8266WiFi.h>// Replace with your network credentialsconst char* ssid     = "REPLACE_WITH_YOUR_SSID";const char* password = "REPLACE_WITH_YOUR_PASSWORD";// Set web server port number to 80WiFiServer server(80);// Decode HTTP GET valueString redString = "0";String greenString = "0";String blueString = "0";int pos1 = 0;int pos2 = 0;int pos3 = 0;int pos4 = 0;// Variable to store the HTTP req  uestString header;// Red, green, and blue pins for PWM controlconst int redPin = 13;     // 13 corresponds to GPIO13const int greenPin = 12;   // 12 corresponds to GPIO12const int bluePin = 14;    // 14 corresponds to GPIO14// Setting PWM bit resolutionconst int resolution = 256;// Current timeunsigned long currentTime = millis();// Previous timeunsigned long previousTime = 0; // Define timeout time in milliseconds (example: 2000ms = 2s)const long timeoutTime = 2000;void setup() {  Serial.begin(115200);    // configure LED PWM resolution/range and set pins to LOW  analogWriteRange(resolution);  analogWrite(redPin, 0);  analogWrite(greenPin, 0);  analogWrite(bluePin, 0);    // Connect to Wi-Fi network with SSID and password  Serial.print("Connecting to ");  Serial.println(ssid);  WiFi.begin(ssid, password);  while (WiFi.status() != WL_CONNECTED) {    delay(500);    Serial.print(".");  }  // Print local IP address and start web server  Serial.println("");  Serial.println("WiFi connected.");  Serial.println("IP address: ");  Serial.println(WiFi.localIP());  server.begin();}void loop(){  WiFiClient client = server.available();   // Listen for incoming clients  if (client) {                             // If a new client connects,    currentTime = millis();    previousTime = currentTime;    Serial.println("New Client.");          // print a message out in the serial port    String currentLine = "";                // make a String to hold incoming data from the client    while (client.connected() && currentTime - previousTime <= timeoutTime) {            // loop while the client's connected      currentTime = millis();      if (client.available()) {             // if there's bytes to read from the client,        char c = client.read();             // read a byte, then        Serial.write(c);                    // print it out the serial monitor        header += c;        if (c == '\n') {                    // if the byte is a newline character          // if the current line is blank, you got two newline characters in a row.          // that's the end of the client HTTP request, so send a response:          if (currentLine.length() == 0) {            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)            // and a content-type so the client knows what's coming, then a blank line:            client.println("HTTP/1.1 200 OK");            client.println("Content-type:text/html");            client.println("Connection: close");            client.println();                               // Display the HTML web page            client.println("<!DOCTYPE html><html>");            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");            client.println("<link rel=\"icon\" href=\"data:,\">");            client.println("<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\">");            client.println("<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js\"></script>");            client.println("</head><body><div class=\"container\"><div class=\"row\"><h1>ESP Color Picker</h1></div>");            client.println("<a class=\"btn btn-primary btn-lg\" href=\"#\" id=\"change_color\" role=\"button\">Change Color</a> ");            client.println("<input class=\"jscolor {onFineChange:'update(this)'}\" id=\"rgb\"></div>");            client.println("<script>function update(picker) {document.getElementById('rgb').innerHTML = Math.round(picker.rgb[0]) + ', ' +  Math.round(picker.rgb[1]) + ', ' + Math.round(picker.rgb[2]);");            client.println("document.getElementById(\"change_color\").href=\"?r\" + Math.round(picker.rgb[0]) + \"g\" +  Math.round(picker.rgb[1]) + \"b\" + Math.round(picker.rgb[2]) + \"&\";}</script></body></html>");            // The HTTP response ends with another blank line            client.println();            // Request sample: /?r201g32b255&            // Red = 201 | Green = 32 | Blue = 255            if(header.indexOf("GET /?r") >= 0) {              pos1 = header.indexOf('r');              pos2 = header.indexOf('g');              pos3 = header.indexOf('b');              pos4 = header.indexOf('&');              redString = header.substring(pos1+1, pos2);              greenString = header.substring(pos2+1, pos3);              blueString = header.substring(pos3+1, pos4);              /*Serial.println(redString.toInt());              Serial.println(greenString.toInt());              Serial.println(blueString.toInt());*/              analogWrite(redPin, redString.toInt());              analogWrite(greenPin, greenString.toInt());              analogWrite(bluePin, blueString.toInt());            }            // Break out of the while loop            break;          } else { // if you got a newline, then clear currentLine            currentLine = "";          }        } else if (c != '\r') {  // if you got anything else but a carriage return character,          currentLine += c;      // add it to the end of the currentLine        }      }    }    // Clear the header variable    header = "";    // Close the connection    client.stop();    Serial.println("Client disconnected.");    Serial.println("");  }}

View raw code

Before uploading the code, don’t forget to insert your network credentials so that the ESP can connect to your local network.

const char* ssid     = "";const char* password = "";

If you’ve built aweb server with the ESP8266 before, this code is not much different. It adds the color picker to the web page and decodes the request to control the strip color. So, we’ll just take a look at the relevant parts for this project.

How the code works

The sketches for the ESP32 and ESP8266 are very similar with just a few differences when it comes to the Wi-Fi library and the way they generate PWM signals. We’ll explain that in this section.

The ESP32 sketch uses theWiFi.h library.

#include <WiFi.h>

The ESP8266 sketch uses theESP8266WiFi.h library.

#include <ESP8266WiFi.h>

The following lines define string variables to hold the R, G, and B parameters from the request.

String redString = "0";String greenString = "0";String blueString = "0";

The next four variables are used to decode the HTTP request later on.

int pos1 = 0;int pos2 = 0;int pos3 = 0;int pos4 = 0;

Create three variables for the GPIOs that will control the strip R, G, and B parameters. In this case we’re usingGPIO 13,GPIO 12, andGPIO 14.

const int redPin = 13;     const int greenPin = 12;  const int bluePin = 14;

These GPIOs need to output PWM signals, so we need to configure the PWM properties first. Set the PWM signal frequency to 5000 Hz. Then, associate a PWM channel for each color (this is not needed in the ESP8266 sketch).

const int freq = 5000;const int redChannel = 0;const int greenChannel = 1;const int blueChannel = 2;

And finally, set the resolution of the PWM channels to 8-bit (not needed in ESP8266 sketch).

const int resolution = 8;

In the setup(), create LEDC pins with the PWM properties defined earlier (not needed in ESP8266 sketch).

  ledcAttachChannel(redPin, freq, resolution, redChannel);  ledcAttachChannel(greenPin, freq, resolution, greenChannel);  ledcAttachChannel(bluePin, freq, resolution, blueChannel);

Learn more about PWM with the ESP32:ESP32 PWM with Arduino IDE (Analog Output)

The following code section displays the color picker in your web page and makes a request based on the color you’ve picked.

client.println("<!DOCTYPE html><html>");client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");client.println("<link rel=\"icon\" href=\"data:,\">");client.println("<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\">");client.println("<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js\"></script>");client.println("</head><body><div class=\"container\"><div class=\"row\"><h1>ESP Color Picker</h1></div>");client.println("<a class=\"btn btn-primary btn-lg\" href=\"#\" id=\"change_color\" role=\"button\">Change Color</a> ");client.println("<input class=\"jscolor {onFineChange:'update(this)'}\" id=\"rgb\"></div>");client.println("<script>function update(picker) {document.getElementById('rgb').innerHTML = Math.round(picker.rgb[0]) + ', ' +  Math.round(picker.rgb[1]) + ', ' + Math.round(picker.rgb[2]);");        client.println("document.getElementById(\"change_color\").href=\"?r\" + Math.round(picker.rgb[0]) + \"g\" +  Math.round(picker.rgb[1]) + \"b\" + Math.round(picker.rgb[2]) + \"&\";}</script></body></html>");// The HTTP response ends with another blank lineclient.println();

When you pick a color, you receive a request with the following format.

/?r201g32b255&

So, we need to split this string to get the R, G, and B parameters. The parameters are saved in redStringgreenString, and blueString variables and can have values between 0 and 255.

pos1 = header.indexOf('r');pos2 = header.indexOf('g');pos3 = header.indexOf('b');pos4 = header.indexOf('&');redString = header.substring(pos1+1, pos2);greenString = header.substring(pos2+1, pos3);blueString = header.substring(pos3+1, pos4);

To control the strip with the ESP32, use theledcWrite() function to generate PWM signals with the values decoded from the HTTP request.

ledcWrite(redPin, redString.toInt());ledcWrite(greenPin, greenString.toInt());ledcWrite(bluePin, blueString.toInt());

Note: learn more about PWM with ESP32:ESP32 PWM with Arduino IDE.

To control the strip with the ESP8266, we just need to use theanalogWrite() function to generate PWM signals with the values decoded from the HTPP request.

analogWrite(redPin, redString.toInt());analogWrite(greenPin, greenString.toInt());analogWrite(bluePin, blueString.toInt())

Because we get the values in a string variable, we need to convert them to integers using thetoInt() method.

Learn more about PWM with the ESP8266:ESP8266 NodeMCU PWM with Arduino IDE – Dim LED (Analog Output)

Demonstration

After inserting your network credentials, select the right board and COM port and upload the code to your ESP32 or ESP8266.

After uploading, open the Serial Monitor at a baud rate of 115200 and press the ESP Enable/Reset button. You should get the board IP address.

Demonstration ESP32/ESP8266 RGB LED Strip

Open your browser and insert the ESP IP address. Now, use the color picker to choose a color for the strip.

Web Server Demonstration ESP32/ESP8266 RGB LED Strip

Then, you need to press the “Change Color” button for the color to take effect.

Demonstration ESP32/ESP8266 5V RGB LED Strip Web Server Color Picker

To turn off the RGB LED strip, select the black color.

The strongest colors (at the top of the color picker), are the ones that will produce better results.

ESP32/ESP8266 5V RGB LED Strip Web Server Color Picker

Now, you use the strip to decorate your house: under the bed, behind a TV, under the kitchen cabinet, and much more.

Wrapping Up

With this article, you’ve learned how to control an RGB LED strip remotely using a web server with your ESP32 or ESP8266 on your local network.

We hope you’ve found this tutorial useful. If you like this project, you may also like:

Learn more about the ESP32 with our resources:

This is an excerpt from our course: Learn ESP32 with Arduino IDE. If you like ESP32 and you want to learn more about it, we recommend enrolling in Learn ESP32 with Arduino IDE course.



SMART HOME with Raspberry Pi ESP32 and ESP8266 Node-RED InfluxDB eBook
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

41 thoughts on “ESP32/ESP8266 RGB LED Strip with Color Picker Web Server”

  1. Can I use the 2n2222 that I have from one of my learning kits in place of the 8050, the current rating is 800ma?

    Reply
    • Hi Bruce.
      Yes, you can use it depending on the number of LEDs you’re controlling.
      In our example, we’re using 12 LEDs. You can use that transistor with 12 LEDs. If you want to use more LEDs, you need to check the current the LEDs draw.
      Regards,
      Sara

      Reply
  2. Hi, Can you list the pins and their connections, of the transistor ?
    I was hoping to see a circuit diagram of what is the “Base” of the transistor connected to ( in respect to the RGB strip) ? The “Collector” and the “Emitter” connected to ?
    Would appreciate that a lot.
    Would help non-electronic engineers too.
    I am using a 2N2222 transistor

    Reply
    • Hi Shashi.
      The emitter connects to GND.
      The base connects to the ESP32/ESP8266 GPIOs through a 1k resistor.
      The collector connects to one of the strip color pins.
      I hope this helps.
      Regards,
      Sara

      Reply
      • Thanks Sara. Tried your suggestion. Did not work !

        My project involves
        – I have 3 2N2222 Transistors instead of your 8050 transistor.
        – I am powering the ESP32 thru the USB cable connected to my Mac Book Air.
        The 1K resistor looks good. Both the ESP32 and the RGB strip are connected thru the same USB power supply from the power jack of the laptop ( I dont think it’d be a problem )

        My ESP32 device is a “ESP32DEV Kit V1″ – should not be different from your blog.
        I can see that the ESP32 connects to my Network, I also uncommented the
        ” Serial.println(redString.toInt());
        Serial.println(greenString.toInt());
        Serial.println(blueString.toInt());

        and I see in the serial console the different numbers .

        == Cut and Paste from Serial Monitor ==

        GET /?r254g104b255& HTTP/1.1
        Host: 192.168.1.21
        Connection: keep-alive
        Upgrade-Insecure-Requests: 1
        User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
        Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
        Referer:http://192.168.1.21/?r255g86b171&amp;
        Accept-Encoding: gzip, deflate
        Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,en-IN;q=0.7

        254
        104
        255
        Client disconnected.

        See the 254, 104 and 255 above.
        This is the color sequence sent from the web server to the ESP32.
        I have a WS2812 LED strip, 1 meter long and I bought it from Ali express. It works with Arduino – and not with ESP32 ! I dont have to add the Transistor & Resistor when connected to the Arduino Uno ( Using the Fast LED library for the Arduino Uno)

        Reply
  3. Hi, The sketch comes back with an error regarding ledcSetup. I looked through several library files and cannot find which .h file to include. Am I missing something?

    Reply
  4. Hi Sara,
    can you incorporate something like WiFiManager in your sketch so i can give this as present to some of my friends?
    So they dont need to use pc every time they start product, they are not hobby makers 🙂
    Tnx

    Reply
  5. Hello Sara, is there a wifimanager for ESP32? because as it appears in the previous point, I can not tell a person or friend to access the arduino to change the SSID. Thank you

    Reply
  6. Hi Sara, is it working for regular LED RGB? Not the RGB LED strip one. Thank you!

    Reply
  7. Awesome , how can i change the code to use Ws2812 / Neo Pixels instead of the RGB strip.

    Many thanks

    scouse

    Reply
  8. Hi
    I am using a 5 meter 12V 5050 RGB LED strip with a 12V 10 Amp power supply and esp8266. The entire strip can draw max current of 8.4Amps, do i need to use resistors? if yes what should be their value and what transistors are needed.

    Reply
  9. Hi Sara,
    Ive set it up with my ESP32, however only the red is working, do you have any idea’s why?

    Reply
  10. This one is pretty much nice. Never new for those functions. Just a question:
    This project could be done using some MOSFETs. Say IRF510 for a longer strip?

    Reply
  11. this html code not working when i set esp8266 as an access point. how to sort it out.

    Reply
    • Hi.
      What do you mean by “not working”?
      Can you provide more details?
      Regards,
      Sara

      Reply
      • I uploaded above sketch as you posted it works well with wifi router but when i use it with access point configuration it is not working.
        // Load Wi-Fi library
        #include <ESP8266WiFi.h>

        // Replace with your network credentials
        const char* ssid = “RGB-led”;
        const char* password = “12345678”;

        // Set web server port number to 80
        WiFiServer server(80);

        // Decode HTTP GET value
        String redString = “0”;
        String greenString = “0”;
        String blueString = “0”;
        int pos1 = 0;
        int pos2 = 0;
        int pos3 = 0;
        int pos4 = 0;

        // Variable to store the HTTP req uest
        String header;

        // Red, green, and blue pins for PWM control
        const int redPin = 13; // 13 corresponds to GPIO13
        const int greenPin = 12; // 12 corresponds to GPIO12
        const int bluePin = 14; // 14 corresponds to GPIO14

        // Setting PWM bit resolution
        const int resolution = 256;

        // Current time
        unsigned long currentTime = millis();
        // Previous time
        unsigned long previousTime = 0;
        // Define timeout time in milliseconds (example: 2000ms = 2s)
        const long timeoutTime = 2000;

        void setup() {
        Serial.begin(115200);

        // configure LED PWM resolution/range and set pins to LOW
        analogWriteRange(resolution);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);

        // Connect to Wi-Fi network with SSID and password
        WiFi.softAP(ssid, password);

        IPAddress IP = WiFi.softAPIP();
        Serial.print(“AP IP address: “);
        Serial.println(IP);
        server.begin();
        }

        void loop(){
        WiFiClient client = server.available(); // Listen for incoming clients

        if (client) { // If a new client connects,
        currentTime = millis();
        previousTime = currentTime;
        Serial.println(“New Client.”); // print a message out in the serial port
        String currentLine = “”; // make a String to hold incoming data from the client
        while (client.connected() && currentTime – previousTime <= timeoutTime) { // loop while the client’s connected
        currentTime = millis();
        if (client.available()) { // if there’s bytes to read from the client,
        char c = client.read(); // read a byte, then
        Serial.write(c); // print it out the serial monitor
        header += c;
        if (c == ‘\n’) { // if the byte is a newline character
        // if the current line is blank, you got two newline characters in a row.
        // that’s the end of the client HTTP request, so send a response:
        if (currentLine.length() == 0) {
        // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
        // and a content-type so the client knows what’s coming, then a blank line:
        client.println(“HTTP/1.1 200 OK”);
        client.println(“Content-type:text/html”);
        client.println(“Connection: close”);
        client.println();

        // Display the HTML web page
        client.println("<!DOCTYPE html><html>");
        client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
        client.println("<link rel=\"icon\" href=\"data:,\">");
        client.println("<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\">");
        client.println("https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js");
        client.println("</head><body><div class=\"container\"><div class=\"row\"><h1>ESP Color Picker</h1></div>");
        client.println("<a class=\"btn btn-primary btn-lg\" href=\"#\" id=\"change_color\" role=\"button\">Change Color</a> ");
        client.println("<input class=\"jscolor {onFineChange:'update(this)'}\" id=\"rgb\"></div>");
        client.println("<script>function update(picker) {document.getElementById('rgb').innerHTML = Math.round(picker.rgb[0]) + ', ' + Math.round(picker.rgb[1]) + ', ' + Math.round(picker.rgb[2]);");
        client.println("document.getElementById(\"change_color\").href=\"?r\" + Math.round(picker.rgb[0]) + \"g\" + Math.round(picker.rgb[1]) + \"b\" + Math.round(picker.rgb[2]) + \"&\";}</script></body></html>");
        // The HTTP response ends with another blank line
        client.println();

        // Request sample: /?r201g32b255&
        // Red = 201 | Green = 32 | Blue = 255
        if(header.indexOf("GET /?r") >= 0) {
        pos1 = header.indexOf('r');
        pos2 = header.indexOf('g');
        pos3 = header.indexOf('b');
        pos4 = header.indexOf('&');
        redString = header.substring(pos1+1, pos2);
        greenString = header.substring(pos2+1, pos3);
        blueString = header.substring(pos3+1, pos4);
        /*Serial.println(redString.toInt());
        Serial.println(greenString.toInt());
        Serial.println(blueString.toInt());*/
        analogWrite(redPin, redString.toInt());
        analogWrite(greenPin, greenString.toInt());
        analogWrite(bluePin, blueString.toInt());
        }
        // Break out of the while loop
        break;
        } else { // if you got a newline, then clear currentLine
        currentLine = "";
        }
        } else if (c != '\r') { // if you got anything else but a carriage return character,
        currentLine += c; // add it to the end of the currentLine
        }
        }
        }
        // Clear the header variable
        header = "";
        // Close the connection
        client.stop();
        Serial.println("Client disconnected.");
        Serial.println("");

        }
        }

        after uploading this sketch color picker button not showing color bar

        Reply
  12. Hi, may I know if I would like to include brightness together with the color, may I know how to go about doing it? For example, I want it to be in red and in 80% of brightness and changing it simultaneously.

    Reply
    • For esp32 specifically. Thank you!

      Reply
      • Hi Amanda,
        You could try making a HSL color picker, then convert the HSL to RGB. The HSL mode works on the basis of Hue, Saturation and Luminance. RGB only works with Red, Green and Blue. You can try building a Luminance slider which allows you to set the intensity of the light.

        Reply
  13. After powering off, Esp8266 generate a new IP. How I can generate a fixed or static IP?

    Reply
  14. I made a version with WifiManager, and store last settings in EEPROM 🙂
    Works great.
    If I manage to get an account on instructable, I will post it.

    Reply
  15. Thank you for the wonderful tutorial!! Absolutely fascinating.

    I’m super new to the world of ardiuno but was wondering what additions to the url/code to add an ability to simple turn a specific LED on or off?

    Use case is a shelf to light up for a specific LED placed at a particular position – one at at time.

    EX. on a 15 LED strip, to turn on or off LED # 4 to Red, or LED #6 to Green, etc.

    Reply
  16. Hi, in this tutorial,https://randomnerdtutorials.com/esp32-esp8266-rgb-led-strip-web-server/, you use:
    #include <WiFi.h>

    In the web server tutorial,https://randomnerdtutorials.com/esp8266-web-server/, and the slider tutorial,https://randomnerdtutorials.com/esp8266-nodemcu-web-server-slider-pwm/, you use
    #include <ESP8266WiFi.h>

    What’s the difference between these wifi libraries and why choose one over the other?

    The slider tutorial, also uses async libraries:
    #include <ESPAsyncTCP.h>
    #include <ESPAsyncWebServer.h>

    Are there any examples with multiple elements, a slider, input buttons, input text box, all on one page? Would they necessarily have to have the async libraries if they include a slider?

    Thanks!

    Reply
  17. Hello
    I want to follow this tutorial but power a 12v led strip. Would I damage the ESP32 board if I connect the Vin input in with the 12v power supply that came with the led strip? Would I need a step down voltage suppliers?
    Thanks
    I’m enjoying the tutorial on this site so far.

    Reply
  18. Hi Sarah/Rui. Once again, great work, thanks. I have loaded this programme into an ESP-32S and all is well when I connect something other than an Android device. I was just wondering if you had received any feedback from anyone else along similar lines? I believe that my Samsung underwent a software upgrade the other day and I am sure that I tried this previously and it worked. Thanks again, Colin.

    Reply
  19. Hi Sara. Sorry that I miss-spelt your name earlier. I have used Chrome, DuckDuckGo, Edge and Firefox for exactly the same result of Express VPN looking to get me connected.

    Reply
  20. Hi Sara, i have a TIP41C,
    It should work the same, right? but at 12v. thank you

    Reply
  21. Greetings and congratulations. How can I control from another network, do you have a tutorial?

    Reply

Leave a CommentCancel reply

Learn ESP32

ESP32 Introduction

ESP32 Arduino IDE

ESP32 Arduino IDE 2.0

VS Code and PlatformIO

ESP32 Pinout

ESP32 Inputs Outputs

ESP32 PWM

ESP32 Analog Inputs

ESP32 Interrupts Timers

ESP32 Deep Sleep

Protocols

ESP32 Web Server

ESP32 LoRa

ESP32 BLE

ESP32 BLE Client-Server

ESP32 Bluetooth

ESP32 MQTT

ESP32 ESP-NOW

ESP32 Wi-Fi

ESP32 WebSocket

ESP32 ESP-MESH

ESP32 Email

ESP32 Text Messages

ESP32 HTTP GET POST

HTTP GET Web APIs

HTTP POST Web APIs

Server-Sent Events

Web Servers

Output Web Server

PWM Slider Web Server

PWM Multiple Sliders Web Server

Async Web Server

Relay Web Server

Servo Web Server

DHT Web Server

BME280 Web Server

BME680 Web Server

DS18B20 Web Server

LoRa Web Server

Plot/Chart Web Server

Chart Multiple Series Web Server

SPIFFS Web Server

Thermostat Web Server

Momentary Switch Web Server

Physical Button Web Server

Input Fields Web Server

Images Web Server

RGB LED Web Server

Timer/Pulse Web Server

HTTP Auth Web Server

MPU-6050 Web Server

MicroSD Card Web Server

Stepper Motor Web Server

Stepper Motor WebSocket

Gauges Web Server

DIY Cloud

ESP32 Weather Station

Control GPIOs

View Sensor Readings

ESP32 MySQL

ESP32 PHP Email

ESP32 SIM800L

Cloud Node-RED Dashboard

Cloud MQTT Broker

ESP32 Cloud MQTT

ESP-NOW

ESP-NOW Introduction

ESP-NOW Two-Way

ESP-NOW One-to-Many

ESP-NOW Many-to-One

ESP-NOW + Wi-Fi Web Server

Firebase

Firebase Realtime Database

Firebase Web App

Firebase Authentication

Firebase BME280

Firebase Web App Sensor Readings

Firebase ESP32 Data Logging

Modules

ESP32 Relay Module

ESP32 DC Motors

ESP32 Servo

ESP32 Stepper Motor

ESP32 MicroSD Card

ESP32 MicroSD Card Data Logging

ESP32 PIR

ESP32 HC-SR04

ESP32 I2C Multiplexer

Sensors

ESP32 DHT11/DHT22

ESP32 BME280

ESP32 BME680

ESP32 DS18B20

ESP32 Multiple DS18B20

ESP32 BMP180

ESP32 BMP388

MQTT DHT11/DHT22

MQTT BME280

MQTT BME680

MQTT DS18B20

ESP32 MPU-6050

Displays

ESP32 OLED

ESP32 LCD

OLED Temperature

ESP32 Features

ESP32 Hall Sensor

ESP32 Touch Sensor

ESP32 I2C

ESP32 Flash Memory

ESP32 Dual Core

Useful Guides

ESP32 Troubleshooting

ESP32 Access Point

ESP32 Fixed IP Address

ESP32 MAC Address

ESP32 Hostname

ESP32 OTA

ESP32 OTA Arduino

ESP32 OTA VS Code

ESP32 Solar Panels

ESP32 Alexa

ESP32 Install SPIFFS

ESP32 Time and Date

ESP32 Epoch Time

ESP32 Google Sheets

ESP32 Email Altert

ESP32 ThingSpeak

Weather Station Shield

ESP32 IoT Shield

ESP32 Weather Station PCB

ESP32 Wi-Fi Manager

VS Code and PlatformIO

VS Code SPIFFS

VS Code Workspaces

Save Data Preferences Library

Reconnect to Wi-Fi

Useful Wi-Fi Functions

Other Projects

Telegram Control Outputs

Telegram Sensor Readings

Telegram Detect Motion

Telegram Group

ESP32 Status PCB

ESP32 BMP388 Datalogger

ESP32 Web Serial

ESP32 Door Monitor

ESP32 Door Telegram

ESP32 NTP Timezones

ESP32 Boards

ESP32 Camera

ESP32 LoRa

ESP32 OLED

ESP32 SIM800L

Learn More

Learn ESP32

Learn ESP8266

Learn ESP32-CAM

Learn MicroPython

Learn Arduino

Build Web Servers eBook

Smart Home eBook

Firebase Web App eBook

ESP32 Premium Course

Affiliate Disclosure:Random Nerd Tutorials is a participant in affiliate advertising programs designed to provide a means for us to earn fees by linking to Amazon, eBay, AliExpress, and other sites. We might be compensated for referring traffic and business to these companies.



Learn ESP32 with Arduino IDE eBook » Complete guide to program the ESP32 with Arduino IDE!



SMART HOME with Raspberry Pi, ESP32, and ESP8266 » learn how to build a complete home automation system.



Learn Raspberry Pi Pico/Pico W with MicroPython​ » The complete getting started guide to get the most out of the the Raspberry Pi Pico/Pico W (RP2040) microcontroller board using MicroPython programming language.



🔥 Learn LVGL: Build GUIs for ESP32 Projects​ » Learn how to build Graphical User Interfaces (GUIs) for ESP32 Projects using LVGL (Light Versatile Graphics Library) with the Arduino IDE.

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.


[8]ページ先頭

©2009-2025 Movatter.jp