This post shows how to build an Arduino Ethernet web server that controls a relay that is attached to a lamp.
You can access your web server with any device that has a browser and it’s connected to the same network.
Recommended resources:
- Guide for Relay Module with Arduino
- Arduino – Webserver with an Arduino + Ethernet Shield
- ESP8266 Web Server with Arduino IDE
- ESP8266 Web Server Tutorial
If you like Arduino projects and you want to build more, I recommend getting my Arduino Step-by-step Projects – Build 25 Projects course.
Note: if you’re not comfortable dealing with mains voltage, but you still want to try to do the project,  you can replace the relay module with an LED, for example. The code and the schematics are very similar.
Ethernet shield
The Arduino Ethernet shield connects your Arduino to the internet in a simple way. Just mount this module onto your Arduino board, connect it to your network with an RJ45 cable and follow a few simple steps to start controlling your projects through the web.
Note: you must connect an Ethernet cable from your router to your Ethernet shield as shown in the following figure.
Pin usage
When the Arduino is connected to an Ethernet shield, you can’t use Digital pins from 10 to 13, because they are being used in order to establish a communication between the Arduino and the Ethernet shield.
Relay module
A relay is an electrically operated switch. It means that it can be turned on or off, letting the current going through or not. The relay module is the one in the figure below.
This particular relay module comes with two relays (those blue cubes).
About mains voltage, relays have 3 possible connections:
- COM: common pin
- NO: normally open – there is no contact between the common pin and the normally open pin. So, when you trigger the relay, it connects to the COM pin and power is provided to the load (a lamp, in our case).
- NC: normally closed – there is contact between the common pin and the normally closed pin. There is always contact between the COM and NC pins, even when the relay is turned off. When you trigger the relay, the circuit is opened and there is no power provided to the load.
Relating this project, it is better to use a normally open circuit, because we want to light up the lamp occasionally. Read this tutorial to learn more about using a relay module with the Arduino board.
The connections between the relay and the Arduino are really simple:
- GND: goes to ground
- IN1: controls the first relay. Should be connected to an Arduino digital pin
- IN2: controls the second relay. Should be connected to an Arduino digital pin
- VCC: goes to 5V
Parts required
Here’s a complete list of the components you need for this project:
- Arduino UNO – read Best Arduino Starter Kits
- Ethernet Shield
- Relay module
- Lamp cord set (view on eBay)
- Breadboard
- Jumper WiresÂ
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Code
Copy the following code to your Arduino IDE and before uploading it to your Arduino board read the “Configuring your network” section below.
/*
* Rui Santos
* Complete Project Details https://randomnerdtutorials.com
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1, 111);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
// Relay state and pin
String relay1State = "Off";
const int relay = 7;
// Client variables
char linebuf[80];
int charcount=0;
void setup() {
// Relay module prepared
pinMode(relay, OUTPUT);
digitalWrite(relay, HIGH);
// Open serial communication at a baud rate of 9600
Serial.begin(9600);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
// Display dashboard page with on/off button for relay
// It also print Temperature in C and F
void dashboardPage(EthernetClient &client) {
client.println("<!DOCTYPE HTML><html><head>");
client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head><body>");
client.println("<h3>Arduino Web Server - <a href=\"/\">Refresh</a></h3>");
// Generates buttons to control the relay
client.println("<h4>Relay 1 - State: " + relay1State + "</h4>");
// If relay is off, it shows the button to turn the output on
if(relay1State == "Off"){
client.println("<a href=\"/relay1on\"><button>ON</button></a>");
}
// If relay is on, it shows the button to turn the output off
else if(relay1State == "On"){
client.println("<a href=\"/relay1off\"><button>OFF</button></a>");
}
client.println("</body></html>");
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
memset(linebuf,0,sizeof(linebuf));
charcount=0;
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
//read char by char HTTP request
linebuf[charcount]=c;
if (charcount<sizeof(linebuf)-1) charcount++;
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
dashboardPage(client);
break;
}
if (c == '\n') {
if (strstr(linebuf,"GET /relay1off") > 0){
digitalWrite(relay, HIGH);
relay1State = "Off";
}
else if (strstr(linebuf,"GET /relay1on") > 0){
digitalWrite(relay, LOW);
relay1State = "On";
}
// you're starting a new line
currentLineIsBlank = true;
memset(linebuf,0,sizeof(linebuf));
charcount=0;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
Configuring your network
Take a look at the configuring your network code snippet:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,XXX);
Important: you actually might need to replace that variable highlighted in red with appropriate values that are suitable for your network, otherwise your Arduino will not establish a connection with your network.
Replace the following line with an IP that is available and suitable for your network:
IPAddress ip(X, X, X, X);
In my case, my IP range is 192.168.1.X and with the software Angry IP Scanner I know that the IP 192.168.1.111 is available in my network, because it doesn’t have any active device in my network with that exact same IP address:
IPAddress ip(192, 168, 1, 111);
Schematics
Wire you circuit accordingly to the schematic below:
Demonstration
Your Arduino Web Sever looks like the figure below:
Here’s a demonstration showing what you have at the end of this project:
Wrapping up
With this project you built an Arduino web server that turns a relay on and off.
Now, you can use this project to control any electronics appliance you want.
This project is a simplified version of one of my projects in the  Arduino Step-by-step Projects. If you liked this project make sure you check out the course that includes 23 Arduino projects.
Thanks for reading,
Rui and Sara
Many thanks for putting this together. I’m hoping to build something very similar but just using an ESP8266. Hopefully the code adapts without too much trouble.
I am begginer of Arduino.so please write a post how to configure IP address ???
If you send the command:
ifconfig
It prints the ip address in the terminal window
Hello, Mr Santos
I very much like your tutorials.
Do you have a paperback book that includes registers,timers,direct port addressing for Arduino Uno, Nano (atmel 328).
I mean something with weird notations like PORT D &= (compound bitwise and) ~ (bitwise not) (1 << 4) << (bitshift left) of 4 bit's
Thanks , Sneppe Rudy
Belgium
Hi Rui,
I tried this project; just replaced relay with LED.
I am always getting for
EthernetClient client = server.available();
client == 0
This is despite I am trying to connect to proper server from web browser.
Any hint? I do understand it is thoroughly an Ethernet library issue, but please see if you can help.
Regards,
Abu.
But does my exact code work in your project?
Yes; it does work and it did work.
The over project also worked as I was able to turn LED on/off using the browser.
Just for clarification so that other readers are helped; I used a cross cable between by Laptop and Arduino Ethernet Shield. I had a Dlink wifi router and possibly it does not work as switch.
Sir,how connect arduino ethernet shield with database.
I don’t have any tutorials on that subject.
Thanks for asking,
Rui
Sir,please send me HTML code of this project.
It’s already embedded in the Arduino code
hi rui my probleem is dat ik van de 19-arduino code-web-server
geen schets kan maken in de ide ze zeggen dat het bestand zich een
schetchmap met die naam moet bevinden maar ik kan hem niet
aanmaken
ik hoop dat je mij kan helpen
groeten wim
Hi Wim,
I only speak English and Portuguese…
Regards,
Rui
can this also be used in conjunction with a program that will turn the relays on and off at specific time of the day but use the web server for an override ?
Yes, It can be used to do that, but I don’t have any tutorial on that exact subject…
This is fine and works on my home net, bug how do I phone my home when I’m away and turn on my air conditioner, so it will be cool when I get home?
Hi, how can I do these in a 8 relay board.
Yes, this project should work with a 8 board relay. You simply have to declare more outputs and add more buttons to the HTML web page.
Hello Rui
I have tried adding declaring more outputs and buttons and have not been successful. The modified code verified and uploads without errors but the browser does connect after doing this.
Please provide more details about the error.
HI Sara
Thank you for the response. I did manage to work it out. I just had to pursue a bit more before giving up. Got there eventually.
Thank you very much.
Olá… este projeto era perfeito para uma pequena situação que tenho em mĂŁos.
Preciso de controlar uma placa de 4 reles para ligar e desligar camaras mas depois de alterar o cĂłdigo para tentar aumentar o numero ( com sucesso ) a pagina web surge com os botões a desaparecer quando se carrega neles… pode ajudar ( pago se for preciso )
Hi Rui,
Thank you for this awesome tutorial. I have a question, can I control the relay just by putting its state in the browser.
For example, if am searching for “192.168.1.111\relayon” directly can I control in this way the relay, instead of going into the page and clicking on the buttons.
Hi.
Yes, you can do that.
In this example, using the URLs: /relay1off and /relay1on
Regards,
Sara
This is a very solid and helpful beginning project for networking “things” and I thank you for your time in putting it together. I wonder about whether there is a way to do the “while do,” in a connection state, in a way that is non-blocking. If there are other bits of code, they don’t run if there is a client connected. Any thoughts? (I just couldn’t think of any.) Great job!
Hi Chris.
Thank you for following your work.
I think this question describes what you want to do: forum.arduino.cc/index.php?topic=129996.0
Regards,
Sara
I tried exact code with just change in IP address. But Server does not connect.
I am sure hardware connection, IP Address etc are all good.
But still i cannot find how where i am going wrong.
Please help me.
Hi.
What is the exact error that you’re getting?
I don’t see any error. Code gets complied and upload to board. But server does not get live when accessed from browser.
Hi.
But do you get any messages about requests on the Serial Monitor?
Hi Rui
its a nice tutorial Thankls alot
im Confused about alot of tutrials on the web about the same project
but your one is more clear
But i need to read a switch & display it on the web page
do you have this to try ?
thanks in advance
Johnny
Hi.
Unfortunately, we don’t have any tutorials like that for the Arduino.
Regards,
Sara
Hi Sara,
I want to add a physical switch near the Arduino to activate the relay.
How can I implement this on the sketch ?
Thanks
Claudio
Hello,
I’m new to Arduino, and found this relay control project and am having some fun. It works really well. I’ve done port forwarding on my router, so I can control it externally from the web on my mobile phone. I’ve hooked it up to my furnace so I can change the heat setting remotely, so I’d like to change the default port to a more obscure setting to keep unwanted agents from accessing it. Any attempts I make to change it from the default port, (by appending the ip address with a colon and port number), result in a message “This page isn’t working 192.168.xx.xx sent an invalid response.” ERR_INVALID_HTTP_RESPONSE
I’ve tried this on the local LAN to rule out any ISP or Router anomalies. Does the port change need to happen somewhere else in the code, in addition to the “EthernetServer server(80);” I’m using a “HiLetgo W5100” ethernet shield I got from amazon for $15.00
Thank you!
I forgot to mention, I already tied modifying this line: from Ethernet.begin(mac, ip);
to this Ethernet.begin(mac, ip, server); which did not resolve the issue.
Hi Sarah,
Sorry that this is not the place to ask, but did you go to Manchester University?
Hi.
No.
I went to FEUP (Faculty of Engineering in Oporto).
Regards,
Sara