Uno R4 quits being connected to Wifi after random amount of time?

I'm just getting started so I thought I'd try to build my own weather station/post weather readings to PWS Weather.

My issue is not with the readings but rather after some seemingly random amount of time the Uno looses it's connection to wifi...or at least that's my assumption.

Code below but when it quits logging to PWS Weather if I hook the IDE up to it to see what prints to the console it prints the temp/pressure etc readings accurately but then says connection failed. Seems to happen randomly - nothing else in my house disconnects from wifi...and oddly it doesn't seem to reconnect without a power cycle of the Uno. Could this be an code/Uno problem or some sort of issue with my wifi (I don't have a short lease time set).

// BME280 Sensor and Wi-Fi Setup
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <WiFiS3.h>
const int bmePowerPin = 3; // Define a GPIO pin to control BME280 power

Adafruit_BME280 bme;  // I2C
WiFiClient client;

// Replace with your network credentials
const char* ssid     = SECRET_SSID;
const char* password = SECRET_PASS;

// PWSweather details
const char* pws_server = "www.pwsweather.com";
const char* pws_api = SECRET_API;
const char* pws_pwsID = SECRET_STATION;

#define EXE_INTERVAL 300000 // rapid fire 2.5 seconds is 2500, normal is 5 min or 300000
unsigned long lastExecutedMillis = 0; // variable to save the last executed time

void setup() {
// Initialize Serial Communication
Serial.begin(9600);

// BME280 power control pin initialization
pinMode(bmePowerPin, OUTPUT);
digitalWrite(bmePowerPin, LOW); // Ensure BME280 is off initially


// Connect to Wi-Fi
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
  
}

void loop() {

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Disconnected from WiFi, reconnecting...");
    WiFi.disconnect();
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(1000);
      Serial.println("Reconnecting to WiFi...");
    }
    Serial.println("Reconnected to WiFi");
  }
  unsigned long currentTime = millis();

  // BME280 Sensor Reading and Data Transmission
  if (currentTime - lastExecutedMillis >= EXE_INTERVAL) {
  lastExecutedMillis = currentTime; // save the last executed time

  // Power on the BME280
  digitalWrite(bmePowerPin, HIGH);
  delay(100); // Wait for the sensor to stabilize

  // Initialize BME280 sensor
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    digitalWrite(bmePowerPin, LOW); // Power off the BME280
    while (1);
  }

  // Read sensor data
  float temperature = bme.readTemperature();
  float humidity = bme.readHumidity();
  float pressure = bme.readPressure() / 100.0F;
  float dewPoint = calculateDewPoint(temperature, humidity);

  // Power off the BME280 after reading
  digitalWrite(bmePowerPin, LOW);
    
  // Print data to Serial Monitor
  Serial.print("Temperature = ");
  Serial.print(temperature);
  Serial.println(" °C");

  Serial.print("Humidity = ");
  Serial.print(humidity);
  Serial.println(" %");

  Serial.print("Pressure = ");
  Serial.print(pressure);
  Serial.println(" hPa");

  Serial.print("Dew Point = ");
  Serial.print(dewPoint);
  Serial.println(" °C");

// Send data to PWSWeather
    if (client.connect(pws_server, 80)) {
      Serial.println("Connected to server");
      
      String pws_url = "/pwsupdate/pwsupdate.php?";
      pws_url += "ID=" + String(pws_pwsID);
      pws_url += "&PASSWORD=" + String(pws_api);
      pws_url += "&dateutc=now";
      pws_url += "&tempf=" + String(temperature * 9.0 / 5.0 + 32.0); // Convert C to F
      pws_url += "&humidity=" + String(humidity);
      pws_url += "&baromin=" + String(pressure * 0.02952998751); // Convert hPa to inHg
      pws_url += "&dewptf=" + String(dewPoint * 1.8 + 32); // Convert °C to °F
      //pws_url += "&rainin=" + String(totalRainLast60Min);  // rain in last hour
      //pws_url += "&dailyrainin=" + String(totalRainfallToday);  // total rain today
      pws_url += "&softwaretype=ArduinoUnoR4WiFi";
      pws_url += "&action=updateraw";

      Serial.print("Requesting URL: ");
      Serial.println(pws_url);

      client.print(String("GET ") + pws_url + " HTTP/1.1\r\n" +
                   "Host: " + pws_server + "\r\n" + 
                   "Connection: close\r\n\r\n");
      delay(1000);

      // Read all the lines of the reply from server and print them to Serial
      while (client.available()) {
        String line = client.readStringUntil('\r');
        Serial.print(line);
      }

      // Stop the client
      client.stop();
      Serial.println();
      Serial.println("Data sent to PWSWeather");
      Serial.println();
    } else {
      Serial.println("Connection failed");
      Serial.println();
    }
}
}


//Functions

float calculateDewPoint(float tempC, float humidity) {
  // Calculate the dew point in Celsius
  float a = 17.27;
  float b = 237.7;
  float alpha = ((a * tempC) / (b + tempC)) + log(humidity / 100.0);
  float dewPoint = (b * alpha) / (a - alpha);
  return dewPoint;
}

That is common behavior with all WiFi connections. Your code has to be able to detect the loss and reconnect when necessary. It is not difficult to implement, and you can find plenty of examples on line.

nothing else in my house disconnects from wifi

Sure they do, they just doesn't complain about having to reconnect in a way that you are likely to notice.

So in my code that I posted the very first thing in my loop is this....is there something wrong with it that would prevent it from reconnecting?

void loop() {

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Disconnected from WiFi, reconnecting...");
    WiFi.disconnect();
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(1000);
      Serial.println("Reconnecting to WiFi...");
    }
    Serial.println("Reconnected to WiFi");
  }

You tell us. Do you not see "Reconnected" messages?

Nope - but I do see "connection failed" messages....from this part much lower in the code....so I don't get why it's not reconnecting - it's been connected for hours, then quits, and won't reconnect.

 // Stop the client
      client.stop();
      Serial.println();
      Serial.println("Data sent to PWSWeather");
      Serial.println();
    } else {
      Serial.println("Connection failed");
      Serial.println();
    }

Those are not necessarily caused by loss of the local WiFi connection.

Technically yes PWSWeather could have been down...but the connection never comes back - meaning it never quits saying connection failed once it starts. Plus if I manually post the URL in a browser on my computer with the same wifi at the time it's stating failed it is successful, so I don't think it's an issue with the url it's sending to.

My guess is that the code is not handing the connect/disconnect/reconnect with the PWSWeather service appropriately, and suggest to check with the user forum (if there is one) or technical support.

1 Like

It's not just you... The same thing has been happening to my R4 for months and it's driving me absolutely nuts.

It runs for a certain amount of time; days, sometimes only hours... And then it's gone. And no amount of retrying brings it back.

All you can do is power cycle.

Nothing else in the house drops like this. The same code on ESP32 stays connected just fine.

Does your WiFi.status remain WL_IDLE_STATUS aka doing nothing even when it should be disconnected or be reconnecting?

I've seen log entries where the connection did return to WL_CONNECTED, but immediate verification of WiFi.SSID() revealed that the SSID was a blank string, where it should have return the wifi's actual SSID.

The connection then returns to WL_IDLE_STATUS and the same endless reconnect loop.

Hello all,

I have the same issue and I got totally crazy spending dozens of hours trying to investigate the problem without success. Uno R4 Wifi has big stability issues with wifi finally. Let's put our hopes the next firmware release...