Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
only_motion_detector/sensor.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
39 lines (30 sloc)
866 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import RPi.GPIO as GPIO | |
import time | |
import paho.mqtt.client as mqtt | |
# MQTT settings | |
MQTT_BROKER = "your_mqtt_broker_ip" | |
MQTT_PORT = 1883 | |
MQTT_TOPIC = "home/motion" | |
# GPIO settings | |
PIR_PIN = 17 # GPIO pin connected to the PIR sensor | |
# Initialize GPIO | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(PIR_PIN, GPIO.IN) | |
# Initialize MQTT client | |
client = mqtt.Client() | |
client.connect(MQTT_BROKER, MQTT_PORT, 60) | |
def on_motion_detected(channel): | |
print("Motion Detected!") | |
client.publish(MQTT_TOPIC, "Motion Detected") | |
# Add event detection on the PIR pin | |
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=on_motion_detected) | |
try: | |
print("PIR Module Test (CTRL+C to exit)") | |
time.sleep(2) # to stabilize sensor | |
print("Ready") | |
# Keep the script running | |
while True: | |
time.sleep(1) | |
except KeyboardInterrupt: | |
print("Quit") | |
GPIO.cleanup() |