Clear Filters
Clear Filters

Thingspeak channel inconsistant data

6 views (last 30 days)
bader
bader on 15 Apr 2024
Edited: Swastik on 21 May 2024
Dear All,
Thingspeak channel got two entries of data and then stopped receiving any new entries. my project consist from the following equipment, Arduino Uno where it have both Current and Voltage sensors, alongside Esp8266 NodeMcu that is receiving Arduino's data as a serial connection, and lastly Thngspeak channel that will display the serial data gathered by ESP8266 NodeMcu. Because the needed data is being transferred via serial connection , there is a JSON object to parse the data. instead of using Tx and Rx Pins on both Arduino and Esp8266 the project have Pin 10 and 11 on the Arduino side and Pin 5 and 6 on the Esp8266 Side. Thngspeak somehow just detected two entries of data and the delay between were much much more than what is coded. while on serial monitor Arduino works perfectly fine in contrast from ESP8266 where it connect to the established WIFI network but not Thngspeak server.
Esp8266 side code
//Include Lib for Arduino to Nodemcu
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
//Wifimodule and thingspeak lib
#include <ESP8266WiFi.h> //Link in description
#include <ThingSpeak.h>
//D6 = Rx & D5 = Tx
SoftwareSerial nodemcu(D6, D5);
//Timer - milliseconds
unsigned long previousMillis = 0;
unsigned long currentMillis;
const unsigned long period = 150000;
//Variable for data
float voltageValue;
float currentValue;
float powerValue;
//Wifi related variables
String apiKey = "GWAAHMFKOZZKVADI"; //Write API key
unsigned long channelID = 2507368;
const char *ssid = "TP-Link_ADE8";
const char *pass = "27621332";
const char *server = "api.thingspeak.com";
//Boolean Variables
boolean state1 = false;
boolean state2 = false;
WiFiClient client;
//-------------------------------------------------- SETUP ------------------------------------------------------------
void setup() {
Serial.begin(9600);
nodemcu.begin(9600);
ThingSpeak.begin(client);
while (!Serial) continue;
delay(1000);
Serial.println("Program Started");
//Establish WiFi Connection
wifi_connect();
}
//-------------------------------------------------- LOOP ------------------------------------------------------------
void loop() {
//Get current time
currentMillis = millis();
if ((currentMillis - previousMillis >= period)) {
//Check if connected to WiFi, else connect
if (WiFi.status() != WL_CONNECTED) {
wifi_connect();
} else {
Serial.println("Currently Connected to WiFi");
}
//Connect to Thingspeak and push data
while (state1 == false) {
while (state2 == false) {
parseJsonObject();
}
cloud_connect();
}
state1 = false;
state2 = false;
Serial.println("Cloud Connect Succesful");
Serial.println("-----------------------------------------");
previousMillis = previousMillis + period;
}
}
//----------------------------------------- FUNCTION - WiFi Connect -----------------------------------------
void wifi_connect() {
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
ThingSpeak.begin(client);
Serial.println("WiFi Connected");
}
//------------------------------------------ FUNCTION Cloud Connect -----------------------------------------
void cloud_connect() {
//"184.106.153.149" or api.thingspeak.com
if (client.connect(server, 80)) {
String postStr = apiKey;
postStr += "&field1=";
postStr += String(currentValue);
postStr += "&field2=";
postStr += String(voltageValue);
postStr += "&field3=";
postStr += String(powerValue);
postStr += "\r\n\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n\n");
client.print(postStr);
Serial.print("Current: ");
Serial.print(currentValue);
Serial.print(" || Voltage: ");
Serial.println(voltageValue);
Serial.print(" || Power: ");
Serial.print(powerValue);
Serial.println("Sent to Thingspeak");
//Change state to true to break while loop
state1 = true;
}
client.stop();
}
void parseJsonObject() {
//Parse JSON object from serial port
StaticJsonDocument<1000> doc;
DeserializationError error = deserializeJson(doc, nodemcu);
Serial.println("Received JSON Data:");
Serial.println(nodemcu.readString());
// Test if parsing succeeds
if (error) {
Serial.println("deserializeJson error");
return;
}
//Parse Json values and store in variable
voltageValue = doc["Voltage"];
currentValue = doc["Current"];
powerValue = doc["Power"];
//ldr = doc["ldr"];
if (isnan(voltageValue) || isnan(currentValue) || isnan(powerValue) || voltageValue == 0.0 || currentValue == 0.0 || powerValue == 0.0) {
Serial.println("Invalid Sensor Readings");
return;
}
state2 = true;
Serial.println("JSON Object Recieved");
}
Arduino Code
//Arduino side code
//DHT11 Lib
//#include <DHT.h>
//Watchdog Timer
#include <avr/wdt.h>
//Arduino to NodeMCU Lib
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
//Initialise Arduino to NodeMCU (10=Rx & 11=Tx)
SoftwareSerial nodemcu(10, 11);
/*Initialisation of DHT11 Sensor
#define DHTPIN 4
DHT dht(DHTPIN, DHT11);
float temp;
float hum;*/
int VoltageSensorPin = A0; // Declaring Pin used with Voltage Sensor
int CurrentSensorPin = A1; // Declaring Pin used with Current Sensor
float voltageValue = 0.0; // decalring the output voltage label, this is the voltage reading sent from the load to the voltage sensor
float currentValue = 0.0; // declaring the output current label, this is the current reading sent from the load to the current sensor
float powerValue = 0.0;
void setup() {
Serial.begin(9600);
// dht.begin();
nodemcu.begin(9600);
delay(1000);
//Enable Watchdog timer
wdt_enable(WDTO_4S);
Serial.println("Program started");
}
void loop() {
StaticJsonDocument<1000> doc;
//Obtain Temp and Hum data
reading_func();
//Assign collected data to JSON Object
doc["Voltage"] = voltageValue;
doc["Current"] = currentValue;
doc["Power"] = powerValue;
//Send data to NodeMCU
serializeJson(doc, nodemcu);
//Reset for WDT
wdt_reset();
}
void reading_func() {
const float R1 = 30000.0; // this is a fixed resistor value embeded onto the voltage sensor
const float R2 = 7500.0; // this is a fixed resistor value embeded onto the voltage sensor
float ref_voltage = 5.0; // Float for Reference Voltage
const float SensavityI = 0.66; // this is a fixed value embeded onto the current sensor due to being 30A sensor
const float offsetI = 2.5; // Voltage measurement if Taking the measurment from Vin and Out of Current sensor
float VasBinary = 0.0; // the representation of measured voltage reading as a Voltage
float IasBinary = 0.0; // the representation of measured current reading as a Voltage
float Samples = 0.0;
float average = 0.0; // the average of detected values after sampling
float IDetectedReading = 0.0; // the measurement that is sent to Arduino
float VDetectedReading = 0.0; // the measurement that is sent to Arduino
Samples = 0.0; // Reset Samples to 0 for each loop iteration
for (int x = 0; x < 150; x++) { //Get 150 samples to provide stebility
IDetectedReading = analogRead(CurrentSensorPin);
Samples = Samples + IDetectedReading;
delay(3);
}
average = Samples / 150.0; //Taking Average of Samples
IasBinary = (average * (5.0 / 1024.0)); // Converting detected measurment from Analog to Digital
currentValue = ((offsetI - IasBinary) / SensavityI);
if (currentValue > -0.000005 && currentValue < 0.000005) {
currentValue = 0;
} else {
currentValue = currentValue - 0.185; // this is to remove the internal offset current after conversion from voltage
}
VDetectedReading = analogRead(VoltageSensorPin);
VasBinary = (VDetectedReading * ref_voltage) / 1024.0; // Converting detected measurment from Analog to Digital
voltageValue = VasBinary * ((R1 + R2) / R2); // Reverting the measurment from voltage sensor to the Real value of the physical componant by invert voltage devider ratio
powerValue = voltageValue * currentValue; // P = VI
Serial.print("Input Voltage = ");
Serial.println(voltageValue, 2);
// Serial.print("Raw Sensor Value = ");
// Serial.print(VDetectedReading);
// Serial.print("\t Voltage = ");
// Serial.print(IDetectedReading, 3);
Serial.print("\t Current = ");
Serial.println(currentValue, 7);
Serial.print("\t Power = ");
Serial.println(powerValue, 3);
delay(15000);
/*hum = dht.readHumidity();
temp = dht.readTemperature();
Serial.print("Humidity: ");
Serial.println(hum);
Serial.print("Temperature: ");
Serial.println(temp);*/
if (isnan(voltageValue) || isnan(currentValue) || isnan(powerValue) || voltageValue == 0.0 || currentValue == 0.0 || powerValue == 0.0) {
while (1) {}
}
}

Answers (1)

Swastik
Swastik on 21 May 2024
Edited: Swastik on 21 May 2024
Hi @bader,
I noticed that you are attempting to send data to the ThingSpeak server at intervals of 150,000 milliseconds, but ThingSpeak seems to only register 2 entries, possibly spaced out by 5 minutes (300,000 milliseconds). This discrepancy suggests there might be an issue with the "cloud_connect" function, as the rest of your code appears to be correctly implemented.
To address this issue, instead of manually crafting the HTTP request, consider utilizing the “thingSpeakWrite” function, which is designed for integrating with ThingSpeak more efficiently. This function also offers the ability to specify timestamps, potentially aligning better with the needs of the application.
You can find detailed guidance on using thingSpeakWrite in the MathWorks documentation here: https://www.mathworks.com/help/thingspeak/thingspeakwrite.html
For Arduino projects, the corresponding function is "ThingSpeak.writeField," which is included in the ThingSpeak Arduino library. You can access detailed instructions and examples in its documentation on GitHub here: https://github.com/mathworks/thingspeak-arduino/blob/master/README.md#writefield
Hope this helps.

Communities

More Answers in the  ThingSpeak Community

Categories

Find more on Write Data to Channel in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!