Play ESP32 (2): WiFi Code implementation

Source: Internet
Author: User
Play ESP32 (2): WiFi Code Implementation

ESP32 as a wifi+ Bluetooth chip, the realization of WiFi is its most basic function, and in ESP32, the use of WiFi can be achieved STA, AP, Sta+ap three ways. STA Code Implementation

First look at one of the simplest examples of implementing WiFi sta.

#include "freertos/freertos.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "esp_system.h" # Include "esp_wifi.h" #include "esp_event_loop.h" #include "esp_log.h" #include "nvs_flash.h" #define EXAMPLE_WIFI_SSID "

HUAWEI001 "#define Example_wifi_pass" 12345678 "static const char *tag =" Espressif "; /* FreeRTOS Event Group to signal when we is connected & ready to make a request * * static eventgrouphandle_t Wifi_ev

Ent_group; /* The Event group allows multiple bits for each event, but we have care about one event-are we connected to the A P with an IP?

*/Const int connected_bit = BIT0; Static esp_err_t Event_handler (void *ctx, system_event_t *event) {switch (event->event_id) {case System_event
        _sta_start:esp_wifi_connect ();
    Break
        Case System_event_sta_got_ip:xeventgroupsetbits (Wifi_event_group, connected_bit);
    Break Case system_event_sta_disconnected:/* This is a workaround as ESPWiFi Libs don ' t currently auto-reassociate.
        */Esp_wifi_connect ();
        Xeventgroupclearbits (Wifi_event_group, connected_bit);
    Break
    Default:break;
} return ESP_OK;
    } static void Initialise_wifi (void) {tcpip_adapter_init ();
    Wifi_event_group = Xeventgroupcreate ();
    Esp_error_check (Esp_event_loop_init (Event_handler, NULL));
    wifi_init_config_t cfg = Wifi_init_config_default ();
    Esp_error_check (Esp_wifi_init (&cfg));
    Esp_error_check (Esp_wifi_set_storage (Wifi_storage_ram)); wifi_config_t wifi_config = {. STA = {. SSID = Example_wifi_ssid,. Password = Example_wifi
    _pass,},};
    Esp_logi (TAG, "Setting WiFi configuration SSID%s ...", WIFI_CONFIG.STA.SSID);
    Esp_error_check (Esp_wifi_set_mode (Wifi_mode_sta));
    Esp_error_check (Esp_wifi_set_config (Esp_if_wifi_sta, &wifi_config));
Esp_error_check (Esp_wifi_start ()); } void App_main () {ESP_error_check (Nvs_flash_init ());
Initialise_wifi ();
 }

The above example mainly implements the router connecting the SSID to Espressif, and obtains the corresponding IP. The SSID and password can be changed according to their own routing information, and we can do the corresponding network operation (TCP/UDP) after we get the IP.
Where: STA code detailed

Now, let's start with a detailed analysis of the above code.

#include "freertos/freertos.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"

#include "Esp_system.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"

#include " Nvs_flash.h "

Above is the implementation of the WiFi STA required header files, of which the first three are FreeRTOS related header files, the following are espressif defined header files, wherein esp_system.h is the system related header files; esp_ Wifi.h is the WiFi related header file; Esp_event_loop.h is the event-related header file. Esp_log.h is the header file for Espressif formatted output.

#define EXAMPLE_WIFI_SSID "HUAWEI001"
#define Example_wifi_pass "12345678"

static const char *tag = "Espressif" ;

/* FreeRTOS Event Group to signal when we is connected & ready to make a request * *
static eventgrouphandle_t wif I_event_group;

/* The Event group allows multiple bits for each event, but we have care about one
   Event-are we connected to the
   AP with an IP? */
const int connected_bit = BIT0;

The above is the definition of some parameters, the first two for the SSID and password, you need to change according to their own router and password. The 3rd one is the prefix of the formatted output, which can be changed freely. Wifi_event_group is the set of events we define, and the event groups are primarily concerned that many network operations need to be made before we can connect to the router and get the IP. Connected_bit is the event group bit bit that we define, and this demo type only needs the WiFi connection event.
*

Note.
Event Group flags and WiFi event groups are not a thing, and event group flags are similar to atomic operations, preventing procedural problems due to sequential confusion. The WiFi Event Group is only a certain state of WiFi during the connection process.

*

static esp_err_t event_handler (void *ctx, system_event_t *event) {switch (event->event_id
        ) {case System_event_sta_start:esp_wifi_connect ();
    Break
        Case System_event_sta_got_ip:xeventgroupsetbits (Wifi_event_group, connected_bit);
    Break Case system_event_sta_disconnected:/* This is a workaround as ESP32 WiFi Libs don ' t currently Auto-rea Ssociate.
        */Esp_wifi_connect ();
        Xeventgroupclearbits (Wifi_event_group, connected_bit);
    Break
    Default:break;
} return ESP_OK; }

The

WiFi connection in ESP32 is implemented with several different sets of event handling, which is the event that needs to be processed in connection with WiFi as an STA. Where System_event_sta_start is the initial event state in which the call Esp_wifi_connect () operation is connected to the router (AP) and the event status bit becomes system_event_sta_ when the connection succeeds CONNECTED, the DHCP request IP is called at this time, and the event status becomes more system_event_sta_got_ip after the IP is taken. Here we use the Xeventgroupsetbits, set the event group flag, follow up if you need to get the IP after the operation only need to call Xeventgroupwaitbits to avoid the network interaction before the IP is not available.
After WiFi has been disconnected for some reason, the event flag bit becomes system_event_sta_disconnected, and you need to call Esp_wifi_connect () reconnect and clear the event group flag bit.

static void Initialise_wifi (void) {tcpip_adapter_init ();
    Wifi_event_group = Xeventgroupcreate ();
    Esp_error_check (Esp_event_loop_init (Event_handler, NULL));
    wifi_init_config_t cfg = Wifi_init_config_default ();
    Esp_error_check (Esp_wifi_init (&cfg));
    Esp_error_check (Esp_wifi_set_storage (Wifi_storage_ram)); wifi_config_t wifi_config = {. STA = {. SSID = Example_wifi_ssid,. Password = Example_wifi
    _pass,},};
    Esp_logi (TAG, "Setting WiFi configuration SSID%s ...", WIFI_CONFIG.STA.SSID);
    Esp_error_check (Esp_wifi_set_mode (Wifi_mode_sta));
    Esp_error_check (Esp_wifi_set_config (Esp_if_wifi_sta, &wifi_config));
Esp_error_check (Esp_wifi_start ()); }

The code above is the core code that implements the initialization of WiFi, where Tcpip_adapter_init () is used to initialize the TCP/IP protocol stack, and Xeventgroupcreate () is used to create Event group flags. Esp_event_loop_init (Event_handler, NULL) is used to initialize the event Event_handler, and the callback Event_handler is the various WiFi events we just processed. The Esp_error_check is used to check whether the return value is ESP_OK. Wifi_init_config_default () specifies that the underlying parameter information needs to be initialized, and Esp_wifi_init uses the above information to initialize the WiFi hardware. Esp_wifi_set_storage set up where the connected WiFi information (SSID and password) is stored, optionally with RAM and Flash. Wifi_config is the configuration information when the WiFi connection, as STA only need to consider the STA parameter information, the above code is only the most basic SSID and password information, in addition, you can specify BSSID and channel and other related information. Esp_logi is the formatted output information of Espressif, and the other includes Esp_loge (Error message), ESP_LOGD (debug information). Esp_wifi_set_mode set WiFi mode, including Wifi_mode_ap,wifi_mode_apsta in addition to Wifi_mode_sta. Esp_wifi_set_config sets the configuration information for STA mode. Esp_wifi_start () turn on WiFi based on current configuration information.

void App_main ()
{
    Esp_error_check (Nvs_flash_init ());
    Initialise_wifi ();
}

void App_main () is the entrance to the Espressif project, similar to the main,nvs_flash_init in C, where NVs storage is initialized, and Initialise_wifi is initialized with WiFi. At the back of the program, when you need to implement additional functionality, you can create it using Vtaskcreate.
At this point, the entire connection process for WiFi ends,
AP Implementations

The implementation of the

AP is similar to the implementation of the STA, with only a few configuration information to be changed.

#include "freertos/freertos.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "esp_system.h" # Include "esp_wifi.h" #include "esp_event_loop.h" #include "esp_log.h" #include "nvs_flash.h" const static char *tag = "E

Spressif ";
    static void Initialise_wifi (void) {tcpip_adapter_init ();
    Esp_error_check (esp_event_loop_init (null, NULL));
    wifi_init_config_t cfg = Wifi_init_config_default ();
    Esp_error_check (Esp_wifi_init (&cfg));
    Esp_error_check (Esp_wifi_set_storage (Wifi_storage_ram));
            wifi_config_t wifi_config = {. AP = {. SSID = "Testap",. AuthMode = Wifi_auth_open,
    . max_connection = 3,. Channel = 12,},};
    Esp_logi (TAG, "Setting WiFi configuration SSID%s ...", WIFI_CONFIG.AP.SSID);
    Esp_error_check (Esp_wifi_set_mode (WIFI_MODE_AP));
    Esp_error_check (Esp_wifi_set_config (Wifi_if_ap, &wifi_config));
Esp_error_check (Esp_wifi_start ()); } void App_maIn (void) {Esp_error_check (Nvs_flash_init ());
Initialise_wifi (); }

When you set up an AP, it is roughly similar to the STA, with only a small portion that needs to be changed to AP information.

    Esp_error_check (esp_event_loop_init (null, NULL));

In AP mode, you can use no callback functions, or you can write callbacks to get more information, and you can refer to the definitions in esp_event.h.

    wifi_config_t wifi_config = {
        . AP = {
            . SSID = "Testap",
            . AuthMode = Wifi_auth_open,
            . max_connection = 3,< C6/>.channel = N,
        },
    };

In this demo, I set the SSID to Testap,authmode is open, that is not encrypted, if set to encrypt, also need to add. password. The maximum number of connections supported by the max_connection. Channel is 12. Other parameters can refer to the wifi_ap_config_t definition in esp_wifi_types.h.

    Esp_logi (TAG, "Setting WiFi configuration SSID%s ...", wifi_config.ap.ssid);
    Esp_error_check (Esp_wifi_set_mode (WIFI_MODE_AP));
    Esp_error_check (Esp_wifi_set_config (Wifi_if_ap, &wifi_config));

Wifi_config.ap.ssid Prints the SSID information for the currently configured AP, Esp_wifi_set_mode (WIFI_MODE_AP) is set to AP mode, Esp_wifi_set_config (Wifi_if_ap, &WIFI_CONFIG) Sets the AP according to the current configuration information. After the
is run, connect the test Ssid:testap with your phone, and the following interface appears:

AP Mode is also set successfully.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.