16、ESP32 Web

        Web 服务器具有移动响应能力,可以使用本地网络上的任何设备作为浏览器进行访问。

        示例功能:

  • 构建 Web 服务器控制连接到 ESP32 的 LED
  • 在本地网络的浏览器上输入 ESP32 IP 地址访问 Web 服务器
  • 通过单击 Web 服务器上的按钮,更改 LED 状态
// 使用 ESP32 构建 Web 服务器,控制 LED

#include <Arduino.h>
#include <WiFi.h>

const char* ssid = "么么";    // Wifi
const char* password = "yaoqiao321";    // 密码

WiFiServer server(80);      // 设置 web 服务器端口号 80

// Variable to store the HTTP request
String header;  // HTTP 请求变量

const int LED = 2;
String led_state = "off";   // 当前 LED 状态

unsigned long currentTime;      // 当前时间
unsigned long previousTime;     // 上次时间
const long timeoutTime = 2000;  // 超时时间 2S

void setup()
{
    Serial.begin(115200);

    pinMode(LED, OUTPUT);
    digitalWrite(LED, LOW);

    // 连接 WIFI,打印 IP
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println();
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    server.begin();     // 启动 web 服务器
}

void loop()
{
    WiFiClient client = server.available();     // 新客户端

    // 有客户端连接
    if (client)
    {
        Serial.println("New Client.");      // 新客户

        String currentLine = "";    // 存储客户端传入数据

        currentTime = millis();
        previousTime = currentTime;

        // 客户端连接时循环,2S刷新
        while (client.connected() && currentTime - previousTime <= timeoutTime)
        {
            currentTime = millis();

            if (client.available())     // 接收到客户端字节
            {
                char c = client.read();
                Serial.write(c);
                header += c;

                // 其他字符存储
                if ((c != '\r') && (c != '\n')) {
                    currentLine += c;
                }
                
                // 结束请求,返回响应
                else if (c == '\n')
                {
                    if (currentLine.length() == 0)
                    {
                        client.println("HTTP/1.1 200 OK");          // 发送响应头 HTTP/1.1 200 OK
                        client.println("Content-type:text/html");   // 发送内容类型 text/html
                        client.println("Connection: close");        // 发送内容
                        client.println();                           // 发送换行
                        
                        if (header.indexOf("GET /LED/on") >= 0)  // 返回指定字符串在原字符串中第一次出现的位置。没有指定的字符串返回-1
                        {
                            Serial.println("LED ON");
                            led_state = "on";
                            digitalWrite(LED, HIGH);
                        }
                        else if (header.indexOf("GET /LED/off") >= 0)
                        {
                            Serial.println("LED OFF");
                            led_state = "off";
                            digitalWrite(LED, LOW);
                        }

                        // 创建网页
                        // 发送 HTML 网页
                        client.println("<!DOCTYPE html><html>");        // 正在发送 HTML
                        client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");   // 在 Web 浏览器中有响应
                        client.println("<link rel=\"icon\" href=\"data:,\">");      // 防止对网站图标的请求

                        // CSS 按钮样式
                        client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");      // Helvetica字体,中心对齐
                        client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");     // 按钮 #4CAF50 色、无边框、白色文本和填充,大小 16px 40px
                        client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");   // 文本修饰 none,字体大小 30px、边距 2px、指向指针的光标
                        client.println(".button2 {background-color: #555555;}</style></head>");     // 第二个按钮改变颜色(OFF)
                        
                        // Web 标题
                        client.println("<body><h1>ESP32 Web Server</h1>");
                        
                        // 显示 LED 当前状态
                        client.println("<p>LED - State " + led_state + "</p>");
                        // 当前是 OFF 显式 ON,当前是 ON 显式 OFF
                        if (led_state == "off")
                        {
                            client.println("<p><a href=\"/LED/on\"><button class=\"button\">ON</button></a></p>");
                        } else
                        {
                            client.println("<p><a href=\"/LED/off\"><button class=\"button button2\">OFF</button></a></p>");
                        } 

                        // HTTP 响应以空行结束
                        client.println();
                        break;
                    }
                    else
                        currentLine = "";   // 有换行符,清除 currentLine
                }
            }
        }
        
        header = "";
        client.stop();      // 关闭连接
        Serial.println("Client disconnected.");
    }
}

代码烧录到 ESP32,返回 IP 地址。

用同网络环境下的设备访问这个 IP。

  点击按钮,可以控制 ESP32 IO 电平

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无敌暴龙战士朵拉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值