Advertisement
pleasedontcode

ESP32 Web Server Setup for OTP Input

Nov 7th, 2024
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 1.96 KB | Source Code | 0 0
  1. #include <WiFi.h>
  2. #include <ESPAsyncWebServer.h>
  3. #include <HTTPClient.h>
  4.  
  5. const char* ssid = "Your_SSID";             // Replace with your WiFi SSID
  6. const char* password = "Your_PASSWORD";     // Replace with your WiFi Password
  7. const char* otp = "123456";                 // Temporary hardcoded OTP, replace with generated OTP
  8.  
  9. AsyncWebServer server(80);                  // Start a web server on port 80
  10.  
  11. const int relayPin = 5;                     // Relay connected to GPIO 5
  12. bool doorUnlocked = false;
  13.  
  14. void setup() {
  15.   Serial.begin(115200);
  16.   pinMode(relayPin, OUTPUT);
  17.   digitalWrite(relayPin, LOW);              // Ensure door is locked by default
  18.  
  19.   WiFi.begin(ssid, password);
  20.   while (WiFi.status() != WL_CONNECTED) {
  21.     delay(1000);
  22.     Serial.println("Connecting to WiFi...");
  23.   }
  24.   Serial.println("Connected to WiFi");
  25.  
  26.   // Web server to enter OTP
  27.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  28.     String html = "<html><body><h2>Enter OTP to Unlock Door</h2><form action='/verify' method='POST'><input type='text' name='otp' placeholder='Enter OTP'><input type='submit' value='Submit'></form></body></html>";
  29.     request->send(200, "text/html", html);
  30.   });
  31.  
  32.   // OTP verification and door control
  33.   server.on("/verify", HTTP_POST, [](AsyncWebServerRequest *request){
  34.     if (request->hasParam("otp", true)) {
  35.       String inputOTP = request->getParam("otp", true)->value();
  36.       if (inputOTP == otp) {
  37.         digitalWrite(relayPin, HIGH);          // Unlock door
  38.         delay(5000);                           // Keep unlocked for 5 seconds
  39.         digitalWrite(relayPin, LOW);           // Lock door again
  40.         request->send(200, "text/html", "Door Unlocked! Welcome.");
  41.         doorUnlocked = true;
  42.       } else {
  43.         request->send(200, "text/html", "Invalid OTP. Try again.");
  44.       }
  45.     }
  46.   });
  47.  
  48.   server.begin();
  49. }
  50.  
  51. void loop() {
  52.   // The main loop remains empty as the web server handles requests
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement