#include <WiFi.h>
#include <ThingSpeak.h>
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
// Name of the router and password
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const int trigPin = 19;
const int echoPin = 18;
long duration;
float distanceCm;
float distanceInch;
//ThingSpeak Setting
unsigned long channelNumber = 2592067; //channel Id
const char* writeAPIKey = "NPBKZIT27XBSO66G"; //API key
WiFiClient client;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT);
// Start wifi - 2 parameters (ssid & password)
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi");
// Connection status
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Connection Info
Serial.println("");
Serial.println("WiFi connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
ThingSpeak.begin(client);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
//set the field
// 2 parameter - 1.field, 2.name of the field
ThingSpeak.setField(1, distanceCm);
//Write to ThingSpeak
//// 2 parameter - 1.channel num, 2.WAPIKEY
int x = ThingSpeak.writeFields(channelNumber, writeAPIKey);
//check wheather running or not
if(x == 200) {
Serial.println("Success!");
} else {
Serial.println("Faild: "+ String(x));
}
delay(1000);
}