Cannot connect to WIFI

ZhengLinLei
Posts: 2
Joined: Wed Mar 27, 2024 11:22 am

Cannot connect to WIFI

Postby ZhengLinLei » Mon Apr 15, 2024 8:01 pm

I'm getting some troubles with my code trying to connect to one Wifi station. I tried changing everything, copied samples from everywhere and nothing worked. The hardware works correctly, because I tried the Arduino IDE Code and it worked

Code of the handler:

Code: Select all

/* FreeRTOS event group to signal when we are connected*/
static EventGroupHandle_t s_wifi_event_group;

/* The event group allows multiple bits for each event, but we only care about two events:
 * - we are connected to the AP with an IP
 * - we failed to connect after the maximum amount of retries */
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT      BIT1

static int s_retry_num = 0;


static void wifi_event_handler(void* arg, esp_event_base_t event_base,
                                int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        esp_wifi_connect();
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
        if (s_retry_num < WIFI_ESP_MAXIMUM_RETRY) {
            esp_wifi_connect();
            s_retry_num++;

#ifdef VERBOSE
            printf("Retry to connect to the AP");
#endif
        } else {
            xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
        }

#ifdef VERBOSE
        printf("Connect to the AP fail");
#endif
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;

#ifdef VERBOSE
        printf("Got ip:" IPSTR, IP2STR(&event->ip_info.ip));
#endif

        s_retry_num = 0;
        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
    }
}

The connect function:

Code: Select all

int wifi_connect(uint8_t* ssid, uint8_t* password) {
    nvs_flash_init();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&cfg);
    s_wifi_event_group = xEventGroupCreate();

    static wifi_config_t wifi_config = {
        .sta = {
            .ssid = "",
            .password = "",
        },
    };

    strcpy((char*)wifi_config.sta.ssid, (const char*)ssid); // copy chars from hardcoded configs to struct
    strcpy((char*)wifi_config.sta.password, (const char*)password);

#ifdef VERBOSE
    printf("SSID: %s\n", wifi_config.sta.ssid);
    printf("Password: %s\n", wifi_config.sta.password);
#endif

    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler, NULL);
    esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, wifi_event_handler, NULL);

    esp_wifi_set_mode(WIFI_MODE_STA);
    esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config);
    esp_wifi_start();

    esp_wifi_connect();

#ifdef VERBOSE
    printf("Connecting to %s\n", ssid);
#endif

    EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, pdFALSE, pdFALSE, WIFI_ESP_CONN_TIMEOUT);

    esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, wifi_event_handler);
    esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler);

    if (bits & WIFI_CONNECTED_BIT) {
#ifdef VERBOSE
        printf("Connected to ssid:%s, password:%s\n", ssid, password);
#endif
        return 0;
    } else if (bits & WIFI_FAIL_BIT) {
#ifdef VERBOSE
        printf("Failed to connect to ssid:%s, password:%s\n", ssid, password);
#endif
        return 1;
    } else {
#ifdef VERBOSE
        printf("Error connecting. Reset 0x00\n");
#endif
        return -1;
    }
}


And the logs:

Code: Select all

SSID: JM_limpia_el_baño
Password: LaTienesEnElRouter
Connecting to JM_limpia_el_baño
Error connecting. Reset 0x00
Function return: 2;

Any printf from wifi_event_handler are printed, I do not know if the problem is that I did not register the handler correctly or if I have something wrong in my code.



Thanks for helping me!!

I tried different version of codes from internet, ChatGPT, idf github and nothing worked :cry:

chegewara
Posts: 2333
Joined: Wed Jun 14, 2017 9:00 pm

Re: Cannot connect to WIFI

Postby chegewara » Tue Apr 16, 2024 6:14 pm

What is this value

Code: Select all

WIFI_ESP_CONN_TIMEOUT

mtraven
Posts: 28
Joined: Thu Jul 07, 2022 3:34 am

Re: Cannot connect to WIFI

Postby mtraven » Tue Apr 16, 2024 10:19 pm

I'm going to assume you're usuing IDF ~5.2ish? please correct me if thats not the case, wifi is different in 4.4.7.

I struggled with this a few weeks ago, my advice:

up your log levels to at least debug, if not verbose. there is ALOT happening that you're not seeing in the logs with it set at INFO. You may find you want to turn off the verbose/debug for things other than wifi. you can do that with esp_log_level_set(tag, ESP_LOG_XXXX);

On that note, I recognize that #if (printf) style, I've used debugs like that for years. In some circumstances, I still do. You'd be wise to familiarize yourself with ESP_LOG(), it does everything you're doing, in a cleaner package. you write them the same as a printf (it uses printf), with a lead term "tag"--a const char* string. That categorizes your debug statements, both on screen & st you can manipulate levels of different things.

lastly, you're missing some stuff from your connect. Here is a file I made as a helper header (iNeedWifi.h) to get wifi. Its largley based on ESP examples, but not the example_connect() crap. do as you like with it. I'd compare your init stuff to mine, pay attention to the event loop & the config structure. My SSID and such as pulled from Kcofig, but you can define them directly the way you did in your code. at first glance, I didn't see these lines in your code:

Code: Select all

 (esp_event_loop_create_default());
    esp_netif_create_default_wifi_sta();
did I miss them?


here is my code: NOTE: i dont initiated NVS with wifi, its assumed to already be initiated in the app, prior to calling

Code: Select all

#ifndef INEEDWIFI_H
#define INEEDWIFI_H

 /// AUTH: MODE: (un comment 1 & put it in main with SSID & PASSWORD)
    
    // 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_ENTERPRISE,       /**< authenticate mode : WiFi EAP security */
    //WIFI_AUTH_WPA2_ENTERPRISE = WIFI_AUTH_ENTERPRISE,  /**< authenticate mode : WiFi EAP security */
    //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_OWE,              /**< authenticate mode : OWE */
    //WIFI_AUTH_WPA3_ENT_192,     /**< authenticate mode : WPA3_ENT_SUITE_B_192_BIT */
    //WIFI_AUTH_WPA3_EXT_PSK,     /**< authenticate mode : WPA3_PSK_EXT_KEY */
    //WIFI_AUTH_WPA3_EXT_PSK_MIXED_MODE, /**< authenticate mode: WPA3_PSK + WPA3_PSK_EXT_KEY */
    //WIFI_AUTH_MAX

    
///////////////////////////////////////////////
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_wifi_types.h"

#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "lwip/err.h"
#include "lwip/sys.h"

#define wifiTxPWR WIFI_POWER_5dBm
EventGroupHandle_t s_wifi_event_group; /* FreeRTOS event group to signal when we are connected*/

#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT      BIT1

static const char *TAG_wifi = "my_wifi_sta";

static int s_retry_num = 0;

/// prototyes: /////////////////////////
void event_handler(void* arg, esp_event_base_t event_base,int32_t event_id, void* event_data);
void wifi_init_sta(void);
void stopWifi(); 
////////////////////////////////////////
void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) 
    {
        esp_wifi_connect();
    } 
    else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) 
    {
        if (s_retry_num < MAXIMUM_RETRY) 
        {
            esp_wifi_connect();
            s_retry_num++;
            ESP_LOGW(TAG_wifi, "\n\n----------------------\n connect retry #%i \n------------------\n", s_retry_num);
        } 
        else 
        {
            xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
        }
        ESP_LOGI(TAG_wifi,"connect to the AP fail");
    } 
    else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) 
    {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        ESP_LOGI(TAG_wifi, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
        s_retry_num = 0;
        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
    }
}

void wifi_init_sta(void) //NVS ASSUMED TO BE INITITATED
{
    ESP_LOGW("TAG_wifi", "initiating wifi...");
    s_wifi_event_group = xEventGroupCreate();
    ESP_ERROR_CHECK(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,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_any_id));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
                                                        IP_EVENT_STA_GOT_IP,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_got_ip));
    wifi_config_t wifi_config = 
    {
        .sta = {
                .ssid = SSID,
                .password = WIFI_PASS,
                .scan_method= WIFI_FAST_SCAN,                  
                .channel=11,
                .threshold={.authmode = WIFI_AUTH_MODE},
                .sae_pwe_h2e = wifi_sae_pwe_method_t(WPA3_SAE_PWE_BOTH),
                .failure_retry_cnt=5,
                .sae_h2e_identifier = "",
                },
    };
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );
    ESP_ERROR_CHECK(esp_wifi_start() );
   
    ESP_LOGI(TAG_wifi, "wifi_init_sta finished. ");
    /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
     * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
    EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
            WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
            pdFALSE,
            pdFALSE,
            portMAX_DELAY);

    /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
     * happened. */
    if (bits & WIFI_CONNECTED_BIT) 
        ESP_LOGI(TAG_wifi, "connected to ap SSID:%s password:%s",SSID, WIFI_PASS);
    else if (bits & WIFI_FAIL_BIT) 
        ESP_LOGI(TAG_wifi, "Failed to connect to SSID:%s, password:%s",SSID, WIFI_PASS);
    else 
        ESP_LOGE(TAG_wifi, "UNEXPECTED EVENT");
    /* The event will not be processed after unregister */
    ESP_ERROR_CHECK(esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip));
    ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id));
    vEventGroupDelete(s_wifi_event_group);
}

void stopWifi()
{
     esp_wifi_disconnect();

}


#endif  // INEEDWIFI_H

Who is online

Users browsing this forum: MicroController and 69 guests