Clear Filters
Clear Filters

Info

This question is locked. Reopen it to edit or answer.

data stops after 6-7 transmissions

2 views (last 30 days)
Shashank
Shashank on 25 Jul 2024
Locked: Rena Berman on 7 Aug 2024
Hi team I am Shashank Verma, I am using arduino r4 wifi to send data on thing speak. I am uploading real time data of temp, humidity, Gas conc, and AQI catagory. I am using Thingspeak free account and only sending data in every 2 min. but the transmission of data stops after 7-8 data upload. please help me in this i am builing this project in public intrest.
the public channel url is " https://thingspeak.com/channels/2606075"
Uploads starts again as soon as i restart arduino.
the arduino code i am using is as follows
"#include <DHT.h>
#include <WiFi.h>
#include <ArduinoHttpClient.h>
#include "ArduinoGraphics.h"
#include "Arduino_LED_Matrix.h"
// Define the pin and type for the DHT sensor
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
// Initialize the LED matrix
ArduinoLEDMatrix matrix;
// Replace with your network credentials
const char* ssid = "BSNL123";
const char* password = "yyyyyyyy";
const char* api_key = "xxxxxxxxxxxxxxxx";
const char* thingspeak_server = "api.thingspeak.com";
const int analogPin = A0;
const float slope = 0.1;
const float intercept = 0.5;
// Initialize the WiFi server on port 80
WiFiServer wifiServer(80);
// Timing variables for various updates
unsigned long lastMatrixUpdate = 0;
const unsigned long matrixUpdateInterval = 25000; // 25 seconds
unsigned long lastSerialUpdate = 0;
const unsigned long serialUpdateInterval = 55000; // 55 seconds
unsigned long lastThingSpeakUpdate = 0;
const unsigned long thingSpeakUpdateInterval = 60000; // 1 minute
unsigned long lastWebDataSent = 0;
const unsigned long webDataUpdateInterval = 10000; // 10 seconds to handle page refresh
// Function to determine AQI category and numeric value
void getAQICategory(float concentration, String &category, int &numericValue) {
if (concentration <= 50) {
category = "Good";
numericValue = 1;
} else if (concentration <= 100) {
category = "Satisfactory";
numericValue = 2;
} else if (concentration <= 200) {
category = "Moderate";
numericValue = 3;
} else if (concentration <= 300) {
category = "Poor";
numericValue = 4;
} else if (concentration <= 400) {
category = "Very Poor";
numericValue = 5;
} else {
category = "Severe";
numericValue = 6;
}
}
void connectToWiFi() {
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println();
Serial.println("Connected to Wi-Fi");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
} else {
Serial.println();
Serial.println("Failed to connect to Wi-Fi");
}
}
void reconnectToThingSpeak() {
Serial.println("Reconnecting to ThingSpeak...");
delay(10000); // Wait before attempting to reconnect
}
void setup() {
Serial.begin(115200);
dht.begin();
matrix.begin();
matrix.beginDraw();
matrix.stroke(0xFFFFFFFF);
const char text[] = "Temp & Humidity";
matrix.textFont(Font_4x6);
matrix.beginText(0, 1, 0xFFFFFF);
matrix.println(text);
matrix.endText();
matrix.endDraw();
delay(2000);
connectToWiFi();
// Start the server
wifiServer.begin();
}
void loop() {
unsigned long currentMillis = millis();
if (WiFi.status() != WL_CONNECTED) {
connectToWiFi();
}
// Read temperature and humidity from the DHT22 sensor
float temperature = dht.readTemperature(); // in Celsius
float humidity = dht.readHumidity(); // in percentage
// Check if the reading is valid
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Convert temperature to Fahrenheit
float ftemp = temperature;
// Read analog value from MQ135
int sensorValue = analogRead(analogPin);
float gasConcentration = (slope * sensorValue) + intercept; // Convert to gas concentration
String aqiCategory;
int aqiCategoryNumeric;
getAQICategory(gasConcentration, aqiCategory, aqiCategoryNumeric); // Get AQI category and numeric value
// Display data on the LED matrix
if (currentMillis - lastMatrixUpdate >= matrixUpdateInterval) {
matrix.beginDraw();
matrix.clear();
matrix.stroke(0xFFFFFFFF);
matrix.textScrollSpeed(90);
matrix.textFont(Font_5x7);
matrix.beginText(0, 1, 0xFFFFFF);
matrix.println("Temp: " + String(ftemp, 1) + " C");
matrix.endText(SCROLL_LEFT);
delay(2000);
matrix.clear();
matrix.beginText(0, 1, 0xFFFFFF);
matrix.println("Hum: " + String(humidity, 1) + " %");
matrix.endText(SCROLL_LEFT);
delay(2000);
matrix.clear();
matrix.beginText(0, 1, 0xFFFFFF);
matrix.println("AQI: " + aqiCategory);
matrix.endText(SCROLL_LEFT);
delay(2000);
matrix.endDraw();
lastMatrixUpdate = currentMillis;
}
// Display data on the serial monitor
if (currentMillis - lastSerialUpdate >= serialUpdateInterval) {
Serial.print("Temperature: ");
Serial.print(ftemp);
Serial.println(" C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("MQ135 Analog Value: ");
Serial.println(sensorValue);
Serial.print("Gas Concentration (ppm): ");
Serial.println(gasConcentration);
Serial.print("AQI Category: ");
Serial.println(aqiCategory);
lastSerialUpdate = currentMillis;
}
// Handle Wi-Fi client connections and send data to the local LAN
WiFiClient client = wifiServer.available();
if (client) {
Serial.println("Client connected");
// Read the client's request
String request = client.readStringUntil('\r');
client.flush();
// Check if it's time to update the web data
if (currentMillis - lastWebDataSent >= webDataUpdateInterval) {
// Send the HTTP response
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
client.print("<!DOCTYPE HTML><html><head><title>Air Quality Monitor</title></head><body>");
client.print("<h1>Temperature and Humidity</h1>");
client.print("<p>Temperature: ");
client.print(ftemp);
client.print(" &deg;C</p>");
client.print("<p>Humidity: ");
client.print(humidity);
client.print(" %</p>");
client.print("<p>AQI: ");
client.print(aqiCategory);
client.print("</p>");
client.print("<p>Gas Concentration: ");
client.print(gasConcentration);
client.print(" ppm</p>");
client.print("</body></html>");
lastWebDataSent = currentMillis; // Update the time of the last data sent
Serial.println("Data sent to client");
} else {
// Inform the client that the data has not changed
client.print("HTTP/1.1 304 Not Modified\r\nContent-Type: text/html\r\n\r\n");
client.print("<!DOCTYPE HTML><html><head><title>Air Quality Monitor</title></head><body>");
client.print("<h1>Temperature and Humidity</h1>");
client.print("<p>Data not updated. Please refresh the page to get new data.</p>");
client.print("</body></html>");
}
delay(1000);
client.stop();
Serial.println("Client disconnected");
}
// Send data to ThingSpeak
if (currentMillis - lastThingSpeakUpdate >= thingSpeakUpdateInterval) {
bool success = false;
int retryCount = 0;
const int maxRetries = 3;
while (retryCount < maxRetries && !success) {
if (WiFi.status() == WL_CONNECTED) {
WiFiClient wifiClient;
HttpClient httpClient = HttpClient(wifiClient, thingspeak_server, 80);
httpClient.setTimeout(20000); // Set a timeout of 20 seconds
String url = "/update?api_key=" + String(api_key) +
"&field1=" + String(temperature) +
"&field2=" + String(humidity) +
"&field3=" + String(gasConcentration) +
"&field4=" + String(aqiCategoryNumeric); // Send AQI category as numeric
httpClient.get(url);
int statusCode = httpClient.responseStatusCode();
String response = httpClient.responseBody();
if (statusCode == 200) {
Serial.println("Data sent to ThingSpeak");
success = true;
} else {
Serial.print("Error sending data to ThingSpeak. Status code: ");
Serial.println(statusCode);
Serial.println("Response: ");
Serial.println(response);
retryCount++;
delay(5000); // Wait before
retrying
}
} else {
reconnectToThingSpeak();
}
}
if (!success) {
Serial.println("Failed to send data after multiple attempts.");
}
lastThingSpeakUpdate = currentMillis;
}
}

Answers (1)

Christopher Stapels
Christopher Stapels on 25 Jul 2024
I recomend using the ThingSpeak library - it takes care of much of the network connectivity for you.
Are you sure its not one of your sensors that is causing the code to stop running? You could try posting static values with no sensors to test this
Network connectivity is my guess for your issue. The wifi library has a function to write RSSI, you can also log that you your channel to see how strong the signal is. Also try moving your device closer to the access point or try connecting to a different network.
As far as I can read it, your code seems fine, and your channel does not seem to show evisence of posting too fast.
Thanks for sharing your cool project, please let us know if you figure out the issue.
  3 Comments
Christopher Stapels
Christopher Stapels on 29 Jul 2024
you have the connection attempts at 20, Im wondering if that means your network strength is too low.
I would try moving to a stronger network.
Alos, for this:
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
Serial.print(".");
attempts++;
}
I have found that 500 is not long enough to connect when the network is weak, I recomend increasing this time to a few seconds.
delay(4000); //perhaps
Shashank
Shashank on 30 Jul 2024
thanks a lot sir. problem is solved now thanks for your support and guidance.

This question is locked.

Communities

More Answers in the  ThingSpeak Community

Categories

Find more on Read Data from Channel in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!