ESP32 as a WiFi Station

 In this post, we will go through an example in which the esp32 connects to a wifi softAP as a station 

The reference code is

https://github.com/espressif/esp-idf/tree/master/examples/wifi/getting_started/station 


The SSID and password is defined at the top 

#define EXAMPLE_ESP_WIFI_SSID      CONFIG_ESP_WIFI_SSID
#define EXAMPLE_ESP_WIFI_PASS      CONFIG_ESP_WIFI_PASSWORD

Here the CONFIG_XXXXX macros are in sdkconfig.h file 


This configuration file is actually modified when you use the $idf.py menuconfig command

So set the SSID and password of your router using menuconfig 


The code uses the default event loop to register and handle the WIFI connection related events 


Initialize the underlying TCP/IP stack using the following function

void tcpip_adapter_init(void);


Initialize wifi_init_config_t type configuration variable by putting the default values and then initialize the wifi stack

wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));


Create the default event loop & Register for WIFI events to the default event loop 

ESP_ERROR_CHECK(esp_event_loop_create_default());

……..

ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL));


Set the SSID and Password to the wifi stack 

    wifi_config_t wifi_config = {
        .sta = {
            .ssid = EXAMPLE_ESP_WIFI_SSID,
            .password = EXAMPLE_ESP_WIFI_PASS
        },
    };


Set the wifi stack as Station Mode and start it 


    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() );


Now as the wifi connection events occur it will get hanlded by the handler function 

static void event_handler(void* arg, 

                          esp_event_base_t event_base,
                          int32_t event_id, 

                          void* event_data)
{
………………….

………………..
}


Compile and flash the program 

~/esp/esp-idf/examples/wifi/getting_started/station$ idf.py -p /dev/ttyUSB0 flash monitor


Check the output log 


0 comments:

Post a Comment

Categories

Pages

Firmware Engineer

My photo
Works on Firmware, Embedded Linux, Smart Metering, RTOS, IoT backend

Contact Form

Name

Email *

Message *

Copyrighted by Hassin. Powered by Blogger.