[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的课程,因为可以连接上网就可以做许多事情,所以这算是基础设置了,如果有兴趣的也可以将该行程序码贴上网路上,查找这段程序码的功用,这也是一种让自己更进步的方法。


<<:  Day1.准备好踏入嵌入式的第一步

>>:  day14 : 前半段小结

D15-(9/15)-南亚(1303)-也是存股好选择的台塑四宝

注:发文日和截图的日期不一定是同一天,所以价格计算上和当日不同,是很正常的。 声明:这一系列文章并无...

感谢此时此刻的自己 - 30天完赛

我喜欢艺术,也喜欢程序码 一开始因为工作关系强迫自己要学会程序码,原本不能接受,甚至觉得我没有天份在...

目录 [10.12更新]

前言 (入门~初阶程度) 篇名"登堂入室",写得冠冕堂皇也只是因为喜欢很台的发音...

Day 01 - 参赛初衷

第一次参加铁人赛,第一天就来纪录一下参赛初衷吧。 身为一个非本科毕业,转职踏入职场才两个多月的菜鸟网...

每日挑战,从Javascript面试题目了解一些你可能忽略的概念 - Day8

tags: ItIron2021 Javascript 前言 昨天我们探讨了undefined、nu...