#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#include <DHT_U.h>
#include <Adafruit_Sensor.h>
#include <HX711.h>
#define DHTPIN 32
const int LOADCELL_DOUT_PIN = 34;
const int LOADCELL_SCK_PIN = 27;
const int redLedPin = 23;
const int greenLedPin = 18;
const int yellowLedPin = 19;
const int irSensorPin = 35; // Define IR sensor pin
unsigned long previousMillis = 0;
const long interval = 500; // Read every 500 milliseconds
// DHT parameters
#define DHTTYPE DHT22 // DHT 22
DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;
HX711 scale;
// Parameters for using non-blocking delay
String msgStr = ""; // MQTT message buffer
float temp, hum, weight;
bool objectDetected = false; // To store the IR sensor state
// WIFI
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_5810957T"; // yourStudentID must be unique
int PORTNUM = 1883;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
const char* mqttTopic = "IoT/LT/5810957T";
void setup_wifi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println();
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("Given IP by the router to ESP32 is ");
Serial.println(WiFi.localIP());
}
void connectMQTT() {
while (!client.connected()) {
Serial.println("Connecting to MQTT ...");
if (client.connect(espClientName)) // , mqttUser, mqttPassword) )
{
Serial.println("Connected");
MQTTSubscribe();
} else {
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Add custom logic to react to messages
}
void MQTTSubscribe() {
client.subscribe("IoT/LT/5810957T");
}
void setup_MQTT() {
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}
void updateLedStates(float weight) {
Serial.print("Weight (for LED logic): ");
Serial.println(weight); // Debug statement to trace weight value
if (weight < 1.0) {
digitalWrite(redLedPin, HIGH); // Turn on red LED
digitalWrite(yellowLedPin, HIGH); // Turn off yellow LED
digitalWrite(greenLedPin, LOW); // Turn off green LED
} else if (weight >= 1.0 && weight <= 5.0) {
digitalWrite(redLedPin, HIGH); // Turn off red LED
digitalWrite(yellowLedPin, LOW);// Turn on yellow LED
digitalWrite(greenLedPin, HIGH); // Turn off green LED
} else if (weight > 5.0) {
digitalWrite(redLedPin, LOW); // Turn off red LED
digitalWrite(yellowLedPin, HIGH); // Turn off yellow LED
digitalWrite(greenLedPin, HIGH); // Turn on green LED
}
}
void setup() {
Serial.begin(9600);
delay(5000);
// Initialize device.
dht.begin();
// Get temperature sensor details.
sensor_t sensor;
dht.temperature().getSensor(&sensor);
dht.humidity().getSensor(&sensor);
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
scale.set_scale(); // Calibrate your scale
scale.tare(); // Reset the scale to 0
setup_wifi();
setup_MQTT();
// Initialize LED pins as outputs
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(yellowLedPin, OUTPUT);
// Initialize IR sensor pin as input
pinMode(irSensorPin, INPUT);
}
void loop() {
if (!client.connected()) {
connectMQTT();
}
client.loop();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// Read temperature and humidity
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
Serial.println(F("Error reading temperature!"));
} else {
Serial.print(F("Temperature: "));
temp = event.temperature;
Serial.print(temp);
Serial.println(F("°C"));
}
// Get humidity event and print its value
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println(F("Error reading humidity!"));
} else {
hum = event.relative_humidity; // Use actual sensor reading
Serial.print(F("Humidity: "));
Serial.print(hum);
Serial.println(F("%"));
}
// Read IR sensor state
objectDetected = digitalRead(irSensorPin);
if (objectDetected) {
Serial.println("Object detected!");
} else {
Serial.println("No object detected.");
}
if (scale.is_ready()) {
weight = scale.get_units(10); // Average 10 readings for stability
Serial.print("Weight: ");
Serial.print(weight);
Serial.println(" kg");
updateLedStates(weight);
// Publish weight to MQTT
msgStr = String(weight) + " kg";
client.publish(mqttTopic, msgStr.c_str());
msgStr = "";
} else {
Serial.println("HX711 not found.");
}
// Publish temperature and humidity to MQTT
msgStr = String(temp) + "," + String(hum) + "," + String(weight) + "," + String(objectDetected);;
byte arrSize = msgStr.length() + 1;
char msg[arrSize];
msgStr.toCharArray(msg, arrSize);
client.publish(mqttTopic, msg);
msgStr = "";
delay(1500);
}
}