Advertisement
microrobotics

D1 Mini Relay Shield

May 8th, 2023
2,941
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. To control a D1 Mini Relay Shield through a web server, you can use the following code example. This code is written for the ESP8266-based D1 Mini board using the Arduino IDE. Make sure to install the "ESP8266WiFi" library before compiling and uploading the code to the board.
  3.  
  4. This code sets up a simple web server that serves an HTML page with a button to toggle the relay. The button sends a request to the "/toggle" route, which toggles the relay state and redirects the user back to the main page.
  5. */
  6.  
  7. #include <ESP8266WiFi.h>
  8. #include <WiFiClient.h>
  9. #include <ESP8266WebServer.h>
  10.  
  11. // Replace with your network credentials
  12. const char* ssid = "your_SSID";
  13. const char* password = "your_PASSWORD";
  14.  
  15. // Create an instance of the server
  16. ESP8266WebServer server(80);
  17.  
  18. // Relay control pin
  19. const int relayPin = D1;
  20. bool relayState = false;
  21.  
  22. void setup() {
  23.   Serial.begin(115200);
  24.   pinMode(relayPin, OUTPUT);
  25.   digitalWrite(relayPin, relayState);
  26.  
  27.   // Connect to Wi-Fi
  28.   WiFi.begin(ssid, password);
  29.   while (WiFi.status() != WL_CONNECTED) {
  30.     delay(1000);
  31.     Serial.println("Connecting to Wi-Fi...");
  32.   }
  33.   Serial.println("Connected to Wi-Fi");
  34.  
  35.   // Setup web server routes
  36.   server.on("/", handleRoot);
  37.   server.on("/toggle", handleToggle);
  38.   server.begin();
  39.   Serial.println("Web server started");
  40. }
  41.  
  42. void loop() {
  43.   server.handleClient();
  44. }
  45.  
  46. void handleRoot() {
  47.   String html = "<html><body><h1>D1 Mini Relay Control</h1>";
  48.   html += "<p><a href=\"/toggle\"><button>Toggle Relay</button></a></p>";
  49.   html += "</body></html>";
  50.   server.send(200, "text/html", html);
  51. }
  52.  
  53. void handleToggle() {
  54.   relayState = !relayState;
  55.   digitalWrite(relayPin, relayState);
  56.   String message = relayState ? "Relay ON" : "Relay OFF";
  57.   Serial.println(message);
  58.   server.sendHeader("Location", "/");
  59.   server.send(303);
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement