Skip to content

Instantly share code, notes, and snippets.

@jossef
Created June 12, 2016 12:26
Show Gist options
  • Select an option

  • Save jossef/dc0a05979ae1eaa2c42055162edb2487 to your computer and use it in GitHub Desktop.

Select an option

Save jossef/dc0a05979ae1eaa2c42055162edb2487 to your computer and use it in GitHub Desktop.
arduino door control
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {0x84, 0xF6, 0x9E, 0x23, 0x5E, 0xFF};
IPAddress ip(192, 168, 90, 248);
EthernetServer server(80);
void setup() {
Serial.begin(9600);
Ethernet.begin(mac, ip);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
open();
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
String split(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {
0, -1
};
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
void open() {
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
delay(5000);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
}
void loop() {
EthernetClient client = server.available();
bool shouldOpen = false;
if (client) {
Serial.println("new client");
String data = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
if (c == '\n') {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: application/json");
client.println("Connection: close");
client.println();
String url = split(data, ' ', 1);
shouldOpen = (url == "/open");
client.println("{\"data\":\"" + url + "\"}");
break;
}
else if (c != '\r') {
data += c;
}
}
}
delay(1);
client.stop();
if (shouldOpen) {
open();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment