ETHERNET






 1.-ETHERNET CON EL MÓDULO DE  ENC28J60 3,3V

Existen una gran variedad de módulos de Ethernet para Arduino. Con estas librerías se consiguien que funcionen la mayoría  de ellos sea su procedencia de donde sean gracias a este link:
http://www.tweaking4all.com/hardware/arduino/arduino-enc28j60-ethernet/#uipethernet


The number “ENC28J60” actually only refers to a chip developed by Microchip.  This chip has 28 pins and contains a complete stand alone Ethernet controller for a 10BASE-T (which uses RJ45 connector) network connection with an SPI interface so microcontrollers like the Arduino can “talk” to it.

10BASE-T is the same connector you’ll find on your computer (if it has one) to connect with a wire to a network, where “10” indicates a maximum speed of 10 Mbit/sec. That might sound slow, but if you consider that it’s being used by devices like the Arduino, then you can’t really expect massive data loads anyway. I’ve found it to be very responsive.

The standard Arduino Ethernet Shield uses a all-in-one Ethernet Controller as well, and the proper libraries are included with your Arduino IDE. The used controller however is a Wiznet W5100!
In this article we focus on modules based on the MicroChip ENC28J60!
Which is NOT the same as the W5100 and is NOT compatible with it either, so other libraries will be needed.

Getting the Right Library

Since I randomly picked this particular model, I had to find out the hard way that things do not seem all that easy, since it’s not compatible with the Arduino “Ethernet” library that comes with your Arduino IDE. And then I’m not even mentioning the lack of good info to determine what pins are to be used, so I had to figure that out by myself.
In the next paragraphs you’ll find my experiences with three Arduino libraries. They all work great!
  • UIPEthernet is great for projects that require “print” to be fully implemented and need to be a drop-in replacement for the standard “Ethernet” library.
  • ETHER_28j60 is great for it’s simplicity and small size, but comes with limitations.
  • Ethercard seems best for very advanced users, but I’m sure UIPEthernet can match it’s capabilities.
I’ve included a “Hello World!” example for all three, which could use some optimizing, where the “Hello World!” message can be viewed in your webbrowser.

CONEXIONES:
Below a table, based on a Arduino Uno, Arduino Nano and my eBay Ethernet module, with the needed pins for the three libraries I tested.
As you can see, all of them use the standard SPI pins 10, 11, 12 and 13. Except Ethercard, that seems to use pin 8 for SS, instead of the “standard” pin 10.




ETHER_28J60 Ethercard UIPEthernet My eBay Module
 SS  10  8 (!)  10  10
 MOSI (SI)  11  11  11  11
 MISO (SO)  12  12  12  12
 SCK  13  13  13  13


The Ethernet Controller (ENC28J60) is a so called SPI device and uses the SPI pins (10, 11, 12, 13) of your Arduino.

  •  SS stands for Slave Select, used to enable or disable the slave device (the Ethernet module in this case).
  • MOSI stands for Master Output Slave Input, or in other words: Arduino OUTPUT (data from Arduino to Ethernet Controller).
  • MISO stands for the opposite, Master Input Slave Output, or: Arduino INPUT (data from Ethernet Controller to Arduino).
  • SCK is the clock used for SPI timing.


A)La librería ETHER_28J60 and EtherShield

 ETHER_28J60 and Ether shield can be downloaded from Github or you can download it from Tweaking4All.

This is the first library I found, which works great for basic purposes, but I quickly ran into the limitations of the build-in print function. Another problem is that after some digging I found that the development either has stopped development or has been very slow in the past year, which is too bad, because of the (initial) simplicity of this library.
Esta librería no es compatible con la que viene por defecto la IDE de Arduino y tiene limitaciones en cuanto a la instrucción de  print.

 CÓDIGO  CON ESTA LIBRERÍA

// A simple web server that always just says "Hello World" #include "etherShield.h" #include "ETHER_28J60.h" // Define MAC address and IP address - both should be unique in your network static uint8_t mac[6] = {0x54, 0x55, 0x58, 0x10, 0x00, 0x24};   static uint8_t ip[4] = {192, 168, 1, 15}; static uint16_t port = 80; // Use port 80 - the standard for HTTP                                     ETHER_28J60 ethernet; void setup(){   ethernet.setup(mac, ip, port); } void loop(){   if (ethernet.serviceRequest())   {     ethernet.print("<H1>Hello World</H1>");     ethernet.respond();   }   delay(100); }


B) La libreria EtherCard

This library seems a very well respected in the Arduino community and with good reason. It seems one of the most complete implementations out there.
The code below might look a little bit more complicated, but that’s mainly because of the added HTML.

CAUTION: Ethercard seems to use pin 8 instead of pin 10!

Pros:Definitely a big plus for this library is that complex tasks like DHCP and such are easy to use, and offers easy accessible advanced features. Definitely excellent for the pro Arduino users.

Cons: A big downside (again) is the lack of a simple to use “print” function to sent data, and I’m fully aware that me bitching about it is based on my own limited experience with working with strings and char arrays etc., but I can imagine that I’m not the only one.

Ethercard is, like UIPEthernet, not the smallest library.

Download: EtherCard can be found at GitHub and on their project page or you can download it from Tweaking4All.
Ethercard.zip:  https://github.com/jcw/ethercard
Again: I recommend getting the latest and greatest version from Github.

CÓDIGO:
#include <EtherCard.h> // Ethernet IP, default gateway and MAC addresses static byte myip[] = { 192,168,1,200 }; static byte gwip[] = { 192,168,1,1 }; static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; byte Ethernet::buffer[500]; // tcp/ip send and receive buffer char page[] PROGMEM = "HTTP/1.0 503 Service Unavailable\r\n" "Content-Type: text/html\r\n" "Retry-After: 600\r\n" "\r\n" "<html>"   "<head><title>"     "Hello World!"   "</title></head>"   "<body>"     "<h3>Hello World! This is your Arduino speaking!</h3>"   "</body>" "</html>"; void setup(){   Serial.begin(57600);   Serial.println("\n[Hello World]");   if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)     Serial.println( "Failed to access Ethernet controller");   ether.staticSetup(myip, gwip);   ether.printIp("IP:  ", ether.myip);   ether.printIp("GW:  ", ether.gwip);     ether.printIp("DNS: ", ether.dnsip);   } void loop(){   // wait for an incoming TCP packet, but ignore its contents   if (ether.packetLoop(ether.packetReceive())) {     memcpy_P(ether.tcpOffset(), page, sizeof page);     ether.httpServerReply(sizeof page - 1);   } }

C) La librería: UIPEthernet

After testing the previous two libraries, I ran into UIPEthernet, at this moment my absolute favorite.
You might see the example code below as more complicated, but that is mainly me to blame. I modified and existing example to make a quick “Hello World” for you.

Pros: This library is a fully compatible drop-in replacement for the standard Ethernet Library found in your Arduino IDE, which makes it easy to adapt existing examples for use with either the Arduino Ethernet shield for use with the ENC28J60 Ethernet shield. One simply changes the two include lines (“#include <Ethernet.h> ” and “#include <SPI.h> “) in standard Ethernet examples to just one include line “#include <UIPEthernet.h>“.
This library also has a complete implementation of the “print” function that works the same as the “print” function for “Serial”, keeping code simple and very easy to use.
Advanced features are available if needed, so “pro” Arduino users might enjoy this library as well.

Cons: It will be a little bigger than ETHER_28J60.

Download:
UIPEthernet can be found on GitHub, is mentioned on the Arduino website, and optionally you can be downloaded from Tweaking4All.
arduino_uip.zip:   https://github.com/ntruchsess/arduino_uip
I recommend getting the latest version from Github.

CÓDIGO:
#include <UIPEthernet.h> // Used for Ethernet // **** ETHERNET SETTING **** byte mac[] = { 0x54, 0x34, 0x41, 0x30, 0x30, 0x31 };                                       IPAddress ip(192, 168, 1, 179);                         EthernetServer server(80); void setup() {   Serial.begin(9600);   // start the Ethernet connection and the server:   Ethernet.begin(mac, ip);   server.begin();   Serial.print("IP Address: ");   Serial.println(Ethernet.localIP()); } void loop() {   // listen for incoming clients   EthernetClient client = server.available();   if (client)   {       Serial.println("-> New Connection");     // an http request ends with a blank line     boolean currentLineIsBlank = true;     while (client.connected()) {       if (client.available())   {         char c = client.read();         // 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) {           client.println("<html><title>Hello World!</title><body><h3>Hello World!</h3></body>");           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(10);     // close the connection:     client.stop();     Serial.println("   Disconnected\n");   } }





2.-  ETHERNET Y SENSOR DE TEMPERATURA.

This article is based on using an Arduino ENC28J60 Ethernet shield, as discussed in our “How to web-enable your Arduino“, which we will use with one or more DS18B20 digital temperature sensors (you can consider using other sensors as well of course). The goal is to READ the data of these sensors from our Arduino over a network connection.

Since we will be using the DS18B20 sensors, we will will also need the “OneWire” library, which can be found at OneWire Project Website (recommended)

Using the demo with the standard Arduino Ethernet Shield
For the examples we use “UIPEthernet” which is a fully compatible drop-in library for the standard “Ethernet” library that comes with the Arduino IDE. So you should be able to use it with the standard, W5100 based, Arduino Ethernet controller and standard Ethernet library as well. Just replace the include line (#include <UIPEthernet.h> ) with these two lines:

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

Retrieving Data remotely

In this example, I’ll take the temperature sensor of my DS18B20 article and I’d like to be able to log the temperature data in a database, for which we will use an Apache, MySQL and PHP setup – so called AMP setups (Linux: LAMP, Windows: WAMP, MacOS X: MAMP).
If you have a capable NAS, for example a QNAP, then please read our “QNAP – Installing MySQL and phpMyAdmin” article on how to install Apache, MySQL and PHP.
A real, full-size, web-server will work as well … if you have access to one of course …
Installation of such an AMP setup on your desktop or laptop PC is relatively simple (especially for MacOS X and Windows):

Pulling or Pushing Data

We have two options to get our Arduino data, and the best option depends on your purpose:
– Pull: An application on our computer (or server) that is going to ask the Arduino for the data.
– Push: The Arduino will connect to a server application to push the data to.

Pulling Data
This is the one I started with, since I didn’t need an application that would ask the Arduino for data. Instead I used a web-browser for testing purposes. In essence we are going to grab the data from the Arduino in the shape of a “webpage”.
Please note that you can format the output anyway you prefer, but for convenience I decided to use XML as a format. There is however nothing wrong with using CSV (Comma Separated Values), HTML, or your own home brew data structure. In the end it’s all text and if you decide to use your home brew application to retrieve the data, then it’s totally up to you what and how you do this.
If you look at the code of the “Hello World!” example that we used for “UIPEthernet” (see this “How to web-enable your Arduino“), then you’ll see in the loop that it’s basically waiting for a connection to be made (line 23). If a connection is detected and a connection actually exists (line 23 and line 30), data will be sent to the connecting party (line 41) and the connection will be closed (line 61).
Pretty simple right? We can grab this example code and replace line 41 with whatever data we would like to sent back to the connecting party.

Reading the DS18B20 Temperature Sensor(s)

This is the point where I’m very happy with UIPEthernet since the print function here is identical to the one we use when sending data to the serial port using Serial.print  or Serial.println .
Even though my code might not be the most awesome code out there, it sure works great. I did my experiments successful with 1 and 2 sensors (I only have 2).
The function “TemperaturesToXML“, in the code below, basically captures the Sketch we used in the DS18B20 Temperature Sensor article using pin 2 for the temperature sensors. For those who actually read the article, now you know what my “other plans” for pin 10 was about. I had the Ethernet module in mind.
The rest of the code is just a modified version of the earlier mentioned “Hello World!” example code.
You can either copy/paste my code or download it as an .ino file.

A few notes on the use of the client.print  and client.println functions (dito for the Serial.print  variants):
  • Prevent combining different datatypes in the same statement – you might get unexpected results.
  • You can use “\n” in a string to add a line feed (start new line).
  • Look at the Arduino Reference for “Serial.print” for more tricks.


My example code will give you the following output in your browser, when using 2 sensors, should look something like this when going to http://192.168.1.179 (match the IP address in your sketch):

<?xml version='1.0'?> <sensordata> <sensor>   <serial>28 88 84 82 05 00 00 6a </serial>   <status>OK</status>   <chip>DS18B20</chip>   <celsius>20.44</celsius>   <fahrenheit>68.79</fahrenheit> </sensor> <sensor>   <serial>28 da ca 27 05 00 00 49 </serial>   <status>OK</status>   <chip>DS18B20</chip>   <celsius>20.31</celsius>   <fahrenheit>68.56</fahrenheit> </sensor> </sensordata>



The Serial Monitor output of your Arduino IDE will show something like this:
 
Tweaking4All.com - Temperature Drone - v1.0
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
IP Address: 192.168.1.179
-> New Connection
   Collecting Sensor Data:
   Sensor     : 28 88 84 82 05 00 00 6a 
   Temperature: 20.44 C  (68.79 F)
   Sensor     : 28 da ca 27 05 00 00 49 
   Temperature: 20.31 C  (68.56 F)
   Done Collecting Sensor Data
   Disconnected


CÓDIGO
#include <UIPEthernet.h> // Used for Ethernet #include <OneWire.h>     // Used for temperature sensor(s) // **** ETHERNET SETTING **** // Ethernet MAC address - must be unique on your network byte mac[] = { 0x54, 0x34, 0x41, 0x30, 0x30, 0x31 };                                       // ethernet interface IP address (unique in your network) IPAddress ip(192, 168, 1, 179);                         // ethernet interface IP port (80 = http) EthernetServer server(80); EthernetClient client; // **** TEMPERATURE SETTINGS **** // Sensor(s) data pin is connected to Arduino pin 2 in non-parasite mode! OneWire  ds(2); void setup() {   // Open serial communications:   Serial.begin(9600);   // start the Ethernet connection and the server:   Ethernet.begin(mac, ip);   server.begin();   Serial.println("Tweaking4All.com - Temperature Drone - v1.0");   Serial.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");   Serial.print("IP Address: ");   Serial.println(Ethernet.localIP());   Serial.println(); } void loop() {   // listen for incoming clients   client = server.available();   if (client){       Serial.println("-> New Connection\n");     // a http request ends with a blank line     boolean currentLineIsBlank = true;     while (client.connected()){       if (client.available()) {         char c = client.read();         // 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){           client.println("<?xml version='1.0'?>\n<sensordata>");           Serial.println("   Collecting Sensor Data:");           TemperaturesToXML();           client.println("</sensordata>");           Serial.println("\n   Done Collecting Sensor Data");           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(10);     // close the connection:     client.stop();     Serial.println("   Disconnected\n");   } } void TemperaturesToXML(void) {   byte counter;   byte present = 0;   byte sensor_type;   byte data[12];   byte addr[8];   float celsius, fahrenheit;   ds.reset_search();   while ( ds.search(addr)) {     client.println("<sensor>");     // Get Serial number     client.print("  <serial>");     Serial.print("\n   Sensor     : ");     for( counter = 0; counter < 8; counter++){       if (addr[counter]<0x10) client.print("0");       client.print(String(addr[counter], HEX));       client.print(" ");       if (addr[counter]<0x10) Serial.print("0");       Serial.print(String(addr[counter], HEX));       Serial.print(" ");     }     Serial.println();     client.println("</serial>");     // Check CRC     if (OneWire::crc8(addr, 7) != addr[7]){         client.println("  <status>Invalid CRC</status>\n</sensor>");         Serial.println("   ERROR\n");         return;     }     client.println("  <status>OK</status>");     // Get Chip type (the first ROM byte indicates which chip)     client.print("  <chip>");     switch (addr[0]){       case 0x10:         client.println("DS18S20</chip>");         sensor_type = 1;         break;       case 0x28:         client.println("DS18B20</chip>");         sensor_type = 0;         break;       case 0x22:         client.println("DS1822</chip>");         sensor_type = 0;         break;       default:         client.println("undefined</chip>");         return;     }     ds.reset();     ds.select(addr);     ds.write(0x44);  // start conversion, with regular (non-parasite!) power     delay(1000);     // maybe 750ms is enough, maybe not     present = ds.reset();     ds.select(addr);         ds.write(0xBE);  // Read Scratchpad     // Get Raw Temp Data, we need 9 bytes     for ( counter = 0; counter < 9; counter++) {                 data[counter] = ds.read();     }     // Convert the data to actual temperature   // because the result is a 16 bit signed integer, it should   // be stored to an "int16_t" type     int16_t raw = (data[1] << 8) | data[0];     if (sensor_type) {       raw = raw << 3; // 9 bit resolution default       if (data[7] == 0x10) {         // "count remain" gives full 12 bit resolution         raw = (raw & 0xFFF0) + 12 - data[6];       }     }     else {       // at lower res, the low bits are undefined, so let's zero them       byte cfg = (data[4] & 0x60);       //// default is 12 bit resolution, 750 ms conversion time       if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms       else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms       else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms     }     celsius = (float)raw / 16.0;     fahrenheit = celsius * 1.8 + 32.0;     client.print("  <celsius>");     client.print(celsius);     client.print("</celsius>\n  <fahrenheit>");     client.print(fahrenheit);     client.println("</fahrenheit>");     Serial.print("   Temperature: ");     Serial.print(celsius);     Serial.print(" C  (");     Serial.print(fahrenheit);     Serial.println(" F)");     client.println("</sensor>");   }   return; }




3.- ETHERNET Y UN POTENCIÓMETRO DE LECTURA

En este tutorial aprenderemos a usar el Módulo Ethernet ENC28J60, con un ejemplo sencillo en donde accederemos a nuestro Arduino desde internet, encenderemos un LED y visualizaremos la lectura de un potenciómetro desde un navegador web.

  el Módulo ENC28J60 usa la comunicación SPI
MÓDULO ENC28J60
- Modelo: N/A
- Color: Azul
- Chip Ethernet ENC28J60, SSOP28 package
- Controlador Ethernet compatible IEEE 802.3:  MAC Integrada, conector 10 BASE-T
- Soporta modos full-duplex y half-duplex
- Interfaz SPI, Maxima tasa de transferencia 10 Mb/s
- Reloj SPI de 20MHz
- Interface compatible: SmartM51 & AVR
- Voltaje: + 3.3V
- 25MHz cristal
- Compatible con Arduino

CONEXIONES

VCC - 3.3V
GND - GND
SCK - Pin 13
 MISO (SO) - Pin_12
MOSI (SI) - Pin_11
SS (CS) - Pin_8   # Selectable with the ether.begin() function

CÓDIGO:
#include <EtherCard.h>
static byte mymac[] = {0xDD,0xDD,0xDD,0x00,0x01,0x05};
static byte myip[] = {192,168,1,177};
byte Ethernet::buffer[700];
const int ledPin = 13;
char* EstadoLed="OFF";
void setup () {
   Serial.begin(9600);
  Serial.println("Test del Modulo  ENC28J60");
   if (!ether.begin(sizeof Ethernet::buffer, mymac, 10))
    Serial.println( "No se ha podido acceder a la controlador Ethernet");
 else
   Serial.println("Controlador Ethernet inicializado");
   if (!ether.staticSetup(myip))
    Serial.println("No se pudo establecer la dirección IP");
  Serial.println();
   pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
}
static word homePage() {
   BufferFiller bfill = ether.tcpOffset();
 bfill.emit_p(PSTR("HTTP/1.0 200 OKrn"
      "Content-Type: text/htmlrnPragma: no-cachernRefresh: 5rnrn"
      "<html><head><title>Naylamp Mechatronics</title></head>"
      "<body>"
      "<div style='text-align:center;'>"
      "<h1>Test del Módulo  ENC28J60</h1>"     
      "Tiempo transcurrido : $L segundos"
      "<br /><br />Estado del LED: $S<br />"     
      "<a href="/?status=ON"><input type="button" value="ON"></a>"
      "<a href="/?status=OFF"><input type="button" value="OFF"></a>"
      "<br /><br />Potenciómetro: $D (resolución de 1024)"
      "<br /><br />"
      "<a href='http://www.naylampmechatronics.com/'>www.naylampmechatronics.com</a>"
      "</body></html>"     
      ),millis()/1000,EstadoLed,analogRead(0));
    return bfill.position();
}
void loop() {
  word len = ether.packetReceive();
  word pos = ether.packetLoop(len);
   if(pos) {
       if(strstr((char *)Ethernet::buffer + pos, "GET /?status=ON") != 0) {
      Serial.println("Comando ON recivido");
      digitalWrite(ledPin, HIGH);
      EstadoLed = "ON";
    }
    if(strstr((char *)Ethernet::buffer + pos, "GET /?status=OFF") != 0) {
      Serial.println("Comando OFF recivido");
      digitalWrite(ledPin, LOW);
       EstadoLed= "OFF";
    }       
    ether.httpServerReply(homePage()); // se envia página Web
  }
}



Ahora expliquemos lo principal del código:

static byte mymac[] = {0xDD,0xDD,0xDD,0x00,0x01,0x05};
static byte myip[] = {192,168,1,177}; 
Aquí configuramos nuestra  Mac y la IP , podemos poner cualquier valor, evitando duplicar con algún otro equipo conectado a nuestra red.

En void setup () inicializamos el módulo Ethernet y reportamos por el puerto serial, aquí también configuramos el pin del led como salida.

En la función static word homePage() escribimos nuestra página web, la cual debe estar en formato HTML:
static word homePage() {
  
 BufferFiller bfill = ether.tcpOffset();
 bfill.emit_p(PSTR("HTTP/1.0 200 OKrn"
      "Content-Type: text/htmlrnPragma: no-cachernRefresh: 5rnrn"
      "<html><head><title>Naylamp Mechatronics</title></head>"
      "<body>"
      "<div style='text-align:center;'>"
      "<h1>Test del Módulo  ENC28J60</h1>"      
      "Tiempo transcurrido : $L segundos"
      "<br /><br />Estado del LED: $S<br />"      
      "<a href="/?status=ON"><input type="button" value="ON"></a>"
      "<a href="/?status=OFF"><input type="button" value="OFF"></a>"
      "<br /><br />Potenciómetro: $D (resolución de 1024)"
      "<br /><br />"
      "<a href='http://www.naylampmechatronics.com/'>www.naylampmechatronics.com</a>"
      "</body></html>"      
      ),millis()/1000,EstadoLed,analogRead(0));
     
  return bfill.position();
}

     
Notar que para enviar datos de variables hay que usar los marcadores $L  $S  $D para después enviar los datos de tipo Long, cadena, y decimal respectivamente.

También estamos configurando para que el navegador vuelva a cargar la página cada 5 segundos esto se hace con “Refresh: 5”, es necesario cuando estamos mostrando datos que cambian constantemente. El tiempo de actualización dependerá del tipo de dato que se está mostrando. En algunas aplicaciones esto no es necesario o se opta por poner un botón para actualizar. Si no se desea simplemente quitar “Refresh: 5” en la función de la página web.

La siguiente comparación se hace para ver si se han enviado datos desde el navegador mediante el método GET
  
    if(strstr((char *)Ethernet::buffer + pos, "GET /?status=ON") != 0) {
      Serial.println("Comando ON recivido");
      digitalWrite(ledPin, HIGH);
      EstadoLed = "ON";
    }

   
En este caso estamos comparando si se ha recibido un dato con el método GET de la siguiente forma ?status=ON , esto sucede si en el navegador se presiona el botón ON (ver el código HTML  del botón en la función anterior)

Una vez escrito el sketch lo cargamos a nuestro Arduino.
Solo faltaría conectar el módulo ENC28J60 con un cable Ethernet a aun modem, router, switch o a la PC.


Ahora desde un navegador web de nuestra laptop, celular o tablet, accedemos a nuestro Arduino escribiendo la IP (para nuestro ejemplo 192.168.1.177) en el navegador.


Modificando el código HTML se pueden lograr diseños da paginas mas complejas, se pueden agregar imágenes, cambiar la fuente y tamaño del texto, agregar tablas, pero esto dependerá de la habilidad de programación en HTML que tengamos.
















MÓDULO W5100

http://www.educachip.com/arduino-ethernet-shield/


CÓDIGO CON MODULO W5100 (sacado del propio Arduino>Ethernet)
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 1, 177);
EthernetServer server(80);

void setup() {
  Serial.begin(9600);
  while (!Serial) {
  }
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}
void loop() {
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
         if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close"); 
          client.println("Refresh: 5");
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");
          }
          client.println("</html>");
          break;
        }
        if (c == '\n') {
          currentLineIsBlank = true;
        } else if (c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }
    delay(10);
    client.stop();
    Serial.println("client disconnected");
  }
}

