在乐鑫更新了ESP8266_RTOS_SDK之后,官方的说话是更加符合ESP-IDF的风格,也就是说在可预见的未来,ESP8266和ESP32在一些功能差不多的应用上,代码是完全可以互相借鉴的

但是目前可以看到的是,官方的RTOS_SDK的手册,可是完全指导不上了,本教程直接贴出连接wifi的代码,仅供RTOS当前版本可用,未来版本不保证……


/*
   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"
#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"


//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底层相关

    //构造需要连接的wifi信息
    wifi_config_t wifi_config = {
        .sta = {
            .ssid = "weiecn_IOT",  //填入wifi名称/ssid
            .password = "iot.weiecn.com" //填入wifi密码
        },
    };

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

}


ZYZ

邹颖峥

Leave a Reply

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