I am currently using an ESP32 connected to a temperature sensor. The data of the sensor is being sent to a server called ThingSpeak. My problem is that i am only able to sent the data some of the times, other times it would display error.
This is my code
#include <WiFi.h> // WiFi control for ESP32
#include "ThingSpeak.h"
#define WIFI_NAME "XXXXXX"
#define WIFI_PASSWORD "XXXXXX"
#include <OneWire.h>
#include <DallasTemperature.h>
#define SENSOR_PIN 13 // ESP32 pin GIOP17 connected to DS18B20 sensor's DATA pin
#define channelID XXXXXXX
#define writeFeedAPIKey "XXXXXXXXXXXXX"
WiFiClient client;
unsigned long myChannelNumber = 1;
OneWire oneWire(SENSOR_PIN);
DallasTemperature DS18B20(&oneWire);
float tempC; // temperature in Celsius
float tempF; // temperature in Fahrenheit
void setup() {
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
// put your setup code here, to run once:
Serial.begin(115200);
delay(10);
Serial.println("Connecting to ");
Serial.println(WIFI_NAME);
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop() {
// put your main code here, to run repeatedly:
DS18B20.requestTemperatures(); // send the command to get temperatures
int h = 0;
tempC = DS18B20.getTempCByIndex(0); // read temperature in °C
tempF = tempC * 9 / 5 + 32; // convert °C to °F
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
delay(5000);
}
Serial.println("\nConnected.");
}
if (WiFi.status() == WL_CONNECTED)
{
// set the fields with the values
ThingSpeak.setField(1, tempC);
int x = ThingSpeak.writeFields(channelID, writeFeedAPIKey);
if (x == 200) {
Serial.println("Channels update successful.");
}
else {
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
}
else {
Serial.println("\r\n############################################################");
Serial.println("Failed to update Data to thingSpeak Server. ");
Serial.println("WiFi not connected...");
Serial.println("############################################################\r\n");
}
Serial.print("Data Reading.");
delay (1000);
}
The error that came out is different most of the time, sometimes it is 304, then its 301, or even 401. I am not sure why it is not sending data all of the time. Whats causing the error?
I also changed the wifi name, password, api key and channel ID for privacy purpose, but i did insert it correctly in my actual code.