chipKIT® Development Platform

Inspired by Arduino™

Last edit: 2021-03-21 22:34 by Majenko

Ethernet

Ethernet
Quick Look
Hardware Uno32 or uC32 with Arduino Ethernet Shield
Include Ethernet.h

The Ethernet library allows a chipKIT to be a client or server and communicate over a network.

  1. Detailed Introduction

  2. Introductory Programs

    1. WebServer

    2. WebClient

  3. Full library usage

    1. Ethernet

      1. Constructors

        1. begin(uint8_t *mac_address)

        2. begin(uint8_t *mac_address, IPAddress local_ip)

        3. begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server)

        4. begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway)

        5. begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet)

      2. Public Functions

        1. maintain()

        2. localIP()

        3. subnetMask()

        4. gatewayIP()

        5. dnsServerIP()

    2. EthernetClient

      1. Constructors

        1. EthernetClient()

        2. EthernetClient(uint8_t sock))

      2. Public Functions

        1. status()

        2. connect(IPAddress ip, uint16_t port)

        3. connect(const char *host, uint16_t port)

        4. write(uint8_t b)

        5. write(const uint8_t *buf, size_t size)

        6. available()

        7. read()

        8. read(uint8_t *buf, size_t size)

        9. peek()

        10. flush()

        11. stop()

        12. connected()

    3. EthernetServer

      1. Constructors

        1. EthernetServer(uint16_t)

      2. Public Functions

        1. available()

        2. begin()

        3. write(uint8_t)

        4. write(const uint8_t *buf, size_t size)

    4. EthernetUDP

      1. Constructors

        1. EthernetUDP()

      2. Public Functions

        1. begin(uint16_t)

        2. stop()

        3. Sending UDP packets

          1. beginPacket(IPAddress ip, uint16_t port)

          2. beginPacket(const char *host, uint16_t port)

          3. write(uint8_t)

          4. write(const uint8_t *buffer, size_t size)

          5. endPacket()

        4. parsePacket()

        5. available()

        6. read()

        7. read(unsigned char* buffer, size_t len)

        8. read(char* buffer, size_t len)

        9. peek()

        10. flush()

        11. remoteIP()

        12. remotePort()

  4. External Links

Detailed Introduction

The Ethernet library is comprised of several classes including Ethernet, EthernetClient, EthernetServer and EthernetUDP. It's capable of sending a webpage to a standard browser. This is known as a WebServer. It's also capable of pullig down content as if it were a browser. This is known as a WebClient. You could also immplement a chat server/client and much more.

This library works with the Arduino Ethernet Shield.

Introductory Programs

WebServer

A simple web server that shows the value of the analog input pins using an Ethernet shield.

/*
  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

 */

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

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

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
  }


  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}


void loop() {
  // listen for incoming clients
  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("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          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') {
          // 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");
  }
}

WebClient

This sketch connects to a website (http://www.google.com) using an Ethernet shield.

/*
  Web client

 This sketch connects to a website (http://www.google.com)
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen

 */

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

Full library usage

Ethernet

Constructors

Name Description
mac The MAC address for the device (array of 6 bytes). This is the Ethernet hardware address of your device or shield.
ip The IP address of the device (array of 4 bytes).
dns The IP address of the DNS server (array of 4 bytes). Defaults to the device IP address with the last octet set to 1
gateway The IP address of the network gateway (array of 4 bytes). Defaults to the device IP address with the last octet set to 1
subnet The subnet mask of the network (array of 4 bytes). Defaults to 255.255.255.0

begin(uint8_t *mac_address)

int begin(uint8_t *mac_address);

Initialise the Ethernet shield to use the provided MAC address and gain the rest of the configuration through DHCP. Returns 0 if the DHCP configuration failed, and 1 if it succeeded.

begin(uint8_t *mac_address, IPAddress local_ip)

void begin(uint8_t *mac_address, IPAddress local_ip);

begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server)

void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server);

begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway)

void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway);

begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet)

void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet);

Public Functions


maintain()

int maintain();

Checks the lease on DHCP. If the lease is good nothing is done. If the lease has expired a new lease is issued. If a new lease is issued the IP address may remain the same or it might change.

localIP()

IPAddress localIP();

Get the IP address of the Ethernet shield. Use this to obatin the IP address assigned by DHCP.

subnetMask()

IPAddress subnetMask();

Gets the subnet mask of the Ethernet shield.

gatewayIP()

IPAddress gatewayIP();

Gets the gateway IP of the Ethernet shield.

dnsServerIP()

IPAddress dnsServerIP();

Gets the DNS Server IP used by the Ethernet shield.

