Stap 4: Arduino Sketch
Schets voor de arduino schets die ik begon van de voorbeeld-webserver.
Ik heb geprobeerd het documenteren van elk ding, maar als je een vraag gerust om te vragen!
#include <SPI.h> #include <Ethernet.h> // Set the MAC address byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // Set the IP address IPAddress ip(192, 168, 1, 177); // Start a server at port 80 (http) EthernetServer server(80); void setup() { // Open serial communications Serial.begin(9600); // start the Ethernet connection and the server Ethernet.begin(mac, ip); server.begin(); // Pin 22 - 24 output (leds) pinMode(22, OUTPUT); pinMode(23, OUTPUT); pinMode(24, OUTPUT); } void loop() { // Check if client connected EthernetClient client = server.available(); if (client) { // If there is a client... boolean currentLineIsBlank = true; String buffer = ""; // A buffer for the GET request while (client.connected()) { if (client.available()) { char c = client.read();// Read the data of the client buffer += c; // Store the data in a buffer if (c == '\n' && currentLineIsBlank) {// if 2x new line ==> Request ended // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); client.println(); // Blank line ==> end response break; } if (c == '\n') { // if New line currentLineIsBlank = true; buffer = ""; // Clear buffer } else if (c == '\r') { // If cariage return... //Read in the buffer if there was send "GET /?..." if(buffer.indexOf("GET /?led1=1")>=0) { // If led1 = 1 digitalWrite(24, HIGH); // led 1 > on } if(buffer.indexOf("GET /?led1=0")>=0) { // If led1 = 0 digitalWrite(24, LOW); // led 1 > off } if(buffer.indexOf("GET /?led2=1")>=0) { // If led2 = 1 digitalWrite(22, HIGH); // led 2 > on } if(buffer.indexOf("GET /?led2=0")>=0) { // If led2 = 0 digitalWrite(22, LOW); // led 2 > off } if(buffer.indexOf("GET /?led3=1")>=0) { // If led3 = 1 digitalWrite(23, HIGH); // led 3 > on } if(buffer.indexOf("GET /?led3=0")>=0) { // If led3 = 0 digitalWrite(23, LOW); // led 3 > off } } else { currentLineIsBlank = false; } } } delay(1); client.stop(); } }
Dat was de code voor op de arduino.
Vrij makkelijk, toch? Let's go to app!