[Day11] Esp32s用AP mode + LED

1.前言

讲了那麽多天的理论,现在该来让各位多动手实作啦,今天主要是会运用Esp32s内建的WiFi来进行实作,并融合两个LED灯,达到可用手机连结Esp32s就可远端操控LED的亮与灭。

2.Esp32s的WiFi运作模式

Esp32s的WiFi有三种运作模式,分别是AP、STA及AP/STA

  • AP mode
    手机连接Esp32s (Esp32s当基地台)
  • STA mode
    Esp32s去连接AP (手机或WiFi分享器当基地台)

而我这样文字叙述肯定很多人到现在还是搞不清楚,所以我准备了一张图片

图片取自:使用者绘制

2-1.那麽这两种区别有什麽呢?

其实我觉得最大的区别就是当Esp32s开启STA mode时,可以去连接手机或AP基地台,而这时候Esp32s也就具备网路,可以上网抓数值,例如抓取PM2.5的数值,并用网页或LCD去做显示,可以做出更多不同的应用。

那接下来就直接进入主题吧,上次的实作呼吸灯还记得吧,不记得罚你回去复习『Day6 呼吸灯制作』,那上次只是让LED灯自己跑程序,跑出呼吸灯的效果,但是今天就比较不同,是自己手动控制LED灯的亮灭状态,那就直接看接线图吧。

2-2.接线图

图片取自:使用者拍摄

许多人应该会想着,为什麽LED不用接地跟为什麽黄色那条要往下接到下方GND,那是因为A区的LED已经在板中已经牵线至下方GND区块,所以A区LED要接地只需要把开发板的GND接线至下方GND区即可接地,对了还有LED有4颗,随便挑两颗就好。

3.程序码

请修改第四行(ssidAP)及第五行(passwordAP)後方的"xxxx",请将资讯输入至""中,千万不可把""删除,xxxx可删除,修改完毕後就可进行烧入,如果忘记如何烧入可以回顾『Day4 Arduino测试烧录』。

#include <WiFi.h>

// Replace with your network credentials
const char* ssidAP     = "xxxx"; //Esp32s基地台名称(随便都可以,要英文且尽量不要跟附近的WiFi撞名)
const char* passwordAP = "xxxxxxxx";//Esp32s基地台密码(至少要8码,例如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("");
  }
}

4.操作画面

还记得前面设置的ssid名称及密码吗?
如果烧录成功,就可开启手机WiFi,就会看见刚刚设置的ssid名称,例如我设置"Esp32_Web_LED_AP",那就会跟下方图片相同

图片取自:使用者拍摄

成功连结WiFi会发现没有无网际网路,这是正常现象,切记不要让手机自动切换至有网际网路的WiFi,後续呢,请打开浏览器(chrome或什麽浏览器都可),在网址列上输入"192.168.4.1",连接至该网址後会看见下方画面

图片取自:使用者拍摄

那这样代表连接成功罗,接下来可以玩罗,点击ON即可让LED亮起(前提线有插好)。

欢迎交流

好了,是不是有进入实作的状态啦,明天会稍微讲解基本操作+程序码,後续就敢用STA mode执行LED啦,是不是很期待更後面章节的实作呀,如果各位有兴趣,也可以趁有空时自己研究此次程序码中可以做些何种有趣修改,让本次程序码不只让LED亮灭那麽简单,那今天的部分就这些,各位明天见罗~


<<:  Day2:在Anaconda上安装Tensorflow以及Keras

>>:  < 关於 React: 开始打地基| 依照条件render画面 >

Day 19. v-bind - Class的绑定

在Vue中,如果我们需要绑定属性就可以用到v-bind,是不是有对这个指令有印象啊,我们在Day 1...

Day06 - this&Object Prototypes Ch3 Objects - Contents - Property Descriptors

透过 Object.defineProperty 可以设定 value writable 值可修改性...

Day15 - Ruby 字串处理入门

线上 Ruby 编辑器:https://runrb.io/ Ruby String 文件:http...

Day23:Greedy Algorithm - 贪婪演算法

贪婪演算法(英语:greedy algorithm),又称贪心演算法,是一种在每一步选择中都采取在...

JS 逻辑运算子及函式预设值 DAY56

逻辑运算子 MDN : https://developer.mozilla.org/zh-TW/do...