Script to detect if circuit is open or closed on Raspberry Pi, Magnetic Reed Switch

Python and python framework

Moderator: leecollings

Post Reply
ben53252642
Posts: 543
Joined: Saturday 02 July 2016 5:17
Target OS: Linux
Domoticz version: Beta
Contact:

Script to detect if circuit is open or closed on Raspberry Pi, Magnetic Reed Switch

Post by ben53252642 »

Python script to detect if a circuit is open or closed.

Eg: connect a wire to GPIO pin 21 and the other end to ground and it will detect it as being closed, remove the wire and it detects as open.

Good for using with Magnetic reed switches around the house which are simple open or closed circuits.

Script sends status of switch to Domoticz on first launch and any time the state changes.

Instructions:
1) Change the GPIO Pin variable if you are using a GPIO other than 21
2) Set Domoticz ipaddress, username, password and IDX in the requests.get sections
3) Install the requirements for Python requests: apt-get install python-requests python3-requests

Code: Select all

# Requirements (covers multiple versions of Python):
# apt-get install python-requests python3-requests

import RPi.GPIO as GPIO
import time
import requests
from time import sleep
from requests.auth import HTTPBasicAuth
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

# Raspberry GPIO Configuration
gpiopin = 21

GPIO.setmode(GPIO.BCM)
GPIO.setup(gpiopin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

previous = "null"
while True:
    state = GPIO.input(gpiopin)
    if state == False and previous == "open" or state == False and previous == "null":
        print('Circuit Closed.')
        requests.get('https://IPADDRESS/json.htm?type=command&param=switchlight&idx=IDX&switchcmd=Off', auth=('USERNAME', 'PASSWORD'), verify=False)
        previous = "closed"
    if state != False and previous == "closed" or state != False and previous == "null":
        print('Circuit Open.')
        requests.get('https://IPADDRESS/json.htm?type=command&param=switchlight&idx=IDX&switchcmd=On', auth=('USERNAME', 'PASSWORD'), verify=False)
        previous = "open"
    sleep(1)

GPIO.cleanup(gpiopin)
Unless otherwise stated, all my code is released under GPL 3 license: https://www.gnu.org/licenses/gpl-3.0.en.html
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest