iT邦幫忙

2021 iThome 鐵人賽

DAY 16
0
自我挑戰組

Maker making IoT !!系列 第 16

[Day15] Esp32s用AP mode + Relay

1.前言

哈喽各位小夥伴,不知不覺系列文章已經進行一半了(感覺要解鎖成就了),不知道各位在看完前幾篇後,對Esp32s、程式寫法有沒有更深的認識,如果沒有的話,可以繼續的看下去,因為後面會有更多應用,可以看到更多不同的程式碼,回歸正題,今天要講解用Esp32s的AP mode控制繼電器(Relay),那我們就直接介紹元件。

2.元件介紹

圖片取自:使用者繪製

上面紅圈所圈選的就是本次會使用到的繼電器(Relay),那繼電器的功能常被拿來當作安全保護或控制的功用,為甚麼說這兩點呢,因為繼電器可以利用較小電流控制較大電流的零件,像是控制燈泡、馬達...等等物品,那這可以解釋利用小電流控制大電流的零件,那沒解釋到如何做到安全保護的功用對吧,因為這講解到繼電器的構造,繼電器內部像是個Y,當繼電器接受到電流時,因繼電器內部有電磁鐵會將內部的簧片拉至常開(NO,Normally Open),但如果沒接收到電內部簧片就固定於至常閉(NC,Normally Close),那我們可以針對繼電器的這功能做出,當繼電器接收到電流就跳掉,用這點做一個安全保護的功能。

3.接線圖

Esp32s GND -> St01 GND
Esp32s Vcc(5V) -> ST01(G) +
Esp32s 23 or 22 -> ST01(G) io
(io這邊可選擇用Esp32s的23或22腳都可以,因為程式碼寫的是兩個按鈕,但如果選擇22那操作時就只能按22的按鈕,反之23也相同)

4.程式碼

#include <WiFi.h>

// Replace with your network credentials
const char* ssidAP     = "E32_Relay_AP";
const char* passwordAP = "12345678";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output0State = "off";
String output2State = "off";

// Assign output variables to GPIO pins
const int output0 = 23;
const int output2 = 22;

void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(output0, OUTPUT);
  pinMode(output2, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output0, LOW);
  digitalWrite(output2, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Setting AP (Access Point)…");
  // Remove the password parameter, if you want the AP (Access Point) to be open
  WiFi.softAP(ssidAP, passwordAP);
  delay(500);
  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);
  
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // turns the GPIOs on and off
            if (header.indexOf("GET /23/on") >= 0) {
              Serial.println("GPIO 23 on");
              output0State = "on";
              digitalWrite(output0, HIGH);
            } else if (header.indexOf("GET /23/off") >= 0) {
              Serial.println("GPIO 23 off");
              output0State = "off";
              digitalWrite(output0, LOW);
            } else if (header.indexOf("GET /22/on") >= 0) {
              Serial.println("GPIO 22 on");
              output2State = "on";
              digitalWrite(output2, HIGH);
            } else if (header.indexOf("GET /22/off") >= 0) {
              Serial.println("GPIO 22 off");
              output2State = "off";
              digitalWrite(output2, LOW);
            }
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #555555;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP32 Web Server</h1>");
            
            // Display current state, and ON/OFF buttons for GPIO 23  
            client.println("<p>GPIO 23 - State " + output0State + "</p>");
            // If the output0State is off, it displays the ON button       
            if (output0State=="off") {
              client.println("<p><a href=\"/23/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/23/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 22  
            client.println("<p>GPIO 22 - State " + output2State + "</p>");
            // If the output2State is off, it displays the ON button       
            if (output2State=="off") {
              client.println("<p><a href=\"/22/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/22/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

5.操作畫面

跟之前操作LED AP那篇相同,一樣是連上WiFi然後在瀏覽器上打192.168.4.1,就可連至Esp32s所開啟得網頁中囉,然後就可以看自己接的腳位是23或22去點擊,就可以控制Relay的開啟予關閉

圖片取自:使用者拍攝

你會發現,你會訝異,怎麼跟LED AP長一樣,哎呀你猜對了,就是一樣的寫法。

歡迎交流

好了,今天先到這裡!沒想到吧,LED AP的寫法在這邊也可做運用,那可以做運用的原因是因為繼電器也只有分做開啟(ON)與關閉(OFF),那LED也是相同的狀況,相信我後面還有一篇也是這樣,那就是STA,但下面一篇就是開始講解loop裡面的程式啦,所以請不要覺得我在划水(雖然真的很像),那我們就下一篇見啦~


上一篇
[Day14] Esp32s用STA mode + LED - (程式碼講解)
下一篇
[ Day16] Esp32s用AP mode + Relay - (程式碼講解)
系列文
Maker making IoT !!30

尚未有邦友留言

立即登入留言