#include <WiFi.h>
#include <ThingSpeak.h>
#include <HX711.h>
// Pin definitions
#define DATA_PIN 15
#define CLOCK_PIN 2
#define BUZZER_PIN 13
// WiFi and ThingSpeak credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const unsigned long CHANNEL_ID = 2040615;
const char* WRITE_API_KEY = "BJGXAH2S16ZAWZ13";
// HX711 load cell setup
HX711 hx711;
// Variables
long weight;
int buzzerState = 0;
WiFiClient client;
void setup() {
Serial.begin(115200);
// Initialize HX711
hx711.begin(DATA_PIN, CLOCK_PIN);
hx711.set_scale(420.0983); // Adjust this to your load cell calibration factor
hx711.tare(); // Reset the scale to 0
// Initialize Buzzer Pin
pinMode(BUZZER_PIN, OUTPUT);
noTone(BUZZER_PIN); // Ensure buzzer is off
// Connect to WiFi
connectToWiFi();
// Initialize ThingSpeak
ThingSpeak.begin(client);
}
void loop() {
// Read weight from HX711
weight = hx711.get_units();
// Map the weight to a range (0 to 3500 in this example)
int mappedWeight = map(weight, 0, 50, 0, 3500);
// Handle buzzer based on weight
if (mappedWeight > 2500) {
buzzerState = 1; // Overload condition
tone(BUZZER_PIN, 1000); // Play buzzer sound
} else if (mappedWeight < 500) {
buzzerState = 0; // Normal condition
noTone(BUZZER_PIN); // Turn off buzzer
} else {
buzzerState = 2; // Intermediate condition
noTone(BUZZER_PIN); // Turn off buzzer
}
// Send data to ThingSpeak
ThingSpeak.setField(1, weight);
ThingSpeak.setField(2, buzzerState); // 0: Off, 1: On, 2: Normal
// Write the fields to ThingSpeak
int statusCode = ThingSpeak.writeFields(CHANNEL_ID, WRITE_API_KEY);
if (statusCode == 200) {
Serial.println("Channel update successful.");
} else {
Serial.println("Problem Writing data. HTTP error code: " + String(statusCode));
}
// Wait 15 seconds before the next update
delay(15000);
}
// Function to connect to WiFi
void connectToWiFi() {
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi.");
}