Basic wifi setup for esp32 and esp8266

This commit is contained in:
Florian Hoss 2022-07-21 13:34:24 +02:00
parent 798f0dec03
commit 5067438b9d
2 changed files with 42 additions and 58 deletions

View file

@ -9,10 +9,17 @@
; https://docs.platformio.org/page/projectconf.html ; https://docs.platformio.org/page/projectconf.html
[platformio] [platformio]
default_envs = esp32 default_envs = esp8266
[env:esp32] [env:esp32]
platform = espressif32 platform = espressif32
board = esp32dev board = esp32dev
framework = arduino framework = arduino
monitor_speed = 115200 monitor_speed = 115200
[env:esp8266]
platform = espressif8266
board = d1_mini
framework = arduino
monitor_speed = 115200

View file

@ -1,72 +1,49 @@
#include <Arduino.h> #include <Arduino.h>
#include "WiFi.h"
#include "theSecrets.h" #include "theSecrets.h"
#include "freertos/FreeRTOS.h" #ifdef ESP32
#include "freertos/task.h" #include "WiFi.h"
#include "esp_wifi.h" #elif defined(ESP8266)
#include "esp_event.h" #include "ESP8266WiFi.h"
#include "nvs_flash.h" #define LED 2
#include "lwip/err.h" #define DELAY 2000
#include "lwip/sockets.h" #endif
#include "lwip/sys.h"
#include <lwip/netdb.h>
void connectToWifi() void toggleLED()
{ {
WiFi.begin(ssid, psk); if (digitalRead(LED) == LOW)
while (WiFi.status() != WL_CONNECTED) digitalWrite(LED, HIGH);
{ else
delay(200); digitalWrite(LED, LOW);
}
}
void handle_wifi_events(WiFiEvent_t event, WiFiEventInfo_t info)
{
Serial.print("[WiFi] ");
switch (event)
{
case ARDUINO_EVENT_WIFI_STA_START:
Serial.printf("Attempting to connect to WPA SSID: %s\n", ssid);
break;
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
Serial.println("connected");
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println("disconnected");
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
break;
default:
Serial.println(event);
}
}
void setup_wifi()
{
WiFi.mode(WIFI_STA);
WiFi.onEvent(handle_wifi_events, ARDUINO_EVENT_MAX);
connectToWifi();
}
static void intercept_task(void *pvParameters)
{
Serial.println("Intercept");
vTaskDelete(NULL);
} }
void setup() void setup()
{ {
ESP_ERROR_CHECK(nvs_flash_init()); #ifdef ESP8266
ESP_ERROR_CHECK(esp_netif_init()); pinMode(LED, OUTPUT);
ESP_ERROR_CHECK(esp_event_loop_create_default()); #endif
Serial.begin(115200); Serial.begin(115200);
setup_wifi(); Serial.println();
xTaskCreate(intercept_task, "intercept", 4096, (void *)AF_INET, 5, NULL); WiFi.begin(ssid, psk);
while (!WiFi.isConnected())
{
#ifdef ESP8266
toggleLED();
#endif
Serial.print(".");
delay(200);
}
Serial.println();
Serial.print("IP: ");
Serial.println(WiFi.localIP());
} }
void loop() void loop()
{ {
#ifdef ESP8266
digitalWrite(LED, LOW);
delay(DELAY);
digitalWrite(LED, HIGH);
delay(DELAY);
#endif
} }