Basic Library
Digital I/O
Analog I/O
Advanced I/O
Time
Math
Trigonometry
Random Numbers
Bits and Bytes
Interrupts
Serial Comm.
Standard Library
Ethernet
Ethernet (Server)
Ethernet (Client)
Servo Motor
Character LCD
SPI
I2C (Wire)
SD Card
SD (File Operations)
Periodic Operation
Clock (RTC)
Ethernet Server
This library allows users to connect via Ethernet as a server. The following sample is based on the mbed library. You can build it using the web compiler.
Sample Program
Sample for the Ethernet server library. The server backs echo.
#include <Arduino.h>
#include <EthernetInterface.h>
#include <stdio.h>
#include <string.h>
EthernetInterface eth;
TCPSocketServer svr;
bool serverIsListened = false;
TCPSocketConnection client;
bool clientIsConnected = false;
void setup (void)
{
pinMode(PIN_LED_BLUE, OUTPUT);
pinMode(PIN_LED_RED, OUTPUT);
digitalWrite(PIN_LED_BLUE, LOW);
digitalWrite(PIN_LED_RED, LOW);
//setup ethernet interface
printf("Start to connect..\n\r");
eth.init(); //Use DHCP
eth.connect();
printf("IP Address is %s\n\r", eth.getIPAddress());
//setup tcp socket
if(svr.bind(80)< 0) {
printf("tcp server bind failed.\n\r");
return ;
} else {
printf("tcp server bind successed.\n\r");
serverIsListened = true;
}
if(svr.listen(1) < 0) {
printf("tcp server listen failed.\n\r");
return ;
} else {
printf("tcp server is listening...\n\r");
}
//listening for http GET request
while (serverIsListened) {
//blocking mode(never timeout)
if(svr.accept(client)<0) {
printf("failed to accept connection.\n\r");
} else {
printf("connection success!\n\rIP: %s\n\r",client.get_address());
clientIsConnected = true;
digitalWrite(PIN_LED_BLUE, HIGH);
while(clientIsConnected) {
char buffer[1024] = {};
switch(client.receive(buffer, 1023)) {
case 0:
printf("received buffer is empty.\n\r");
clientIsConnected = false;
break;
case -1:
printf("failed to read data from client.\n\r");
clientIsConnected = false;
break;
default:
printf("Received Data: %d\n\r\n\r%.*s\n\r",strlen(buffer),strlen(buffer),buffer);
if(buffer[0] == 'G' && buffer[1] == 'E' && buffer[2] == 'T' ) {
printf("GET request incomming.\n\r");
//setup http response header & data
char echoHeader[256] = {};
sprintf(echoHeader,"HTTP/1.1 200 OK\n\rContent-Length: %d\n\rContent-Type: text\n\rConnection: Close\n\r\n\r",strlen(buffer));
client.send(echoHeader,strlen(echoHeader));
client.send(buffer,strlen(buffer));
clientIsConnected = false;
printf("echo back done.\n\r");
}
break;
}
}
printf("close connection.\n\rtcp server is listening...\n\r");
client.close();
digitalWrite(PIN_LED_BLUE, LOW);
}
}
}
void loop(){
}