Skip to content

Instantly share code, notes, and snippets.

@caseyfw
Created February 19, 2016 12:15
Show Gist options
  • Save caseyfw/c67bc03eddfae7a3f849 to your computer and use it in GitHub Desktop.
Save caseyfw/c67bc03eddfae7a3f849 to your computer and use it in GitHub Desktop.
A simple Arduino/ESP8266 sketch to automate sprinklers.
#include <ESP8266WiFi.h>
const char ssid[] = "28 Fort Avenue";
const char password[] = "radelaide";
const unsigned long sleepTime = 60;
int controlA = 12;
int controlB = 14;
WiFiClient client;
String response;
void setSprinkler(bool setting);
void setup()
{
Serial.begin(9600);
// Set solenoid control pins to output mode.
pinMode(controlA, OUTPUT);
pinMode(controlB, OUTPUT);
Serial.print("Joining Wifi network... ");
// Join wifi network.
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
}
Serial.println("Done.");
Serial.print("Connecting to server... ");
// Connect to remote host.
while (!client.connect("10.0.0.2", 80)) {
delay(100);
}
Serial.println("Done.");
Serial.println("Issuing request.");
// Issue request.
client.println("GET /sprinkler.php HTTP/1.1");
client.println("Host: 10.0.0.2");
client.println("Connection: close");
client.println();
}
void loop()
{
// If there are incoming bytes available from the server, read them.
while (client.available()) {
char c = client.read();
if (response.length() < 1000) {
response += c;
}
}
// If the server has disconnected, stop the client, do action and go to sleep.
if (!client.connected()) {
Serial.println("Server has disconnected.");
Serial.println("Response:");
Serial.println(response);
client.stop();
if (response.indexOf("ON") > 0) {
Serial.println("Turning sprinkler on.");
setSprinkler(true);
} else if (response.indexOf("OFF") > 0) {
Serial.println("Turning sprinkler off.");
setSprinkler(false);
} else {
Serial.println("Null response.");
}
Serial.println("Sleeping.");
delay(500);
Serial.end();
ESP.deepSleep(sleepTime * 1000000);
}
}
void setSprinkler(bool setting)
{
if (setting) {
digitalWrite(controlA, HIGH);
digitalWrite(controlB, LOW);
} else {
digitalWrite(controlA, LOW);
digitalWrite(controlB, HIGH);
}
delay(250);
digitalWrite(controlA, LOW);
digitalWrite(controlB, LOW);
}
@caseyfw
Copy link
Author

caseyfw commented Feb 19, 2016

The sprinkler.php on my server currently looks like this:

<?php
//echo (rand(0, 1)) ? "ON" : "OFF";
//echo "ON";
//echo "OFF";
echo "NULL";
exit;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment