Chapter 15 ESP32 idf framework wifi networking_WiFi AP mode_mobile phone connected to esp32 development board

Part 1: How to install Arduino and ESP32 development boards

Part 2: ESP32 helloword’s first program demonstration lights up the onboard LED

Part 3: vscode builds esp32 arduino development environment

Part 4: vscode + platformio to build esp32 arduino development environment

Part 5: doit_esp32_devkit_v1 experiment using pmw breathing lamp

Part 6: ESP32 is connected to a passive speaker to play the music “The Sound of the Waves Are Still”

Part 7: ESP32 connection button lights up the LED passive speaker to play sound

Part 8: ESP32 connected to ultrasonic HC-SR04 for distance measurement, lighting up the LED passive speaker to play sound

Part 9: Writing ESP32 Ultrasonic HC-SR04Arduino Class Library

Part 10: Use of ESP32 external interrupt function

Part 11: ESP32vscode_platformio_idf framework helloworld lights up the LED

Part 12: ESP32 simulated SPI driver 12864LCD_ST7920 display screen

Part 13: ESP32 idf wifi networking uses SNTP to synchronize network time LCD ST7920 LCD screen display
Chapter 14 ESP32 idf wifi networking_WiFi STA mode (connected to WIFI) LCD ST7920 LCD screen display

ESP32’s Wi-Fi can work in the following working states:

  • Station Mode (STA): In this mode, the ESP32 connects to an existing wireless network, similar to a regular Wi-Fi client device.
  • Access Point Mode (AP): In this mode, the ESP32 acts as a Wi-Fi hotspot itself and accepts connections from other Wi-Fi client devices, similar to a router.
  • Station + Access Point mode (STA + AP): In this mode, ESP32 works in both Station and Access Point modes at the same time, which can connect to existing Wi-Fi networks and provide Wi-Fi hotspots.
  • Wi-Fi Direct mode (P2P): In this mode, ESP32 acts as a Wi-Fi Direct device and can communicate directly with other Wi-Fi Direct devices without using a router.
  • Promiscuous mode: In this mode, the ESP32 can listen for all Wi-Fi packets, not just those related to the AP or P2P device it is connected to.

The previous article introduced the working mode of ESP32 as a station. Today we use its (SoftAP mode) Access Point mode.

Part 14 ESP32 idf wifi networking_WiFi STA mode (connected to WIFI) LCD ST7920 LCD screen display

In the WIFI example, we can see that there is a default event loop. My understanding of event loop is task event, that is, after we register the callback function and perform wifi initialization, the wifi task will be executed, and then after the wifi task has an event, There will be an interrupt-like event generated in the callback event. The registration function is as follows:

ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
                                                        ESP_EVENT_ANY_ID,
                                                         &wifi_event_handler,
                                                        NULL,
                                                        NULL));

WIFI_EVENT is a string, which is the basic event of our event loop. The component to which the subsequent event loop is sent is determined based on this parameter. ESP_EVENT_ANY_ID means that when sending the event loop event, as long as the data of the basic event WIFI_EVENT is called, we will be called The callback function. When we use ESP_EVENT_ANY_BASE, any other basic event other than the WIFI_EVENT basic event sent will call the callback function we registered. When we use the specified ID, this time it will only be used as a callback function. Our registered callback function will be called only when this ID event is triggered. For example, when we register the ID as WIFI_EVENT_AP_STACONNECTED, only when the WIFI_EVENT_AP_STACONNECTED event is triggered will the execution of our callback function wifi_event_handler be triggered. Other WIFI_EVENT_AP_STADISCONNECTED and WIFI_EVENT_AP_START events will be triggered. The callback function we registered will not be called when generated.
WIFI authentication modes include the following. Our default is basically WIFI_AUTH_WPA_WPA2_PSK.

typedef enum {
    WIFI_AUTH_OPEN = 0, /**< authenticate mode : open */
    WIFI_AUTH_WEP, /**< authenticate mode : WEP */
    WIFI_AUTH_WPA_PSK, /**< authenticate mode : WPA_PSK */
    WIFI_AUTH_WPA2_PSK, /**< authenticate mode : WPA2_PSK */
    WIFI_AUTH_WPA_WPA2_PSK, /**< authenticate mode : WPA_WPA2_PSK */
    WIFI_AUTH_WPA2_ENTERPRISE, /**< authenticate mode : WPA2_ENTERPRISE */
    WIFI_AUTH_WPA3_PSK, /**< authenticate mode : WPA3_PSK */
    WIFI_AUTH_WPA2_WPA3_PSK, /**< authenticate mode : WPA2_WPA3_PSK */
    WIFI_AUTH_WAPI_PSK, /**< authenticate mode : WAPI_PSK */
    WIFI_AUTH_MAX
} wifi_auth_mode_t;

When we set the password length of the hotspot to 0, we need to set the encryption method to WIFI_AUTH_OPEN open.

1.wifi_config_t structure

The sample code sets the Wi-Fi module of ESP32 to work in AP mode, and also configures some parameters of the Wi-Fi AP hotspot to facilitate client connection.

// Set to AP mode, configure name, password, channel, maximum number of connections, authentication mode
wifi_config_t wifi_config = {
           .ap = {
                   .ssid = EXAMPLE_ESP_WIFI_SSID,
                   .ssid_len = strlen(EXAMPLE_ESP_WIFI_SSID),
 .channel = EXAMPLE_ESP_WIFI_CHANNEL,
 .password = EXAMPLE_ESP_WIFI_PASS,
 .max_connection = EXAMPLE_MAX_STA_CONN,
  .authmode = WIFI_AUTH_WPA_WPA2_PSK
 },
};
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, & amp;wifi_config));

2.wifi_event_handler event

(1)esp_event_handler_instance_register registration event

Example:

//wifi related settings initialization
 ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, //Check ESP_EVENT_ANY_ID, & amp;wifi_event_handler, NULL, NULL));

esp_event_handler_instance_register is used to register event handlers in the event loop. Its parameter explanation:

  • WIFI_EVENT: The basic type of event, this function will register a handler to the WiFi event.
  • ESP_EVENT_ANY_ID: This is the event ID. ESP_EVENT_ANY_ID is used here to register all WiFi events.
  • &wifi_event_handler: This is a pointer to the event handler that will be called when a WiFi event occurs.
  • NULL: This is the parameter of the event handler, no parameter is used here, so it is set to NULL.
  • NULL: This is an instance of the event handler, multiple instances are not used here, so set it to NULL.

(2)system_event_sta_connected_t structure

In ESP-IDF, when a device connects to the ESP32’s WiFi hotspot via WiFi, the ESP32 triggers a connection event. This event will contain a structure system_event_sta_connected_t, which contains the MAC address of the connected device (event->mac) and the AID of the connected device under the AP hotspot (event->aid).

Among them, event->aid represents the AID (Association ID) of the connected device under the AP hotspot. AID is an integer value indicating the number of the device connected to the AP hotspot.
In the 802.11 standard, AID is a value assigned by the AP hotspot that can be used to uniquely identify a STA (Station) device. In ESP-IDF, the AID range is 1~16, which represents the number of connected devices.

3. Close SoftAP

ESP_LOGI(TAG, "Max clients reached, shutting down AP");
//Close softAP
esp_wifi_stop();
esp_wifi_deinit();
esp_netif_deinit();
vTaskDelete(NULL);

3. Example

ESP32 can operate in AP (Access Point) mode through the Wi-Fi chip and serve as a hotspot. The following is a sample code to enable ESP32 hotspot:

#include "driver/gpio.h"
#include <stdio.h>
#include "unistd.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include <stddef.h>
#include <time.h>

#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "esp_system.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_attr.h"
#include "esp_sleep.h"
#include "nvs_flash.h"
#include "esp_sntp.h"
#include "esp_wifi.h"
#include "lcd12864st7920idf.h"

#include "lwip/err.h"
#include "lwip/sys.h"
/* The examples use WiFi configuration that you can set via project configuration menu.If you'd rather not, just change the below entries to strings with the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
 *Header file contains
 */


// Macros related to networking
//#define EXAMPLE_ESP_WIFI_SSID "xx" // Account
//#define EXAMPLE_ESP_WIFI_PASS "@xx68" // Password
#define EXAMPLE_ESP_WIFI_SSID "ESP32_AP_t" // WIFI name
#define EXAMPLE_ESP_WIFI_PASS "12345678" // WIFI password
#define EXAMPLE_ESP_WIFI_CHANNEL 1 //
#define EXAMPLE_MAX_STA_CONN 2 //
#define MAC2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5]
#define MACSTR " X: X: X: X: X: X"//The converted format can be modified as needed

#define EXAMPLE_ESP_MAXIMUM_RETRY 5 //The number of times the wifi connection can be reconnected after failure
#define WIFI_CONNECTED_BIT BIT0 // WiFi connection success flag
#define WIFI_FAIL_BIT BIT1 // WiFi connection failure flag bit
#define AR_SIZE(a) sizeof(a) / sizeof(a[0])

unsigned char show1[] = {0xB0, 0xA2, 0xCE, 0xE4, 0xBF, 0xC6, 0xBC, 0xBC}; //Awu Technology

unsigned char show_we_chat1[] = "wechat:";
unsigned char show_nick1[] = "txwtech";
unsigned char show_wifi_connecting[] = "wifi_connecting...";
unsigned char show_wifi_reconnect[] = "wifi_reconnecting...";
unsigned char show_wifi_connected[] = "wifi_connected";

// Network related variables
static EventGroupHandle_t s_wifi_event_group; // Event group, used to mark wifi response results
static int s_retry_num = 0; // Record the number of wifi reconnection attempts

static const char *TAG = "esp32idf_title_txwtech";

// void app_main()
// {
//Initialise();
// DisplayString(0, 0, show_wifi_connecting, AR_SIZE(show_wifi_connecting));

// int mLevel = 0;
// int temp = 0;

// esp_err_t ret = nvs_flash_init();
// if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
// {
// ESP_ERROR_CHECK(nvs_flash_erase());
// ret = nvs_flash_init();
// }
// ESP_ERROR_CHECK(ret);
// //CLEAR();
// // Connect to wifi
// //ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
// ESP_LOGI(TAG, "ESP_WIFI_MODE_AP");
// wifi_init_sta();

// CLEAR();
// DisplayString(1, 0, show_wifi_connected, AR_SIZE(show_wifi_connected));
// while (false)
// {
// time_t timer; // time_t is long int type
// // DisplayString(0, 1, show1, AR_SIZE(show1)); //The first row starts with the third cell
// // DisplayString(3, 2, show_wifi_connected, AR_SIZE(show_wifi_connected)); //
// DisplayString(1, 0, show_wifi_connected, AR_SIZE(show_wifi_connected));
// usleep(1000 * 1000 * 1); //Microseconds, 1000 microseconds = 1 millisecond, 1000 milliseconds = 1 second
// }
// }

/* WiFi softAP ExampleThis 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 ORCONDITIONS OF ANY KIND, either express or implied.
 */

// static const char *TAG = "wifi softAP";
static void wifi_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    if (event_id == WIFI_EVENT_AP_STACONNECTED)
    {
     wifi_event_ap_staconnected_t *event = (wifi_event_ap_staconnected_t *)event_data;
     ESP_LOGI(TAG, "station "MACSTR" join, AID=%d",MAC2STR(event->mac), event->aid);
        
    }
    else if (event_id == WIFI_EVENT_AP_STADISCONNECTED)
    {
        wifi_event_ap_stadisconnected_t *event = (wifi_event_ap_stadisconnected_t *)event_data;
        // ESP_LOGI(TAG, "station "MACSTR" leave, AID=%d",MAC2STR(event->mac), event->aid);
    }
}
void wifi_init_softap(void)
{
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_create_default_wifi_ap();
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init( & amp;cfg));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, & amp;wifi_event_handler, NULL, NULL));
    wifi_config_t wifi_config =
        {
            .ap =
                {
                    .ssid = EXAMPLE_ESP_WIFI_SSID,
                    .ssid_len = strlen(EXAMPLE_ESP_WIFI_SSID),
                    .channel = EXAMPLE_ESP_WIFI_CHANNEL,
                    .password = EXAMPLE_ESP_WIFI_PASS,
                    .max_connection = EXAMPLE_MAX_STA_CONN,
                    .authmode = WIFI_AUTH_WPA_WPA2_PSK},
        };
    if (strlen(EXAMPLE_ESP_WIFI_PASS) == 0)
    {
        wifi_config.ap.authmode = WIFI_AUTH_OPEN;
    }
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
    ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_AP, & amp;wifi_config));
    ESP_ERROR_CHECK(esp_wifi_start());
    ESP_LOGI(TAG, "wifi_init_softap finished. SSID:%s password:%s channel:%d", EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS, EXAMPLE_ESP_WIFI_CHANNEL);
}
void app_main(void)
{ // Initialize NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    ESP_LOGI(TAG, "ESP_WIFI_MODE_AP");
    wifi_init_softap();
}