CÓDIGO HTML+DHT11+A[i]
#include <SPI.h>
#include <Ethernet.h>
#include <DHT11.h>  //cargar la libreria DHT11.ZIP
byte mac[]= {0xDE,0xAD,0xBE,0xEF,0xFE,0xED};
IPAddress ip(192, 168, 1, 177);
EthernetServer server(80);
int pin=7;
DHT11 dht11(pin);
void setup() {
  Serial.begin(9600);
  while (!Serial){ }
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}
void loop() {
 float temp, hum;
 EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
         if (c == '\n' && currentLineIsBlank) {
          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("<!DOCTYPE HTML>");
          client.println("<html>");
          client.println("<BODY BGCOLOR=aa9900>");
          client.println("<br>");
          client.print("Datos de Ricardo:");
          client.println("<br>");
                     
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");
          }
            client.println("<br>");
            client.print(" Temperatura:");
            client.print(temp);
            client.print("  Humedad: ");
            client.print(hum);
          client.println("</html>");
          break;
         }
        if (c == '\n') {
          currentLineIsBlank = true;
        } else if (c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }
    delay(10);
    client.stop();
    Serial.println("client disconnected");
  }
 int err;
      if((err = dht11.read(hum, temp)) == 0)  {  // Si devuelve 0 es que ha leido bien
             Serial.print("Temperatura: ");
             Serial.print(temp);
             Serial.print(" Humedad: ");
             Serial.print(hum);
             Serial.println();
          }
       else {
             Serial.print("Error Num :");
             Serial.print(err);
             Serial.println();
          }
       delay(2000);           
}