EthernetClient

Constructors

EthernetClient()

EthernetClient();

Creates a client object which can connect to a specified IP address and port. IP and Port are set in client.Connect(IPAddress ip, uint16_t port)

EthernetClient(uint8_t sock))

EthernetClient(uint8_t sock);

Public Functions


status()

uint8_t status();

connect(IPAddress ip, uint16_t port)

virtual int connect(IPAddress ip, uint16_t port);

Connects to the specified IP an Port. Returns the status of the connection. 1 = Success, -1 = TIMED_OUT, -2 = INVALID_SERVER, -3 = TRUNCATED, and -4 = INVALID_RESPONSE.

connect(const char *host, uint16_t port)

virtual int connect(const char *host, uint16_t port);

Connects to a specified host (URL) and Port. Returns the status of the connection. 1 = Success, -1 = TIMED_OUT, -2 = INVALID_SERVER, -3 = TRUNCATED, and -4 = INVALID_RESPONSE.

write(uint8_t b)

virtual size_t write(uint8_t b);

Write a single data byte to the server that the client is connected to.

write(const uint8_t *buf, size_t size)

virtual size_t write(const uint8_t *buf, size_t size);

Write a series of data bytes to the server that the client is connected to. buf is an array of bytes and size is the number of bytes to be sent.

available()

virtual int available();

Returns the number of bytes available for reading.

read()

virtual int read();

Read the next byte received from the server that we are connected to.

read(uint8_t *buf, size_t size)

virtual int read(uint8_t *buf, size_t size);

Read an array of bytes from the server that we are connected to.

peek()

virtual int peek();

Returns the first byte in the receive queue.

flush()

virtual void flush();

Not implemented

stop()

virtual void stop();

Closes the connection.

connected()

virtual uint8_t connected();

Returns true if the client is connected, false if not.

EthernetServer

Constructors

EthernetServer(uint16_t)

EthernetServer(uint16_t port);

Create a server object that listens for incoming connections on the specified port.

Public Functions


available()

EthernetClient available();

Returns a client object that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling client.stop().

begin()

virtual void begin();

Instructs the server to begin listening for client connections.

write(uint8_t)

virtual size_t write(uint8_t);

Write a single data byte to all clients that are connected to the server.

write(const uint8_t *buf, size_t size)

virtual size_t write(const uint8_t *buf, size_t size);

Write an array of data bytes to all clients that are connected to the server.

EthernetUDP

  • Parent class: UDP

Constructors

EthernetUDP()

EthernetUDP();

Creates a UDP objectio.

Public Functions


begin(uint16_t)

virtual uint8_t begin(uint16_t);	

Initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use

stop()

virtual void stop();  

Finish with the UDP socket

Sending UDP packets

beginPacket(IPAddress ip, uint16_t port)
virtual int beginPacket(IPAddress ip, uint16_t port);

Start building up a packet to send to the remote host specific in ip and port. Returns 1 if successful, 0 if there was a problem with the supplied IP address or port.

beginPacket(const char *host, uint16_t port)
virtual int beginPacket(const char *host, uint16_t port);

Start building up a packet to send to the remote host specific in host and port. Returns 1 if successful, 0 if there was a problem resolving the hostname or port.

write(uint8_t)
virtual size_t write(uint8_t);

Write a single byte into the packet

write(const uint8_t *buffer, size_t size)
virtual size_t write(const uint8_t *buffer, size_t size);

Write size bytes from buffer into the packet

endPacket()
virtual int endPacket();

Finish off this packet and send it. Returns 1 if the packet was sent successfully, 0 if there was an error

parsePacket()

virtual int parsePacket();

Start processing the next available incoming packet. Returns the size of the packet in bytes, or 0 if no packets are available.

available()

virtual int available();

Number of bytes remaining in the current packet.

read()

virtual int read();

Read a single byte from the current packet.

read(unsigned char* buffer, size_t len)

virtual int read(unsigned char* buffer, size_t len);

Read up to len bytes from the current packet and place them into buffer. Returns the number of bytes read, or 0 if none are available.

read(char* buffer, size_t len)

virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); };

Read up to len characters from the current packet and place them into buffer. Returns the number of characters read, or 0 if none are available.

peek()

virtual int peek();

Return the next byte from the current packet without moving on to the next byte.

flush()

virtual void flush();	

Finish reading the current packet.

remoteIP()

virtual IPAddress remoteIP() { return _remoteIP; };

Return the IP address of the host who sent the current incoming packet.

remotePort()

virtual uint16_t remotePort() { return _remotePort; };

Return the port of the host who sent the current incoming packet.

External Links