My current project consists of a MKR 1010 with a DHT11 sensor that sends its readings to an Airtable by posting the data to the its API endpoint. For a while it worked like magic, but when I left it on overnight, I could see in the logs that it had stopped working. The orange light was also blinking. Tapping reset gets it working again.
My code's posted below (full Airtable URL remove so I don't expose the API key). I've used chunks of things posted online since there are a few threads about this same problem, usually with different solutions.
#include <WiFiNINA.h>
#include <SPI.h>
#include <ArduinoJson.h>
#include "arduino_secrets.h"
#include <DHT.h>
#define DHTPIN 7 // DHT
#define DHTTYPE DHT11 // DHT
DHT dht(DHTPIN, DHTTYPE); // DHT
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char server[] = "api.airtable.com";
int status = WL_IDLE_STATUS;
WiFiSSLClient client;
bool wifiBegun(false);
void setup() {
dht.begin();
Serial.begin(9600);
delay(1000);
if (WiFi.status() == WL_NO_MODULE) { // Check for wifi module
Serial.println("Communication with WiFi module failed!");
while (true);
}
}
void loop() {
if (!wifiBegun) {
WiFi.begin(ssid, pass);
delay(250); // acceptable freeze for this props (otherwise use PropsAction for async-like behavior)
if (WiFi.status() == WL_CONNECTED) {
wifiBegun = true;
Serial.println("Connected to Wifi.");
} else {
WiFi.end();
}
} else if (wifiBegun && WiFi.status() != WL_CONNECTED) {
WiFi.end();
wifiBegun = false;
}
while (client.available()) {
char c = client.read();
Serial.write(c);
}
float tmp = dht.readTemperature();
float hmd = dht.readHumidity();
float hic = dht.computeHeatIndex(tmp, hmd, false);
if (client.connect(server, 443)) {
Serial.println("Connected to server.");
StaticJsonDocument<200> doc;
JsonObject reading = doc.createNestedObject("fields");
reading["Temperature"] = tmp;
reading["Humidity"] = hmd;
reading["Heat Index"] = hic;
Serial.print(F("Sending: "));
serializeJson(doc, Serial);
Serial.println();
Serial.println("Sending data...");
client.println("POST /v0/URLREMOVED HTTP/1.1");
client.println("Host: api.airtable.com");
client.println("Content-Type: application/json");
client.println("Authorization: Bearer KEYREMOVED");
client.print("Content-Length: ");
client.println(measureJsonPretty(doc));
client.println();
serializeJsonPretty(doc, client);
client.println("Closed the connection");
client.println();
client.stop();
Serial.println("Data sent successfully!");
}
else {
// if you couldn't make a connection:
Serial.println("Connection failed");
}
Serial.println("Stopping now.");
delay(60000);
}