Hello,
I made a portable dust meter with ESP8266 that shows the value on the OLED display and sent it to the website thinkspeak. It is okay when I use it at home because there is WiFi but I’ve got a problem when I go outside with no WiFi. Could you please let me know how to write a code for both works with and without the WiFi. Thank you so much. Your E-books are so great.
Sagun Teerapong
Hi Sagun,
Try something like this:
#include <WiFi.h> #include <Arduino.h> const char * SSID = "MY_SSID"; const char * PASSWORD = "MY_PASSWORD"; const uint16_t WIFI_TIMEOUT = 5000; // delay in milliseconds uint32_t start; bool connected; void initSerial() { Serial.begin(115200); delay(1000); } void initPins() { pinMode(LED_BUILTIN, OUTPUT); } void initWiFiConnection() { WiFi.mode(WIFI_MODE_STA); WiFi.begin(SSID, PASSWORD); Serial.print("Trying to connect"); start = millis(); } void waitForWiFiConnection() { while (!(connected = WiFi.status() == WL_CONNECTED) && millis() - start < WIFI_TIMEOUT) { Serial.print("."); delay(100); } Serial.println(); } void printWiFiConnectionDiagnosis() { if (connected) { Serial.printf("Connected to %s after %d ms with IP address: ", SSID, millis() - start); Serial.println(WiFi.localIP()); } else { Serial.printf("Connection failed after %d ms\n", WIFI_TIMEOUT); } } void setup() { initSerial(); initPins(); initWiFiConnection(); waitForWiFiConnection(); printWiFiConnectionDiagnosis(); } void loop() { // built-in LED flashes if the WiFi connection has been established digitalWrite(LED_BUILTIN, connected && (millis() % 1000 < 50) ? HIGH : LOW); }
You can set the timeout as you wish… If the connection is still not established after this delay, the program will resume its normal course. And if the connection has been established, the LED will flash briefly.
Hopefully that’s what you were looking for…
Regards,
Steph