Exploring Raspberry Pi 5 GPIO with Libgpiod: A Guide for Beginners

 
How to Control the Raspberry Pi 5 GPIO with Python 3
How to Control the Raspberry Pi 5 GPIO with Python 3

The Raspberry Pi 5: A New Generation of GPIO Interaction

The Raspberry Pi 5 has recently hit the market, offering improved power and performance. One significant change with this release is the GPIO (General Purpose Input/Output) interface, which, while still featuring 40 pins, now operates differently. In the Raspberry Pi 5, the GPIO is connected to the new RP1 southbridge chip. This change has important implications for coding and interacting with GPIO. 

In the past, many projects favored the use of RPi.GPIO, a community project led by Ben Croston, which served multiple generations of Raspberry Pi devices. However, with the introduction of the Raspberry Pi 5, RPi.GPIO is no longer a viable option due to the new memory mapping of GPIO pins. This necessitates the adoption of an alternative, and one such alternative is the focus of this guide: Libgpiod.

Libgpiod, specifically the Python module python3-gpiod, provides a pure Python solution for GPIO interaction. It offers a familiar feel to RPi.GPIO, requiring users to explicitly configure GPIO pins before utilizing them. Libgpiod can be considered an intermediate module for Python and GPIO. If you are new to this field, an even more user-friendly option is GPIO Zero, a library that also works seamlessly with the Raspberry Pi 5. GPIO Zero was developed by Ben Nuttall and Dave Jones, and it greatly simplifies GPIO usage for beginners.

In this guide, we'll walk you through two straightforward hardware projects using Libgpiod. The first project involves creating an output by blinking an LED, while the second project explores input by reacting to a button press to turn the LED on and off.

For these projects, you'll need:

- Raspberry Pi 5
- Breadboard
- 4 x male-to-female jumper wires
- 1x LED
- 100 Ohm resistor (Brown-Black-Brown-Gold)
- Push button

Project 1: Creating an Output - Blinking an LED


The initial step when learning any language or framework is to create a "Hello World" program. In the world of hardware, this is often symbolized by a blinking LED.

The circuit setup is extremely simple. Connect the long leg (anode) of an LED to GPIO 17 using a jumper wire. The short leg (cathode) is connected to GND via a resistor and another jumper wire. The resistor can have any value between 100 and 330 Ohms.

1. Open Thonny and import two essential modules: `gpiod`, used to control and read GPIO, and `time`, which introduces time intervals in your code.

```python
import gpiod
import time
```

2. Create a variable named `LED_PIN` and assign it the value 17. This variable contains the Broadcom pin reference for GPIO, which is a standard reference used across all Raspberry Pi models.

```python
LED_PIN = 17
```

3. Specify the location of the GPIO. With the Raspberry Pi 5 and the RP1 chip, GPIO is now at 'gpiomem4'.

```python
chip = gpiod.Chip('gpiochip4')
```

4. Create a variable called `led_line` and assign it a reference to the LED GPIO pin. The `gpiod` module uses lines to refer to GPIO pins.

```python
led_line = chip.get_line(LED_PIN)
```

5. Set the LED as an output, allowing current to flow to the LED.

```python
led_line.request(consumer="LED", type=gpiod.LINE_REQ_DIR_OUT)
```

6. Wrap the main code within a `try` block and a `while True` loop. This construct is essential for handling exceptions and ensuring your code runs continuously.

```python
try:
    while True:
```

7. Turn on the LED and wait for one second, forcing the LED to remain on for that duration.

```python
        led_line.set_value(1)
        time.sleep(1)
```

8. Turn off the LED and wait for one second, keeping it off for that duration.

```python
        led_line.set_value(0)
        time.sleep(1)
```

9. Add a section of code to clean up the GPIO when the program exits. While GPIO Zero handles this automatically, with Libgpiod (and the older RPi.GPIO), manual cleanup is necessary.

```python
finally:
    led_line.release()
```

10. Save the code as `blinky.py`, and click "Run" to start the program. The LED connected to GPIO 17 will blink on and off every second. You can press CTRL + C or click "Stop" to end the program.

Complete Code for Project 1:

```python
import gpiod
import time

LED_PIN = 17
chip = gpiod.Chip('gpiochip4')
led_line = chip.get_line(LED_PIN)
led_line.request(consumer="LED", type=gpiod.LINE_REQ_DIR_OUT)

try:
    while True:
        led_line.set_value(1)
        time.sleep(1)
        led_line.set_value(0)
        time.sleep(1)
finally:
    led_line.release()
```

Project 2: Creating an Input - Reacting to User Input


After creating the "Hello World" of hardware by blinking an LED, the next step is to work with inputs. In this project, we'll create a button that, when pressed, turns on an LED. The button is connected on one side to the Button GPIO pin and on the other side to 3V3. The Button GPIO pin has a default state of no power (0 or Low). When the button is pressed, it connects the 3V3 pin to the Button GPIO pin, changing its state to powered (1 or High). Our code will detect this state change and react accordingly. You'll need the button and two jumper wires for this project.

1. Open Thonny and import the necessary modules, `gpiod` for GPIO control and `time` for timing operations.

```python
import gpiod
import time
```

2. Create a variable called `LED_PIN` and set it to 17. This variable represents the GPIO pin for the LED.

```python
LED_PIN = 17
```

3. Create a variable called `BUTTON_PIN` and assign it the value 27. GPIO 27 is conveniently located next to GPIO 17.

```python
BUTTON_PIN = 27
```

4. Specify the location of the GPIO. With the Raspberry Pi 5 and the RP1 chip, the GPIO is at 'gpiomem4'.

```python
chip = gpiod.Chip('gpiochip4')
```

5. Create a variable named `led_line` and store a reference to the LED GPIO

 pin.

```python
led_line = chip.get_line(LED_PIN)
```

6. Create a variable named `button_line` and store a reference to the Button GPIO pin.

```python
button_line = chip.get_line(BUTTON_PIN)
```

7. Set the LED as an output to allow current to flow.

```python
led_line.request(consumer="LED", type=gpiod.LINE_REQ_DIR_OUT)
```

8. Set the Button as an input to detect changes in state.

```python
button_line.request(consumer="Button", type=gpiod.LINE_REQ_DIR_IN)
```

9. Wrap the main code in a `try` block and a `while True` loop, ensuring that your code can handle exceptions and run continuously.

```python
try:
    while True:
```

10. Retrieve the current state of the Button GPIO pin and store it in a variable called `button_state`.

```python
        button_state = button_line.get_value()
```

11. Use an `if` condition to check if the button has been pressed. If it has, turn on the LED. The default state of the Button GPIO pin is low (0 or False), but when the button is pressed, it connects the 3V pin of the Raspberry Pi 5 to the Button GPIO pin, changing the state to high (1 or True). This state change triggers our code.

```python
        if button_state == 1:  # Button is pressed
            led_line.set_value(1)  # Turn the LED on
```

12. Use an `else` condition to turn off the LED when the button is not pressed.

```python
        else:
            led_line.set_value(0)  # Turn the LED off
```

13. Add a section of code to clean up the GPIO when the program exits. With GPIO Zero, this step is automatic, but for Libgpiod (and the older RPi.GPIO), manual cleanup is required.

```python
finally:
    led_line.release()
    button_line.release()
```

14. Save the code as `button-press.py`, and click "Run" to start the program. Press the button to turn the LED on, and release it to turn it off. You can press CTRL + C or click "Stop" to end the program.

Complete Code for Project 2:

```python
import gpiod

LED_PIN = 17
BUTTON_PIN = 27
chip = gpiod.Chip('gpiochip4')
led_line = chip.get_line(LED_PIN)
button_line = chip.get_line(BUTTON_PIN)
led_line.request(consumer="LED", type=gpiod.LINE_REQ_DIR_OUT)
button_line.request(consumer="Button", type=gpiod.LINE_REQ_DIR_IN)

try:
    while True:
        button_state = button_line.get_value()
        if button_state == 1:
            led_line.set_value(1)
        else:
            led_line.set_value(0)
finally:
    led_line.release()
    button_line.release()
```

0 تعليقات

إرسال تعليق

Post a Comment (0)

أحدث أقدم