[Day17] Esp32用STA mode + Relay

1.前言

各位有理解loop中很长的咒语吗?不懂得可以多看几次,不要气馁,文章不会跑走,所以继续加油吧~那今天就不废话那麽多呢,今天如标题一样要介绍STA mode,我相信如果看过Relay AP与LED AP的程序码,应该就不难猜到Relay STA也是相同情况,只能跟你们这群优秀得各位说,一点都猜得没错,但在下一篇结束後,会进入读取数值的应用,各位可以期待一下~

2.接线图

和STA AP接线相同

图片取自:使用者拍摄

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.操作画面

利用手机或笔电等装置,并打开WiFi连接至AP或手机基地台,後续打开浏览器并输入Esp32s的IP(这边需要透过Arduino中的监控视窗查看)

图片取自:使用者拍摄

图片取自:使用者拍摄

欢迎交流

好了,不知不觉已经介绍完2个很常使用到的元件了,下一篇会讲解html的基础写法,就不会有程序码的介绍拉,因为都大概介绍完了,如果有不懂可以在下方留言区留言,如有看到就会帮你们解答疑问,那如开头所讲,下一篇结束後会开始进入感测器时代,并会透过那个感测器做出许多应用,那这边就稍微卖点关东煮 (我就是想卖关东煮),所以先不讲是甚麽元件,那就明天见拉


<<:  找寻你的设计灵感、素材及好工具

>>:  Day 3 我要开始Mock了

30天程序语言研究

今天是30天程序语言研究的第十七天,由於深度学习老师多让我们上了python的进阶课程里面包括之前没...

System Design: 读书心得4

Elasticsearch/Solr/ELK Stash Caveat of using Elast...

MySQL学习_Day2

学习内容 资料储存、约束资料、修改&删除资料 储存资料: 在输入字串资料时,若资料型态是VA...

D-08-排程设定 ? hangfire

如何处理定期的需求 相信很多人会遇到需要定期做某些事情的状况,例如每分钟去计算一次资料,或者一分钟跟...

彻底卸载 Mac 应用程序

并不是所有的都是常用的应用程序,而且多数情况下都是下载了 App 之後却没怎麽使用。渐渐地,这些应用...