Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- // Replace with your Wi-Fi credentials
- const char* ssid = "WiFi-SSID";
- const char* password = "WI-FI_PASSWORD";
- // MQTT Server details
- const char* mqtt_server = "192.168.0.xxx";
- const char* mqtt_user = "USERNAME";
- const char* mqtt_password = "PASSWORD";
- const int mqtt_port = 1883;
- // PIR Sensor
- int LED = LED_BUILTIN; // Choose the pin for the LED
- int pirPin = 3; // Using the RX Pin as input from the PIR
- int val = 0; // Variable for reading the pin status
- WiFiClient espClient;
- PubSubClient client(espClient);
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Message arrived [");
- Serial.print(topic);
- Serial.print("] ");
- for (unsigned int i = 0; i < length; i++) {
- Serial.print((char)payload[i]);
- }
- Serial.println();
- }
- void blink(int times, int delayTime) {
- for (int j = 1; j <= times; j++) {
- digitalWrite(LED, LOW);
- delay(delayTime);
- digitalWrite(LED, HIGH);
- delay(delayTime);
- }
- }
- void connectToMQTT() {
- while (!client.connected()) {
- Serial.println("Connecting to MQTT server...");
- if (client.connect("espClient", mqtt_user, mqtt_password)) {
- Serial.println("Connected to MQTT server");
- client.setCallback(callback);
- client.subscribe("inTopic");
- } else {
- Serial.print("Failed to connect, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- delay(5000);
- }
- }
- }
- void setup() {
- pinMode(LED, OUTPUT);
- digitalWrite(LED, HIGH);
- pinMode(pirPin, INPUT);
- Serial.begin(115200);
- delay(10);
- WiFi.begin(ssid, password);
- Serial.print("Connecting to WiFi");
- while (WiFi.status() != WL_CONNECTED) {
- delay(1000);
- Serial.print(".");
- }
- Serial.println("\nConnected to WiFi");
- client.setServer(mqtt_server, mqtt_port);
- blink(3, 100);
- connectToMQTT();
- }
- void loop() {
- if (!client.connected()) {
- connectToMQTT();
- }
- client.loop();
- val = digitalRead(pirPin);
- Serial.print("PIR Sensor Value: ");
- Serial.println(val); // Debug print for PIR sensor value
- if (val == HIGH) {
- digitalWrite(LED, LOW);
- Serial.println("Motion Detected!");
- if (client.publish("MainEntrancePir/sensor", "Motion Detected!")) {
- Serial.println("Motion Detected message sent");
- } else {
- Serial.println("Failed to send Motion Detected message");
- }
- delay(10000); // short delay before checking the PIR again
- } else {
- digitalWrite(LED, HIGH);
- Serial.println("No Motion Detected.");
- if (client.publish("MainEntrancePir/sensor", "No Motion Detected.")) {
- Serial.println("No Motion Detected message sent");
- } else {
- Serial.println("Failed to send No Motion Detected message");
- }
- delay(2000);
- blink(1, 200);
- ESP.deepSleep(0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment