I was travelling this week, so I post-hoc made the simplest possible hello-world project for this week.
The set-up here was the same as for my MVP final project (motion sensor & servo), with an HTML page sneaked into the ESP.
Surprisingly, this took only a few tries to iron out (thanks to GPT's help too). I struggled with the wifi for a while, but eventually everything worked out. Production code:
#include
#include
#include
const char* ssid = "MLDEV";
const char* password = "[CENSORED]";
int pinIR = 44;
int servoPin = 43;
Servo myServo;
WebServer server(80);
bool isLidOpen = false;
bool webControlActive = false;
unsigned long webControlTimeout = 0;
void handleRoot() {
server.send(200, "text/html", R"rawliteral(
Servo Control
ESP32 Servo Control
)rawliteral");
}
void handleOpen() {
if (!isLidOpen) {
Serial.println("Web: Lid Open");
myServo.write(0);
isLidOpen = true;
webControlActive = true;
webControlTimeout = millis() + 5000;
server.send(200, "text/plain", "Lid Opened");
} else {
server.send(200, "text/plain", "Lid is already open");
}
}
void handleClose() {
if (isLidOpen) {
Serial.println("Web: Lid Close");
myServo.write(85);
isLidOpen = false;
webControlActive = true;
webControlTimeout = millis() + 5000;
server.send(200, "text/plain", "Lid Closed");
} else {
server.send(200, "text/plain", "Lid is already closed");
}
}
void setup() {
Serial.begin(9600);
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nWi-Fi connected!");
Serial.print("Access the server at: http://");
Serial.println(WiFi.localIP());
pinMode(pinIR, INPUT);
myServo.attach(servoPin, 500, 2500);
myServo.write(85);
server.on("/", handleRoot);
server.on("/open", handleOpen);
server.on("/close", handleClose);
server.begin();
Serial.println("Server started...");
}
void loop() {
server.handleClient();
if (webControlActive && millis() > webControlTimeout) {
webControlActive = false;
}
if (!webControlActive) {
int IRstate = digitalRead(pinIR);
if (IRstate == LOW && !isLidOpen) {
Serial.println("IR: Detected - Opening Lid");
myServo.write(0);
isLidOpen = true;
delay(5000);
} else if (IRstate == HIGH && isLidOpen) {
Serial.println("IR: Not Detected - Closing Lid");
myServo.write(85);
isLidOpen = false;
}
}
delay(500);
}
The main problem I faced was unreliability. I usually took 5 tries for the web interface button to successfully activate the servo. But -- hello world!
Well, I wasn't in town for this group assignment. So here's a few personal notes from looking into these tools: