#include <WiFi.h>
#include <ThingSpeak.h>
#include <HX711.h>
#include <LiquidCrystal_I2C.h>
#include <HTTPClient.h>
#define LED 2
#define LED2 4
#define GREEN_LED_PIN 5 // Green LED for sufficient stock
#define RED_LED_PIN 18 // Red LED for low stock
// Low stock threshold
#define LOW_STOCK_THRESHOLD 1.0 // Weight threshold in kg
// IFTTT Webhooks settings
const char* serverName = "http://maker.ifttt.com/trigger/low_stock/with/key/your_IFTTT_key"; // Replace with your IFTTT key
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int LOADCELL_DOUT_PIN = 15;
const int LOADCELL_SCK_PIN = 2;
const float calibration_factor = 100.0;
HX711 scale;
long units;
char ssid[] = "Wokwi-GUEST"; // Replace with your Wi-Fi SSID
char pass[] = ""; // Replace with your Wi-Fi password
WiFiClient client;
unsigned long myChannelNumber = 2279390;
const char * myWriteAPIKey = "DMV9RHKW37I550XH";
int statusCode;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
scale.set_scale(calibration_factor);
scale.tare();
Serial.println("Hello, ESP32!");
lcd.init();
lcd.backlight();
pinMode(LED, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to Wi-Fi...");
}
Serial.println("Connected to Wi-Fi");
}
void loop() {
// Get the current weight from the load cell
float weightValue = scale.get_units();
// LED control logic for stock indication
if (weightValue < LOW_STOCK_THRESHOLD) {
// Low stock condition
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(RED_LED_PIN, HIGH);
// Send alert to IFTTT
sendLowStockAlert();
} else {
// Sufficient stock condition
digitalWrite(GREEN_LED_PIN, HIGH);
digitalWrite(RED_LED_PIN, LOW);
}
// Print the weight on the LCD and serial monitor
Serial.print("Weight: ");
lcd.setCursor(2, 0);
lcd.print("Weight :");
lcd.print(weightValue);
lcd.print(" kg");
Serial.print(weightValue);
Serial.println(" kg");
delay(1000);
// Update ThingSpeak with the current weight
ThingSpeak.setField(1, weightValue);
statusCode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (statusCode) { // Successful writing code
Serial.println("Channel update successful.");
} else {
Serial.println("Problem Writing data. HTTP error code: " + String(statusCode));
}
delay(10000); // Check every 10 seconds
}
void sendLowStockAlert() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// Send HTTP GET request to IFTTT
http.begin(serverName);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("IFTTT Response: " + response);
} else {
Serial.println("Error in sending request");
}
http.end();
} else {
Serial.println("Wi-Fi Disconnected");
}
}