Monday, April 27, 2015

ELT222 Lab 04



This was a difficult one. However, I found out after about 2 hours of troubleshooting that I had one character wrong that was making the whole program not work correctly..


Code examples I used were from:
http://www.instructables.com/id/Arduino-Webserver-Control-Lights-Relays-Servos-etc/

Here is the code:
#include <SPI.h>
#include <Ethernet.h>

int led = 3;

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x09, 0x63 };
byte ip[] = { 192, 168, 1, 21 };

EthernetServer server(80); //server port
String readString;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
pinMode(led, OUTPUT);

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

}

void loop() {

EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();

//read char by char HTTP request
if (readString.length() < 100) {
//store characters to string
readString += c;
//Serial.print(c);
}

if (c == '\n') {
Serial.println(readString);

client.println("HTTP/1.1 200 OK"); //send new page
client.println("Content-Type: text/html");
client.println();
client.println("<HTML>");
client.println("<HEAD>");
client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
client.println("<TITLE>Jimi's Over Complicated Light Switch</TITLE>");
client.println("</HEAD>");
client.println("<BODY>");
client.println("<hr />");
client.println("<br />");
client.println("<H1>Arduino with Ethernet Shield</H1><br />");
client.println("<H2>ELT222 Lab04</H2>");
client.println("<br />");
client.println("<a href=\"/?button1on\"\">Turn On LED</a>");
client.println("<a href=\"/?button1off\"\">Turn Off LED</a><br />");

client.println("</BODY>");
client.println("</HTML>");
delay(1);
//stop client
client.stop();
//controls the Arduino if you press the buttons
if (readString.indexOf("?button1on") > 0){
digitalWrite(led, HIGH);
}
if (readString.indexOf("?button1off") > 0){
digitalWrite(led, LOW);
}

//clearing string for next read
readString="";

}
}
}
}
}



No comments: