ESP32 : Connecting to WiFi network

There is no fun in IoT without a network connection. Lets connect our ESP32 to a WiFi access point.

In this post we will connect to given SSID and print the IP of the ESP32

The WiFi Driver provided in  ESP-IDF , communicates to the user code through events and callbacks. When ever there is change in the WiFi state , the WiFi driver will call the event handler ( that was added using esp_event_loop_init ) with the specific event  , we can write a switch to find the event that is occured take appropriate action.

WiFi  driver Events :

All the events are defined in esp_event.h file

esp32 wifi events
esp32 wifi events

First we need initialize the WiFi driver , call initialise_wifi() method from main, and register the event handler. Once Station is ready call wifi_connect() method.

Connection Flow :

esp32 wifi connection
esp32 wifi connection
void wifi_connect(){
 wifi_config_t cfg = {
 .sta = {
 .ssid = SSID,
 .password = PASSPHARSE,
 },
 };
 ESP_ERROR_CHECK( esp_wifi_disconnect() );
 ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_STA, &cfg) );
 ESP_ERROR_CHECK( esp_wifi_connect() );
}

static esp_err_t event_handler(void *ctx, system_event_t *event)
{
  switch(event->event_id) {
    case SYSTEM_EVENT_STA_START:
      wifi_connect();
      break;
   case SYSTEM_EVENT_STA_GOT_IP:
      xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
      break;
   case SYSTEM_EVENT_STA_DISCONNECTED:
      esp_wifi_connect();
      xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
      break;
   default:
      break;
  }
 return ESP_OK;
}

static void initialise_wifi()
{
 esp_log_level_set("wifi", ESP_LOG_NONE); // disable wifi driver logging
 tcpip_adapter_init();
 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
 ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
 ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
 ESP_ERROR_CHECK( esp_wifi_start() );
}

We are using the Event Groups to synchronize other tasks that are waiting for WiFi connection, in this case “printWiFiIP” task is waiting for the IP. For more on Event Groups check this post

full code is available on git repo

 

One Comment

Add a Comment

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