#include <WiFi.h> // WiFi library for ESP32
#include <HTTPClient.h> // HTTPClient library for making HTTP requests
// Define analog sensor pin (use the correct GPIO pin number)
#define ANALOG_SENSOR_PIN 34 // GPIO pin for analog input
// Define weight threshold (2500 kg)
const float weightThreshold = 2500; // Weight in kg
// Define alarm pin
#define ALARM_PIN 2
// Calibration factor to convert analog reading to weight
const float calibrationFactor = 0.01 * (5500 / 50.0); // Adjust based on sensor
// ThingSpeak credentials
const char* ssid = "Wokwi-GUEST"; // Your Wi-Fi network SSID
const char* password = ""; // Your Wi-Fi network password
const char* server = "http://api.thingspeak.com"; // ThingSpeak server
const char* apiKey = "1YK6YMY3VD4JIEUO"; // Your ThingSpeak Write API Key
void setup() {
Serial.begin(115200); // Initialize serial communication
pinMode(ANALOG_SENSOR_PIN, INPUT); // Set analog sensor pin as input
pinMode(ALARM_PIN, OUTPUT); // Set alarm pin as output
digitalWrite(ALARM_PIN, LOW); // Ensure buzzer is off at startup
// Connect to Wi-Fi
Serial.print("Connecting to Wi-Fi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println(" Connected!");
}
void loop() {
// Read weight from analog sensor
int sensorValue = analogRead(ANALOG_SENSOR_PIN);
// Convert sensor value to weight
float weight = sensorValue * calibrationFactor;
// Print weight to serial monitor
Serial.print("Weight: ");
Serial.print(weight);
Serial.println(" kg");
// Send weight to ThingSpeak via HTTP request
if (WiFi.status() == WL_CONNECTED) { // Check Wi-Fi connection
HTTPClient http;
String url = String(server) + "/update?api_key=" + apiKey + "&field1=" + String(weight);
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.println("Data sent to ThingSpeak successfully!");
} else {
Serial.print("Error sending data to ThingSpeak. HTTP error code: ");
Serial.println(httpResponseCode);
}
http.end(); // Close connection
}
// Check if the weight exceeds the threshold
if (weight >= weightThreshold) {
digitalWrite(ALARM_PIN, HIGH); // Turn on the buzzer
Serial.println("Overload detected! Buzzer ON.");
tone(ALARM_PIN, 3000); // Play a 3000 Hz tone on the buzzer
} else {
digitalWrite(ALARM_PIN, LOW); // Turn off the buzzer
noTone(ALARM_PIN); // Stop any tone that might be playing
}
delay(20000); // Wait for 20 seconds before the next reading (as per ThingSpeak's limit)
}