Skip to content

Instantly share code, notes, and snippets.

@apaprocki
Created December 11, 2013 01:52
Show Gist options
  • Save apaprocki/7903894 to your computer and use it in GitHub Desktop.
Save apaprocki/7903894 to your computer and use it in GitHub Desktop.
Splashr -- RobotsConf 2013 Hack
const int ledPin = D1;
const int waterSensor = A0;
int wetStatus = 0;
int lastWetStatus = 0;
int waterAvg = 0;
int smsActive = 0;
// Endpoint must deliver SMS message when root HTTP request is received.
// Real implementation would have to somehow retrieve a token so that
// server would associate valid Twilio credentials with the device token.
// This is necessary because the Spark Core can not make an HTTPS request.
TCPClient client;
byte ip[] = { 192, 168, 1, 123 };
int waterRead(int ms) {
// Return ADC average value over 8 reads.
int avg = 0;
for(int x = 0; x < 8; x++) {
avg += analogRead(waterSensor);
delay(ms);
}
avg /= 8;
return avg;
}
void setup() {
// Enable serial console output.
Serial.begin(9600);
delay(1000);
Serial.println("Initializing...");
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Calculate ADC average to compare against in runtime loop.
pinMode(waterSensor, INPUT_PULLUP);
waterAvg = waterRead(50);
digitalWrite(ledPin, LOW);
Serial.print("Water Avg: ");
Serial.println(waterAvg);
}
void sms() {
smsActive = 1;
if (client.connect(ip, 8080)) {
Serial.println("Connected.");
client.println("GET / HTTP/1.1");
client.println();
} else {
Serial.println("Connection failed.");
}
}
void loop() {
// Handle socket I/O, cleanup before sensor read.
if (client.connected() && client.available()) {
char c = client.read();
Serial.print(c);
}
if (smsActive && !client.connected()) {
Serial.println();
Serial.println("Socket disconnected.");
client.stop();
smsActive = 0;
}
// Check for significant difference in conductivity over avg.
int waterDifference = abs(waterRead(5) - waterAvg);
Serial.print("Water avg: ");
Serial.println(waterAvg);
Serial.print("Water diff: ");
Serial.println(waterDifference);
if (waterDifference > 100) {
wetStatus = HIGH;
} else {
wetStatus = LOW;
}
// Check for status change since last loop pass and act accordingly.
if (wetStatus != lastWetStatus) {
if (wetStatus == HIGH) {
Serial.println("Water detected!");
sms();
digitalWrite(ledPin, HIGH);
} else {
Serial.println("Subject is dry.");
digitalWrite(ledPin, LOW);
}
}
lastWetStatus = wetStatus;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment