#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* server = "api.thingspeak.com";
const char* apiKey = "0NDCO11WCJYJETJL"; // Obtain your API key from ThingSpeak
#define TRIG_PIN 2
#define ECHO_PIN 3
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize the OLED display
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
// Clear the display buffer
display.clearDisplay();
}
void loop() {
// Send a pulse to the trigger pin to start the measurement
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration of the pulse on the echo pin
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance based on the duration
// Speed of sound at sea level is 343 meters/second or 0.0343 cm/microsecond
float distance = duration * 0.0343 / 2; // Divide by 2 because it's a round trip
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Print the distance to the OLED display
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0,0);
display.print("Distance: ");
display.print(distance);
display.println(" cm");
display.display();
// Send data to ThingSpeak
sendDataToThingSpeak(distance);
// Wait before taking the next measurement
delay(10000); // Adjust delay as needed
}
void sendDataToThingSpeak(float distance) {
if ((WiFi.status() == WL_CONNECTED)) {
HTTPClient http;
// Construct the URL for ThingSpeak
String url = "http://";
url += server;
url += "/update?api_key=";
url += apiKey;
url += "&field1=";
url += String(distance);
Serial.print("Sending data to ThingSpeak: ");
Serial.println(url);
http.begin(url); // Initialize HTTP connection
int httpResponseCode = http.GET(); // Send HTTP GET request
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error sending data to ThingSpeak. HTTP error code: ");
Serial.println(httpResponseCode);
}
http.end(); // Close HTTP connection
}
}