#include <WiFi.h>
#include <ThingSpeak.h> // always include thingspeak header file after other header files and custom macros
const int trig = 2;
const int echo = 4;
long duration;
float distance;
#define SECRET_SSID "Wokwi-GUEST" // replace with your WiFi network name
#define SECRET_PASS "" // replace with your WiFi password
#define SECRET_CH_ID 2005909 // replace 0000000 with your channel number
#define SECRET_CH_IDr 2024385
#define SECRET_WRITE_APIKEY "8F81TFABW61HAHSI" // replace XYZ with your channel write API Key
#define SECRET_READ_APIKEY "47F3VAS1J5ZLFY1G" // replace XYZ with your channel read API Key
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;
unsigned long myChannelNumber = SECRET_CH_ID;
unsigned long readmyChannelNumber = SECRET_CH_IDr;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;
const char * myReadAPIKey = SECRET_READ_APIKEY;
unsigned int dataFieldOne = 1;
float aConst = 2.25E-02;
void setup() {
Serial.begin(115200);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(15, OUTPUT);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo native USB port only
}
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
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.");
}
//Ultrasonic
digitalWrite(trig,LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
//Serial.println(duration);
distance = duration*0.034/2;
Serial.println(distance);
//Thingspeak
int statusCode;
ThingSpeak.setField(3, distance);
statusCode = ThingSpeak.writeFields(myChannelNumber,SECRET_WRITE_APIKEY);
aConst = readTSData( readmyChannelNumber, dataFieldOne );
Serial.println(aConst);
if(aConst == 1){
digitalWrite(15, HIGH);
Serial.println("Relay on");
}
else{
digitalWrite(15,LOW);
Serial.println("Relay off");
}
if(statusCode == 200) { //successful writing code
Serial.println("Channel update successful.");
}
else {
Serial.println("Problem Writing data. HTTP error code :" + String(statusCode));
}
delay(15000); // data to be uploaded every 15secs
}
float readTSData( long TSChannel, unsigned int TSField ) {
float data = ThingSpeak.readFloatField( TSChannel, TSField, SECRET_READ_APIKEY );
// Serial.println( " Data read from ThingSpeak: " + String( data, 9 ) );
return data;
}