CÓDIGO CON HTML Y CSS
#include <SPI.h>;
#include <Ethernet.h>;
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
EthernetServer server(80);
void setup() {
//  Serial.begin(9600);
//   while (!Serial) {
//    ;
//  }
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}
void loop() {
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println("Refresh: 5");
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html lang='es'>");
          client.println("<head>");
          client.println("<meta charset='UTF-8'>");
          client.println("<title>");
          client.println("Casa domótica con RICARDO");
          client.println("</title>");
          client.println("<link");
          client.println("href='http://fonts.googleapis.com/css?family=Roboto:300|Playfair+Display:400'");
          client.println("rel='stylesheet'");
          client.println("type='text/css'/>");
          client.println("<link rel='stylesheet'");
          client.println("href='http://static.tumblr.com/pjglohe/2qinf00ga/estilos.min.css'>");
          client.println("</head>");
          client.println("<body>");
          client.println("<div class='page-wrap'>");
          client.println("<header class='header'>");
          client.println("<h1>");
          client.println("La casa domótica de RICARDO");
          client.println("</h1>");
          client.println("<div class='Ricardo'>");
          client.println("<span>Realizado por </span>");
          client.println("<a href='http://www.educachip.com' target='_blank'>");
          client.println("www.educachip.com");
          client.println("</a>");
          client.println("</div>");
          client.println("</header>");
          client.println("<section class='content-wrap'>");
          client.println("<div class='device'>");
          client.println("<div class='device-name'>");
          client.println("<h2>");
          client.println("Dispositivo #1");
          client.println("</h2>");
          client.println("</div>");
          client.println("<div class='forms'>");
          client.println("<form class='transition button on'>");
          client.println("<input type='button' value='ON'/>");
          client.println("</form></div><div class='forms'>");
          client.println("<form class='transition button off'>");
          client.println("<input type='button' value='OFF'/>");
          client.println("</form>");
          client.println("</div>");
          client.println("</div>");
          client.println("<div class='device'>");
          client.println("<div class='device-name'>");
          client.println("<h2>");
          client.println("Dispositivo #2");
          client.println("</h2>");
          client.println("</div>");
          client.println("<div class='forms'>");
          client.println("<form class='transition button on'>");
          client.println("<input type='button' value='ON'/>");
          client.println("</form>");
          client.println("</div>");
          client.println("<div class='forms'>");
          client.println("<form class='transition button off'>");
          client.println("<input type='button' value='OFF'/>");
          client.println("</form>");
          client.println("</div>");
          client.println("</div>");
          client.println("</section>");
          client.println("</div>");
          client.println("</body>");
          client.println("</html>");
          break;
        }
        if (c == '\n') {
           currentLineIsBlank = true;
        }
        else if (c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }

    delay(10);
    client.stop();
    Serial.println("client disonnected");
  }
}