Skip to content

Instantly share code, notes, and snippets.

@MichMich
Created April 13, 2015 18:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MichMich/cda49fcbcdb7f478a5fe to your computer and use it in GitHub Desktop.
Save MichMich/cda49fcbcdb7f478a5fe to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#define BUTTON 2 // button on GPIO2
#define LED 0 // led on GPIO0
const char* ssid = "yourwifinetwork";
const char* password = "yourwifipassword";
const char* host = "homesensor.parseapp.com";
String API_KEY = "supersecretapikey";
String Identifier = "sensorname";
boolean lastState;
void setup() {
Serial.begin(115200);
pinMode(LED, OUTPUT);
pinMode(BUTTON, INPUT_PULLUP);
lastState = !digitalRead(BUTTON);
WiFi.begin(ssid, password);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
digitalWrite(LED, HIGH);
delay(50);
digitalWrite(LED, LOW);
delay(250);
boolean currentState = !digitalRead(BUTTON);
if (lastState != currentState) {
sendState(Identifier, currentState);
lastState = currentState;
}
}
void sendState(String identifier, boolean state) {
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
String stateString = (state) ? "true" : "false";
String json = "{\"identifier\":\"" + Identifier + "\", \"state\":" + stateString + "}";
String postData;
postData += "POST /sensor HTTP/1.0 \r\n";
//postData += "X-Parse-Application-Id: " + APP_ID + "\r\n";
postData += "X-Parse-REST-API-Key: " + API_KEY + "\r\n";
postData += "Content-Type: application/json \r\n";
postData += "Host: " + String(host) + " \r\n";
postData += "Content-Length: " + String(json.length()) + "\r\n\r\n";
postData += json;
// Send the postdata to the server.
client.print(postData);
delay(1000);
// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment