Skip to content

Instantly share code, notes, and snippets.

@mdales
Created December 29, 2010 17:12
Show Gist options
  • Save mdales/758762 to your computer and use it in GitHub Desktop.
Save mdales/758762 to your computer and use it in GitHub Desktop.
Simple code to turn LEDs on/off based on web request.
#include <Client.h>
#include <Dhcp.h>
#include <dns.h>
#include <Ethernet.h>
#include <Server.h>
#include <sockutil.h>
#include <Udp.h>
#include <util.h>
#include <SPI.h>
#define PINOFFSET 2
#define PINRANGE 5
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
boolean ipAcquired = false;
Server server(80);
void setup()
{
for (int i = 0; i < PINRANGE; i++)
{
pinMode(i + PINOFFSET, OUTPUT);
digitalWrite(i + PINOFFSET, 0);
}
for (int i = 0; i < PINRANGE; i++)
{
digitalWrite(i + PINOFFSET, 1);
delay(100);
}
delay(1000);
for (int i = 0; i < PINRANGE; i++)
{
digitalWrite(i+ PINOFFSET, 0);
}
Serial.begin(9600);
// Get an IP address to use and also find out our DNS server address
while (Dhcp.beginWithDHCP(mac) != 1)
{
Serial.println("Error getting IP address via DHCP, trying again...");
delay(15000);
}
delay(1000);
uint8_t localIP[4];
Dhcp.getLocalIp(localIP);
Serial.print((int)localIP[0]);
Serial.print(".");
Serial.print((int)localIP[1]);
Serial.print(".");
Serial.print((int)localIP[2]);
Serial.print(".");
Serial.println((int)localIP[3]);
}
void loop()
{
Client client = server.available();
if (client)
{
boolean currentLineIsBlank = true;
char lineBuffer[255];
int index = 0;
for (int i = 0; i < 255; i++)
lineBuffer[i] = 0;
while (client.connected())
{
if (client.available())
{
char c = client.read();
lineBuffer[index++] = 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();
client.println("OK");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
String buffer = String(lineBuffer);
if (buffer.startsWith("GET"))
{
char led, state;
led = lineBuffer[5] - '0';
state = lineBuffer[6] - '0';
Serial.println((int)led);
Serial.println((int)state);
Serial.println(lineBuffer);
digitalWrite(led + PINOFFSET, state);
}
index = 0;
for (int i = 0; i < 255; i++)
lineBuffer[i] = 0;
}
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment