Este basic example showcases como usar PlatformIO con ESP-IDF only (no Arduino) para connect a Wifi en station mode y print Hello world en un loop. Esta based en el basic Hello World example de Ejemplo minimal PlatformIO ESP32 con ESP-IDF C++:
espidf_wifi_hello.cpp
#include <cstdio>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_wifi.h>
#include <esp_log.h>
#include <nvs_flash.h>
#include <esp_netif.h>
#include <esp_event.h>
extern "C" {
void app_main(void);
}
static void NetworkEventHandler(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) {
esp_wifi_connect();
ESP_LOGI("wifi", "Retrying to connect to Wifi...");
} 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("wifi", "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
}
}
void InitNVS() {
// Inicializar NVS
esp_err_t 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);
}
void InitWifi() {
// Inicializar TCP/IP network interface (required para Wi-Fi)
ESP_ERROR_CHECK(esp_netif_init());
// Inicializar el event loop
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
// Inicializar Wi-Fi
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
// Setear Wi-Fi a station mode
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
// Configurar el Wi-Fi connection
wifi_config_t wifi_config = {
.sta = {
.ssid = "MyWifi",
.password = "mypassword"
}
};
// Register event handler
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
ESP_EVENT_ANY_ID,
&NetworkEventHandler,
NULL,
NULL));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
IP_EVENT_STA_GOT_IP,
&NetworkEventHandler,
NULL,
NULL));
// Setear Wi-Fi configuration y start Wi-Fi
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
}
void app_main() {
InitNVS();
InitWifi();
while(true) {
printf("Hello PlatformIO!\n");
// Wait for one second
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}platformio.ini
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = espidf
monitor_speed = 115200All sdkconfig settings have been left at their respective defaults.
Echa un vistazo a artículos similares por categoría:
C/C++ ESP8266/ESP32 PlatformIO
Si este artículo te ha ayudado, considera invitarme a un café o hacer una donación vía PayPal para apoyar la investigación y publicación de nuevos artículos en TechOverflow