#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
int RLED = 23;
int GLED = 19;
int PIR1 = 25;
int PIR2 = 27;
// Codes to connect to HiveMQTT
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_8828880c"; // change
int PORTNUM = 1883;
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) )
{
Serial.println("Connected");
MQTTSubscribe();
}
else
{
Serial.print("Failed with state ");
Serial.print(client.state() );
delay(2000);
}
}
}
void callback(String topic, byte* payload, unsigned int length)
{
String messageTemp;
Serial.print("Message received in topic: ");
Serial.print(topic);
Serial.print(" length is: ");
Serial.println(length);
Serial.print("Data received from broker: ");
for (int i = 0; i < length; i++)
{
Serial.print( (char)payload[i] );
messageTemp += (char)payload[i];
}
/*if (topic == "DEIOT/8828880c")
{
if (messageTemp == "Alert")
{
digitalWrite(redLED, LOW);
}
else if (messageTemp == "OK")
{
digitalWrite(redLED, HIGH);
}
}*/
}
void MQTTSubscribe()
{
client.subscribe("PIOT/8828880c");
client.subscribe("PIOT/8828880");
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
setup_wifi();
setup_MQTT();
pinMode(RLED, OUTPUT);
pinMode(GLED, OUTPUT);
pinMode(PIR1, INPUT);
pinMode(PIR2, INPUT);
digitalWrite(RLED, HIGH);
digitalWrite(GLED, HIGH);
}
void loop() {
delay(10);
bool Motion1 = digitalRead(PIR1); // boolean is true/false logic, TRUE = 1, FALSE = 0
//Statement means: Is there motion? Read PIR pin. If True = 1, if False = 0
bool Motion2 = digitalRead(PIR2);
if (Motion1 == 1)
{
digitalWrite(RLED, LOW);
Serial.println(Motion1);
Serial.println("Motion is detected");
client.publish("PIOT/8828880c","Bin is full");
}
else
{
if (Motion1 == 0)
{
Serial.println(Motion1);
digitalWrite(RLED, HIGH);
Serial.println("Motion is not detected");
client.publish("PIOT/8828880c","Bin is not full");
}
}
if (Motion2 == 1)
{
digitalWrite(GLED, LOW);
Serial.println(Motion2);
Serial.println("Motion is detected");
client.publish("PIOT/8828880","Bin is full");
}
else
{
if (Motion2 == 0)
{
Serial.println(Motion2);
digitalWrite(GLED, HIGH);
Serial.println("Motion is not detected");
client.publish("PIOT/8828880","Bin is not full");
}
}
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
}