Approach for use ADC2 and Wifi on ESP32
Posted: Tue Nov 18, 2025 7:34 pm
Hello, this is my first post here. I am firmware programmer for years and I want to ask if there is a well-know way to use ADC2 and Wifi on a standar ESP32. I know there is not possible simultaneusly because the design of the wifi core but I would like to have an procedure trying to stop wifi, use adc2, and the reinit the wifi. In my mind seems ok, but in my implementation it is not working. In fact, in my current project I do not need to have wifi permantly on, just turn on when needed to send some data and then stop but I really need to have adc2 as much time as possible...
I tried this in 5.4, 5.5 and the newer 6.0 versions of idf:
if I do something like this, it fails on the second InitWifi, rebooting:
Any ideas?
Best regards!
I tried this in 5.4, 5.5 and the newer 6.0 versions of idf:
Code: Select all
void InitWiFi() {
const wifi_init_config_t wifi_init_config = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&wifi_init_config));
esp_netif_config_t netif_config = ESP_NETIF_DEFAULT_WIFI_STA();
esp_netif_t *netif = esp_netif_new(&netif_config);
assert(netif);
ESP_ERROR_CHECK(esp_netif_attach_wifi_station(netif));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, ip_event_t::IP_EVENT_STA_GOT_IP, &on_got_ip, NULL));
ESP_ERROR_CHECK(esp_wifi_set_default_wifi_sta_handlers());
ESP_ERROR_CHECK(esp_wifi_set_storage(wifi_storage_t::WIFI_STORAGE_RAM));
wifi_config_t wifi_config;
memset(&wifi_config, 0, sizeof(wifi_config));
strncpy(reinterpret_cast<char*>(wifi_config.sta.ssid), WIFI_SSID, strlen(WIFI_SSID) + 1);
strncpy(reinterpret_cast<char*>(wifi_config.sta.password), WIFI_PASSWORD, strlen(WIFI_PASSWORD) + 1);
ESP_LOGI("MAIN", "Connecting to %s...", wifi_config.sta.ssid);
ESP_ERROR_CHECK(esp_wifi_set_mode(wifi_mode_t::WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(wifi_interface_t::WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_ERROR_CHECK(esp_wifi_connect());
}
void StopWifi() {
ESP_ERROR_CHECK(esp_wifi_disconnect());
ESP_ERROR_CHECK(esp_wifi_stop());
ESP_ERROR_CHECK(esp_wifi_deinit());
}
void read_adc2(void)
{
adc_init();
vbat=Vbat_meas();
vcc=Vcc_meas();
ESP_ERROR_CHECK(adc_oneshot_del_unit(adc2_handle));
}Code: Select all
read_adc2(); // first ac2 readings ok
InitWiFi();
.... wait IP...
.... IP is ok...
... do some stuff
StopWifi();
read_adc2(); // this second adc2 reading is succesful
InitWifi(); // this second InitWifi causes rebooting the board.Best regards!