Advertisement
TolentinoCotesta

Ethernet web server

Oct 28th, 2020
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. #include <SPI.h>
  3. #include <Ethernet.h>
  4.  
  5.  
  6. const char web_page[] PROGMEM =
  7.   "<HTML><HEAD>"  \
  8.   "<meta name='apple-mobile-web-app-capable' content='yes'>"  \
  9.   "<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent'>"  \
  10.   "<link rel='stylesheet' type='text/css' href='http://www.progettiarduino.com/uploads/8/1/0/8/81088074/style3.css'>" \
  11.  
  12.   "<TITLE>Controllo Dispositivi da Remoto</TITLE>"\
  13.   "</HEAD><BODY>" \
  14.   "<H1>Controllo Dispositivi da Remoto</H1><br>"  \
  15.   "<H2>Arduino UNO con Ethernet Shield</H2><br>"  \
  16.  
  17.   "<button id='button1' onClick='sendRequest(this.id);'>Accendi/Spegni LED 1</button><br>"    \
  18.   "<div id='outputLed1'> Spento </div><br><br>"    \
  19.  
  20.   "<button id='button2' onClick='sendRequest(this.id);'>Accendi/Spegni LED 2</button><br>"    \
  21.   "<div id='outputLed2'> Spento </div><br><br>"    \
  22.  
  23.   "<button id='button3' onClick='sendRequest(this.id);'>Accendi/Spegni LED 3</button><br>"    \
  24.   "<div id='outputLed3'> Spento </div><br><br>"    \
  25.  
  26.   "<button id='button4' onClick='sendRequest(this.id);'>Accendi/Spegni LED 4</button><br>"    \
  27.   "<div id='outputLed4'> Spento </div><br><br>"    \
  28.  
  29.   "<button id='button5' onClick='sendRequest(this.id);'>Accendi/Spegni LED 5</button><br>"    \
  30.   "<div id='outputLed5'> Spento </div><br><br>"    \
  31.  
  32.   "<br><br><p>Creato da Michele Zandon&aacute; </p>" \
  33.  
  34.   "<script>"                                                   \
  35.     "function updateOutEl(obj) {"                              \  
  36.     "   var outs = obj.split(';');"                            \  
  37.     "   outs.forEach( function(item, index) {"                 \  
  38.     "       var el = 'outputLed' + (index+1).toString() ;"     \  
  39.     "       document.getElementById( el).innerHTML = item;"    \  
  40.     "   });"                                                   \  
  41.     "}"                                                        \  
  42.    
  43.     "function sendRequest(id) {"                               \  
  44.     "   var xhttp = new XMLHttpRequest();"                     \  
  45.     "   xhttp.onreadystatechange = function() {"               \  
  46.     "       if (this.readyState == 4 && this.status == 200)"   \  
  47.     "           updateOutEl(this.responseText);"               \  
  48.     "   };"                                                    \  
  49.    
  50.     "   var request = '/?' + id + 'on';"                       \  
  51.     "   console.log(request);"                                 \  
  52.     "   xhttp.open('GET', request, true);"                     \  
  53.     "   xhttp.send();"                                         \  
  54.     "}"                                                        \  
  55.    
  56.     "var myVar = setInterval("                                 \  
  57.     "   function(){"                                           \  
  58.     "       var xhttp = new XMLHttpRequest();"                 \  
  59.     "       xhttp.onreadystatechange = function() {"           \  
  60.     "           if(this.readyState == 4 && this.status == 200)"\  
  61.     "               updateOutEl(this.responseText);"           \  
  62.     "       };"                                                \  
  63.  
  64.     "       xhttp.open('GET', '/updateOuts', true);"           \  
  65.     "       xhttp.send();"                                     \  
  66.     "   },"                                                    \  
  67.     "1000); "                                                  \
  68.   "</script>"                                                  \  
  69.   "</BODY></HTML>" ;
  70.  
  71.  
  72. const byte outputLed[] = {13, 14, 2, 3, 5};       // I pin su cui sono collegate le uscite
  73. const byte inputBack[] = {13, 14, 2, 3, 5};       // I pin di ingresso per il feedback on/off (uso gli stessi per semplicità)
  74. uint32_t   onTime[]    = {0, 0, 0, 0, 0};       // Il tempo in cui vengono attivate le uscite (cosi evitiamo l'uso del delay(5000))
  75.  
  76. int val = 0;
  77. byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   // mac address
  78. byte ip[] = { 192, 168, 2, 177 };                      // configurate il vostro IP di arduino a vostra scelta("192.168.1.31")
  79.  
  80. EthernetServer server(80);                              //server port
  81. int refreshPage = 5;
  82. String readString;
  83.  
  84.  
  85. String updateOutState(){
  86.     String outState;
  87.     for(byte i=0; i<sizeof(outputLed); i++){
  88.       if(digitalRead(inputBack[i]))
  89.         outState += "Acceso";
  90.       else
  91.         outState += "Spento";
  92.       if(i != sizeof(outputLed)-1)
  93.         outState += "; ";
  94.     }
  95.     Serial.println(outState);
  96.     return outState;
  97. }
  98.  
  99. void setup() {
  100.   // Apro la comunicazione seriale:
  101.   Serial.begin(9600);
  102.   while (!Serial) {
  103.     ; // wait for serial port to connect. Needed for Leonardo only
  104.   }
  105.   //Imposto i pin come OUTPUT
  106.   for(byte i=0; i<sizeof(outputLed); i++){
  107.       pinMode(outputLed[i], OUTPUT);    
  108.   }
  109.  
  110.   //Imposto i pin come INGRESSO
  111.   for(byte i=0; i<sizeof(inputBack); i++){
  112.       pinMode(inputBack[i], INPUT);    
  113.   }
  114.  
  115.  
  116.   // Inizio la comunicazione Ethernet con il server:
  117.   Ethernet.begin(mac, ip);
  118.   server.begin();
  119.   Serial.print("server is at ");
  120.   Serial.println(Ethernet.localIP());
  121. }
  122.  
  123.  
  124. void loop() {
  125.  
  126.   // Spengo il led dopo 5 secondi senza delay
  127.   for(byte i=0; i<sizeof(outputLed); i++){
  128.     if(millis() - onTime[i] > 5000){
  129.       digitalWrite(outputLed[i], LOW);  
  130.     }
  131.   }
  132.    
  133.  
  134.   EthernetClient client = server.available();      // Creo una connessione al client
  135.   if (client) {
  136.     while (client.connected()) {
  137.       if (client.available()) {
  138.         char c = client.read();
  139.  
  140.         //Leggo i caratteri da HTTP
  141.         if (readString.length() < 100) {
  142.           //Inserisco i caratteri nella stringa
  143.           readString += c;
  144.           //Serial.print(c);
  145.         }
  146.  
  147.         //Se la richiesta HTTP è andata a buon fine
  148.         if (c == '\n') {
  149.           Serial.println(readString); //scrivi sul monitor seriale per debugging
  150.  
  151.           //Controlli su Arduino:
  152.  
  153.           // Se è una richiesta di aggiornamento stato delle uscite
  154.           if(readString.indexOf("/updateOuts") > -1){
  155.             client.print(updateOutState());
  156.           }
  157.          
  158.           // Se è stato premuto un pulsante qualsiasi
  159.           else if (readString.indexOf("/?button") > -1) {
  160.             //Ricaviamo dinamicamente le informazioni per capire quale pulsante è stato premuto
  161.             int start = readString.indexOf("/?button") + sizeof("/?button") -1;
  162.             int stop =  readString.indexOf("on", start) ;
  163.             int btn = readString.substring(start, stop).toInt() - 1;  // Il primo elemento dell'array ha indice 0
  164.                
  165.             Serial.print("Pulsante: "); Serial.print(btn);
  166.             Serial.print("\t Uscita: "); Serial.print(outputLed[btn]);
  167.            
  168.             digitalWrite(outputLed[btn], HIGH);
  169.             onTime[btn] = millis();
  170.             client.print(updateOutState());
  171.  
  172.           }
  173.  
  174.           // Nessuna delle precedenti -> invio l'homepage
  175.           else if (readString.indexOf("/ HTTP/1.1") > -1 ){
  176.             Serial.println("Invio dell'homepage");
  177.            
  178.             // Invio della pagina web
  179.             // Siccome usiamo PROGMEM per non sprecare RAM, è necessario recuperare i dati dalla flash con queste istruzioni
  180.             for (int k = 0; k < strlen_P(web_page); k++) {
  181.               char myChar = pgm_read_byte_near(web_page + k);
  182.               client.print(myChar);
  183.             }    
  184.                  
  185.           }
  186.  
  187.           readString = "";  
  188.           client.stop();
  189.         }        
  190.       }      
  191.     }
  192.   }
  193. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement