#include <WiFi.h>
#include "ThingSpeak.h"
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = ""; // Replace with your actual WiFi password
const int myChannelNumber = 2324330;
const char* myApiKey = "JKEPA4O0D6CEC55U";
const char* server = "api.thingspeak.com";
WiFiClient client;
const int trigPin = 5;
const int echoPin = 18;
// Define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
void setup() {
Serial.begin(9600); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
// Connect to WiFi
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED){
delay(1000);
Serial.println("WiFi not connected");
}
Serial.println("WiFi connected!");
Serial.println("Local IP: " + String(WiFi.localIP()));
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 microseconds
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 in centimeters
distanceCm = duration * SOUND_SPEED / 2;
// Send distance data to ThingSpeak
ThingSpeak.setField(1, distanceCm);
int x = ThingSpeak.writeFields(myChannelNumber, myApiKey);
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Print the distance in the Serial Monitor
Serial.println("Distance (cm): " + String(distanceCm));
// Check if data was sent to ThingSpeak successfully
if(x == 200){
Serial.println("Data pushed successfully");
} else {
Serial.println("Push error " + String(x));
}
Serial.println("---");
delay(10000); // Delay for 10 seconds before the next measurement
}