ESP8266 NodeMCU Relay Module – Control AC Appliances (Web Server)

Using a relay with the ESP8266 is a great way to control AC household appliances remotely. This tutorial explains how to control a relay module with the ESP8266 NodeMCU. We’ll take a look at how a relay module works, how to connect the relay to the ESP8266 and build a web server to control a relay remotely (or as many relays as you want).

ESP8266 Relay Module - Control AC Appliances (Web Server)

Learn how to control a relay module with ESP32 board: Guide for ESP32 Relay Module – Control AC Appliances + Web Server Example.

Watch the Video Tutorial

Watch the following video tutorial or keep reading this page for the written instructions and all the resources.

Introducing Relays

A relay is an electrically operated switch and like any other switch, it that can be turned on or off, letting the current go through or not. It can be controlled with low voltages, like the 3.3V provided by the ESP8266 GPIOs and allows us to control high voltages like 12V, 24V or mains voltage (230V in Europe and 120V in the US).

1, 2, 4, 8, 16 Channels Relay Modules

There are different relay modules with a different number of channels. You can find relay modules with one, two, four, eight and even sixteen channels. The number of channels determines the number of outputs we’ll be able to control.

Relay modules with different number of channels

There are relay modules whose electromagnet can be powered by 5V and with 3.3V. Both can be used with the ESP8266 – you can either use the Vin pin (that provides 5V) or the 3.3V pin.

Additionally, some come with built-in optocoupler that add an extra “layer” of protection, optically isolating the ESP8266 from the relay circuit.

Get a relay module:

Relay Pinout

For demonstration purposes, let’s take a look at the pinout of a 2-channel relay module. Using a relay module with a different number of channels is similar.

2-channel Relay Module Pinout

The two connectors (with three sockets each) on the left side of the relay module connect high voltage, and the pins on the right side (low-voltage) connect to the ESP8266 GPIOs.

Mains Voltage Connections

Relay module mains voltage side

The relay module shown in the previous photo has two connectors, each with three sockets: common (COM), normally closed (NC), and normally open (NO).

  • COM: connect the current you want to control (mains voltage).
  • NC (Normally Closed): the normally closed configuration is used when you want the relay to be closed by default. The NC are COM pins are connected, meaning the current is flowing unless you send a signal from the ESP8266 to the relay module to open the circuit and stop the current flow.
  • NO (Normally Open): the normally open configuration works the other way around: there is no connection between the NO and COM pins, so the circuit is broken unless you send a signal from the ESP8266 to close the circuit.

Control Pins

2-channel Relay Module

The low-voltage side has a set of four pins and a set of three pins. The first set consists of VCC and GND to power up the module, and input 1 (IN1) and input 2 (IN2) to control the bottom and top relays, respectively.

If your relay module only has one channel, you’ll have just one IN pin. If you have four channels, you’ll have four IN pins, and so on.

The signal you send to the IN pins, determines whether the relay is active or not. The relay is triggered when the input goes below about 2V. This means that you’ll have the following scenarios:

  • Normally Closed configuration (NC):
    • HIGH signal – current is flowing
    • LOW signal – current is not flowing
  • Normally Open configuration (NO):
    • HIGH signal – current is not flowing
    • LOW signal – current is flowing

You should use a normally closed configuration when the current should be flowing most of the times, and you only want to stop it occasionally.

Use a normally open configuration when you want the current to flow occasionally (for example, turn on a lamp occasionally).

Power Supply Selection

2-channel relay module control pins

The second set of pins consists of GND, VCC, and JD-VCC pins. The JD-VCC pin powers the electromagnet of the relay. Notice that the module has a jumper cap connecting the VCC and JD-VCC pins; the one shown here is yellow, but yours may be a different color.

With the jumper cap on, the VCC and JD-VCC pins are connected. That means the relay electromagnet is directly powered from the ESP8266 power pin, so the relay module and the ESP8266 circuits are not physically isolated from each other.

Without the jumper cap, you need to provide an independent power source to power up the relay’s electromagnet through the JD-VCC pin. That configuration physically isolates the relays from the ESP8266 with the module’s built-in optocoupler, which prevents damage to the ESP8266 in case of electrical spikes.

ESP8266 Safest Pins to Use with Relays

Some ESP8266 pins output a 3.3V signal when the ESP8266 boots. This may be problematic if you have relays or other peripherals connected to those GPIOs.

Additionally, some pins must be pulled HIGH or LOW in order to boot the ESP8266.

Taking this into account, the safest ESP8266 pins to use with relays are: GPIO 5, GPIO 4, GPIO 14, GPIO 12 and GPIO 13.

For more information about the ESP8266 GPIOs read: ESP8266 Pinout Reference: Which GPIO pins should you use?

Wiring a Relay Module to the ESP8266 NodeMCU Board

Connect the relay module to the ESP8266 as shown in the following diagram. The diagram shows wiring for a 2-channel relay module, wiring a different number of channels is similar.

Warning: in this example, we’re dealing with mains voltage. Misuse can result in serious injuries. If you’re not familiar with mains voltage ask someone who is to help you out. While programming the ESP or wiring your circuit make sure everything is disconnected from mains voltage.

Alternatively, you can use a 12V power source to control 12V appliances.

Wiring a Relay Module to the ESP8266 NodeMCU Board

In this example, we’re controlling a lamp. We just want to light up the lamp occasionally, so it is better to use a normally open configuration.

We’re connecting the IN1 pin to GPIO 5, you can use any other suitable GPIO. See ESP8266 GPIO Reference Guide.

Controlling a Relay Module with the ESP8266 NodeMCU – Arduino Sketch

The code to control a relay with the ESP8266 is as simple as controlling an LED or any other output. In this example, as we’re using a normally open configuration, we need to send a LOW signal to let the current flow, and a HIGH signal to stop the current flow.

Control a Lamp with the ESP8266 using a Relay

The following code will light up your lamp for 10 seconds and turn it off for another 10 seconds.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp8266-relay-module-ac-web-server/
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

const int relay = 5;

void setup() {
  Serial.begin(115200);
  pinMode(relay, OUTPUT);
}

void loop() {
  // Normally Open configuration, send LOW signal to let current flow
  // (if you're usong Normally Closed configuration send HIGH signal)
  digitalWrite(relay, LOW);
  Serial.println("Current Flowing");
  delay(5000); 
  
  // Normally Open configuration, send HIGH signal stop current flow
  // (if you're usong Normally Closed configuration send LOW signal)
  digitalWrite(relay, HIGH);
  Serial.println("Current not Flowing");
  delay(5000);
}

View raw code

How the Code Works

Define the pin the relay IN pin is connected to.

const int relay = 5;

In the setup(), define the relay as an output.

pinMode(relay, OUTPUT);

In the loop(), send a LOW signal to let the current flow and light up the lamp.

digitalWrite(relay, LOW);

If you’re using a normally closed configuration, send a HIGH signal to light up the lamp. Then, wait 5 seconds.

delay(5000); 

Stop the current flow by sending a HIGH signal to the relay pin. If you’re using a normally closed configuration, send a LOW signal to stop the current flow.

digitalWrite(relay, HIGH);

Control Multiple Relays with ESP8266 NodeMCU Web Server

Control Multiple Relays with ESP8266 Web Server

In this section, we’ve created a web server example that allows you to control as many relays as you want via web server whether they are configured as normally opened or as normally closed. You just need to change a few lines of code to define the number of relays you want to control and the pin assignment.

To build this web server, we use the ESPAsyncWebServer library.

Installing the ESPAsyncWebServer library

Follow the next steps to install the ESPAsyncWebServer library:

  1. Click here to download the ESPAsyncWebServer library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get ESPAsyncWebServer-master folder
  3. Rename your folder from ESPAsyncWebServer-master to ESPAsyncWebServer
  4. Move the ESPAsyncWebServer folder to your Arduino IDE installation libraries folder

Alternatively, in your Arduino IDE, you can go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded.

Installing the ESPAsyncTCP Library for ESP8266

The ESPAsyncWebServer library requires the ESPAsyncTCP library to work. Follow the next steps to install that library:

  1. Click here to download the ESPAsyncTCP library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get ESPAsyncTCP-master folder
  3. Rename your folder from ESPAsyncTCP-master to ESPAsyncTCP
  4. Move the ESPAsyncTCP folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Alternatively, in your Arduino IDE, you can go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded.

After installing the required libraries, copy the following code to your Arduino IDE.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp8266-relay-module-ac-web-server/
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

// Import required libraries
#include "ESP8266WiFi.h"
#include "ESPAsyncWebServer.h"

// Set to true to define Relay as Normally Open (NO)
#define RELAY_NO    true

// Set number of relays
#define NUM_RELAYS  5

// Assign each GPIO to a relay
int relayGPIOs[NUM_RELAYS] = {5, 4, 14, 12, 13};

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

const char* PARAM_INPUT_1 = "relay";  
const char* PARAM_INPUT_2 = "state";

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    html {font-family: Arial; display: inline-block; text-align: center;}
    h2 {font-size: 3.0rem;}
    p {font-size: 3.0rem;}
    body {max-width: 600px; margin:0px auto; padding-bottom: 25px;}
    .switch {position: relative; display: inline-block; width: 120px; height: 68px} 
    .switch input {display: none}
    .slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 34px}
    .slider:before {position: absolute; content: ""; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 68px}
    input:checked+.slider {background-color: #2196F3}
    input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}
  </style>
</head>
<body>
  <h2>ESP Web Server</h2>
  %BUTTONPLACEHOLDER%
<script>function toggleCheckbox(element) {
  var xhr = new XMLHttpRequest();
  if(element.checked){ xhr.open("GET", "/update?relay="+element.id+"&state=1", true); }
  else { xhr.open("GET", "/update?relay="+element.id+"&state=0", true); }
  xhr.send();
}</script>
</body>
</html>
)rawliteral";

// Replaces placeholder with button section in your web page
String processor(const String& var){
  //Serial.println(var);
  if(var == "BUTTONPLACEHOLDER"){
    String buttons ="";
    for(int i=1; i<=NUM_RELAYS; i++){
      String relayStateValue = relayState(i);
      buttons+= "<h4>Relay #" + String(i) + " - GPIO " + relayGPIOs[i-1] + "</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"" + String(i) + "\" "+ relayStateValue +"><span class=\"slider\"></span></label>";
    }
    return buttons;
  }
  return String();
}

String relayState(int numRelay){
  if(RELAY_NO){
    if(digitalRead(relayGPIOs[numRelay-1])){
      return "";
    }
    else {
      return "checked";
    }
  }
  else {
    if(digitalRead(relayGPIOs[numRelay-1])){
      return "checked";
    }
    else {
      return "";
    }
  }
  return "";
}

void setup(){
  // Serial port for debugging purposes
  Serial.begin(115200);

  // Set all relays to off when the program starts - if set to Normally Open (NO), the relay is off when you set the relay to HIGH
  for(int i=1; i<=NUM_RELAYS; i++){
    pinMode(relayGPIOs[i-1], OUTPUT);
    if(RELAY_NO){
      digitalWrite(relayGPIOs[i-1], HIGH);
    }
    else{
      digitalWrite(relayGPIOs[i-1], LOW);
    }
  }
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  // Print ESP8266 Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html, processor);
  });

  // Send a GET request to <ESP_IP>/update?relay=<inputMessage>&state=<inputMessage2>
  server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {
    String inputMessage;
    String inputParam;
    String inputMessage2;
    String inputParam2;
    // GET input1 value on <ESP_IP>/update?relay=<inputMessage>
    if (request->hasParam(PARAM_INPUT_1) & request->hasParam(PARAM_INPUT_2)) {
      inputMessage = request->getParam(PARAM_INPUT_1)->value();
      inputParam = PARAM_INPUT_1;
      inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
      inputParam2 = PARAM_INPUT_2;
      if(RELAY_NO){
        Serial.print("NO ");
        digitalWrite(relayGPIOs[inputMessage.toInt()-1], !inputMessage2.toInt());
      }
      else{
        Serial.print("NC ");
        digitalWrite(relayGPIOs[inputMessage.toInt()-1], inputMessage2.toInt());
      }
    }
    else {
      inputMessage = "No message sent";
      inputParam = "none";
    }
    Serial.println(inputMessage + inputMessage2);
    request->send(200, "text/plain", "OK");
  });
  // Start server
  server.begin();
}
  
void loop() {

}

View raw code

Define Relay Configuration

Modify the following variable to indicate whether you’re using your relays in normally open (NO) or normally closed (NC) configuration. Set the RELAY_NO variable to true for normally open os set to false for normally closed.

#define RELAY_NO true

Define Number of Relays (Channels)

You can define the number of relays you want to control on the NUM_RELAYS variable. For demonstration purposes, we’re setting it to 5.

#define NUM_RELAYS 5

Define Relays Pin Assignment

In the following array variable you can define the ESP8266 GPIOs that will control the relays.

int relayGPIOs[NUM_RELAYS] = {5, 4, 14, 12, 13};

The number of relays set on the NUM_RELAYS variable needs to match the number of GPIOs assigned in the relayGPIOs array.

Network Credentials

Insert your network credentials in the following variables.

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

Wiring 8 Channel Relay to ESP8266 NodeMCU

For demonstration purposes, we’re controlling 5 relay channels. Wire the ESP8266 NodeMCU board to the relay module as shown in the next schematic diagram.

ES8266 8-channel relay module wiring diagram schematic

Demonstration

After making the necessary changes, upload the code to your ESP8266.

Open the Serial Monitor at a baud rate of 115200 and press the ESP8266 RST button to get its IP address.

Then, open a browser in your local network and type the ESP8266 IP address to get access to the web server.

You should get something as follows with as many buttons as the number of relays you’ve defined in your code.

ESP8266 Web Server controlling AC lamp with relay module

Now, you can use the buttons to control your relays remotely using your smartphone.

Enclosure for Safety

For a final project, make sure you place your relay module and ESP inside an enclosure to avoid any AC pins exposed.

Enclosure for Relay Module

Wrapping Up

Using relays with the ESP8266 is a great way to control AC household appliances remotely. You can also read our other Guide to control a Relay Module with ESP32.

Controlling a relay with the ESP8266 is as easy controlling any other output, you just need to send HIGH and LOW signals as you would do to control an LED.

You can use our other web server examples that control outputs to control relays. You just need to pay attention to the configuration you’re using. In case you’re using a normally open configuration, the relay works with inverted logic. You can use the following web server examples to control your relay:

Learn more about the ESP8266 with our resources:

Thanks for reading.



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!

143 thoughts on “ESP8266 NodeMCU Relay Module – Control AC Appliances (Web Server)”

    • The project is amazing, it works and all but the code seems to be made considering “OPEN”= “the flow is on” or “CLOSE”=”The flow is off” just like in water taps. But in Electrical/electronics OPEN actually means incomplete electrical path, so OFF, and CLOSE means complete electrical path, so ON.

      For NO state as default, the Digital write to GPIO should be ‘Active LOW’, while for NC as default state, the DigitalWrite state of the respective GPIO pin should be ‘Active HIGH’. We can always switch the wires at relay output, it is a simple thing to do, but while testing with LED before relay connection, it stays on by default. While the switch is in ON state in the server page, which creates unnecessary confusion.

      Reply
  1. Really nice tutorial. We have to add some security on the page. Is there a way to adapt it and make it with username and password please?

    Reply
  2. Very nice project. Clean operation as viewed on WireShark. How about a detailed explanation / tutorial on the Client – Server communications used in this sketch.

    Reply
  3. Just wanted to add, the library you’re pointing to does not contain ESPAsyncTCP but I downloaded it separately and all works.

    Reply
    • Hi.
      Thanks for your feedback.
      What link are you referring to?
      I’ve tested all links and these just seem to work fine.
      Regards,
      Sara

      Reply
      • Thank you for this beautiful project but I get a problem how can I make the lamp on 10 seconds and off another 10 sec and again etc … please reply for me at email

        Reply
  4. Hello,
    First, thank you for making and sharing this very interesting tutorial.
    I have a question and i hope that you can help: how to convert this sketch and make it work with the ESP as an Access Point, so that it does not need internet or another router to connect to it?

    Reply
  5. Hi Sarah. Good time. I compiled the Top of this page program on the esp8266 board but I don’t know why my Wifi Control Mobile app doesn’t have ( Does not know ) this board. The top button on my phone is red.Does it guide me?

    How to find out if I did the compiler correctly on the board esp8266 mcu???
    Thank you

    Reply
  6. Hi Sarah,

    Great tutorial and works amazingly well.

    Now I am looking for a little alteration of the script, based on the webserver toggle.
    I would to automatically flip the switch back after 1 second, but I can’t get it to work.
    I tried it in the scripting part as well as with a delay (1000).

    The reason this is that I want to use it as a pulse switch for the garage; switching it on for only 1 second to open, and then to switch it on briefly on and off to close the door again.

    Could you help me out?

    Kind regards,
    Remco

    Reply
  7. First of all thank you for this well documented and detailed website that has helped me in several DIY projects.
    I am building a simple website very similar to the one built in this project to control 4 different gates with a 4-relay module and an esp8266. Your example works perfectly but I would like to send just a short period impulse to the relay, capable of changing the state of the gate’s motor.
    In order to do that I tried to adapt your code by using a simple button instead of a switch and the idea was to activate the relay while the button was being pressed and deactivate if it wasn’t.
    Due to my lack of knowledge about javascript and esp communications I haven’t figured the way to do it so I wonder if you can help me!

    Reply
  8. Hello, great tutorial, but there is some problem: with arduino ide code works great, but whe i tried with vs code-platformio, i’ve got an error:
    src\main.cpp: In function ‘String processor(const String&var)’:
    src\main.cpp:61:49: error: ‘relayState’ was not declared in this scope
    String relayStateValue = relayState(i);

    Reply
    • When using PlatformIO you must write the right C/C++ code. In this case you have to add the function prototype:

      String relayState(int numRelay);

      before using it. Just add that line at the beginning of the program after the #defines and variable declarations.

      Reply
      • hi
        Please help it gives this error message
        Arduino: 1.8.12 (Windows 7), Board: “NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200”

        sketch_may28a:11:31: fatal error: ESPAsyncWebServer.h: No such file or directory

        #include “ESPAsyncWebServer.h”

        ^

        compilation terminated.

        exit status 1
        ESPAsyncWebServer.h: No such file or directory

        This report would have more information with
        “Show verbose output during compilation”
        option enabled in File -> Preferences.

        Reply
  9. Thanks for the help but there is another mistake

    Arduino: 1.8.12 (Windows 7), Board: “NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200”

    C:\Users\MICRO\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-4-b40a506/bin/xtensa-lx106-elf-ar: unable to rename ‘core\core.a’; reason: File exists

    exit status 1
    Error compiling for board NodeMCU 1.0 (ESP-12E Module).

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    Reply
    • Hi
      You would have to choose 16 GPIOs to control the relay, which is not possible in the case of the ESP8266.
      So, you would need to use a multiplexer or other solution to expand the number of GPIOs.
      Regards,
      Sara

      Reply
      • Thank you! Is there a schematic or anything to how to connect the nodemcu ESP8266 with a multiplexer to a 16 channel relay and powering said relay. Thank you for all your help.

        Reply
        • Hi.
          At the moment, we don’t have any example about that.
          Search for “ESP8266 IO Expander” and you’ll find tutorials about controlling more outputs.
          Regards,
          Sara

          Reply
  10. Hi, I have a problem with the Arduino IDE compiler. It says that it can not compile the program for the Generic ESP8266 Module. Can someone help me?

    Reply
  11. Luis and Sara, I used/modified your code for a single 5v relay (like the middle one in your pictures— with a high-low choice) and a generic ESP8266 01s. Much to my amazement and delight it works! I assumed the “low” setting meant it would work with 3.3 V. So it has one 3.3 v source, and I am using GPIO2.
    Can a second relay be placed on GPIO1?
    THANKS again.
    ~ Bruce

    Reply
    • Hi Bruce.
      I think you can.
      But you can only connect the relay after uploading the code, because you need that pin to upload code(TX pin).
      Regards,
      Sara

      Reply
  12. Hey Sara Santos
    This is Working Awesome, im using 10 Relays, instead of displaying relay on the page how to customize appliance name, getting confused of relay1,2,3,…. plz help.

    Reply
    • Hi.
      The names of the relays are assigned on the processor function, on the buttons variable.
      Instead of having:
      ” – GPIO ” + relayGPIOs[i-1] + ”

      Add the name for a particular relay. You may need to add some if statements to give each relay a name. For example, if i=0, then it means it is the kitchen relay, and so on.
      I hope this helps.
      Regards,
      Sara

      Reply
  13. Hello Sara,

    Thank you for sharing this tutorial. I I updated my code based on one of your early tutorials for one relay only. Works like a charm. I like this version more.

    Is it possible to incorporate a simple WiFi manager with captive portal? A tip on how to proceed with it will be very helpful. Thank you, again.

    Reply
  14. Thank you Rui and Maria, it worked here as Soft AP relay on-off switch.
    A question, how can i add or change a relay to a momentary 1 second on (to act like like a pushbutton) ?
    Now, your code is to complicate for me to change it.

    Reply
  15. Hi sara. I compiled and uploaded code to nodeMcu esp8266 evrthng is fine but in serial monito showing that **Connectong to Wifi…
    Connecting to Wifi

    But not showing ip address .how to fix this issue . Its not working for me please helpme

    Reply
  16. Hi Sara
    this above code is not working if relay numbers more then 7 for esp8266 node mcu please solve this problem.

    // Set number of relays
    #define NUM_RELAYS 8

    // Assign each GPIO to a relay
    int relayGPIOs[NUM_RELAYS] = {16, 5, 4, 0, 14, 12, 13, 15};

    Reply
  17. Thank you for all your wonderful tutorials. I would like to combine the relay sketch and the DHT11 temp sketch web pages into one. I want to turn on the furnace in my garage and be able to monitor the temperature remotely(from inside my warm house). Any advice would be appreiciated.

    Reply
  18. Hola
    Tengo un problema, me copila todo el codigo y la pagina tambien pero el relé solo se queda encendido y cuando lo intento apagar por la pagina no se apaga.

    Hice el anterior proyecto, el de encender los leds y me funcionó perfectamente y pensaba si puedo utilar ese codigo para encender el rele.
    Lo intente pero no me funcionó, quisiera utiliar el mismo codigo de los leds para encender el relé. Si me ayudan. Gracias 🙂

    Reply
  19. Hi,
    I have a problem. When I try to upload the code, it shows me an error. The error is: Arduino: 1.8.13 (Mac OS X), Πλακέτα:”NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200″

    Executable segment sizes:
    IROM : 264912 – code in flash (default or ICACHE_FLASH_ATTR)
    IRAM : 27492 / 32768 – code in IRAM (ICACHE_RAM_ATTR, ISRs…)
    DATA : 1288 ) – initialized variables (global, static) in RAM/HEAP
    RODATA : 2616 ) / 81920 – constants (global, static) in RAM/HEAP
    BSS : 25288 ) – zeroed variables (global, static) in RAM/HEAP

    What should I do?
    Thanks

    Reply
  20. Hi. Great article as always (well thought-out and presented) – thank you very much!

    Can you recommend how I can power a project like this. I am going to use a 12v 3A linear actuator. Does this mean I need two power supplies – one for the actuator (12v) and one for the ESP8266 (5v)? Or is there some way I can use one transformer for both?

    Thanks again
    Tim

    Reply
  21. Hi, I tried this project found working perfectly, when my smart phone is connected to same wifi,
    What should be done to control it when the smart phone is on other internet connection and the ESP is on wifi. Please help.

    Reply
    • Hi. Witch port? 80? Is it possible to change to another and connect remotely trouth a free dyndns server? For example opening a webpage mydyndns.org:49999 outside the network.

      Reply
  22. Hi Sara,
    thanks for the well explained tutorial.
    I’m trying to incorporate this with an IOs connecting to a push buttons, so I can update the relay (as well as the webpage) with no luck.
    Also, sending a message like “IP adds/update?relay=1&state=1” (from another browser or ESP) change the states (as can be seen after updating), but the webpage showing the relays status is not refreshing.
    Can you please help, so the webpage will be update?
    Thanks

    Reply
  23. Thanks Sara,
    I’m familiar with these codes.
    What I liked in the toggle one switch ( https://RandomNerdTutorials.com/esp8266-nodemcu-async-web-server-espasyncwebserver-library/) is that I can change the status of the buttons from another pc (or esp) by sending the appropriate link (/update?output=5&state=1) and both webpage will be updated to reflect the current status of the pins.
    I tried copy the setInterval(function ( ) code into the HTML script to the other sketch, but this doesn’t work.
    any suggestions?
    for connecting the physical pins, I understood that I need to have the code in the loop, right?

    Regards,
    Doron

    Reply
  24. Hi, thank you for posting this. I uploaded to my eps8266 and it works great.
    I noticed that when more than one person is accessing the webpage from different devices, the buttons do not show the current state of each slider. For example, when person A slides Relay #1 – GPIO 5 slider to the on position is turns blue.
    But when person B accesses the webpage from their own device, it does not show the current state of Relay #1 – GPIO 5 as being already ON (blue) but it shows OFF gray.
    Is there a way to have the web page show the current state of each slider so that when two or more people are accessing the webpage, it will show/display the current state to the users?
    Thanks.

    Reply
  25. Thanks for your reply abut the websockets, I tried it already and it does exactly what I asking about!!

    Next question:
    Would it be possible to dynamically change the web page content text for the naming of the buttons? For example, rename the “GPIO 5” button on the web page to “Living Room Lamp” by sending it through a Linux command-lind curl command?
    e.g. something like this,
    curl “http://10.0.0.66:8090/id=2&text=Living%20Room%20Lamp”

    This way I would not have to re-edit the source code and re-upload it each time I wanted to redefine what the button names should be and what they control.

    Reply
  26. Thanks for the tutorial. I’d like to add a few things I learned while playing with a relay module for the first time a couple of weeks ago.

    1.) Some relay modules have LEDs which tell you whether or not the relay is powered. These do NOT always fail safe – i.e. do not trust them to let you know it is safe to touch the high voltage areas.

    2.) Bear in mind that there are a few bits on the back of the relay board which are also high voltage (just where your fingers want to sit when securing the high voltage wires, as it happens). Obviously no-one (else) is going to be stupid enough to do live work, but it is also potentially relevant for what those pins are close to when you do turn the power on.

    Reply
    • Thanks for the tips.
      It’s always good to remember that you should not touch the relay unless mains power is disconnected.
      Regards,
      Sara

      Reply
  27. Hi All, Very nice tutorial, i have learned a lot, how difficult will it be to add a timer control to this project, the idea is to switch on relay 1 one at lets say 6.00AM for 20 seconds then relay 2 for 10 seconds, now this must repeat let say at 18:00 and different times over weekends? Any ideas im new with this programming

    Reply
  28. I got it working! Thanks for a great instructable
    Wanted to share with others the extra steps required.

    //First off –
    with ESP8266 I needed to fold SSID lowercase.
    OurWifi // doesn’t work
    ourwifi // works
    That solved one problem.

    //Secondly –
    I had to add this line above the WiFi.begin
    WiFi.mode (WIFI_STA);
    WiFi.begin(ssid, password);

    // Last –
    I added these debugging lines. I wish i knew what the return values were.

    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print (“WiFi.status “);
    Serial.print (WiFi.status());
    Serial.print (” wsgc status “);
    Serial.print(wifi_station_get_connect_status());
    Serial.println (” “);
    }

    Reply
    • Hi Dave.
      Thanks for sharing.
      However, using uppercase should work. My SSID is uppercase and it always worked with uppercase.
      For the returned values, see this: github.com/esp8266/Arduino/blob/193043d19b2b670fe419d3ec2c6a1916baf6b2b3/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.cpp#L524
      Regards,
      Sara

      Reply
  29. Hi Sara,

    I had to do some weird workaround to get this working.
    I am using a nodemcu v3 and I was only able to control my relay module FL-3FF-S-Z by toggling the pinMode of GPIO5 to input/output rather than setting it to HIGH/LOW.

    Another thing I noticed is that the relay is activated when connecting the IN pin to either GND or 3V. Connecting it to VIN deactivates it as expected. VIN disconncted also deactivates the relay.

    I wonder if the 2 volts threshold to deactivate the relay is higher for this module, something above 3.3V, but I couldn’t find anything in the module’s datasheet.

    Any ideas?

    Reply
  30. Arduino: 1.8.16 (Linux), Board: “Generic ESP8266 Module, 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200”

    In file included from /home/alizard/Downloads/arduino-1.8.16/libraries/Robot_Motor/src/ArduinoRobotMotorBoard.h:22,
    from /home/alizard/Arduino/ESP8266_Relay_Module_Web_Server/ESP8266_Relay_Module_Web_Server.ino:3:
    /home/alizard/Downloads/arduino-1.8.16/libraries/Robot_Motor/src/EasyTransfer2.h:42:10: fatal error: avr/io.h: No such file or directory
    42 | #include <avr/io.h>
    | ^~~~~~~~~~
    compilation terminated.
    exit status 1
    Error compiling for board Generic ESP8266 Module.
    Arduino: 1.8.16 (Linux), Board: “Generic ESP8266 Module, 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200”

    In file included from /home/alizard/Downloads/arduino-1.8.16/libraries/Robot_Motor/src/ArduinoRobotMotorBoard.h:22,
    from /home/alizard/Arduino/ESP8266_Relay_Module_Web_Server/ESP8266_Relay_Module_Web_Server.ino:3:
    /home/alizard/Downloads/arduino-1.8.16/libraries/Robot_Motor/src/EasyTransfer2.h:42:10: fatal error: avr/io.h: No such file or directory
    42 | #include <avr/io.h>
    | ^~~~~~~~~~
    compilation terminated.
    exit status 1
    Error compiling for board Generic ESP8266 Module.

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    Reply
  31. Hey thank you for these great tutorials. May i ask how can i control the relay and also it can auto turn on relay in a certain point?.

    Reply
  32. Hi Sarah.
    Thank you for your instructive tutorials.
    I built this project with 2 relays at switch standby mains power to a caravan. It works brilliantly except that it is18650 battery powered and the fully charged battery normally doesn’t last one whole day.
    I’ve been reading up on using deep sleep but can’t find anywhere how to start deep sleep from midnight and wake up at about 8am.
    There are many ways of waking up esp8266 from deep sleep but nowhere Ive found a scheduled deep sleep event as described.
    Thank you.
    Melvin Lee

    Reply
    • Hi.
      I deleted the link from your comment.
      Yes, I know.
      And there are many other websites that besides copying the content without giving credit, they even copy our website theme…
      Unfortunately, there’s nothing we can do about that…
      Regards,
      Sara

      Reply
  33. Olá!
    Estou com um problema com o meu projeto. Tenho o teu código, um nodemcu e um módulo de 2 relés. O meu problema é que assim que faço a ligação do pino D1 ao IN1 do módulo de relés, este atraca, e só desliga se tirar o fio. Os botões no webserver não fazem nada. Basicamente se o fio estiver conectado o relé está ligado. E se desligar o fio, desliga o relé.
    Será que me podem ajudar?
    Obrigado

    Reply
  34. Hello
    I have an issue with connecting to my wifi. I am not completely sure but it appears that the issue is coming from my network having 2g and 5g so my ssid’s end with -2G and -5G. Does this make sense and if so is there a way to get this to connect?

    Reply
  35. Hello Sara
    Did you know if it is possible to control the relay with a laptop key ? Like S to let do the relay let the current pass and then P for it stop the current flux, for example.

    Reply
  36. Hello thanks for the code works great!! for ppl who is asking web login they must know that even if its added no protection is really on..Better install a vpn server at ur home and connect to it. Anyway!!:) how can i modify the text? example instead of (Relay #1 – GPIO 5) – (kitchen lights)

    Reply
  37. Hello Sara and Luis. I am just starting to learn programming. I love your projects posted here.

    Is there a way to merge this ESP8266 NodeMCU Relay Module (https://randomnerdtutorials.com/esp8266-relay-module-ac-web-server/) with your ESP8266 Node MCU Temperature Monitor Using DHT-11 Module (instructables.com/ESP8266-Nodemcu-Temperature-Monitoring-Using-DHT11/) ?

    I want to be able to monitor temperature and humidity from GPIO 14 and manually control GPIO4 and 5 from my browser.

    Can you offer any guidance on this is greatly appreciated. Many thanks in advance. Jim

    Reply
  38. Really thanks for this project. It does work, but I have a weird problem. I used your sketch on an ESP01 to turn on a light bulb, which is supposed to stay on until I turn it off hours later. But after a short while from turning it on, it turns the bulb off by itself. I also noticed that it sometimes flickers the bulb on when in off mode (I confirm I don’t live in a possessed house).
    I’ve tried this with a few ESP01 boards and relay modules, as well as all GPIOs (prefer GPIO2 on this board), but they all behaved the same. I also noticed that the ESP’s blue light flickers when this happens.
    The relay and the ESP get plenty of power from separate sources and all joints are soldered well (so no loose connections).
    Could this be fixed in the code?
    Thanks for any advice.

    Reply
  39. Hi. I have successfully uploaded this project and was able to put different coloured LEDs on 8 relays to check for operation. All good.
    My question is based on Halloween:
    How do I change the text on the web page for either the Relay ID or the GPIO ID to text that would identify the Halloween prop my D-I-L wants to start / stop? For example:
    Relay 1 might turn on sound affects, Relay 2 might turn on an animatronic monster, and so on.
    Any ideas or a link to further information will be greatly appreciated.
    Thanks

    Reply
  40. Hi Sara

    Why when i open serial monitor it always says Connecting to wifi, then when i press RST button it prints

    rll�r$�n�l�b|���rb�b�nnlnnbbp�$blrlp�n��l�bn�n��b��nn’l�l�nn$nr���nrr�p�n0r�<bbn�nb��nn'l�nn$nr���nrlr��nrl�$rbl��n�`Connecting to WiFi..

    Thanks

    Reply
  41. Hello,

    Thanks for the article.
    I have a problem, however, in that the WiFi never connects. Everything compiles normally, but the “Connecting” prompt never stops.
    Was there some error discovered and mentioned in the comments? I tried on two different ESP8266s without success. I do have the mentioned two libraries installed. I tried downloading the “Raw Code” page as well as copying and pasting the code (second piece).
    The only difference I noticed was the line terminations; in Windows and in the Chrome browser.
    I host my website from one of my laptops, so the site is up when the laptop and router are on.

    Thanks again,
    Jim Julian

    Reply
    • Hi.
      Try to run the ESP8266 WiFiScan sketch and check if it is finding your network and if it shows up with the exact name that you’re inserting on the code.
      The sketch can be found in your Arduino IDE File > Examples > ESP8266WiFi > WiFiScan.
      Regards,
      Sara

      Reply
      • Thanks for the suggestion.
        My network does not show up.I’d forgotten the cause since a lot of time has passed since I first encountered the issue.

        My networks are hidden.
        Right off hand, do you know of a way to bypass the problem without making my networks visible?

        Thanks,
        Jim Julian

        Reply
  42. Dear Sara,
    Please advise: as per the sketch in this example – one can control his devices via IP address while both the ESP board and his/her mobile phone are connected to the same Wifi router.
    Is it possible to control device if you are away many hundred kilometers from home?
    Does this involve the requirement for the static IP on the router? Is there any way to control the remote ESP if the static IP on the router is not available?
    Thanks

    Reply
  43. Hello Sara, I also get what others have with never connecting to WiFi. I am NODEMCU and have tried two different boards with the same results, just the never ending “Connecting to WiFi..” I use these boards for other wifi projects and have checked the SSID & PW and performed many resets, but still no luck. I do have both libraries installed directly from the .zip files.

    Reply
      • I found that it was our LAN wifi system that boogered things up. I am running EEROS for our 802.11 and had to either fold() or UPPER() the SSID

        Reply
  44. To those having issues not connecting… some of my friends had issues. The code above works, therefore, the issue must be something local to yourselves.
    Check… The station you are trying to access is NOT a 5g access point.
    Checks your case.
    A lot of access points will not allow access if you have less than 8 digits in your password.
    From an engineering/fault finding point of view…. if 1000s of users don’t have the issue, therefore, the issue must be local to you.
    You could also try using a local hotspot on your cell/mobile phone. as some APs can be very specific. in security settings etc.

    Reply
  45. thank you, very good article, great depth.

    however, i have a problem..

    what i need is to be able to power my board from the A/C i am controlling, in the same way that virtually all IOT gadgets are usually powered, in the real world.

    nobody seems to be talking about how to do this – am i just not looking in the right place?

    any help would be much appreciated.

    Reply
  46. Hello, thank you for this project. I am experiencing a small issue. I noticed that the kind of relays I am using sometimes get switched on when being powered on. The whole system is supposed to reboot, and this issue with the relay being powered on doesn’t happen 9 out of 10 times. But when it happens it’s annoying and I waste power without noticing that the relay is turned since I have not turned it on in the web server. Can you tell me how to initialize this code so it waits 5 seconds after being powered on, and always switches the relays to LOW, and then execute the rest of the program? Thank you for any response.

    Reply
  47. Hi.
    Works well for me on my ESP-07.
    I would like to add a temp display just like your DS18B20 web server example.
    Do you have a tutorial which uses both parts (outputs an inputs)?
    Preferably using the ESPAsyncWebServer library.
    I too need inside information on to understand all these WEB things, suggestion for any easy reading would be apriciated.
    Thanks

    Reply
  48. Dear Sara,

    I apologise upfront for possibly being a bit off topic, but I do not seem to be able to find information on the combination of two subjects: I am trying to program a WEMOS D1 mini to activate a relay when either a button on a webserver is toggled or an MQTT message is received. I have been able to make a program that works through a webserver and another program that works through the reception of MQTT messages. But I do not seem to be able to have both functionalities that work in one sketch simultaneously. Could you point me to any tutorial that covers the combination of these two functionalities in one sketch, if that exists, or any other source of information on this subject please?

    Thank you so much for your answer,

    Kind regards, Ruud

    Reply
  49. Hi Sara,

    Thanks for a great tutorial. I have a different situation where I would like to monitor and get alerts when a 24VAC line connected to a water tank float switch changes state (turns on and off). I don’t want to actually control this state change, just get alerts when it happens as the float drops/rises with the water level.
    I have a NodeMCU ESP8266 for this project.
    I’ve done a lot of research online but have not been able to find anything that explains how to do this.
    Any suggestions?
    Thanks in advance!

    Reply
    • Hi Lonnie, for alerts this is not the correct tutorial, this one is buttons on a smartphone that controls relays who are connected to the NodeMCU.

      But a give little help for you, you can connect a 24 Vac relay to the watertank float switch output and his contact you connect to a NodeMCU input. Also you must provide some input protection and noise filtering.
      The alert you can receive for example with Whatsapp or Telegram.
      Look then for the correct tutorial at Randomnerdtutorial.com

      Reply
      • Thanks Luc but I’m still not sure I understand how this would work or what input protection and noise filtering I would need. I haven’t been able to find any tutorials on this use case so if you or anyone has a link to one I would greatly appreciate it.
        Thanks

        Reply
        • Hi Lonnie, if i understand well enough your project to detect 24V ac, perhaps you can use something like that: learn.edwinrobotics.com/230v110v-ac-mains-detection-using-arduino-raspberry-pi-and-esp8266-thing/, but the resistor of 390k can be smaller.

          Reply
  50. Hello , can you provide the static IP of the code.
    I try with
    // Replace with your network credentials
    const char* ssid = “MY_SSID”;
    const char* password = “MY_PSWD”;

    IPAddress staticIP(192, 168, 1, 108);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);

    but the second code that you provided have set as dynamic IP. If it is possible can you give me the code with

    Reply
  51. hi there!
    I am using ESP01 with one relay v4.
    After hours of burning brain, I debug and noticed that, when de #include ESP8266WebServer.h is up, the ESP01 does not have energy to move the relay.

    I find a workaround that stop the server, wait 500ms, move the relay, wait 500ms, and restart the webserver 🙂 it is working now!

    any clue what is causing that?

    void handleRoot() {
    flag = !flag;
    contador++;

    server.stop();
    server.close();
    delay(500);

    digitalWrite(RELAY, flag);
    digitalWrite(led, flag);

    delay(500);

    server.on(“/”, handleRoot);
    server.begin();
    server.send(200, “text/html”, ”

    Ola, ESP01! contador = ” + String(contador) + ”

    “);
    }

    Reply
  52. Hello, im using this code to turn on my lamp and i want to automatic turn it off for several seconds , how to modified the code?

    Reply
  53. Hello Sara,

    Great tutorial! I have a question.

    Basically, I’m using a relay to control a water pump, I’m following this article here:

    https://srituhobby.com/how-to-make-a-plant-watering-system-with-the-nodemcu-esp8266-board-and-the-new-blynk-update

    and I’m using the ESPAsyncWebServer library to make an API to control the water pump, similar to how you did it, and I’m getting this error when I call the endpoint to turn off the engine.

    Follow the code and the error.

    Code:

    server.on(“/v1/waterPump/on”, HTTP_GET, [](AsyncWebServerRequest *request) {
    digitalWrite(WATER_PUMP_PIN, LOW);

    request->send(200);

    });

    server.on(“/v1/waterPump/off”, HTTP_GET, [](AsyncWebServerRequest *request) {
    digitalWrite(WATER_PUMP_PIN, HIGH);

    request->send(200);

    });

    Error:

    wdt reset
    load 0x4010f000, len 3460, room 16
    tail 4
    chksum 0xcc
    load 0x3fff20b8, len 40, room 4
    tail 4
    chksum 0xc9
    csum 0xc9
    v0007b150
    ~ld

    Reply
  54. Hello , I am using nodemcu esp8266 with Songle Single-channel 5V 30A Relay Module.
    I am having issue where relay is not getting initialized when water level drops. however getting change in the voltage level on D5. Also LED on the modules goes on and off correctly but relay does not change the status. Changed relay module already. Could anyone suggest me on this issue please.

    Reply
  55. Hi,
    I’ve setup the program for four relays and everything works fine.
    I’m controlling a ball valve to start/stop water flow to a presure tank.
    For this I need to be able to give each slider a unique name.
    I’ve studied the code. Is there a simple way to label each relay with a unique name?

    I’ve enjoyed and run many of your ESP8266 apps the last few years. Thanks for your contributions.

    Jim J.

    Reply
    • I just noticed something in the code. There seems to be a mechanism for specifying N.O and N.C. ( normal state ).
      However, the webpage has no indication and the serial monitor only indicates N.O..
      I could dissect the code (after a refresher course) but would rather just ask. Is that piece of code ever used?
      Thank you,
      Jim J.

      Reply
  56. Thanks for the article.
    I think more attention could have been paid to the power supply/source. Typically, a USB cable connects the ESP8266 to a power supply. In practical use, some other means of powering the unit would be used. An article on power scenarios would be good. Also good for the ESP-32.

    Reply
  57. … also, there’s a limit on how many relays the ESP-8266 can drive.
    Can a single 12VDC source drive the entire circuit if a 12VDC device is being controlled?

    Leave the jumper off and connect 12VDC to the relay board.
    Connect 12VDC to Vin on the ESP8266.
    Connect 12VDC to the relay wiper contacts.

    The alternative, for me, is to combine a 12VDC power source with an Apple iPhone charger and ESP-8266 USB cable.

    Reply
  58. Ciao Sara
    Thanks for this beautiful project but I would like to add 3 physical buttons, one for each relay to be used simultaneously with those of the web server. The state of each relay is updated on the web page, regardless of whether it is changed via a physical button or a web server.
    I can’t fit the project “ESP32/ESP8266: Control Outputs with Web Server and a Physical Button Simultaneously” by Rui Santos onto this sketch. Can you give me some suggestions?
    Thank you
    Notify me of follow-up comments by email.
    Thank you
    ciao
    Marco

    Reply
  59. Hiii. Thanks for the very nice project that you learned me. I just have a question. why the number of LEDs that i connected to the est8266 revered after my first try. The first one became the last one. the first try was ok by the way. the second question is why when i turn off the bottons on my mobile or PC the LEDs turn OFF :))))

    Reply
  60. Hiiii Again. I have another question too. how many LEDs or Relays can i control with this project with esp8266? Sorry i’m just starting Electronics and i love it. My main job is IT like Linux and if anyhow i could be helpfull i trully would be glad:)))

    Reply
  61. Hi. I’ve found out the bottons are working reversely. so i changed the following code and now when a botton is ON the LED or Relay will turn on too. Here is the code.

    if(element.checked){ xhr.open(“GET”, “/update?relay=”+element.id+”&state=0”, true); }
    else { xhr.open(“GET”, “/update?relay=”+element.id+”&state=1”, true); }

    I’ve just changed the zero with one and changed the one with zero and now it’s works fine

    Reply
    • My gut feeling is that you probably could find 8 outputs (especially if you were prepared to lose the onboard WiFi) but I agree that finding the specific ones can be problematic.

      Look to see if there are any relay modules which use the I2C interface – that might considerably simplify things as you only need 1 (2?) pins

      I haven’t used nodemcu; still not clear whether it’s a specific board or software you install on a board.

      Reply

Leave a Comment

Download Our Free eBooks and Resources

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