#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqttServer = "mqtt-dashboard.com";
const int mqttPort = 1883;
const String topic = "motion";
// MQTT client
WiFiClient espClient;
PubSubClient client(espClient);
// Motion sensor settings
int calibrationTime = 30;
long unsigned int lowIn;
long unsigned int pauseTime = 5000; // Changed variable name
boolean lockLow = true;
boolean takeLowTime;
int pirPin = 2; // D2 on ESP32
void setup() {
Serial.begin(9600);
// Connect to WiFi and MQTT
connectWiFiAndMQTT();
pinMode(pirPin, INPUT);
digitalWrite(pirPin, LOW);
// Sensor calibration
Serial.print("Calibrating sensor ");
for (int i = 0; i < calibrationTime; i++) {
Serial.print(".");
delay(1000);
}
Serial.println(" done");
Serial.println("SENSOR ACTIVE");
delay(50);
}
void loop() {
if (!client.connected()) {
connectWiFiAndMQTT();
}
client.loop();
// Motion detection
if (digitalRead(pirPin) == HIGH) {
if (lockLow) {
lockLow = false;
Serial.println("---");
Serial.print("Motion detected at ");
Serial.print(millis() / 1000);
Serial.println(" sec");
// Publish MQTT message
client.publish(topic.c_str(), "Motion detected");
delay(50);
}
takeLowTime = true;
}
if (digitalRead(pirPin) == LOW) {
if (takeLowTime) {
lowIn = millis();
takeLowTime = false;
}
if (!lockLow && millis() - lowIn > pauseTime) { // Changed variable name
lockLow = true;
Serial.print("Motion ended at ");
Serial.print((millis() - pauseTime) / 1000); // Changed variable name
Serial.println(" sec");
delay(50);
}
}
}
void connectWiFiAndMQTT() {
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Connect to MQTT
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client")) {
Serial.println("Connected to MQTT");
client.subscribe(topic.c_str());
} else {
Serial.print("Failed with state ");
Serial.println(client.state());
delay(2000);
}
}
}