In questo esempio accenderemo un led collegato ad arduino tramite un pulsante sul nostro browser.
//ARDUINO 1.0
//include tutti i pacchetti necessari
String readString;
#include <Ethernet.h>
#include <SPI.h>
boolean reading = false;
////////////////////////////////////////////////////////////////////////
//configurazione della rete
////////////////////////////////////////////////////////////////////////
byte ip[] = { 192, 168, 1, 17 }; //ip:modificabile, da digitare nel browser
byte gateway[] = { 192, 168, 1, 1 }; //non modificare
byte subnet[] = { 255, 255, 255, 255 }; //non modificare
// MAC address
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetServer server = EthernetServer(80); //port 80
////////////////////////////////////////////////////////////////////////
void setup(){
Serial.begin(9600);
pinMode(2, OUTPUT);//Pin 2 led
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.println(Ethernet.localIP());
}
void loop(){
checkForClient();
}
void checkForClient(){
EthernetClient client = server.available();
if (client) {
boolean currentLineIsBlank = true;
boolean sentHeader = false;
while (client.connected()) {
if (client.available()) {
if(!sentHeader){
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println("<html>");
client.println("<head><title>Arduino accendere e spegnere LED</title>");
client.println("<center><h1>Accendere e spegnere LED</h1></center> </head>");
client.println("<body>");
client.println("<center>");
client.println("<table width=100>");
client.println("<form METHOD=get action=\"\">");
client.println("<input type=hidden name=\"c\" value=\"2\">");
client.println("<input type=submit value=\"LED On\">");
client.println("</form>");
client.println();
client.println("<form METHOD=get action=\"\">");
client.println("<input type=hidden name=\"c\" value=\"3\">");
client.println("<input type=submit value=\"LED Off\">");
client.println("</form>");
client.println();
client.println("</table>");
client.println("</center>");
client.println("</body>");
client.println("</html>");
sentHeader = true;
}
char c = client.read();
if(reading && c == ' ') reading = false;
if(c == '?') reading = true;
if(reading){
Serial.print(c);
switch (c) {
case '2':
//add code here to trigger on 2
digitalWrite(2, HIGH);
break;
case '3':
//add code here to trigger on 3
digitalWrite(2, LOW);
break;
}
}
if (c == '\n' && currentLineIsBlank) break;
if (c == '\n') {
currentLineIsBlank = true;
}else if (c != '\r') {
currentLineIsBlank = false;
}
if (c == '\n' && currentLineIsBlank) break;
if (c == '\n') {
currentLineIsBlank = true;
}else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
delay(1);
client.stop(); // chiude la connessione
}
}
Nessun commento:
Posta un commento