Door Opener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ESP8266WiFi.h> | |
const int BUZZER_INPUT_IO = 5; | |
const int DOOR_OUTPUT_IO = 4; | |
const int LED_IO = 0; | |
enum { STARTING, READY, NOTIFYING, OPENING }; | |
void setup() { | |
Serial.begin(115200); | |
Serial.write("starting up\n"); | |
WiFi.begin("redacted", "redacted"); | |
pinMode(LED_IO, OUTPUT); | |
pinMode(BUZZER_INPUT_IO, INPUT); | |
pinMode(DOOR_OUTPUT_IO, OUTPUT); | |
} | |
int last_val = LOW; | |
boolean check_button_pressed() { | |
int val = digitalRead(5); | |
boolean pressed = (val == HIGH && last_val == LOW); | |
last_val = val; | |
return pressed; | |
} | |
void client_loop(int &main_state) { | |
enum { BEGIN, CONNECTING, CONNECTED, RECEIVING, ERROR, DONE }; | |
static int state = BEGIN; | |
static WiFiClient client; | |
const char * domain = "iot.example.com"; | |
int port = 80; | |
String content; | |
switch(state) { | |
case BEGIN: | |
if (!client.connect(domain, port)) { | |
Serial.println("connection failed"); | |
state = ERROR; | |
return; | |
} | |
state = CONNECTED; | |
case CONNECTED: | |
client.print("GET /button HTTP/1.1\r\nUser-Agent:door\r\nHost: iot.example.com\r\n\r\n"); | |
state = RECEIVING; | |
case RECEIVING: | |
if (!client.connected()) { | |
Serial.println("server disconnected\r\n"); | |
main_state = READY; | |
state = BEGIN; | |
return; | |
} | |
else if (!client.available()) { | |
return; | |
} | |
content = client.readString(); | |
Serial.print(">>> "); | |
Serial.print(content); | |
state = BEGIN; | |
main_state = (content.indexOf("\nopen") > 0) ? OPENING : READY; | |
Serial.println(content.indexOf("\nopen")); | |
client.stop(); | |
digitalWrite(0, LOW); | |
} | |
} | |
void _blink(int counter, int cycles) { | |
if (counter % cycles == 0) digitalWrite(LED_IO, (counter / cycles) % 2); | |
} | |
void open_door(int & main_state) { | |
Serial.print("Opening door\r\n"); | |
digitalWrite(DOOR_OUTPUT_IO, HIGH); | |
delay(5000); | |
digitalWrite(DOOR_OUTPUT_IO, LOW); | |
main_state = READY; | |
} | |
void loop() { | |
static int state = STARTING, counter = 0, status = 0; | |
counter++; | |
switch(state) { | |
case STARTING: // STARTING | |
_blink(counter, 10000); | |
status = WiFi.status(); | |
if (status == WL_CONNECTED) { | |
state = READY; | |
digitalWrite(0, LOW); | |
} | |
case READY: | |
if (check_button_pressed()) { | |
digitalWrite(0, HIGH); | |
Serial.println("button pressed"); | |
state = NOTIFYING; | |
} | |
break; | |
case NOTIFYING: // send request and read response | |
client_loop(state); | |
break; | |
case OPENING: // open door request | |
open_door(state); | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment