WiFi not connected in ESP-IDF?

295 views Asked by At

I'm trying to create an ESP32 application using ESP-IDF framework. I am new to ESP-IDF and Embedded C.

This is main.c file

#include <stdio.h>
#include "esp_log.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "aht25_driver.h"
#include "lwip/inet.h"

#define WIFI_SSID "K"
#define WIFI_PASS "kuralmozhi"

// Event group for Wi-Fi events
static EventGroupHandle_t wifi_event_group;

// Bit to indicate that Wi-Fi is connected
static const int CONNECTED_BIT = BIT0;

// Define the TAG for ESP-IDF logging
static const char *TAG = "AHT25_SENSOR";

void wifi_event_handler(void* arg, esp_event_base_t 
   event_base, int32_t event_id, void* event_data) {
   if (event_id == WIFI_EVENT_STA_START) {
      ESP_LOGI(TAG, "Connecting to Wi-Fi...");
      esp_wifi_connect();
   } else if (event_id == WIFI_EVENT_STA_CONNECTED) {
      ESP_LOGI(TAG, "Wi-Fi connected");
   } else if (event_id == WIFI_EVENT_STA_DISCONNECTED) {
       ESP_LOGI(TAG, "Wi-Fi disconnected");
       esp_wifi_connect();
   }
 }

void ip_event_handler(void* arg, esp_event_base_t 
   event_base, int32_t event_id, void* event_data) {
   if (event_id == IP_EVENT_STA_GOT_IP) {
    ip_event_got_ip_t* event = (ip_event_got_ip_t*)event_data;

    // Convert IP address to string format using ip4addr_ntoa
    char ip_address[16]; // Buffer to store IP address string
    inet_ntoa_r(event->ip_info.ip, ip_address, sizeof(ip_address));

    ESP_LOGI(TAG, "Got IP address: %s", ip_address);
    xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
}
}

void app_main(void)
{
   esp_log_level_set(TAG, ESP_LOG_DEBUG); // or ESP_LOG_INFO for less verbose logs

  ESP_LOGI(TAG, "Wi-Fi SSID: %s", WIFI_SSID);
ESP_LOGI(TAG, "Wi-Fi Password: %s", WIFI_PASS);

esp_err_t ret;

// Initialize NVS
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);

// Create Wi-Fi event group
wifi_event_group = xEventGroupCreate();

// Initialize Wi-Fi
esp_netif_init();
esp_event_loop_create_default();
esp_netif_create_default_wifi_sta();

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

esp_event_handler_instance_t instance_any_id;
esp_event_handler_instance_t instance_got_ip;
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
                                                    ESP_EVENT_ANY_ID,
                                                    &wifi_event_handler,
                                                    NULL,
                                                    &instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
                                                    IP_EVENT_STA_GOT_IP,
                                                    &ip_event_handler,
                                                    NULL,
                                                    &instance_got_ip));

ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
wifi_config_t wifi_config = {
    .sta = {
        .ssid = WIFI_SSID,
        .password = WIFI_PASS,
    },
};
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());

// Wait for Wi-Fi connection
ESP_LOGI(TAG, "Waiting for Wi-Fi connection...");
EventBits_t bits = xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
                                       pdFALSE, pdTRUE, portMAX_DELAY);
if (bits & CONNECTED_BIT) {
    // Wi-Fi connected and got IP address
    ESP_LOGI(TAG, "Connected to Wi-Fi");

    // Get IP address information
    esp_netif_ip_info_t ip_info;
    esp_netif_t *sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
    ESP_ERROR_CHECK(esp_netif_get_ip_info(sta_netif, &ip_info));

    // Initialize AHT25 sensor
    i2c_port_t i2c_num = I2C_NUM_0;
    ret = aht25_init(i2c_num);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "AHT25 sensor initialization failed. Error code: 0x%X", ret);
        return; // Return from app_main as we cannot proceed without a working sensor
    }

    AHT25Data sensor_data;
    ret = aht25_read_data(i2c_num, &sensor_data);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "AHT25 sensor read failed. Error code: 0x%X", ret);
        return; // Return from app_main as we cannot proceed without valid data
    }

    // Prepare JSON data
    char ip_address[16]; // Buffer to store IP address string
    snprintf(ip_address, sizeof(ip_address), IPSTR, IP2STR(&ip_info.ip));
    char json_data[100];
    snprintf(json_data, sizeof(json_data), "{\"ip\": \"%s\", \"temperature\": %.2f, \"humidity\": %.2f}",
             ip_address, sensor_data.temperature, sensor_data.humidity);

    // Display JSON data or send it to a server
    ESP_LOGI(TAG, "JSON data: %s", json_data);
} else {
    ESP_LOGE(TAG, "Failed to connect to Wi-Fi");
}

while (1) {
    vTaskDelay(1000 / portTICK_PERIOD_MS); // Delay for 1 second
}
}

aht_driver.c

#include "aht25_driver.h"

static esp_err_t aht25_write_cmd(i2c_port_t i2c_num, 
  uint8_t cmd)
{
  i2c_cmd_handle_t cmd_handle = 
  i2c_cmd_link_create();
  i2c_master_start(cmd_handle);
  i2c_master_write_byte(cmd_handle, AHT25_I2C_ADDR << 
        1 | I2C_MASTER_WRITE, true);
  i2c_master_write_byte(cmd_handle, cmd, true);
  i2c_master_stop(cmd_handle);

  esp_err_t ret = i2c_master_cmd_begin(i2c_num, cmd_handle, 1000 / portTICK_PERIOD_MS);
  i2c_cmd_link_delete(cmd_handle);

  return ret;
 }

 static esp_err_t aht25_read_data_internal(i2c_port_t 
     i2c_num, AHT25Data *data)
 {
   uint8_t buf[6];
   i2c_cmd_handle_t cmd_handle = 
       i2c_cmd_link_create();
   i2c_master_start(cmd_handle);
   i2c_master_write_byte(cmd_handle, AHT25_I2C_ADDR 
     << 1 | I2C_MASTER_WRITE, true);
   i2c_master_write_byte(cmd_handle, AHT25_CMD_MEASURE, true);
   i2c_master_stop(cmd_handle);

   esp_err_t ret = i2c_master_cmd_begin(i2c_num, cmd_handle, 1000 / portTICK_PERIOD_MS);
   if (ret != ESP_OK) {
      i2c_cmd_link_delete(cmd_handle);
      return ret;
   }

   vTaskDelay(100 / portTICK_PERIOD_MS); // Wait for measurement to complete

   i2c_cmd_handle_t cmd_handle_read = 
    i2c_cmd_link_create();
    i2c_master_start(cmd_handle_read);
   i2c_master_write_byte(cmd_handle_read, AHT25_I2C_ADDR << 1 | I2C_MASTER_READ, true);
   i2c_master_read(cmd_handle_read, buf, sizeof(buf) - 1, I2C_MASTER_ACK);
   i2c_master_read_byte(cmd_handle_read, buf + sizeof(buf) - 1, I2C_MASTER_NACK);
   i2c_master_stop(cmd_handle_read);

   ret = i2c_master_cmd_begin(i2c_num, cmd_handle_read, 1000 / portTICK_PERIOD_MS);
   i2c_cmd_link_delete(cmd_handle);
   i2c_cmd_link_delete(cmd_handle_read);

    if (ret != ESP_OK) {
       return ret;
    }

    data->humidity = ((uint32_t)buf[1] << 12) | ((uint32_t)buf[2] << 4) | ((uint32_t)buf[3] & 0x0F);
    data->humidity = (100.0 * data->humidity) / 0x1000000;

    data->temperature = ((uint32_t)buf[3] & 0xF0) | ((uint32_t)buf[4] << 4) | (uint32_t)buf[5];
    data->temperature = (200.0 * data->temperature) / 0x1000000 - 50.0;

    return ESP_OK;
 }

  esp_err_t aht25_init(i2c_port_t i2c_num)
 {
   esp_err_t ret = aht25_write_cmd(i2c_num, AHT25_CMD_SOFT_RST);
   if (ret != ESP_OK) {
      return ret;
     }

vTaskDelay(100 / portTICK_PERIOD_MS);

ret = aht25_write_cmd(i2c_num, AHT25_CMD_INIT);
if (ret != ESP_OK) {
    return ret;
}

return ESP_OK;
}

 esp_err_t aht25_read_data(i2c_port_t i2c_num, AHT25Data *data)
 {
    return aht25_read_data_internal(i2c_num, data);
 }

aht_driver.h

#ifndef AHT25_DRIVER_H
#define AHT25_DRIVER_H

#include "driver/i2c.h"

#define AHT25_I2C_ADDR     0x38
#define AHT25_CMD_INIT     0xE1
#define AHT25_CMD_MEASURE  0xAC
#define AHT25_CMD_SOFT_RST 0xBA

typedef struct {
   float temperature;
   float humidity;
} AHT25Data;

esp_err_t aht25_init(i2c_port_t i2c_num);
esp_err_t aht25_read_data(i2c_port_t i2c_num, AHT25Data *data);

#endif /* AHT25_DRIVER_H */

There are no errors in my code by it doesn't connect to the wifi.

enter image description here

even I change my router 3 times.It shows the same error. I am new to ESP-IDF. Can anyone solve this error?

1

There are 1 answers

0
Yoni Code On

I have used your code and it connects perfectly. I removed the sensor configuration but should connect anyway.

I (472) cpu_start: Starting scheduler on PRO CPU.
I (0) cpu_start: Starting scheduler on APP CPU.
I (482) AHT25_SENSOR: Wi-Fi SSID: SSID
I (492) AHT25_SENSOR: Wi-Fi Password: Password
I (532) wifi:wifi driver task: 3ffc177c, prio:23, stack:6656, core=0
I (532) system_api: Base MAC address is not set
I (532) system_api: read default base MAC address from EFUSE
I (552) wifi:wifi firmware version: eb52264
I (552) wifi:wifi certification version: v7.0
I (552) wifi:config NVS flash: enabled
I (552) wifi:config nano formating: disabled
I (552) wifi:Init data frame dynamic rx buffer num: 32
I (562) wifi:Init management frame dynamic rx buffer num: 32
I (562) wifi:Init management short buffer num: 32
I (572) wifi:Init dynamic tx buffer num: 32
I (572) wifi:Init static rx buffer size: 1600
I (572) wifi:Init static rx buffer num: 10
I (582) wifi:Init dynamic rx buffer num: 32
I (582) wifi_init: rx ba win: 6
I (582) wifi_init: tcpip mbox: 32
I (592) wifi_init: udp mbox: 6
I (592) wifi_init: tcp mbox: 6
I (602) wifi_init: tcp tx win: 5744
I (602) wifi_init: tcp rx win: 5744
I (602) wifi_init: tcp mss: 1440
I (612) wifi_init: WiFi IRAM OP enabled
I (612) wifi_init: WiFi RX IRAM OP enabled
I (662) phy_init: phy_version 4670,719f9f6,Feb 18 2021,17:07:07
I (752) wifi:mode : sta (40:22:d8:e8:ca:8c)
I (752) wifi:enable tsf
I (762) AHT25_SENSOR: Waiting for Wi-Fi connection...
I (762) AHT25_SENSOR: Connecting to Wi-Fi...
I (962) wifi:new:<13,0>, old:<1,0>, ap:<255,255>, sta:<13,0>, prof:1
I (1712) wifi:state: init -> auth (b0)
I (1722) wifi:state: auth -> assoc (0)
I (1732) wifi:state: assoc -> run (10)
I (1752) wifi:connected with SSID, aid = 14, channel 13, BW20, bssid = 00:00:00:00:00:00
I (1752) wifi:security: WPA2-PSK, phy: bgn, rssi: -35
I (1782) wifi:pm start, type: 1

I (1782) wifi:AP's beacon interval = 204800 us, DTIM period = 2
I (1782) AHT25_SENSOR: Wi-Fi connected
I (5022) esp_netif_handlers: sta ip: 192.168.1.30, mask: 255.255.255.0, gw: 192.168.1.1
I (5022) AHT25_SENSOR: Got IP address: 192.168.1.30
I (5022) AHT25_SENSOR: Connected to Wi-Fi