Advertisement
microrobotics

ESP8266-2CH-30A Webserver Code

Apr 6th, 2024 (edited)
2,084
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <ESP8266WiFi.h>
  2.  
  3. // WiFi Settings
  4. const char* ssid = "Your_WiFi_SSID";
  5. const char* password = "Your_WiFi_Password";
  6.  
  7. // Relay Pins
  8. const int relay1Pin = 14; // GPIO 14 (D5), Bridge with RY1
  9. const int relay2Pin = 16; // GPIO 16 (D0), Bridge with RY2
  10.  
  11. // Web Server on port 80
  12. WiFiServer server(80);
  13.  
  14. void setup() {
  15.   Serial.begin(115200);
  16.   delay(10);
  17.  
  18.   // Configure Relay Pins
  19.   pinMode(relay1Pin, OUTPUT);
  20.   pinMode(relay2Pin, OUTPUT);
  21.   digitalWrite(relay1Pin, HIGH); // Relays might be active-low, adjust if needed
  22.   digitalWrite(relay2Pin, HIGH); // Relays might be active-low, adjust if needed
  23.  
  24.   // Connect to WiFi
  25.   WiFi.begin(ssid, password);
  26.   Serial.println("Connecting to WiFi...");
  27.   while (WiFi.status() != WL_CONNECTED) {
  28.     delay(500);
  29.     Serial.print(".");
  30.   }
  31.  
  32.   // Print IP Address
  33.   Serial.println("\nWiFi connected. IP address: ");
  34.   Serial.println(WiFi.localIP());
  35.  
  36.   // Start the server
  37.   server.begin();
  38.   Serial.println("Web server started.");
  39. }
  40.  
  41. void loop() {
  42.   WiFiClient client = server.available();  
  43.   if (!client) return;
  44.  
  45.   // Read incoming request
  46.   String request = client.readStringUntil('\r');
  47.   Serial.println(request);
  48.   client.flush();
  49.  
  50.   // Handle Relay Control
  51.   if (request.indexOf("/relay1on") != -1)  {
  52.     digitalWrite(relay1Pin, LOW);
  53.     client.println("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nRelay 1 ON");
  54.   } else if (request.indexOf("/relay1off") != -1)  {
  55.     digitalWrite(relay1Pin, HIGH);
  56.     client.println("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nRelay 1 OFF");
  57.   }
  58.   // Add more 'else if' blocks for relay 2 and any future additions
  59.  
  60.   // Add a simple webpage control interface (optional)
  61.   client.println("HTTP/1.1 200 OK");
  62.   client.println("Content-Type: text/html");
  63.   client.println("");
  64.   client.println("<!DOCTYPE html>");
  65.   // ... Rest of your HTML webpage code ...
  66.  
  67.   client.stop();
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement