iT邦幫忙

2021 iThome 鐵人賽

DAY 14
0
自我挑戰組

Maker making IoT !!系列 第 14

[Day13] Esp32s用STA mode + LED

1.前言

今天比較晚po文,開學了超多事情要忙,課也超多(三條線)。好了抱怨時間結束!!這篇如前兩篇所說是實作篇喔~是不是很開心又要看到非常長的程式碼啦,相信我,還有很多機會可以見到,那這次要教各位的是Esp32s的STA mode的使用方法,STA與AP在setup()設定時寫法較為不同,但loop基本上沒什麼差別,那最主要STA需要看到手機所提供的IP位址,所以此次一定要觀看昨天所提及的序列埠監控視窗,因為此次網頁輸入IP不在是192.168.4.1,而是由手機電信商所提供的IP,所以也不能跟你肯定IP是多少,要自己看呦。
※IP位址,就是像上次192.168.4.1

2.接線圖

那此次因為只有程式做改動,所以接線圖依舊相同。

圖片取自:使用者拍攝

3.程式碼

#include <WiFi.h>
// Replace with your network credentials
const char* ssid     = "xxxx";  //AP分享器SSID
const char* password = "xxxxxxxx";    //AP分享器密碼
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output22State = "off";
String output23State = "off";

// Assign output variables to GPIO pins
const int output22 = 22;
const int output23 = 23;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

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

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  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
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();         
      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 /22/on") >= 0) {
              Serial.println("GPIO 22 on");
              output22State = "on";
              digitalWrite(output22, HIGH);
            } else if (header.indexOf("GET /22/off") >= 0) {
              Serial.println("GPIO 22 off");
              output22State = "off";
              digitalWrite(output22, LOW);
            } else if (header.indexOf("GET /23/on") >= 0) {
              Serial.println("GPIO 23 on");
              output23State = "on";
              digitalWrite(output23, HIGH);
            } else if (header.indexOf("GET /23/off") >= 0) {
              Serial.println("GPIO 23 off");
              output23State = "off";
              digitalWrite(output23, 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: #195B6A; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP32 Web Server</h1>");
            
            // Display current state, and ON/OFF buttons for GPIO 22  
            client.println("<p>GPIO 22 - State " + output22State + "</p>");
            // If the output22State is off, it displays the ON button       
            if (output22State=="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>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 23  
            client.println("<p>GPIO 23 - State " + output23State + "</p>");
            // If the output23State is off, it displays the ON button       
            if (output23State=="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>");
            }
            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("");
  }
}

請記得ssid跟password要填寫正確,如果填寫錯誤Esp32s會無法連結到AP(你的手機基地台或AP(WiFi)分享器)

4.操作畫面

燒入後,點開監控視窗,查看Esp32s的IP位址。

圖片取自:使用者拍攝

出現亂碼或連接不到AP,可重新查看鮑率是否正確或點擊Esp32s上的EN按鍵(左方按鈕)
得知Esp32s位址後,依舊是打開瀏覽器,輸入IP位址,後來就可以開始玩啦

圖片取自:使用者拍攝

歡迎交流

好了,今天先到這裡,明天講解會說明STA及AP mode的setup()的不同之處,那各位也可以稍微去比對一下是哪裡不同,那這個部分其實是最重要的部分,因為Esp32s會做到許多WiFi的課程,因為可以連接上網就可以做許多事情,所以這算是基礎設置了,如果有興趣的也可以將該行程式碼貼上網路上,查找這段程式碼的功用,這也是一種讓自己更進步的方法。


上一篇
[Day12] Esp32s用AP mode + LED - (認識序列埠監控視窗&程式碼講解)
下一篇
[Day14] Esp32s用STA mode + LED - (程式碼講解)
系列文
Maker making IoT !!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言