/* Project Aug 2024
* Name: Gan Lin
* class: B
* Date: 1st Aug 2024
*/
int led =23; //LED is connected to esp32 D23
int pirdata =15; //pir D is connected to D15
int pirstate =LOW; // assuming no motion
int value =0; // to read pin status
#define Buzzer 4 // Buzzer connected to D4
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_S10251644B";
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");
client.subscribe("Candice/10251644/motion"); // Subscribe to motion topic
}
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("Message: ");
for (int i = 0; i<length; i++)
{
Serial.print( (char)payload[i] );
messageTemp += (char)payload[i];
}
Serial.println();
// Perform actions based on the message received
if (String(topic) == "Candice/10251644/motion")
{
if (messageTemp == "ON")
{
digitalWrite(led, HIGH); //Turn on LED
Serial.println("LED turned ON");
}
else if (messageTemp == "OFF")
{
digitalWrite(led, LOW); //Turn off LED
Serial.println("LED turned OFF");
}
}
}
void MQTTSubscribe()
{
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}
void setup()
{
Serial.begin(115200);
Serial.println("Hello Buzz!");
pinMode(pirdata, INPUT);
pinMode(led, OUTPUT); // LED as output
pinMode(Buzzer, OUTPUT);
setup_wifi();
setup_MQTT();
}
void loop()
{
value = digitalRead(pirdata); //Reading status of sensor pin
if (value == HIGH) // If motion detected
{
if (pirstate == LOW)
{
Serial.println("motion detected ...");
pirstate = HIGH;
client.publish("Candice/10251644/motion","ON"); //Publish motion detected
tone(Buzzer, 1000); // Activate buzzer at 1000Hz
delay(500); // Buzz for 500ms (adjust as needed)
}
else
{
if (pirstate == HIGH)
{
Serial.println("no motion ...");
pirstate = LOW;
client.publish("Candice/10251644/motion","OFF"); //Publish no motion
noTone(Buzzer); // Turn off buzzer
}
}
}
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
}