Web-Based console for Raspberry Pi: python code to control GPIO

Posted by:

|

On:

|

The GPIO pin status on a Raspberry Pi is managed through the /sys/class/gpio/ directory in the Linux file system. This directory contains a series of files and directories that allow you to interact with the GPIO pins. When you configure a GPIO pin as an input or output, a corresponding entry is created in the /sys/class/gpio/ directory. The naming convention for these entries follows the pattern gpio<number>, where <number> represents the GPIO pin number. By reading from and writing to these files, you can control and monitor the status of GPIO pins on a Raspberry Pi programmatically.

It’s important to note that the /sys/class/gpio/ directory does not exist when the Raspberry Pi boots up. Therefore, if you attempt to read the files without a proper writing procedure, errors may occur. To avoid such errors, I use a try-except block in the code to handle exceptions gracefully.

    def read_pin_value(self):
        try:
            path = '/sys/class/gpio/gpio' + str(self.pin) + '/value'
            f = open(path,'r')
            value = f.readline().strip()
            return value
        except Exception as e:
            log.info('read pin value error: %s' % e)

Two separate Python files have been created to control two GPIO pins, each driving a separate LED. The first file, gpio.py, includes a class called “GpioManager,” which is responsible for reading and writing various GPIO files to control the pin value (high or low) and the direction (input or output). The second file, board_ctrl.py, utilizes the “GpioManager” class to accomplish three primary functions to can turn on a LED, turn off a LED and read the status of a LED :

def LED_on(pin):
    gpio = GpioManager(pin, 'out', 1)
    gpio.run_without_unexport()

def LED_off(pin):
    gpio = GpioManager(pin, 'out', 0)
    gpio.run_without_unexport()

def LED_status(LED_pin):
    gpio = GpioManager(LED_pin)
    value = gpio.read_pin_value()
    if value:
        value = int(value)
    return value

The temperature value of Raspberry Pi CPU is stored in “/sys/class/thermal/thermal_zone0/temp”. I created a function get_cpu_temp() in board_ctrl.py to read the CPU temperature from the file.

def get_cpu_temp():
    try:
        temp_file = open("/sys/class/thermal/thermal_zone0/temp")
        cpu_temp = temp_file.read()
        temp_file.close()
        return str(float(cpu_temp)/1000) + " °C"
    except:
        return 'N/A'

These two Python scripts can be downloaded from GitHub using the following link

https://github.com/FelixT123/CS-Student/blob/main/web-based%20console/board_ctrl.py

https://github.com/FelixT123/CS-Student/blob/main/web-based%20console/gpio.py

Posted by

in