由于毕设需要单片机实现联网功能进而实现手机控制,我对ESP32的Wi-Fi的Station的程序进行一番理解和整理。
ESP32例程下载地址
我们先分析每一句代码所蕴含的信息:
/* WiFi station Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.*/
#include <string.h>//内存和字符串函数的定义
#include "freertos/FreeRTOS.h"//实时操作系统freertos头文件
#include "freertos/task.h"//freertos任务(线程)头文件
#include "freertos/event_groups.h"//freertos事件组
#include "esp_system.h"//ESP32系统头文件(包括系统枚举的定义和函数的声明)
#include "esp_wifi.h"//ESP32Wi-Fi功能头文件
#include "esp_event_loop.h"//ESP32事件轮询头文件
#include "esp_log.h"//ESP32日志信息头文件(打印输出代码信息)
#include "nvs_flash.h"//Non-volatile storage (NVS)非易失性存储库。用于把数据存储到 flash中,掉电或重启后数据仍然存在
#include "lwip/err.h"//轻量级TCP/IP协议栈之错误代码相应的头文件
#include "lwip/sys.h"//轻量级TCP/IP协议栈之系统相应的头文件
/* The examples use WiFi configuration that you can set via 'make menuconfig'.
If you'd rather not, just change the below entries to strings with
the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
*/
//可以通过make menuconfig(Linux下)进行配置Wi-Fi Station要连接的AP的SSID和PSW
#define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID//AP对应的SSID
#define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD//AP对应的连接密钥
#define EXAMPLE_ESP_MAXIMUM_RETRY CONFIG_ESP_MAXIMUM_RETRY//Station连接AP时重试的次数
//上面这三个宏定义可以直接修改(注意SSID和PSW都是字符串形式)或者在Kconfig.projbuild文件中进行修改。
/* FreeRTOS event group to signal when we are connected*/
static EventGroupHandle_t s_wifi_event_group;
/* The event group allows multiple bits for each event, but we only care about one event
* - are we connected to the AP with an IP? */
const int WIFI_CONNECTED_BIT = BIT0;//事件组允许每个事件有多个位,但是我们只关心一个事件,所以只设置一位(可追溯程序找到#define BIT0 0x00000001)
static const char *TAG = "wifi station";//该程序的标签为WiFi基站
static int s_retry_num = 0;//重试次数计数
static esp_err_t event_handler(void *ctx, system_event_t *event)//事件句柄(WiFi状态机)
{