【ESP32】Arduino开发 | WiFi开发 | AP模式 + 基站连接例程

关于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节点了。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

马浩同学

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

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

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

打赏作者

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

抵扣说明:

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

余额充值