Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Most of this code came from https://randomnerdtutorials.com/esp8266-web-server-with-arduino-ide/
#include <ESP8266WiFi.h>
#include <Servo.h>
const char* ssid = "NiceTry";
const char* password = "ImNotStupid";
Servo servo;
WiFiServer server(80);
String header;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void RunServo(int angle) {
if (angle == 90 && servo.attached()) {
servo.write(89);
delay(1000);
servo.detach();
} else if (angle != 90) {
if (!servo.attached()) {
// Attach the servo to D4.
servo.attach(2);
delay(1000);
}
servo.write(angle);
}
}
void loop(){
WiFiClient client = server.available();
if (client) {
String currentLine = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
header += c;
if (c == '\n') {
if (currentLine.length() == 0) {
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
if (header.indexOf("/left") > 0) {
client.println("Servo-state: left");
RunServo(180);
} else if (header.indexOf("/right") > 0) {
client.println("Servo-state: right");
RunServo(0);
} else if (header.indexOf("/off") > 0) {
client.println("Servo-state: off");
RunServo(90);
}
client.println();
break;
} else {
currentLine = "";
}
} else if (c != '\r') {
currentLine += c;
}
}
}
header = "";
client.stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment