ESP32系列--第四篇 WiFi概述

一、目的

        ESP32能火的很大一部分原因是其既有WiFi又有Bluetooth,而传统的MCU如果需要能够访问网络则必须外接WiFi芯片,从本篇开始我们将介绍ESP32的WiFi功能。

二、介绍

        按照惯例我们贴上官网资料方便大家学习 

Wi-Fi - ESP32 - — ESP-IDF Programming Guide latest documentation (espressif.com)https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html

       特点

        ESP32 WiFi支持三种模式,分别为:

  • Station模式(作为WiFi设备主动连接路由器,也叫做WiFi Client)
  • AP模式(作为一个Access Point,让其他WiFi设备来连接)即WiFi热点
  • Station/AP共存模式(ESP32连接路由器的同时自身也是一个热点供其他WiF设备来连接)

        支持各种加密方式(WPA、WPA2、WEP等)

        支持主动或者被动扫描WiFi热点

        Promiscuous 混杂模式用于监听IEEE802.11 WiFi包

        其中需要特别强调的是混杂模式,因为这个模式的存在我们才可以实现airkiss配网、微信配网等功能。

        WiFi库框架

                 

        参看资料为esp-idf里面的components/esp_wifi/include/esp_wifi.h

        从上图我们可以看到总共四个模块,分别为tcpip协议栈、事件循环任务、WiFi Driver以及用户任务。WiFi Driver是一个黑盒,它只能接收API调用产生事件或者自身主动产生事件。

        WiFi功能的核心是一个事件循环任务,配合上tcp/ip协议栈和WiFi Driver,我们就可以在应用层使用各种网络功能;

        在嵌入式平台上TCP/IP协议栈首选LwIP,所以上图中最左边是lwip协议栈的内容(以后台任务的形式处理各种网络事件);

        在应用层中我们通过调用各种API来控制WiFi Driver来使用WiFi,WiFi的各种事件(如联网成功、扫描网络完成等事件都转发给事件循环任务,事件循环任务则执行一些必要处理后通过回调的形式通知应用层;

        应用层再根据事件类型进行业务处理,完成我们需要的功能。

        这种分层的设计有助于应用层与驱动层解耦。

        API介绍

esp_err_t esp_wifi_init(const wifi_init_config_t *config)

        在使用wifi功能之前必须先进行初始化,上面的函数用来初始化WiFi Driver需要的各种资源并且启动一个WiFi后台任务;需要注意的是,总是使用WIFI_INIT_CONFIG_DEFAULT宏作为入参,这样可以正确地初始化默认值;当然如果你很熟悉里面的配置项也可以手动修改某些参数以达到某些特殊需求。

esp_err_t esp_wifi_deinit(void)

        如果不想再使用WiFi相关功能,可以调用上面的接口销毁WiFi模块使用的资源。

esp_err_t esp_wifi_set_mode(wifi_mode_tmode)

        设置WiFi的模式(STA、AP、STA&AP)

esp_err_t esp_wifi_get_mode(wifi_mode_t *mode)

        获取当前WiFi设置的模式 

esp_err_t esp_wifi_set_config(wifi_interface_t interface, wifi_config_t *conf);

        设置WiFi配置,我们看一下wifi_config_t这个联合体

/** @brief Soft-AP configuration settings for the ESP32 */
typedef struct {
    uint8_t ssid[32];           /**< SSID of ESP32 soft-AP. If ssid_len field is 0, this must be a Null terminated string. Otherwise, length is set according to ssid_len. */
    uint8_t password[64];       /**< Password of ESP32 soft-AP. */
    uint8_t ssid_len;           /**< Optional length of SSID field. */
    uint8_t channel;            /**< Channel of ESP32 soft-AP */
    wifi_auth_mode_t authmode;  /**< Auth mode of ESP32 soft-AP. Do not support AUTH_WEP in soft-AP mode */
    uint8_t ssid_hidden;        /**< Broadcast SSID or not, default 0, broadcast the SSID */
    uint8_t max_connection;     /**< Max number of stations allowed to connect in, default 4, max 10 */
    uint16_t beacon_interval;   /**< Beacon interval which should be multiples of 100. Unit: TU(time unit, 1 TU = 1024 us). Range: 100 ~ 60000. Default value: 100 */
    wifi_cipher_type_t pairwise_cipher;   /**< pairwise cipher of SoftAP, group cipher will be derived using this. cipher values are valid starting from WIFI_CIPHER_TYPE_TKIP, enum values before that will be considered as invalid and default cipher suites(TKIP+CCMP) will be used. Valid cipher suites in softAP mode are WIFI_CIPHER_TYPE_TKIP, WIFI_CIPHER_TYPE_CCMP and WIFI_CIPHER_TYPE_TKIP_CCMP. */
    bool ftm_responder;         /**< Enable FTM Responder mode */
    wifi_pmf_config_t pmf_cfg;  /**< Configuration for Protected Management Frame */
} wifi_ap_config_t;

/** @brief STA configuration settings for the ESP32 */
typedef struct {
    uint8_t ssid[32];      /**< SSID of target AP. */
    uint8_t password[64];  /**< Password of target AP. */
    wifi_scan_method_t scan_method;    /**< do all channel scan or fast scan */
    bool bssid_set;        /**< whether set MAC address of target AP or not. Generally, station_config.bssid_set needs to be 0; and it needs to be 1 only when users need to check the MAC address of the AP.*/
    uint8_t bssid[6];     /**< MAC address of target AP*/
    uint8_t channel;       /**< channel of target AP. Set to 1~13 to scan starting from the specified channel before connecting to AP. If the channel of AP is unknown, set it to 0.*/
    uint16_t listen_interval;   /**< Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set. Units: AP beacon intervals. Defaults to 3 if set to 0. */
    wifi_sort_method_t sort_method;    /**< sort the connect AP in the list by rssi or security mode */
    wifi_scan_threshold_t  threshold;     /**< When sort_method is set, only APs which have an auth mode that is more secure than the selected auth mode and a signal stronger than the minimum RSSI will be used. */
    wifi_pmf_config_t pmf_cfg;    /**< Configuration for Protected Management Frame. Will be advertized in RSN Capabilities in RSN IE. */
    uint32_t rm_enabled:1;        /**< Whether Radio Measurements are enabled for the connection */
    uint32_t btm_enabled:1;       /**< Whether BSS Transition Management is enabled for the connection */
    uint32_t mbo_enabled:1;       /**< Whether MBO is enabled for the connection */
    uint32_t reserved:29;         /**< Reserved for future feature set */
} wifi_sta_config_t;

/** @brief Configuration data for ESP32 AP or STA.
 *
 * The usage of this union (for ap or sta configuration) is determined by the accompanying
 * interface argument passed to esp_wifi_set_config() or esp_wifi_get_config()
 *
 */
typedef union {
    wifi_ap_config_t  ap;  /**< configuration of AP */
    wifi_sta_config_t sta; /**< configuration of STA */
} wifi_config_t;

         我们配置时使用对应的字段就可以了,其中最主要的两个字段就是ssid和password。

esp_err_t esp_wifi_start(void)

        根据当前的设置的模式和配置信息启动WiFi;如果是WIFI_MODE_STA,那么就创建station控制块并且启动station;如果是WIFI_MODE_AP,就创建softap控制块并且启动softap;如果是WIFI_MODE_APSTA,就创建station和softap控制块并启动。

esp_err_t esp_wifi_stop(void)

        停止WiFi 运行并销毁对应资源

esp_err_t esp_wifi_connect(void);

        连接WiFi热点,注意只在WIFI_MODE_STA或者WIFI_MODE_APSTA模式下生效。

esp_err_t esp_wifi_disconnect(void);

         主动断开连接

esp_err_t esp_wifi_scan_start(const wifi_scan_config_t *config, bool block);

        主动发起扫描,wifi_scan_config_t的字段如下,用来指定扫描策略

/** @brief Parameters for an SSID scan. */
typedef struct {
    uint8_t *ssid;               /**< SSID of AP */
    uint8_t *bssid;              /**< MAC address of AP */
    uint8_t channel;             /**< channel, scan the specific channel */
    bool show_hidden;            /**< enable to scan AP whose SSID is hidden */
    wifi_scan_type_t scan_type;  /**< scan type, active or passive */
    wifi_scan_time_t scan_time;  /**< scan time per channel */
} wifi_scan_config_t;

        block字段指明是否阻塞等待扫描结果 ,阻塞情况下只有扫描到结果此接口才退出。

esp_err_t esp_wifi_scan_stop(void);

        停止扫描(只有在非阻塞扫描调用下可以使用)

esp_err_t esp_wifi_scan_get_ap_num(uint16_t *number)

        获取上一次扫描到AP个数

esp_err_t esp_wifi_scan_get_ap_records(uint16_t *number, wifi_ap_record_t *ap_records)

        获取上一次的扫描结果(扫描完成后一定要调用此接口,否则会有内存泄漏) 

        以上就是WiFi相关的一些接口,下面我们去看看WiFi相关的事件

/** WiFi event declarations */
typedef enum {
    WIFI_EVENT_WIFI_READY = 0,           /**< ESP32 WiFi ready */
    WIFI_EVENT_SCAN_DONE,                /**< ESP32 finish scanning AP */
    WIFI_EVENT_STA_START,                /**< ESP32 station start */
    WIFI_EVENT_STA_STOP,                 /**< ESP32 station stop */
    WIFI_EVENT_STA_CONNECTED,            /**< ESP32 station connected to AP */
    WIFI_EVENT_STA_DISCONNECTED,         /**< ESP32 station disconnected from AP */
    WIFI_EVENT_STA_AUTHMODE_CHANGE,      /**< the auth mode of AP connected by ESP32 station changed */

    WIFI_EVENT_STA_WPS_ER_SUCCESS,       /**< ESP32 station wps succeeds in enrollee mode */
    WIFI_EVENT_STA_WPS_ER_FAILED,        /**< ESP32 station wps fails in enrollee mode */
    WIFI_EVENT_STA_WPS_ER_TIMEOUT,       /**< ESP32 station wps timeout in enrollee mode */
    WIFI_EVENT_STA_WPS_ER_PIN,           /**< ESP32 station wps pin code in enrollee mode */
    WIFI_EVENT_STA_WPS_ER_PBC_OVERLAP,   /**< ESP32 station wps overlap in enrollee mode */

    WIFI_EVENT_AP_START,                 /**< ESP32 soft-AP start */
    WIFI_EVENT_AP_STOP,                  /**< ESP32 soft-AP stop */
    WIFI_EVENT_AP_STACONNECTED,          /**< a station connected to ESP32 soft-AP */
    WIFI_EVENT_AP_STADISCONNECTED,       /**< a station disconnected from ESP32 soft-AP */
    WIFI_EVENT_AP_PROBEREQRECVED,        /**< Receive probe request packet in soft-AP interface */

    WIFI_EVENT_FTM_REPORT,               /**< Receive report of FTM procedure */

    /* Add next events after this only */
    WIFI_EVENT_STA_BSS_RSSI_LOW,         /**< AP's RSSI crossed configured threshold */
    WIFI_EVENT_ACTION_TX_STATUS,         /**< Status indication of Action Tx operation */
    WIFI_EVENT_ROC_DONE,                 /**< Remain-on-Channel operation complete */

    WIFI_EVENT_STA_BEACON_TIMEOUT,       /**< ESP32 station beacon timeout */

    WIFI_EVENT_MAX,                      /**< Invalid WiFi event ID */
} wifi_event_t;

        WIFI_EVENT_STA_CONNECTED这个事件就是代表已经连接到AP

        以上事件就不一一介绍了,大家可以看看源码和注释。

        好了,本篇内容到此结束,后面会针对每个功能进行详细的使用介绍。

### 关于ESP32-WROOM-32E模块的原理图 ESP32-WROOM-32E 是基于 ESP32 芯片设计的一个集成模块,其主要特点在于内置了 4MB 的闪存以及支持多种无线通信协议(Wi-Fi 和 Bluetooth/BLE)。该模块广泛应用于物联网设备中。对于寻找 ESP32-WROOM-32E 原理图的需求,通常可以通过官方文档或制造商提供的资料获取。 以下是关于如何找到并理解 ESP32-WROOM-32E 模块原理图的相关信息: #### 官方资源 Espressif Systems 提供了详细的硬件设计指南和技术规格书,其中包含了 ESP32-WROOM-32E 的电路连接方式及其内部结构说明[^1]。这些文件可以在 Espressif 的官方网站或者相关开发者社区下载到。 #### 主要特性概述 - **处理器核心**: 双核 Xtensa® LX6 处理器运行频率最高可达 240 MHz。 - **存储配置**: 集成了 4 MB PSRAM 和 Flash 存储单元用于程序加载与数据缓存操作。 - **外设接口**: 支持丰富的 GPIO 引脚分配方案以及其他串口、I²C/SPI/I²S 总线形式的数据交换机制。 下面是一段 Python 示例代码展示如何初始化一个基本 Wi-Fi 连接过程: ```python import network sta_if = network.WLAN(network.STA_IF) ap_if = network.WLAN(network.AP_IF) def connect_wifi(ssid, password): if not sta_if.isconnected(): print('Connecting to WiFi...') sta_if.active(True) sta_if.connect(ssid, password) while not sta_if.isconnected(): pass print('Network config:', sta_if.ifconfig()) connect_wifi("your_SSID", "your_PASSWORD") ``` 此代码片段展示了通过调用 `network` 库来建立稳定网络环境的方法. #### 获取具体 Schematic Diagram 方法建议 访问 Espressif 官网的产品页面可以直接定位至目标型号的技术手册部分;另外也可以参考第三方开源项目贡献者分享的经验总结文章链接作为补充参考资料来源之一.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值