Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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.
- 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.
- */
- #include <ESP8266WiFi.h>
- #include <WiFiClient.h>
- #include <ESP8266WebServer.h>
- // Replace with your network credentials
- const char* ssid = "your_SSID";
- const char* password = "your_PASSWORD";
- // Create an instance of the server
- ESP8266WebServer server(80);
- // Relay control pin
- const int relayPin = D1;
- bool relayState = false;
- void setup() {
- Serial.begin(115200);
- pinMode(relayPin, OUTPUT);
- digitalWrite(relayPin, relayState);
- // Connect to Wi-Fi
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(1000);
- Serial.println("Connecting to Wi-Fi...");
- }
- Serial.println("Connected to Wi-Fi");
- // Setup web server routes
- server.on("/", handleRoot);
- server.on("/toggle", handleToggle);
- server.begin();
- Serial.println("Web server started");
- }
- void loop() {
- server.handleClient();
- }
- void handleRoot() {
- String html = "<html><body><h1>D1 Mini Relay Control</h1>";
- html += "<p><a href=\"/toggle\"><button>Toggle Relay</button></a></p>";
- html += "</body></html>";
- server.send(200, "text/html", html);
- }
- void handleToggle() {
- relayState = !relayState;
- digitalWrite(relayPin, relayState);
- String message = relayState ? "Relay ON" : "Relay OFF";
- Serial.println(message);
- server.sendHeader("Location", "/");
- server.send(303);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement