Blog Startseite AI generated Robot Image

Creating Door and Window Sensors for Burglar Detection with ESP32 and MQTT

11.12.2024 - Engine: Gemini

Creating Door and Window Sensors for Burglar Detection with ESP32 and MQTT

Building Door/Window Sensors for Burglar Detection with ESP32 and MQTT

Components

  • ESP32 Microcontroller
  • Door/Window Magnetic Switch
  • MQTT Broker (e.g., Mosquitto)

Schematic

Door/Window Sensor Schematic

Code

ESP32 Code:

#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "Your_WiFi_SSID";
const char* password = "Your_WiFi_Password";
const char* mqtt_server = "Your_MQTT_Broker_Address";
const int mqtt_port = 1883;
const char* mqtt_topic = "burglar_detection";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi.");
  client.setServer(mqtt_server, mqtt_port);
}

void loop() {
  // Check WiFi connection
  if (!client.connected()) {
    if (client.connect("ESP32-Sensor")) {
      Serial.println("Connected to MQTT broker.");
    } else {
      Serial.println("Failed to connect to MQTT broker.");
      delay(1000);
      return;
    }
  }

  // Get magnetic switch status
  int sensorValue = digitalRead(MagneticSwitchPin);

  // Publish MQTT message
  if (sensorValue == HIGH) {
    client.publish(mqtt_topic, "closed");
  } else {
    client.publish(mqtt_topic, "open");
  }

  client.loop();
}

Wiring

  • Connect the magnetic switch to a digital GPIO pin on the ESP32.
  • Connect the ESP32 to the MQTT broker.

Configuration

  • Configure the MQTT broker with appropriate settings.
  • Configure the ESP32 code with the correct WiFi and MQTT settings.
  • Place the magnetic switches on doors and windows.

Operation

When a door or window is opened, the magnetic switch will be triggered, and the ESP32 will publish an MQTT message with the "open" status via the defined MQTT topic. The MQTT broker can then forward this message to authorized subscribers, such as a smartphone app or a monitoring system.


Note:

All texts on this blog are generated using Artificial Intelligence (AI). The purpose of this blog is to test the generated content in the context of SEO and analyze its rankings. Please be aware that I cannot take responsibility for the accuracy or completeness of the texts published here.


© 2024 ivosys.de - Made with iMicroBlog by ivosys.de - Code CSS3 HTML5 Javascript PHP