Arduino – Webserver with an Arduino + Ethernet Shield

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..)

Related Content: Like ESP8266? Check out Home Automation Using ESP8266

1a

And I’ll be using a brand new arduino board that my friend at BJTechNews Sent me!
Check his youtube channel here for some cool tech tips.

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.

UntitledWatch this video tutorial

Parts Required

  • 1x Arduino Uno
  • 1x Ethernet Shield
  • 1x 220 Ohm Resistor
  • 1x LED
  • 1x Micro Servo Motor
  • 1x Breadboard
  • Jumper Cables3a

Schematics

[Schematics]

Upload the code below

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.

a

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.

Comments

  1. alain frenois says

    great achievement and very useful for achieving a home automation with relay perifairique comander of the 220 v or 110 v

    • Rui says

      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

    • Rui says

      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.

    • Rui says

      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.

    • Rui Santos says

      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

  2. Decka says

    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?

  3. nataraj says

    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…..

  4. Jaap says

    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.

    • Rui Santos says

      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?)

      • Jaap says

        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.

        • Jaap says

          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…
          :-)

  5. Constantinos Lambrou says

    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?

    • Rui Santos says

      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

  6. Murp says

    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 :)

    • Rui Santos says

      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?

      • Murp says

        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)

        • Rui Santos says

          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..

          • Murp says

            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

  7. Dimitris says

    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?

    • Rui Santos says

      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/

  8. dany says

    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?

    • says

      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

      • dany says

        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?

  9. Frankarduino says

    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

  10. Hallow says

    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

  11. Hallow says

    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

  12. Dimitris says

    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.

    • says

      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

    • fathul says

      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

      • Dimitris says

        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)

    • says

      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

  13. Tahir says

    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 ?

    • says

      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.

  14. Dimitris says

    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.

  15. majdi says

    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?

  16. João says

    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

    • João says

      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.

  17. Sneha pawar says

    Rui sir your projects are really awesum n it’s helps we student whoes new for this arduino!!!! thanks rui sir

  18. fathul says

    hey rui santos…can this command input in my arduino uno and using ethernet shield hlk-rm04 to create some web server.tq…

  19. Hélio Baldutti says

    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: http://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

  20. Mario says

    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!

  21. fathul says

    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??

  22. PhuPhi says

    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,cool@gmail.com

  23. maheshkumar says

    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”);

    }

Trackbacks

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">