ESP32 开发笔记(十一)使用 ESP32 做为 WebServer

本文详细介绍如何使用ESP32搭建简易Web服务器,包括HTML文件压缩、头文件生成及存储于Flash的方法,适用于手机等移动终端访问ESP32数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 ESP32 做为 WebServer

在某些场景,我们可能需要在手机上或者其他移动终端访问 ESP32 的数据,这个时候我们需要在手机上展示 ESP32 设备的相关信息,这个时候可以用 APP 在手机上展示数据,或者在手机浏览器中打开存储在 ESP32 上的网页。或者其他的方式。

这篇文章我们将介绍第二种方式。在 ESP32 上存储网页文件,将 ESP32 做为一个简单的 WebServer。

工作流程:(第一种方式)

  1. 首先通过 gzip 将 HTML 文件压缩为 .gz 文件
  2. 使用 filetoarray 工具将 .gz 文件转为头文件
  3. 在 ESP32 程序中将头文件中的数组发送出去

工作流程:(第二种方式)

  1. 首先通过 gzip 将 HTML 文件压缩为 .gz 文件
  2. 使用 ESP32 构建系统中的嵌入二进制数据的方式,将其添加到 Flash 中的 .rodata 部分
  3. 在 ESP32 程序中将 Flash 中的数组发送出去

filetoarray 工具

使用这个工具将 .gz 文件转换为包含十六进制数组和其长度的头文件。

源码如下:

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    FILE *fp;
    char *buffer;
    long flen;
    char *fname;
    char pname[1024];

    if ( argc == 2 ) {
        fname = argv[1];
        strcpy(pname, fname);
        char *dot = strchr(pname, '.');
        while (dot != NULL) {
            *dot = '_';
            dot = strchr(pname, '.');
        }
    } else {
        printf("Filename not supplied\n");
        return 1;
    }

    fp = fopen(fname, "rb");
    fseek(fp, 0, SEEK_END);
    flen = ftell(fp);
    rewind(fp);

    buffer = (char *)malloc((flen + 1) * sizeof(char));
    fread(buffer, flen, 1, fp);
    fclose(fp);

    printf("\n//File: %s, Size: %lu\n", fname, flen);
    printf("#define %s_len %lu\n", pname, flen);
    printf("const uint8_t %s[] PROGMEM = {\n", pname);
    long i;
    for (i = 0; i < flen; i++) {
        printf(" 0x%02X", (unsigned char)(buffer[i]));
        if (i < (flen - 1)) {
            printf(",");
        }
        if ((i % 16) == 15) {
            printf("\n");
        }
    }
    printf("\n};\n\n");
    free(buffer);
    return 0;
}

HTML 文件到头文件

使用方式:

  1. 使用 gzip 将 HTML 文件转换为 .gz 文件
gzip index.html
  1. 编译 filetoarray.c 源文件,生成可执行文件
gcc filetoarray.c -o filetoarray
  1. 使用 filetoarray 将 .gz 文件转为头文件
./filetoarray index.html.gz > index.h

HTML 文件到 Flash

使用方式:

  1. 使用 gzip 将 HTML 文件转换为 .gz 文件
gzip index.html
  1. 在工程 main 目录下的 component.mk 中添加
COMPONENT_EMBED_FILES := www/index.html.gz
  1. 在工程源码中这样使用
extern const unsigned char index_html_gz_start[] asm("_binary_index_html_gz_start");
extern const unsigned char index_html_gz_end[]   asm("_binary_index_html_gz_end");
size_t index_html_gz_len = index_html_gz_end - index_html_gz_start;

httpd_resp_set_type(req, "text/html");
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
httpd_resp_send(req, (const char *)index_html_gz_start, index_html_gz_len);

在 ESP32 中启动 HTTP Server

第一种方式:

#include "index.h"

static esp_err_t index_handler(httpd_req_t *req){
    httpd_resp_set_type(req, "text/html");
    httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
    return httpd_resp_send(req, (const char *)index_html_gz, index_html_gz_len);
}

第二种方式:

static esp_err_t index_handler(httpd_req_t *req){
    extern const unsigned char index_html_gz_start[] asm("_binary_index_html_gz_start");
	extern const unsigned char index_html_gz_end[]   asm("_binary_index_html_gz_end");
	size_t index_html_gz_len = index_html_gz_end - index_html_gz_start;


    httpd_resp_set_type(req, "text/html");
    httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
    return httpd_resp_send(req, (const char *)index_html_gz_start, index_html_gz_len);
}
#include "app_httpd.h"
#include "esp_http_server.h"

void app_httpd_main() {
	httpd_handle_t camera_httpd = NULL;
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();

    httpd_uri_t index_uri = {
        .uri       = "/",
        .method    = HTTP_GET,
        .handler   = index_handler,
        .user_ctx  = NULL
    };

    ESP_LOGI(TAG, "Starting web server on port: '%d'", config.server_port);
    if (httpd_start(&camera_httpd, &config) == ESP_OK) {
        httpd_register_uri_handler(camera_httpd, &index_uri);
    }
}

Example

web server

### ESP8266开发资源概述 #### 功能特性 ESP8266是一款集成了Wi-Fi功能的微控制器芯片,能够轻松嵌入各种物联网(IoT)项目中。该芯片不仅具备强大的处理能力和丰富的外设接口,还支持多种编程语言和框架,使得开发者可以根据具体需求灵活选择开发方式[^1]。 #### 教程与指南 对于初学者而言,官方提供的帮助文档是非常宝贵的参考资料,其中包含了详细的硬件介绍、快速入门指导以及常见问题解答等内容。此外,网络上也存在大量由社区成员分享的经验贴和技术博客,这些资料往往更贴近实际应用场景,有助于加速学习过程并解决遇到的技术难题。 #### 库文件和支持材料 为了简化开发流程,提高效率,市面上有许多现成的库可供调用,比如用于管理文件系统的SPIFFS(SPI Flash File System),或是实现HTTP服务器功能的WebServer类等。同时,Arduino IDE内置了对ESP8266的支持,这意味着可以直接利用庞大的Arduino生态系统中的各类扩展包来增强项目的功能性。 #### 引脚定义及数据手册 关于具体的引脚分配情况,可以从官方发布的数据手册中获得最权威的信息。这份文档详尽列出了各个引脚的作用及其电气参数规格,是进行电路设计不可或缺的重要依据之一。另外,针对不同型号的产品版本,可能还会附有额外的应用笔记(Application Note),进一步解释特定特性的使用方法。 #### 示例代码 最后但同样重要的是,开源平台上提供了大量的实例程序作为参考模板。例如,可以通过网页加载闪存文件系统中的图片、CSS和JavaScript;或者借助Ajax技术实现实时交互效果,像控制PWM输出亮度变化或读取模拟输入电压值并在界面上动态呈现等等。 ```cpp // 示例:创建一个简单的Web服务器以响应客户端请求 #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> const char* ssid = "your_SSID"; const char* password = "your_PASSWORD"; ESP8266WebServer server(80); void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } server.on("/", [](){ server.send(200, "text/plain", "Hello from ESP8266!"); }); server.begin(); } void loop() { server.handleClient(); } ```
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值