Hi, I've been scratching my head over trying to send data from my metal proximity sensor to thingspeak for over a week now. I tried it with UNO and Wemos D1-R2 as well. I'm able to send random numbers to thingspeak but not that of sensor's. Could someone help me figure out where am I doing it wrong?
#include "ThingSpeak.h"
#include "secrets.h"
#include <ESP8266WiFi.h>
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
WiFiClient client;
const int ProxSensor = D2;
unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;
void setup() {
Serial.begin(115200); // Initialize serial
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
pinMode(D14, OUTPUT);
//Pin 14 is connected to the output of proximity sensor
pinMode(ProxSensor,INPUT);
}
void loop() {
// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect to SSID: ");
Serial.println(SECRET_SSID);
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP network
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected.");
}
if(digitalRead(ProxSensor)==HIGH) //Check the sensor output
{
digitalWrite(D14, HIGH); // set the LED on
}
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeField(myChannelNumber, 1, 1, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
if(digitalRead(ProxSensor)==LOW)
{
digitalWrite(13, LOW); // set the LED off
}
delay(100);
int y = ThingSpeak.writeField(myChannelNumber, 1, 0, myWriteAPIKey);
if(y == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
// change the value
delay(20000); // Wait 20 seconds to update the channel again
}
p.s: I used a thingspeak library to code this. (Hence why secrets.h)