关于AP模式的详细讲解放在了对应的ESP-IDF开发文章中,点击栏目目录即可跳转找到。
1. API函数
1.1 初始化
bool softAP(const char* ssid, const char* passphrase = NULL, int channel = 1, int ssid_hidden = 0, int max_connection = 4, bool ftm_responder = false);
- ssid:SSID,即WiFi名;
- passphrase:密码;
- channel:信道,默认为1;
- ssid_hidden:是否隐藏SSID,默认不隐藏;
- max_connection:最大连接数,默认为4;
- ftm_responder:(有知道的评论区解释一下吧),一般保持默认即可。
1.2 IP配置
bool softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dhcp_lease_start = (uint32_t) 0);
- local_ip:IP地址;
- gateway:网关IP地址;
- subnet:子网掩码;
- dhcp_lease_start:DHCP IP池的起始地址。
1.3 注册回调
wifi_event_id_t onEvent(WiFiEventCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX);
wifi_event_id_t onEvent(WiFiEventFuncCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX);
wifi_event_id_t onEvent(WiFiEventSysCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX);
回调注册函数有3个,区别在于第一个参数,第二个参数定义接收的事件。
上面第一个参数对应的定义分别如下:
typedef void (*WiFiEventCb)(arduino_event_id_t event);
typedef std::function<void(arduino_event_id_t event, arduino_event_info_t info)> WiFiEventFuncCb;
typedef void (*WiFiEventSysCb)(arduino_event_t *event);
都是函数指针,第一个就只返回事件的ID;第二个返回事件ID之余还会返回事件对应的信息;第三个返回的这个结构体里面就包含了前者的两个结构体。
2. 例程
#include <Arduino.h>
#include <WiFi.h>
static void wifi_event_cb(arduino_event_t *event)
{
if (event->event_id == ARDUINO_EVENT_WIFI_AP_STACONNECTED) {
Serial.printf("station " MACSTR " join, AID=%d\r\n",
MAC2STR(event->event_info.wifi_ap_staconnected.mac),
event->event_info.wifi_ap_staconnected.aid);
} else if (event->event_id == ARDUINO_EVENT_WIFI_AP_STADISCONNECTED) {
Serial.printf("station " MACSTR " leave, AID=%d\r\n",
MAC2STR(event->event_info.wifi_ap_stadisconnected.mac),
event->event_info.wifi_ap_stadisconnected.aid);
} else if (event->event_id == ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED) {
esp_ip4_addr_t *ip = &(event->event_info.wifi_ap_staipassigned.ip);
Serial.printf("station assigned IP: " IPSTR "\r\n",
IP2STR(ip));
}
}
void setup()
{
/* 初始化串口 */
Serial.begin(115200);
/* 初始化AP */
WiFi.onEvent(wifi_event_cb);
WiFi.softAP("ESP32", "12345678");
}
void loop()
{
}
AP的所有操作都是通过回调完成的,所以初始化前先注册回调;回调里面我就处理基站连接、赋IP成功和断开三个事件。然后再调初始化函数,传入SSID和密码即可。之后就可以用手机去连接ESP32的AP节点了。