代码和之前sta模式类似,只不过需要改动一些地方

适用于RTOS_SDK V2.0以后版本

#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "rom/ets_sys.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "driver/uart.h"

#define EXAMPLE_ESP_WIFI_SSID      "WEIECN_IOT_AP"
#define EXAMPLE_ESP_WIFI_PASS      "iot.weiecn.com"

//wifi的回调事件注册
//static EventGroupHandle_t wifi_event_group;
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
    switch(event->event_id) {
    //station模式下开始连接
    case SYSTEM_EVENT_STA_START:
        printf("开始连接wifi\n");
        esp_wifi_connect();
        break;
    //station模式下已完成连接并且获取到了IP
    case SYSTEM_EVENT_STA_GOT_IP: 
        //将其ip信息打印出来
        printf("获取到IP:%s\n",ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
        break;
    //AP模式下的其他设备连接上了本设备AP
    case SYSTEM_EVENT_AP_STACONNECTED:
    //将其连接上本设备的设备的信息打印出来
    printf("设备:"MACSTR" join, AID=%d\n",MAC2STR(event->event_info.sta_connected.mac),event->event_info.sta_connected.aid);
        break;
    //AP模式下,其他设备与本设备断开的连接
    case SYSTEM_EVENT_AP_STADISCONNECTED:
    printf("station:"MACSTR"leave, AID=%d\n",MAC2STR(event->event_info.sta_disconnected.mac),event->event_info.sta_disconnected.aid);
        break;
    //station模式下 本设备从AP断开/AP踢了本设备
    case SYSTEM_EVENT_STA_DISCONNECTED:
        esp_wifi_connect();//重新连接之前的AP
        break;
    default:
        break;
    }
    return ESP_OK;
}

void app_main(void)
{
     uart_set_baudrate(0,115200);//将串口设置成115200
     
     esp_err_t ret = nvs_flash_init();
     if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
      ESP_ERROR_CHECK(nvs_flash_erase());
      ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    printf("SDK version:%s\n", esp_get_idf_version());

    //开始wifi 连接
    //wifi_event_group = xEventGroupCreate(); //创建一个事件组
    tcpip_adapter_init();           //初始化TCP/IP相关,这个函数只需要调用一次
    
    esp_event_loop_init(event_handler, NULL);   //注册事件

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&cfg); //初始化wifi底层相关

    //构造AP信息
    wifi_config_t wifi_config = {
        .ap = {
            .ssid = EXAMPLE_ESP_WIFI_SSID,//wifi的名称
            .ssid_len = strlen(EXAMPLE_ESP_WIFI_SSID), 
            .password = EXAMPLE_ESP_WIFI_PASS, //wifi密码
            .max_connection = 10, //最大连接数
            .authmode = WIFI_AUTH_WPA_WPA2_PSK //加密方式
        },
    };

    esp_wifi_set_mode(WIFI_MODE_AP); //设置wifi模式,设置为AP模式
    esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config); //将其wifi信息配置进去
    esp_wifi_start(); //开启wifi状态机 ()

}

 


ZYZ

邹颖峥

Leave a Reply

Your email address will not be published. Required fields are marked *