Advertisement
hwthinker

relay10A-8ch-esp12f-01-test-serverweb

Sep 19th, 2023 (edited)
1,393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <ESP8266WiFi.h>
  2. #include <ESP8266WebServer.h>
  3.  
  4. // Definisikan SSID dan Password WiFi Anda
  5. const char* ssid = "poco";  //seuaikan dengan ssid access point anda
  6. const char* password = "12345678";  //seusiakan dengan password access point anda
  7.  
  8. // Inisialisasi ESP8266WebServer
  9. ESP8266WebServer server(80);
  10.  
  11. // Daftar status relay (0 = OFF, 1 = ON)
  12. int relayStatus[8] = {0, 0, 0, 0, 0, 0, 0, 0};
  13.  
  14. // Daftar pin GPIO yang terhubung ke relay
  15. int rly1 = 16;
  16. int rly2 = 14;
  17. int rly3 = 12;
  18. int rly4 = 13;
  19. int rly5 = 15;
  20. int rly6 = 0;
  21. int rly7 = 4;
  22. int rly8 = 5;
  23. int relayPins[8] = {rly1, rly2, rly3, rly4, rly5, rly6, rly7, rly8};
  24.  
  25.  
  26. void setup() {
  27.   // Inisialisasi pin relay sebagai OUTPUT
  28.   for (int i = 0; i < 8; i++) {
  29.     pinMode(relayPins[i], OUTPUT);
  30.     digitalWrite(relayPins[i], LOW);
  31.   }
  32.  
  33.   // Mulai serial
  34.   Serial.begin(115200);
  35.  
  36.   // Sambungkan ke WiFi
  37.   WiFi.begin(ssid, password);
  38.   while (WiFi.status() != WL_CONNECTED) {
  39.     delay(1000);
  40.     Serial.println("Menghubungkan ke WiFi...");
  41.   }
  42.   Serial.println("Terhubung ke WiFi");
  43.   Serial.println("IP Address: " + WiFi.localIP().toString());
  44.   // Mengatur rute web
  45.   server.on("/", HTTP_GET, handleRoot);
  46.   server.on("/relay", HTTP_GET, handleRelay);
  47.   server.begin();
  48.   Serial.println("Server berjalan");
  49. }
  50.  
  51. void loop() {
  52.   server.handleClient();
  53. }
  54.  
  55. void handleRoot() {
  56.   String html = "<html><body>";
  57.   html += "<h1>Control Relay via Web</h1>";
  58.   for (int i = 0; i < 8; i++) {
  59.     html += "<p>Relay " + String(i+1) + ": ";
  60.     html += (relayStatus[i] == 1) ? "ON" : "OFF";
  61.     html += " <a href='/relay?state=";
  62.     html += (relayStatus[i] == 1) ? "0" : "1";
  63.     html += "&relay=";
  64.     html += String(i);
  65.     html += "'>Toggle</a></p>";
  66.   }
  67.   html += "</body></html>";
  68.   server.send(200, "text/html", html);
  69. }
  70.  
  71. void handleRelay() {
  72.   if (server.hasArg("state") && server.hasArg("relay")) {
  73.     int relay = server.arg("relay").toInt();
  74.     int state = server.arg("state").toInt();
  75.     if (relay >= 0 && relay < 8 && (state == 0 || state == 1)) {
  76.       relayStatus[relay] = state;
  77.       digitalWrite(relayPins[relay], state);
  78.     }
  79.   }
  80.   handleRoot();
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement