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).
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.
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:
- 5V 2-channel relay module (with optocoupler)
- 5V 1-channel relay module (with optocoupler)
- 5V 8-channel relay module (with optocoupler)
- 5V 16-channel relay module (with optocoupler)
- 3.3V 1-channel relay module (with optocoupler)
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.
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
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
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
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.
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.
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);
}
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
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:
- Click here to download the ESPAsyncWebServer library. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get ESPAsyncWebServer-master folder
- Rename your folder from
ESPAsyncWebServer-masterto ESPAsyncWebServer - 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:
- Click here to download the ESPAsyncTCP library. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get ESPAsyncTCP-master folder
- Rename your folder from
ESPAsyncTCP-masterto ESPAsyncTCP - Move the ESPAsyncTCP folder to your Arduino IDE installation libraries folder
- 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() {
}
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.
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.
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.
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:
- ESP8266 Web Server – Arduino IDE
- ESP8266 Web Server using SPIFFS (control outputs)
- ESP32/ESP8266 MicroPython Web Server – Control Outputs
Learn more about the ESP8266 with our resources:
- Home Automation using ESP8266
- MicroPython Programming with the ESP32 and ESP8266
- More ESP8266 resources…
Thanks for reading.
Error line AsyncWebServer server(80);
Hi.
Have you installed the required libraries?
https://github.com/me-no-dev/ESPAsyncTCP
https://github.com/me-no-dev/ESPAsyncWebServer
Regards,
Sara
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.
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?
If you look in the Arduino Webserver examples, you should find a couple of authentication sketches.
Very nice project. Clean operation as viewed on WireShark. How about a detailed explanation / tutorial on the Client – Server communications used in this sketch.
Thank you for this very nice project.It works perfect.
Ivan
Nice project. Easy to extend as I’ve a 6 relay shield. Thank you for sharing
Just wanted to add, the library you’re pointing to does not contain ESPAsyncTCP but I downloaded it separately and all works.
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
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
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?
Hi Carlos.
Take a look at this tutorial: https://randomnerdtutorials.com/esp8266-nodemcu-access-point-ap-web-server/
Regards,
Sara
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
Hi.
This is the code that you need to upload to your board: https://raw.githubusercontent.com/RuiSantosdotme/Random-Nerd-Tutorials/master/Projects/ESP8266/ESP8266_Relay_Module_Web_Server.ino
Change the code with your network credentials.
After uploading the code, the IP address should be printed on the Serial Monitor.
On your smartphone, open the browser and type the IP address. Your smartphone needs to be connected to the same network that the ESP32 is.
I hope this helps.
Regards,
Sara
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
Hi.
Try this code, it does exactly what you want:
– gist.github.com/sarasantos/5e60cf40caaf5865cf56f39621501b5c
Basically, you just need to make some changes to the JavaScript function, see lines 52 to 56.
I hope this helps.
Regards,
Sara
Hi, i dont know how to implement some security mesures. Can you help me? You know, some password or pincode. I dont want other people to controll my garare door. Mikulas
Hi.
See this tutorial: https://randomnerdtutorials.com/esp32-esp8266-web-server-http-authentication/
Regards,
Sara
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!
Hi Andre.
We’ve recently published a project that does that.
Here it is: https://randomnerdtutorials.com/esp32-esp8266-web-server-outputs-momentary-switch/
I hope this helps.
Regards,
Sara
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);
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.
That works even my relays works for 5v and esp8266 working on 3.3V?
It usually works.
You can power the relay module using the ESP8266 VIN pin that provides 5V.
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.
Hi.
You need to install these libraries:
https://github.com/me-no-dev/ESPAsyncWebServer/archive/master.zip
https://github.com/me-no-dev/ESPAsyncTCP/archive/master.zip
Click the links to download and then in your Arduino IDE, you can go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded.
Regards,
Sara
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.
I was wondering, how would the configs change for a 16 channel relay?
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
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.
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
How much relay can I use with NODEMCU
It depends on how many gpio pins your board has.
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?
Hi.
What is exactly the error that you’re getting?
Regards,
Sara
Thank for the reply. I finally found the problem. I didn’t download the tcp library.
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
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
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.
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
Hey Sara!
Any hints you could share about where these if statements should be placed?
Jay
🙂
😅sorry to say but iam new to this language. Can you give the exact code block to to display a particular name?
Hello,
If the WIFI connection is accidently lost between NODMCU and the router, does it reconnect automaticaly?
Thanks!
Hi.
It reconnects if you reset the board.
Or you can take a look at this https://rntlab.com/question/esp32-wifi-not-connecting-after-2-hours/
There’s a suggestion that checks for the connection and tries to reconnect if the connection is lost.
Regards,
Sara
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.
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.
Hi.
You can take a look at this tutorial: https://randomnerdtutorials.com/esp32-esp8266-web-server-outputs-momentary-switch/
Or this one:
https://randomnerdtutorials.com/esp32-esp8266-web-server-timer-pulse/
I hope this helps.
Regards,
Sara
Thank you Sara, i found something here that i can try:
https://gist.github.com/sarasantos/5e60cf40caaf5865cf56f39621501b5c
Really well done instructions and screen shots!
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
Hi Make sure that you’ve inserted the right ssid an password on the code, so that the ESP8266 can connect to your local network.
Regards,
Sara
Yes i have inserted right ssid but its not showing ip address on serial monitor .i have tried 2 boards but not fixed
Its showing connecting to wifi on serial monitor but not getting ip address .
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};
Hello,
How do I send LOW or HIGH signals using Arduino IDE?
use the serial console on the IDE. It will read and write.
Hi Sara.
Very good post, I loved it.
Can I use one digital port from Esp8266 to activate to IN’s on module?
Tks.
Sorry.
Can I use one digital port from Esp8266 to activate (two) 2 IN’s on module?
Hi.
Yes. I think you can do that.
Regards,
Sara
Many thanks.
Hi.
I’m sorry, but I didn’t understand your question.
Regards,
Sara
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.
Hi.
This tutorial might be useful: https://randomnerdtutorials.com/esp32-esp8266-thermostat-web-server/
Regards,
Sara
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 🙂
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
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
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.
Switch to the correct wifi group or port forward to the esp from the outside.
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.
Works nice from the first time
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
Hi.
It might help to take a look at the following tutorials:
https://randomnerdtutorials.com/esp32-esp8266-web-server-physical-button/
https://randomnerdtutorials.com/esp8266-nodemcu-websocket-server-arduino/
https://randomnerdtutorials.com/esp8266-nodemcu-async-web-server-espasyncwebserver-library/
Regards,
Sara
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
Hi.
To update the state in all web pages, use Websockets.
It provides a function that allows you to update all clients whenever there’s a change. See this tutorial: https://randomnerdtutorials.com/esp8266-nodemcu-websocket-server-arduino/
Regards,
Sara
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.
Hi.
Yes. You can use websockets for that. All clients are always updated.
Check this tutorial (it is for multiple sliders, but works similar for a single slider):
– https://randomnerdtutorials.com/esp8266-nodemcu-web-server-websocket-sliders/
I hope this helps.
Regards,
Sara
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.
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.
Thanks for the tips.
It’s always good to remember that you should not touch the relay unless mains power is disconnected.
Regards,
Sara
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
Hi.
Take a look at this discussion: https://forum.arduino.cc/t/how-to-make-esp8266-things-happen-on-specific-times/561022/8
Then, this tutorial might help:
– https://randomnerdtutorials.com/esp8266-nodemcu-date-time-ntp-client-server-arduino/
Regards,
Sara
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 (” “);
}
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
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?
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.
Hi.
It is complaining about a library called Robot_Motor that is included in your code. What library os that?
Regards,
Sara
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?.
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
Hiii… This site uses all your content giving credit in a ridiculous way
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
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
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?
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.
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)
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
Hi.
Yes.
It is possible to merge the two projects. However, we use AsynWebSerber to build the web server, and the other project uses other method.
To make it easy to combine both projects, I recommend using AsynWebServer library in both examples.
We have an example for the DHT sensor using the AsyncWebServer: https://randomnerdtutorials.com/esp8266-dht11dht22-temperature-and-humidity-web-server-with-arduino-ide/
If you take a closer look at both projects, you’ll see that it’s easier to merge them if they use the same method to build the web server.
Regards,
Sara
I’ll give that a try!
Many thanks from an old retired dog trying to learn a few new tricks…
Jim
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.
I’m having trouble powering the relay. What spec power supply should I use? Any ideas how I should wire it?
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
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���nrl
r��nrl�$rbl
��n�`Connecting to WiFi..Thanks
Check the serial monitor baud rate.
It should be 115200.
Regards,
Sara
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
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
my eero wifi does weird things witb ssid. i had to fold to all lower, or was it all caps. works fine
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
Just put the name of the said and password in as normal.
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
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.
Hi.
Did you try to run the WiFiScan sketch example on your board? To check if it is able to “see” your network?
Regards,
Sara
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
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.
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.
Hi,
You can use any 5V 1A phone charger for this.
To use a decent switching regulating power supply is a bit overkill.
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.
Hi.
You just need to use:
digitalWrite(GPIO, LOW);
in which GPIO corresponds to the number of the GPIO you’re controlling.
Add that line of code in the setup() for all relays,
Regards,
Sara
Hi Sara, thank you for the response. It works well now!
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
Hi.
We don’t have any tutorial that combines those two specific subjects.
You can take a look at the DS18B20 web server and try to combine with this one: https://randomnerdtutorials.com/esp32-ds18b20-temperature-arduino-ide/
If you want to learn more about all these web server subjects, we have an eBook dedicated to this subject that covers all you need to start building your web servers from scratch. If you’re interested, you can take a look at the eBook table of contents at the following link: https://randomnerdtutorials.com/build-web-servers-esp32-esp8266-ebook/
Regards,
Sara
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
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!
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
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
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.
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
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) + ”
“);
}
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?
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
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.
i connected the pins and uploaded the code to esp826. i receive values from the serial monitor but the lamp doesn’t go on or off
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.
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.
Regarding the relay “state” code, found it. Happy holidays.
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.
… 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.
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
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 :))))
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:)))
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
Hello, dear sir
Is it possible to control 8 relays with nodemcu?
If so which pins should be used?
Thanks
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.