Complete Communications Engineering

Controlling GPIOs from Python requires running the correct Linux system calls from Python code.  Python includes built-in functions that can make system calls like open, read, write and ioctl.  This is how the standard libgpiod works.  Writing system-level code in Python can be time consuming, so in most cases using an existing Python package that already does this is easier.  One such package is python3-libgpiod which defines Python classes that work similar to the standard libgpiod API.  The following is an example Python program that uses this package:

#!/usr/bin/python

 

import time

import gpiod

 

CHIP_LABEL = “1-0077”

LINE_INDEX = 5

POLL_INTERVAL = 100 # milliseconds

 

mychip = gpiod.chip(CHIP_LABEL, gpiod.chip.OPEN_BY_LABEL)

myline = mychip.get_line(LINE_INDEX)

 

reqconfig = gpiod.line_request()

reqconfig.consumer = “gpiod_example”

reqconfig.flags = gpiod.line_request.FLAG_ACTIVE_LOW

reqconfig.request_type = gpiod.line_request.DIRECTION_INPUT

 

myline.request(reqconfig)

 

# Poll for 10 seconds

for i in range(int(10 * (1000 / POLL_INTERVAL))):

    state = myline.get_value()

    print(str(state))

    time.sleep(POLL_INTERVAL/1000)

When the python3-libgpiod package is properly installed, it can be imported using the name gpiod.  This example opens a chip by its label, which means it will search all GPIO chips and open the one that has a matching label.  After the chip is opened, it requests one line from the chip.  Next, the line is requested as an active low input.  This is the same procedure used to open an input GPIO using the standard libgpiod.  Once the line is requested, this example polls its value for 10 seconds and prints each value it reads.