Switching from WiFi to ESP Now does not change the channel as needed. (esp_wifi_set_channel)

gary.kuipers
Posts: 2
Joined: Tue May 07, 2024 6:00 am

Switching from WiFi to ESP Now does not change the channel as needed. (esp_wifi_set_channel)

Postby gary.kuipers » Tue May 07, 2024 6:13 am

Problem: Switching from WiFi to ESP Now does not change the channel as needed.
Using: ESP32-WROOM-32 board
Question you may have: Why not use the channel of the Wifi? Answer: I cycle through multiple SSIDs to find a path via WiFi. WHen I can't I switch to ESPNow where I have a receiver at a fixed channel (11 in this case)
Important note: THe code below is from a different application which works in ESP Now exclusively. The setup in that program is done inside the setup()


In this testing I set the list of SSIDs to none. What this does is switch the program to ESPnow without trying to communicate via WiFi at all. Note that WiFi is setup in the setup() while switching to ESPnow is handled within the loop()

this is in my setup():

Code: Select all

    WiFi.mode(WIFI_STA);
    WiFi.begin();
    delay(100); // Short delay to ensure WiFi starts
    Serial.print("WiFi Channel: ");
    Serial.println(WiFi.channel());
    WiFi.macAddress(my_mac_as_uint8_t);
    // Convert the MAC address to String format
    char macStr[18];
    snprintf(macStr, sizeof(macStr), "%02X:%02X:%02X:%02X:%02X:%02X", my_mac_as_uint8_t[0], my_mac_as_uint8_t[1],
            my_mac_as_uint8_t[2], my_mac_as_uint8_t[3], my_mac_as_uint8_t[4], my_mac_as_uint8_t[5]);
    my_mac_as_string = String(macStr);
    Serial.print("MAC Address: ");
    Serial.println(my_mac_as_string);



The above prints:
WiFi Channel: 1
MAC Address: 48:E7:29:8B:F1:A0


I go into the loop(). In the loop I see there are no WiFi SSIDs to connect to, so in the loop I decide I do not want to use WiFi any more becasue I cannot get the messages through to the server if there is no SSID to connect to so I want to no longer use WiFi any more at all for the rest of the time this program runs and want to switch exclusively to ESPnow.

Code: Select all

            if (!EspNowHasBeenSetUp) {
                Serial.println("SETUP ESPNOW");
                storage.readStorage();  // Note: storage is programmed by uid_burner.ino
                String peerString = storage.peer;
                Serial.printf("SETUP ESPNOW: storage.channel=%i from storage\n", storage.channel);
                // ESPNOW vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
                Serial.println("SETUP ESPNOW: Disabling WiFi and reinitializing radio");
                WiFi.disconnect();        // Disconnect from any existing WiFi connection
                WiFi.mode(WIFI_OFF); // Ensure WiFi is turned off before setting up ESP-NOW
                btStop(); // Disable Bluetooth if not used, to save power and reduce potential interference
                delay(100);
                if (esp_wifi_stop() != ESP_OK) {  // Stop WiFi driver
                    Serial.println("Warning: WiFi stop failed, might already be stopped");
                }
                if (esp_wifi_deinit() != ESP_OK) {  // Deinitialize WiFi to ensure clean state
                    Serial.println("Warning: WiFi deinit failed, might already be deinitialized or not initialized");
                }
                delay(100);               // Allow some time for deinitialization
                // Initialize WiFi with default configuration only if not already initialized
                wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
                esp_err_t init_status = esp_wifi_init(&cfg);  // Initialize WiFi with the default config
                if (init_status != ESP_OK) {
                    Serial.printf("WiFi Init Error: %d\n", init_status);
                }
                esp_wifi_set_mode(WIFI_MODE_NULL);  // Set mode to null to not start WiFi
                if (esp_wifi_start() != ESP_OK) {  // Start WiFi with no mode set
                    Serial.println("Warning: WiFi start failed, check initialization status");
                }
                Serial.println("SETUP ESPNOW: Initializing");
                bool EspNowSetupOK = false;
                // TODO: guard against infinite loop and failover to LoRa
                while (!EspNowSetupOK) {
                    esp_err_t initResult = esp_now_init();
                    if (initResult == ESP_OK) {
                        Serial.println("ESP-NOW: Initialization successful");
                        int attempts = 5;
                        while (attempts-- > 0) {
                            // Set ESP-NOW channel
                            Serial.printf("SETUP ESPNOW: attempt=%i storage.channel=%i setting up channel\n", attempts, storage.channel);
                            // ?? esp_wifi_set_promiscuous(true);
                            if (esp_wifi_set_channel(storage.channel, WIFI_SECOND_CHAN_NONE) == ESP_OK) {
                                Serial.printf("ESP-NOW channel set to %i\n", storage.channel);
                            } else {
                                Serial.printf("Failed to set ESP-NOW channel to %i\n", storage.channel);
                            }

                            delay(100);
                            Serial.print("SETUP ESPNOW: Current channel after setup ");
                            uint8_t current_channel = Serial.println(WiFi.channel());
                            // ?? esp_wifi_set_promiscuous(false);
                            if (current_channel == storage.channel) {
                                EspNowSetupOK = true;
                            }
                        }
                        if (attempts <= 0) {
                            Serial.println("Failed to set the channel correctly after multiple attempts");
                        }
                    } else {
                        Serial.println("ESP-NOW Initialization failed, retrying...");
                        esp_now_deinit(); // De-initialize if previously initialized
                        delay(200);
                        esp_now_init();
                    }
                }
                Serial.println("SETUP ESPNOW: setup OK");
                esp_now_register_send_cb(OnDataSent);
                esp_now_register_recv_cb(OnDataRecv);
                esp_now_peer_info_t peerInfo;
                memset(&peerInfo, 0, sizeof(esp_now_peer_info_t));
                memcpy(peerInfo.peer_addr, EGWmacBytes, 6);
                peerInfo.channel = storage.channel;
                peerInfo.encrypt = false;
                esp_now_add_peer(&peerInfo);

                WiFi.macAddress(myMacBytes);
                peerString.toCharArray(EGWmacChars, sizeof(EGWmacChars));
                EGWmacChars[sizeof(EGWmacChars) - 1] = '\0';
                macBytesToMacChars(myMacBytes, myMacChars);
                macCharsToMacBytes(EGWmacChars, EGWmacBytes);
                Serial.printf("SETUP ESPNOW: myMacChars=%s EGWmacChars=%s\n", myMacChars, EGWmacChars);

prints:

SETUP ESPNOW
SETUP ESPNOW: storage.channel=11 from storage
SETUP ESPNOW: Disabling WiFi and reinitializing radio
Warning: WiFi stop failed, might already be stopped
E (30134) wifi_init: Failed to deinit Wi-Fi driver (0x3001)
Warning: WiFi deinit failed, might already be deinitialized or not initialized
SETUP ESPNOW: Initializing
ESP-NOW: Initialization successful
SETUP ESPNOW: attempt=4 storage.channel=11 setting up channel
ESP-NOW channel set to 11
SETUP ESPNOW: Current channel after setup 0
SETUP ESPNOW: attempt=3 storage.channel=11 setting up channel
ESP-NOW channel set to 11
SETUP ESPNOW: Current channel after setup 0
SETUP ESPNOW: attempt=2 storage.channel=11 setting up channel
ESP-NOW channel set to 11
SETUP ESPNOW: Current channel after setup 0
SETUP ESPNOW: attempt=1 storage.channel=11 setting up channel
ESP-NOW channel set to 11
SETUP ESPNOW: Current channel after setup 0
SETUP ESPNOW: attempt=0 storage.channel=11 setting up channel
ESP-NOW channel set to 11

gary.kuipers
Posts: 2
Joined: Tue May 07, 2024 6:00 am

Re: Switching from WiFi to ESP Now does not change the channel as needed. (esp_wifi_set_channel)

Postby gary.kuipers » Thu May 09, 2024 1:03 pm

SOLVED:

The section of code:

Code: Select all

        uint8_t current_channel;
        esp_wifi_get_channel(&current_channel, NULL);
        if (current_channel == storage.channel) {
            Serial.printf("Channel verification successful: Current channel is %d\n", current_channel);
        } else {
            Serial.printf("Channel verification failed: Expected %d, but got %d\n", storage.channel, current_channel);
        }
esp_wifi_get_channel(&current_channel, NULL);

Returns an incorrect channel.

The channel has, in fact, been changed and the communications to other ESP32s on that channel function.

Who is online

Users browsing this forum: No registered users and 39 guests