This project is all about using an Arduino with an Ethernet shield. I’ll be controlling one LED and a servo, but you can apply this method to control any electronic device you want. (such as DC motors, buzzers, relays, stepper motors, etc..)
Introduction
The code provided when uploaded and connected to the internet it creates a webserver in your LAN and you simply use the IP to access that webserver through your browser. After that it shows a webpage similar to that one below. When you press the button “Turn On LED” your url will change to: “http://192.168.1.178/?button1on” the arduino will read that information and It turns the LED On.
By default the IP is “192.168.1.178”. That also can be found on the arduino code provided.
Watch this video tutorial
Parts Required
- Arduino UNO – read Best Arduino Starter Kits
- 1x Ethernet Shield
- 1x 220 Ohm Resistor
- 1x LED
- 1x Micro Servo Motor
- 1x Breadboard
- Jumper Cables
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!
Schematics
Upload the code below
/*
Created by Rui Santos
Visit: https://randomnerdtutorials.com for more arduino projects
Arduino with Ethernet Shield
*/
#include <SPI.h>
#include <Ethernet.h>
#include <Servo.h>
int led = 4;
Servo microservo;
int pos = 0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 178 }; // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port
String readString;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
pinMode(led, OUTPUT);
microservo.attach(7);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
// Create a client connection
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();
//read char by char HTTP request
if (readString.length() < 100) {
//store characters to string
readString += c;
//Serial.print(c);
}
//if HTTP request has ended
if (c == '\n') {
Serial.println(readString); //print to serial monitor for debuging
client.println("HTTP/1.1 200 OK"); //send new page
client.println("Content-Type: text/html");
client.println();
client.println("<HTML>");
client.println("<HEAD>");
client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
client.println("<link rel='stylesheet' type='text/css' href='https://randomnerdtutorials.com/ethernetcss.css' />");
client.println("<TITLE>Random Nerd Tutorials Project</TITLE>");
client.println("</HEAD>");
client.println("<BODY>");
client.println("<H1>Random Nerd Tutorials Project</H1>");
client.println("<hr />");
client.println("<br />");
client.println("<H2>Arduino with Ethernet Shield</H2>");
client.println("<br />");
client.println("<a href=\"/?button1on\"\">Turn On LED</a>");
client.println("<a href=\"/?button1off\"\">Turn Off LED</a><br />");
client.println("<br />");
client.println("<br />");
client.println("<a href=\"/?button2on\"\">Rotate Left</a>");
client.println("<a href=\"/?button2off\"\">Rotate Right</a><br />");
client.println("<p>Created by Rui Santos. Visit https://randomnerdtutorials.com for more projects!</p>");
client.println("<br />");
client.println("</BODY>");
client.println("</HTML>");
delay(1);
//stopping client
client.stop();
//controls the Arduino if you press the buttons
if (readString.indexOf("?button1on") >0){
digitalWrite(led, HIGH);
}
if (readString.indexOf("?button1off") >0){
digitalWrite(led, LOW);
}
if (readString.indexOf("?button2on") >0){
for(pos = 0; pos < 180; pos += 3) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
if (readString.indexOf("?button2off") >0){
for(pos = 180; pos>=1; pos-=3) // goes from 180 degrees to 0 degrees
{
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
//clearing string for next read
readString="";
}
}
}
}
}
Note: If you try this project. You can only access that IP address from your home. This means you must be connected to the same router that you’re ethernet shield is connected to. That picture below is from me accessing my webserver with my iPad.
Thanks for reading, you can contact me by leaving a comment. If you like this post probably you might like my next ones, so please support me by subscribing my blog and my Facebook Page.
great achievement and very useful for achieving a home automation with relay perifairique comander of the 220 v or 110 v
Thanks for your feedback!
yes that’s exactly what I want to show.
you can use this code to apply to your own projects for home automation
Wow…. really awesome project dude. You can use HTML also to create attractive and powerful web application i.e. webpage. I will give you link about that.
This is the link here : http://internetofthings-pune.blogspot.in/2013/07/this-is-open-source-home-automation.html
Hi!!
Thanks for the feedback Er Ajinkya Dixit!
Yes we can customize the CSS file and the HTML to create a better webpage. But I’m not very experienced in that programming languages yet. So I’ve just made a basic webpage with my knowledge 🙂
Thanks for the resource!
My next webpage will be more customized.
Hi!!
Thanks for the feedback Er Ajinkya Dixit!
Yes we can customize the CSS file and the HTML to create a better webpage. But I’m not very experienced in that programming languages yet. So I’ve just made a basic webpage with my knowledge 🙂
Thanks for the resource!
My next webpage will be more customized.
Hi do you have the source code for webpage?
Hi,
yes Con. You can download the source code for the webpage here:
https://randomnerdtutorials.com/download
Or simply click the like or tweet button and the download link will unlock.
the best way is by entering your email and you’ll have access to a secret page where you can
download all my projects every time I release a new one.
thanks for stopping by,
Rui Santos
hmm I pressed like but only got the source code for the arduino not the browser
ignore my previous comments, thanks for the code
would u please send me the android webpage source code
what you mean by the android webpage?
That webpage can be accessed through your tablet/smartphone browser…
and all the code used can be download on this page if you click like.
Thanks for leaving a comment,
Rui
what a nice project rui, but it’s the first time i saw arduino ethernet shield, can you make a tutorial about how to configure ip address or something like that on ethernet shield, or how to configure that on router using dhpc?
Thanks Decka.
Right now I’m working on a different project related to the Ethernet shield.
So stay tuned, because that project will be released soon…
I might do what you’re looking for later though.
All the best,
Rui
okay, good luck on your project bro.
keep it up…
btw it’s dhcp not dhpc, sorry for typo…
Yeah I know, I got it!
Unfortunelety I don’t have time right now to do that. as i said… maybe later
Have a nice day,
Rui
hi sir,
Thank you very much for your reply and i need some more details like i want to get the sensor value through html . .and.i want to know what is going on home through sensor..suppose if any human is enter into the home .it has to inform to web page through HTML using PIR sensor…. so this kind of application i need…i hope you will understand very well,..please do the needful to complete my project as soon as possible…..
Hi Nataraj,
sorry for taking a few days to answer..
I’ve been really busy.
What you’re looking for is an Arduino data webserver…
http://g33k.blogspot.pt/2010/09/arduino-data-webserver-sample-web.html
You can combine that project with mine if you want to customize the look of the hmtl page!
Hi,
Really great projects here! I learned a lot.
A question:
I see when clicking the buttons on the page they work oke for a while bit after some time the site seems to hang. Sometimes texts messed up and nothing works anymore. Do you recognize this? Is there a solution?
I see it happens running IE on my PC but also running Chrome browser and Safari on my iPad.
Thanks jaap.
I’m glad you’re enjoying my projects!
That never happened to me.
It might be a problem with your network/ethernet shield.
In another project I’ve made recently I noticed that sometimes if the ethernet shield is connected for too long, It gets disconnected and no longer works until you reset manually the arduino.
With this webserver project I’ve tested to run for 17hours, 8 hours, 32hours and It worked just fine.
Now what I recommend you to do,
is to comment the project with Serial.print() commands and see where the problem is coming from and how long it takes until it stops…
Just one more question which ethernet shield are you using?
(the one with the Wiznet 5100 chip?)
Hello Rul,
Thanks for your help!
Yes, it’s a shield with the Wiznet 5100 chip. I ordered it from BangGood. Worked fine in other projects.
You wrote: “17hours, 8 hours, 32hours…” but have you also done some testing by using all buttons one after another multiple times? Let’s say 10 time.
Hello Rui,
I think the problem is fixed.
Changed the delay time from 1 to 100 in this part of the sketch:
client.println(“”);
delay(100);
And now my page keeps running…
🙂
I’m glad to hear that ! 🙂
Thanks for trying my project Jaap.
Have a nice day,
Rui
I cann’t open the link 🙁
Which link Seva?
if you can help me control the lights via the web, control light intensity,
Search on the web for a PWM project to control the lights intensity.
Then change my code for this project.
so instead of controlling an led to turn on/off you’re going to increase or decrease the light.
Thanks for asking,
Rui
I notice the code references a CSS file. Is it possible to have the code be stand alone? Meaning one would not have to host a CSS file?
yes, you can customize the html without the CSS file.
The CSS just makes it easy to customize the html without repeating the same styling options again and again.
Thanks for asking,
Rui
Hi Rui, I’m trying to adapt your code to control 8 LEDs through internet but I have one problem…With 4 leds, works ok,but if I configure a 5th led, don´t work…..
Can I send you the code to some email to see if you see any faults?? (Ide recognizes the code without errors..)
Thanks and regards 🙂
Hi Murp,
I don’t have the time to debug your code I’m sorry…
I don’t know how experienced you are with Electronics, so just a few questions
are you defining the right LED’s pins properly as inputs? are your LED’s in the right way?
Hi Rui, no problem 🙂
To your questions, no and yes..Leds are configured as “int” –> outputs and all is connected ok (It works ok with 4 but not with 5..With 5, the buttons are on screen but don´t work if I press any…)
The code, I think that works right (No error on IDE, less than 20000 bytes), but I don´t understand what´s the matter…
With 4, I configured twice:
Pins 2,3,4 and 5
Pins 6,7,8 and 9
And all works ok (Arduino,leds,proto connetions,code…), and for that, I discarded all parts of the system like bad or broken components..
Thanks for all..
Regards 🙂
(About my experience with electronics, let’s say my level is medium jeje)
That might be a problem with your html then…
You’re probably doing some sort of mistake that makes an error on the html page (in your ip/webserver page)
and breaks the pages so any button works…
That’s my guess..
Hi 🙂
I only add the neccesary code, any more line, any less line, and because I don´t understand what is the problem…
Thanks anyway..
Regards
first of all i would like to say thanks for sharing all those super cool projects.
i was wondering if it is possible to access the web page this arduino serves throught internet when you are not in home if you open a port at your router and set it to forward the packages to arduino (im talking about a simple port forward)
would that work in order to access arduinos web page and controll a device in home from thousand kilometers away through internet?
Hi Dimitris,
You’re 100% right this project could work exactly as you described.
There’s just one problem, anyone with your ip can control your home.
(And that’s really easy to find if someone leaves near you…)
The best way to do that is to encrypt that data and also create some sort of authentication but that requires a more powerful device such as a Raspberry Pi for example.
I’ve made a project that allows you to control your home from anywhere in the world with an arduino and an ethernet shield.
please take a look:
http://homeautomationserver.com/
Hei, it’s awesome project dude. I have a question for you.
After I read this project, can I assume that the LED and servo was controlled over IP? or it’s something different?
You’re right dany.
With this method you can only control the LED and servo if you’re connected to the same router.
Then you open the browser with the arduino webserver ip
Thanks for your response, so just like what I thought. I’m a bit curious, can it works on a linux router? Do you think it can work?
Hi, this is amazing project. But I got a problem when i try to access the webserver through my browser. I typed the address: 192.168.1.178 on my browswer, it shown a blank page. Is it because of my router? Thanks
I’m not sure, It should be working just fine… there’s might be an incompatibility with your router.
Hello Rui,
How i can add more pages to this
say Home Page : Control two relays
First Floor : Control two relays and sensors
Like that
Pls Help
Hello Rui,
How i can add more pages to this project
Say Home Page : Control Two relays
First Floor : Control relays and sensors
Master Bed Room : etc…..
Pls Help
Regards
Hi Hallow,
Simply insert those buttons on my arduino code,
take a look at my code and see how i add the other buttons.
Hello Rui you said earlier that arduino is not powerfull enough for encryption and so anyone might be able to controll your house using this web server.
i thought about it and i modified your code in order to create a simple pin-password that is needed in order to activate the relays.
it is done by declaring a new variable that needs to get a certain value in order to let the relays activate.
in order to give values to this variable i added 12 new buttons for 0-9, * and #
what i am doing is simple or advanced mathematic operations in order to give a specific value in the variable by pressing the correct pin on the buttons i added.
this is the link of the sketch i made.
it may be usefull to someone.
https://www.dropbox.com/s/1w1nolo7i6ufb0p/web_server_modified_pc_control.ino
relays password: 4321
so in this sketch i set the correct variable value to be number 9
when you arrive at the web site the pin variable value is 0 and the relays wont work
so in order to activate the relays you will have to press the button 4 in order to add 4 to the pin variable
followed by 3 in order to multiply the current pin value (4)*3
followed by 2 in order to substruct 2 from the current pin value
and finally 1 in order to substruct 1 from the current pin value
after this the final pin variable value is 9 and now you can activate the relays.
so in conclusion you can select what mathematic operation does every single button, you can use as many digits as you want for the pin (4-5-8-10 buttons) and you can also select the value of every single button, which means you can do pretty much anything with the password.
now another interesting thing i done, is that i set every single button that is not used in the password to reset the pin value.
so if someone just tries to put random passwords he will keep reseting the pin value and wont be able to activate the relays.
you can also use this function if you mistakenly pressed twice a button which will mean that the pin value will be wrong and you will have to reset the pin value in order to re enter the password.
just press any of the unused buttons and the pin is reseted.
you can add big passwords like 8 12 digits and so on to make brute force attacks difficult or you can add buttons with letters too.
i added some pin value reports over serial connection for debugging and also i added 2 outputs in order to connect 2 leds with a resistor on each one of them.
one led is off when the pin value is not yet correct and lights up only when the pin value is correct (password correct)
the second one is kept off when the pin value is lower than the correct one
and is turned on if the pin value is over the correct one.
those 2 leds is just for visual indication of pin-password status (for debuggind purposes again. if you dont want it just delete the line with the comments)
finally the last modification i made is that i removed the servo buttons
and i made the other 2 buttons to activate and deactivate after 1 second in order to controll my computer’s power and reset buttons.
thats it, the project finally is heavilly modifies in order to match my needs but i thought i should post it here because someone may want to use simple password protected relays in this web server project.
i hope you and everyone else likes it.
Hi Dimitris,
Thank you so much for sharing your work!
It’s a really clever idea what you did there.
The data is still not encrypted by SSH for example, so if someone performs a man in the middle attack they can get the raw data and can use to access your webserver. (If you have your router ports open)
Again, thanks for sharing!
I might do a tutorial/project with your idea in mind.
Have a nice day,
Rui Santos
hey dmitri can u please give some step to me for this project i think this project very cool,i try to understand but not really help, tq
Firstly let me inform you that i am no arduino expert.
i am just a beginner who has almost no knowledge on programming.
after all i didnt used this project because while at first it was working ok after a few hours arduino was crashing.
i thought it must had to do with its memory getting full and i tried removing all the unnecessary stuff from the code which did help but still arduino was crashing after a few days and the project was unsuable.
because of the lack of programming knowledge i didnt manage to stop it from crashing or to locate the problem but having said that if you still need more info and want to get the latest sketch i made that works for a few days i can email it to you so you can try to fix it.
the basic idea is pretty simple actually.
in the original project made by rui you could just press a button to activate a relay.
i wanted to dial a password before being able to activate the relays.
in order to do it you need to
1) declare a new variable at the setup part of the sketch which will be set at 0 at the beggining (this variable will have to get a specific number in order to allow the use of the relays)
2)add more buttons on the web page in order to have a numeric keypad
3)make these new buttons to add a number to the variable you declared to step 1 , you can also substruct a number from the variable , multiply a number or make any mathepatic operation and store the new value to the variable
4)add an if command in order to operate the relays) if the variable declared in a has a certain value then activate the relay, if not reset the variable value (so a new pin can be entered)
hello i was thinking can this be done by using a arduino yun and not using the ethernet sheild
Hi Tristan,
Definitely the Arduino Yun is really powerful.
In the Arduino IDE examples code tab you will find similar projects that provide you a web interface for your project
hi ! Rui
thanks for the post …
I just want to know why we use arduino uno with arduino ethernet sheild , i want to make a project like yours ,
my question is why arduino uno is necessory with arduino ethernet sheild , and how to connect uno with pc (Which port) ?
and , can arduino ethernet sheild work without arduino uno ?
You can connect your arduino to any pc port you want.
Then in your Arduino IDE you just need to select the right COM port for your project (Usually the Arduino IDE selects the right COM port by default)
You need an Ethernet shield, because the Arduino uno by himself can’t serve a webpage.
Hello rui, im having some trouble with this project and i suspect that somewhere in your code you have made a mistake. since i dont really know to code i thought i should give you some information and maybe you have a clue on whats going on or the possible reason.
the only modifications i have done in your code that is running right now on my arduino is that i completely removed everything that has to do with the servo button-library and instead the button that used to controll the servo now is just an on off switch like the led switch.
the problem is that if you keep your arduino running this code after some days maybe a week or maybe more it stops responding. it stops serving the page and when you try to access the page, the page isnt found.
if you try to ping the arduino ip address it responds to the pings but doesnt serve the page.
in order to fix this all you have to do is to open the arduino sdk and just enable the serial monitor. nothing more! just that!
once the window of the serial monitor opens and the arduino reports that the web server runs on the ip address you set it, then the web page immediately starts to be served again.
i was trying some heavy modifications and found out that the bigger the sketch is the sooner it stops responding and if is big enought it starts messing the program and stops responding so i thought that maybe there is a memory overflow issue or something like that.
then again i dont know if its router related, maybe after some days of no use the router stops to forward the port to the arduino and you have to set the arduino to send packages to the router from time to time so the router always knows that the arduino is still connected-working and needs to receive the packages on the port 80.
i hope you can review your code and find out what is causing this malfunction, because this is a really nice project but this malfunction makes it unusable.
Hello and good day Rui, can i connect hanrun Wiznet 5100 chip ethernet module to TP-Link MR-3020 and use broadband 3g modem to make it run online and capability to access from internet?
What if we use arduino WIFI SHIELD ? Is the source code the same ?
Rui antes de mais deixa-me felicitar-te por partilhares os teus excelentes projetos. O meu nível em programação é muito baixo então gostaria de te fazer uma pergunta. É possível correr o CSS a partir do SDcard?
Renomeei o ficheiro para respeitar o formato 8.3
Consigo iniciar o sdcard e listar os ficheiros, mas não sei como referir o ficheiro no código do arduino.
Já experimentei isto:
client.println(“”);
mas a página aparece sem a formatação.
Agradeço desde já toda a ajuda que me puderes dar ou se não tiveres tempo que me apontasses na direção certa
Já resolvi o problema meti o código CSS dentro do HTML caso contrário teria de chamar um segundo ficheiro no arduino para alem do index.htm( style.css por ex) para responder ao pedido HTTP e apresentar a página com a formatação pretendida.
hello I can not seem to control my arduino because the web page is not displayed help me
Rui sir your projects are really awesum n it’s helps we student whoes new for this arduino!!!! thanks rui sir
Thank you Sneha!
Rui
Hey..
Send me webpage coding and detailed process for this project
Ty…
You can download the code right here on this blog post.
Thanks!
hey rui santos…can this command input in my arduino uno and using ethernet shield hlk-rm04 to create some web server.tq…
You might have to do some changes.
This code was written for the Wiznet chips on the ethernet shield.
-Rui
Dear Rui,
My name is Hélio and I am from Brazil.
Firstly I wanna thank you to share your knowledge with us.
This is really important to people are beginning to use Arduino as I.
I have based in your project to implement my one. I wanna turn on / turn off several lights (but I need to monitor the real status of these lights), control TVs, radio and etc. I know how to do this in Arduino, but I have difficulty in php.
In this program below, I am using just one button to turn on / turn off a light and I am using a LDR sensor to check the light’s status.
How I wanna use the Arduino in pararel with a switch in the wall, the status of light just update when I refresh the webpage. This isn’t happening automatically.
My doubt is: how can I change this program to update the status always this changed without need to refresh the page?
Please check the program:
/*
Referenced by Rui Santos
Visit: https://randomnerdtutorials.com for more arduino projects
Arduino with Ethernet Shield
*/
#include // Biblioteca da Ethernet Shield
#include // Biblioteca da Ethernet Shield
int Rele_1 = 2; // Iluminação Entrada
byte Estado_rele_1 = 0; // Estado bobina do relé
int sensor = 0; // Pino analógico em que o sensor LDR está conectado.
int valorSensor = 0; // Variável usada para ler o valor do sensor em tempo real.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 25, 105 }; // ip in lan (that’s what you need to use in your browser. (“192.168.1.178”)
byte gateway[] = { 192, 168, 25, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port
String readString;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);// velocidade da conecao
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
//apos ter setado o pino, coçlocando qual sua função
pinMode(Rele_1, OUTPUT);
// start the Ethernet connection and the server:
//iniciando a placa shield ethernet
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.print(“server is at “);
Serial.println(Ethernet.localIP());
}
void loop() {
// Create a client connection
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();
//read char by char HTTP request
if (readString.length() < 100) {
//store characters to string
readString += c;
//Serial.print(c);
}
//if HTTP request has ended
if (c == '\n') {
Serial.println(readString); //print to serial monitor for debuging
client.println("HTTP/1.1 200 OK"); //send new page
client.println("Content-Type: text/html");
client.println();
client.println("”);
client.println(” “);
client.println(“”);
client.println(” “);
client.println(” “);
client.println(” Projeto Casa e Automacao Residencial”);
client.println(“”);
client.println(“”);
client.println(” Projeto Casa e Automacao Residencial”);
client.println(“”);
client.println(“”);
client.println(“Arduino em Ethernet Shield”);
client.println(” “);
client.println(“Quarto”);
client.println(“”);
client.println(“ Lampada“);
client.println(“”);
client.println(“”);
int valorSensor = analogRead(sensor);
if (valorSensor < 750)
{
client.println("Status = Lampada Apagada”);
}
else {
client.println(“Status = Lampada Acesa”);
}
client.println(“”);
client.println(“”);
client.println(“”);
delay(1);
//stopping client
client.stop();
//controls the Arduino if you press the buttons
if (readString.indexOf(“?luz_quarto”) >0){
Estado_rele_1 = !Estado_rele_1;
digitalWrite(Rele_1, Estado_rele_1);
delay(50);
}
//clearing string for next read
readString=””;
}
}
}
}
}
Once more thank you for your help.
Best Regards,
Hélio
Nice project.
Will this project will work anywhere and anyplace as long as the arduino and the device controlling it are connected in the same router? Can I connect it to different routers and I will work on each of them? Do the router needs to be connected to internet?
thanks for sharing it!
You can only access the web server when you’re connected with device that is connected to the same router.
hye rui, why after i input this command into arduino uno and then i input the ip address at the browser,the browser can’t detect that ip,what the problem rui??
Hi 🙂
I do not have access control websites (ip 192 168 178)
I tried to change it but failed.
I’ve followed all the way and read the comments, but not positive
pls reply for me .. sorry for bad english proficiency. tks
reply or mail: phuphi,[email protected]
Do you need to put in your own IP address or does it not matter?
Thanks
You just need to set an IP address that is available in your network. That IP address that I’ve set will work in most cases
please get output for the following program
this about obstacle finder using pir and print on the webpage
i dont know why it occur more than one time
#include
#include
byte mac[] =
{
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(172, 16, 20, 157);
IPAddress gateway(172, 16, 16, 1);
IPAddress subnet(255, 255, 224, 0);
EthernetServer server(80);
int e1=9;
int in1=3;
int in2=4;
int e2=10;
int in3=11;
int in4=12;
int count=0;
void setup()
{
Serial.begin(9600);
while (!Serial) {
// wait for serial port to connect. Needed for Leonardo only
}
Ethernet.begin(mac, ip);
server.begin();
Serial.print(“server is at “);
Serial.println(Ethernet.localIP());
Serial.println(“configure the input and output”);
pinMode(8,INPUT);
pinMode(2,OUTPUT);
pinMode(e1, OUTPUT);
pinMode(e2, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
}
void loop()
{
{
while(1)
{
ethernet();
}
}
}
// c
void ethernet()
{
EthernetClient client = server.available();
if (client) {
Serial.println(“new client”);
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
// 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) {
// send a standard http response header
client.println(“HTTP/1.1 200 OK”);
client.println(“Content-Type: text/html”);
client.println(“Connection: close”); // the connection will be closed after completion of the response
client.println(“Refresh: 5”); // refresh the page automatically every 5 sec
client.println();
client.println(“”);
client.println(“”);
client.println(“”);
client.println(“OBSTACLE FINDER “);
Serial.print(“heading”);
int sensorvalue=digitalRead(8);
if(sensorvalue==HIGH)
client.println(“MOTION DETECTED!”);
else
client.println(“CHECKING FOR ANY MOVEMENT!”);
client.println(“”);
break;
}
if (c == ‘\n’) {
// you’re starting a new line
currentLineIsBlank = true;
}
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 disconnected”);
demo();
}
}
void demo()
{
int sensorvalue=digitalRead(8);
// digitalWrite(in1, HIGH);
//digitalWrite(in2, LOW);
analogWrite(e1,200);
//digitalWrite(in3, HIGH);
//digitalWrite(in4, LOW);
analogWrite(e2,200);
Serial.print(“read the sensor value”);
if(sensorvalue==HIGH)
{
digitalWrite(2,HIGH);
Serial.print(“motion detected”);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
delay(200);
}
digitalWrite(2,LOW);
Serial.print(“checking for any movement”);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(200);
Serial.print(“Over”);
}
Hey man, great project, i’m from Brazil and i’m still learning about arduino, i’d like to know if you have a similar project, but with the possibility of using the arduino remotely, i mean, like, if you are not connected in the same router as the arduino.
Anyway, your project helped me a lot, but if you could help me with this another problem, i’d sure like it :X
Hi Gabrial,
I have this project using Arduino: http://homeautomationserver.com/
With the ESP8266: http://app.homeautomationserver.com/
Hello, I’m trying to drive a stepper motor, but is not rotating. I do not have a shield motor, so I insist on this sketch.
Please tell me what to do?
//+++++++++++++++++++++++++++++++
#include
#include
#include
#include //Inclui a biblioteca Thermistor.h
int ac = 7;
int lamp_A1 = 8;
int lamp_A2 = 9;
const int stepsPerRevolution = 200;
Stepper motor(stepsPerRevolution, 2,3,4,5);
//int statusBotao1 = 0;
//int statusBotao2 = 0;
//int botaoHorario,botaoAntihorario; //gira motor sentido horario & gira motor sentido antihorario
int steps = 0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 0, 178 }; // ip in lan (that’s what you need to use in your browser. (“192.168.1.178”)
byte gateway[] = { 192, 168, 0, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port
String readString;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
pinMode(ac, OUTPUT);
pinMode(lamp_A1, OUTPUT);
//pinMode(lamp_A2, OUTPUT);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.print(“server is at “);
Serial.println(Ethernet.localIP());
}
void loop() {
Thermistor temp(5); //Instância a biblioteca Thermistor.h para ser utilizado o pino A5
int temperature = temp.getTemp(); //Pega a temperatura ambiente já convertida em graus celcius e armazena na variável temperature
// Create a client connection
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();
//read char by char HTTP request
if (readString.length() < 100) {
//store characters to string
readString += c;
//Serial.print(c);
}
//if HTTP request has ended
if (c == '\n') {
Serial.println(readString); //print to serial monitor for debuging
client.println("HTTP/1.1 200 OK"); //send new page
client.println("Content-Type: text/html");
client.println();
client.println("”);
client.println(“”);
client.println(“”);
client.println(“”);
client.println(“”);
client.println(“REMOTUS”);
client.println(“”);
client.println(“”);
client.println(“Internet das Coisas – IoT”);
client.println(“”);
client.println(“”);
client.println(“Casa com Remotus”);
client.println(“”);
client.println(“Temperatura da Casa: “);
client.println(“\t “);
client.println(temperature);
client.println(” *C”);
client.println(“”);
client.println(“”);
client.println(“Ligar AC“);
client.println(“”);
client.println(“Desligar AC“);
client.println(“”);
client.println(“”);
client.println(“Ligar Lampada_1“);
client.println(“”);
client.println(“DesligarLampada_1“);
client.println(“”);
client.println(“”);
/*
client.println(“Ligar Lampada_2“);
client.println(“”);
client.println(“DesligarLampada_2“);
client.println(“”);
*/
client.println(“Abrir“);
client.println(“”);
client.println(“Fechar“);
client.println(“Created by Geraldo Albano & Silvio da Gama. Getting Pro for life!”);
client.println(“”);
client.println(“”);
client.println(“”);
delay(1);
//stopping client
client.stop();
//controls the Arduino if you press the buttons
if (readString.indexOf(“?button1on”) >0){
digitalWrite(ac, HIGH);
}
if (readString.indexOf(“?button1off”) >0){
digitalWrite(ac, LOW);
}
if (readString.indexOf(“?button1on”) >0){
digitalWrite(lamp_A1, HIGH);
}
if (readString.indexOf(“?button1off”) >0){
digitalWrite(lamp_A1, LOW);
}
/* if (readString.indexOf(“?button4on”) >0){
digitalWrite(lamp_A2, HIGH);
}
if (readString.indexOf(“?button4off”) >0){
digitalWrite(lamp_A2, LOW);
}*/
if (readString.indexOf(“?button2on”) >0){
// if(statusBotao1 == HIGH){
motor.step(1);
motor.setSpeed(13);
// }
}
if (readString.indexOf(“?button2off”) >0){
// if(statusBotao2 == HIGH){
motor.step(-1);
motor.setSpeed(13);
// }
}
//clearing string for next read
readString=””;
}
}
}
}
}
I can’t test your code right now. But before you try to create a web server and control your motor at the same time. Can you please try to control the motor in a simple sketch?
Maybe you should use the library that came with your motor shield…
Thanks for your help!
I did all of these steps, and had no success.
Maybe one day when you work with something similar project…
I love your work, Keep it up.
But try to use the default library that came with your motor shield to control them…
Thank you for your kind words!
hello sir Rui Santos, can you make an android apps would control on same device.?
Yes, I have a tutorial on that subject here: https://randomnerdtutorials.com/arduino-control-2-dc-motors-via-bluetooth/
thanks man, how about using arduino ethernet control by android apps?
or voice command?
I have a tutorial on how to create an android app https://randomnerdtutorials.com/arduino-control-2-dc-motors-via-bluetooth/
thanks bro, my project is success, arduino ethernet with ardroid apps voice command..
hello Rui santos Thanks For source code . i use this code for my project ” Green House Monitoring and ControlSystem for Cactus Growing ” and it work very well .
now i will make something different from this . and i have i question .
can i make a field for input a number from web to processed by arduino ?
thanks
sorry for my english
Yes, you should be able to do that! Simply create an input html field.
thank a lot,,work to me,,im using 4 led,,
very nice,,
what app android for this project sir?thank
sorry to my language english is bad..
There’s no android app for this project…
It’s a web server generated by your Arduino
You’re welcome!
You’re welcome!
Thank you for reading
Thanks very helpfull project!!
Easy to access from everywere with ddns for home automatation…
You’re welcome!
Hi – been running an Arduino fine with no shields attached. When I attached the Ethernet Shield and try to upload a sketch I get the output below.
I can upload the sketch without the shield attached and it’s fine.
I’m using windows 7. Tried searching and I think the Ethernet shield might be using the serial ports differently. I’m very new to networking.
Help!!
Binary sketch size: 6958 bytes (of a 30720 byte maximum)
processing.app.SerialException: Serial port ‘/dev/tty.usbserial-A6008jGi’ not found. Did you select the right one from the Tools > Serial Port menu?
at processing.app.Serial.(Serial.java:153)
at processing.app.Serial.(Serial.java:76)
at processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:71)
at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:78)
at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:53)
at processing.app.Sketch.upload(Sketch.java:1460)
at processing.app.Sketch.exportApplet(Sketch.java:1427)
at processing.app.Sketch.exportApplet(Sketch.java:1382)
at processing.app.Editor$45.run(Editor.java:2165)
at java.lang.Thread.run(Thread.java:613)
processing.app.debug.RunnerException: Serial port ‘/dev/tty.usbserial-A6008jGi’ not found. Did you select the right one from the Tools > Serial Port menu?
at processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:91)
at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:78)
at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:53)
at processing.app.Sketch.upload(Sketch.java:1460)
at processing.app.Sketch.exportApplet(Sketch.java:1427)
at processing.app.Sketch.exportApplet(Sketch.java:1382)
at processing.app.Editor$45.run(Editor.java:2165)
at java.lang.Thread.run(Thread.java:613)
processing.app.debug.RunnerException: Serial port ‘/dev/tty.usbserial-A6008jGi’ not found. Did you select the right one from the Tools > Serial Port menu?
at processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:91)
at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:78)
at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:53)
at processing.app.Sketch.upload(Sketch.java:1460)
at processing.app.Sketch.exportApplet(Sketch.java:1427)
at processing.app.Sketch.exportApplet(Sketch.java:1382)
at processing.app.Editor$45.run(Editor.java:2165)
at java.lang.Thread.run(Thread.java:613)
But it works if you upload your code and then attach the shield?
Thanks this really works
You’re welcome!
For anyone having issues with the web server crashing, you need to supply your servo with its own power supply. You can’t use USB power or the Arduino will reset when the servo is triggered. Get a dual double-AA battery cartridge and hook the servo to that. Don’t forget to tie the negative end of the battery cartridge to the Arduino GRD. Hope this helps!
Thanks for sharing Dave!
i dit it and finish build app android.
i will share for anyone, contact me: [email protected]
Awesome and innovative article about “Arduino – Webserver with an Arduino + Ethernet Shield”. Really like your post concept. My hearty wish is, I use this amazing concept in my Arduino project. Thanks for sharing a great post.
Thank you Donna!
hello,
the project is really cool.
and i am new to arduino and shield but my project is something similar to this .so can you please help me as i am a bit confused on how to start with .
moreover in my project i have to connect to the arduino from any network i am connected to, so how do i do that and how to start with .
This project might be helpful: https://randomnerdtutorials.com/home-automation-server-project-example-tutorial/
is there a way to create a website my self as you did in this project
can u plss tl me how to connect this to cloud we only done with local ip, if there any code to connect DNS.
can u plss tl me how to connect arduino +ethernet shield to cloud we only done with local ip, if there any code to connect DNS.
This might help: https://randomnerdtutorials.com/home-automation-server-project-example-tutorial/
Sir,do you the code to store the fingerprints in server using ethernet through arduino
No, I don’t have any tutorial on that exact subject.
Thanks for asking,
Rui
web control
Yes
The Arduino Ethernet Shield 2 allows an Arduino Board to connect to the internet. It is based on the winzet. Which provides both UDP and TCP.
Could you please explain how this bit of code works?
if (readString.indexOf(“?button1on”) >0){
digitalWrite(led, HIGH);
}
I know what indexOf does, but can’t understand how this works!
Fantastic site, incredibly helpful!
Hi Ben.
The readString variable saves the HTTP request. When you click the ON button, your browser sends an HTTP request that contains the “?button1on” expression.
In that if statement we are checking whether the readString variable contains that expression. The indexOf function will return -1, if it doesn’t find the expression on the readString variable. That’s why we use the “>0”.
If it returns a positive number, that means the string contains the “?button1on” expression, so we turn on the LED.
We have a more detailed explanation about how the web server code works on the ESP32 web server example. The code was built for the ESP32, but the explanations can be useful to understand the concepts.
Here’s a link for the tutorial:
https://randomnerdtutorials.com/esp32-web-server-arduino-ide/
I hope this helps.
Regards 🙂
Hi, can you give us an example project where we can control any appliances using website but the code is in the server and send only instructions to the Arduino. we are very inspired about your tutorial and we want to learn more. thanks 🙂
Hi.
We have other projects about web server, but they are very similar to this one.
What exactly do you want to do?
hi there! nice project u got there. ik working on a project also. i just need some help. im trying to get my webserver to send text to a lcd 16×2 . i have the web server going but it seems the text cant be send to the lcd. ive tried many code from other websites. it seems not to work. pls help me 🤕
Hi.
We don’t have any tutorials with what you want to do and without further information it is very difficult to understand what can be wrong.
You can take a look at this tutorial to see how to use the LCD display: https://randomnerdtutorials.com/arduino-display-the-led-brightness-on-a-lcd-16×2/
Regards,
Sara
Hi, is there anything for the ethernet shield but like the async Web Server for ESP?
Hello!
Thanks for this tutorial! I tried it but for some reason when I press the ON or OFF buttons from the browser, I can only see that the led blinks quicly and then turns off. It doesn’t stay on.
Any ideas what’s going on? I have tried Chrome and Firefox.
Thanks,
Pete.
Thank you very much.
Wanted to do this to host a webpage for controlling the arduino.
But has problems, first being that code did not result in arduino being allocated ip address but another sketch with same ethernet code but no controls did host a simple page. ANSWER- my ethernet shield has a mmicro SD card reader on it- if not in use pin 4 has to be HIGH. So edited the sketch and sorted it.
Regarding the css, I reckon you could writre your own stylesheet (mystyle.css) and save it in the same directory as the .cpp file, and call it in the sketch by name with no path. This would let you customise your page BUT uses memory as the whole of the .css is uploaded with the sketch.