Diferencia entre revisiones de «WebServer»

De ArduWiki
Saltar a: navegación, buscar
(Web Server)
(Ejemplo)
 
(No se muestran 4 ediciones intermedias del mismo usuario)
Línea 1: Línea 1:
== Web Server ==
 
 
 
En este ejemplo, con Ethernet Shield y Arduino se crea un servidor web simple. Con la biblioteca Ethernet, su dispositivo podrá responder a una solicitud HTTP. Después de abrir un navegador y navegar a la dirección IP de su escudo Ethernet, su Arduino responderá con HTML para que un navegador muestre los valores de entrada de los seis pines analógicos.
 
En este ejemplo, con Ethernet Shield y Arduino se crea un servidor web simple. Con la biblioteca Ethernet, su dispositivo podrá responder a una solicitud HTTP. Después de abrir un navegador y navegar a la dirección IP de su escudo Ethernet, su Arduino responderá con HTML para que un navegador muestre los valores de entrada de los seis pines analógicos.
  
 +
== Ejemplo ==
 
<syntaxhighlight lang="c++">
 
<syntaxhighlight lang="c++">
/*
 
  Web Server
 
 
A simple web server that shows the value of the analog input pins.
 
using an Arduino Wiznet Ethernet shield.
 
 
Circuit:
 
* Ethernet shield attached to pins 10, 11, 12, 13
 
* Analog inputs attached to pins A0 through A5 (optional)
 
 
created 18 Dec 2009
 
by David A. Mellis
 
modified 9 Apr 2012
 
by Tom Igoe
 
modified 02 Sept 2015
 
by Arturo Guadalupi
 
 
*/
 
 
 
#include <SPI.h>
 
#include <SPI.h>
 
#include <Ethernet.h>
 
#include <Ethernet.h>
  
// Enter a MAC address and IP address for your controller below.
+
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //Asignar MAC al modulo
// The IP address will be dependent on your local network:
+
IPAddress ip(192, 168, 1, 177);                       //Asignar IP al servidor
byte mac[] = {
 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
 
};
 
IPAddress ip(192, 168, 1, 177);
 
  
// Initialize the Ethernet server library
+
//Ethernet shield attached to pins 10, 11, 12, 13
// with the IP address and port you want to use
+
//Analog inputs attached to pins A0 through A5 (optional)
// (port 80 is default for HTTP):
+
EthernetServer server(80);                             //Inicializa Ethernet
EthernetServer server(80);
 
  
 
void setup() {
 
void setup() {
  // Open serial communications and wait for port to open:
+
  Serial.begin(9600);
  Serial.begin(9600);
+
  Serial.println("Ejemplo Servidor Web");
  while (!Serial) {
+
  Ethernet.begin(mac, ip);                //Inicializa Ethernet
    ; // wait for serial port to connect. Needed for native USB port only
+
 
  }
+
  // Check for Ethernet hardware present
 +
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
 +
      Serial.println("Modulo Ethernet no encointrado. No podemos hacer nada sin hardware.");
 +
      while (true) {
 +
        delay(1);    //do nothing, no point running without Ethernet hardware
 +
      }
 +
  }
 +
  if (Ethernet.linkStatus() == LinkOFF) {
 +
      Serial.println("Conecta el cable RJ-45 en el modulo.");
 +
  }
 +
  server.begin();                       //Inicializa servidor
 +
  Serial.print("El servidor este en IP: ");
 +
  Serial.println(Ethernet.localIP());
 +
}
  
 
void loop() {
 
void loop() {
  // listen for incoming clients
+
  EthernetClient client = server.available();   //Esperando algún cliente
  EthernetClient client=server.available();
+
  if (client) {
  if(client) {
+
      Serial.println("Nuevo cliente");
    Serial.println("new client");
+
      boolean blanco = true;
    // an http request ends with a blank line
+
      while (client.connected()) {
    boolean currentLineIsBlank = true;
+
        if (client.available()) {
    while (client.connected()) {
+
            char c = client.read();
      if (client.available()) {
+
            Serial.write(c);
        char c = client.read();
+
            if (c == '\n' && blanco) {
        Serial.write(c);
+
              client.println("HTTP/1.1 200 OK");      //Envia respuesta estandar
        // if you've gotten to the end of the line (received a newline
+
              client.println("Content-Type: text/html");
        // character) and the line is blank, the http request has ended,
+
              client.println("Connection: close");    //Cierra la conexion luego de completar
        // so you can send a reply
+
              client.println("Refresh: 5");            //Refresca pagina automaticamente cada 5 sec
 
+
              client.println();
 +
              client.println("<!DOCTYPE HTML>");
 +
              client.println("<html><body>");
 +
              //Lee todo los puertos análogos
 +
              for (byte pin=0; pin<6; pin++) {
 +
                  int sensorReading = analogRead(pin);
 +
                  client.print("analog input ");
 +
                  client.print(pin);
 +
                  client.print(" is ");
 +
                  client.print(sensorReading);
 +
                  client.println("<br />");
 +
              }
 +
              client.println("</body></html>");
 +
              break;
 +
            }
 +
            if (c == '\n') {
 +
              blanco = true;
 +
            }else if (c != '\r') {
 +
              blanco = false;
 +
            }
 +
        }
 +
      }
 +
      delay(1);
 +
      client.stop();                  //Cierra conexion del cliente
 +
      Serial.println("cliente desconectado.");
 +
  }
 +
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
== Vea también ==
 
== Vea también ==
 +
<categorytree mode=all>Libreria Ethernet</categorytree>
  
 
== Referencias ==
 
== Referencias ==
  
 
[[Category:Ejemplos]]
 
[[Category:Ejemplos]]
 +
[[Category:Libreria Ethernet]]

Revisión actual del 20:39 30 may 2019

En este ejemplo, con Ethernet Shield y Arduino se crea un servidor web simple. Con la biblioteca Ethernet, su dispositivo podrá responder a una solicitud HTTP. Después de abrir un navegador y navegar a la dirección IP de su escudo Ethernet, su Arduino responderá con HTML para que un navegador muestre los valores de entrada de los seis pines analógicos.

Ejemplo

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //Asignar MAC al modulo
IPAddress ip(192, 168, 1, 177);                        //Asignar IP al servidor

//Ethernet shield attached to pins 10, 11, 12, 13
//Analog inputs attached to pins A0 through A5 (optional)
EthernetServer server(80);                             //Inicializa Ethernet

void setup() {
   Serial.begin(9600);
   Serial.println("Ejemplo Servidor Web");
   Ethernet.begin(mac, ip);                 //Inicializa Ethernet

   // Check for Ethernet hardware present
   if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Modulo Ethernet no encointrado. No podemos hacer nada sin hardware.");
      while (true) {
         delay(1);    //do nothing, no point running without Ethernet hardware
      }
   }
   if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Conecta el cable RJ-45 en el modulo.");
   }
   server.begin();                        //Inicializa servidor
   Serial.print("El servidor este en IP: ");
   Serial.println(Ethernet.localIP());
}

void loop() {
   EthernetClient client = server.available();    //Esperando algún cliente
   if (client) {
      Serial.println("Nuevo cliente");
      boolean blanco = true;
      while (client.connected()) {
         if (client.available()) {
            char c = client.read();
            Serial.write(c);
            if (c == '\n' && blanco) {
               client.println("HTTP/1.1 200 OK");       //Envia respuesta estandar
               client.println("Content-Type: text/html");
               client.println("Connection: close");     //Cierra la conexion luego de completar
               client.println("Refresh: 5");            //Refresca pagina automaticamente cada 5 sec
               client.println();
               client.println("<!DOCTYPE HTML>");
               client.println("<html><body>");
               //Lee todo los puertos análogos
               for (byte pin=0; pin<6; pin++) {
                   int sensorReading = analogRead(pin);
                   client.print("analog input ");
                   client.print(pin);
                   client.print(" is ");
                   client.print(sensorReading);
                   client.println("<br />");
               }
               client.println("</body></html>");
               break;
            }
            if (c == '\n') {
               blanco = true;
            }else if (c != '\r') {
               blanco = false;
            }
         }
      }
      delay(1);
      client.stop();                  //Cierra conexion del cliente
      Serial.println("cliente desconectado.");
   }
}

Vea también


Referencias