GPIO read status of input port

If you want to read the status of a GPIO input port use the following Python script.

 

The next Python script is reading the status of the GPIO PIN 22 on a 0/1 value and will print "closed"or "OPEN".

I use this script to read the status of the garage door.

---------------------------------------------------------------

#!/usr/bin/python3

from time import sleep
import os.path
#import gpiod
#from gpiod import Chip, LINE_REQ_DIR_IN, LINE_REQ_DIR_OUT, LINE_REQ_FLAG_BIAS_PULL_DOWN, LINE_REQ_FLAG_BIAS_PULL_UP, Line
from gpiod import Chip, LINE_REQ_DIR_IN, LINE_REQ_FLAG_BIAS_PULL_UP, Line

PI_PIN = 22

path = '/dev/gpiochip4'
check_file = os.path.exists(path)
if (check_file):
    GPIOCHIPSET = 'gpiochip4'
else:
    GPIOCHIPSET = 'gpiochip0'

#chip = gpiod.Chip('gpiochip4', gpiod.Chip.OPEN_BY_NAME)
chip = Chip(GPIOCHIPSET, Chip.OPEN_BY_NAME)
line = chip.get_line(PI_PIN)

try:
    line.request(consumer="gdoorget", type=LINE_REQ_DIR_IN, flags=LINE_REQ_FLAG_BIAS_PULL_UP)
except OSError:
    sleep(1)
    try:
        line.request(consumer="gdoorget", type=LINE_REQ_DIR_IN, flags=LINE_REQ_FLAG_BIAS_PULL_UP)
    except OSError:
        sleep(1)
        try:
            line.request(consumer="gdoorget", type=LINE_REQ_DIR_IN, flags=LINE_REQ_FLAG_BIAS_PULL_UP)
        except OSError:
            print("closed", end='')
        else:
            gdoor = line.get_value()
            if gdoor == 1:
                print("closed", end='')
            else:
                print("OPEN", end='')
    else:
        gdoor = line.get_value()
        if gdoor == 1:
            print("closed", end='')
        else:
            print("OPEN", end='')
else:
    gdoor = line.get_value()
    if gdoor == 1:
        print("closed", end='')
    else:
        print("OPEN", end='')

line.release()
exit()

-------------------------------------------------------------------------------------------------------------

  Donate now via the Paypal button on the top in US Dollar and on the bottom in Euro