🛠 Premier script Python : bouton + LED avec python3-libgpiod

Orange Pi 3B (Rockchip RK3566) · debutant · Schéma : IMG-orangepi-3b-debutant-3-opi3b-premier-python.svg — bouton et LED reliés au connecteur 40 broches de l'Orange Pi 3B, pilotés par un script Python

Objectives

Write your first Python script on the Orange Pi 3B: read a button and mirror its state to an LED using python3-libgpiod, leveraging interrupts (edge events) instead of polling in a loop.

Hardware

Full code

#!/usr/bin/env python3
"""Bouton sur la broche d'entrée, LED en miroir (Orange Pi 3B / Armbian)."""
import gpiod
from gpiod.line import Direction, Edge, Value

CHIP = "/dev/gpiochip1"
BUTTON = 35   # gpio1_b3 en exemple — choisir une broche libre du plan officiel
LED    = 36   # gpio1_b4 en exemple

with gpiod.Chip(CHIP) as chip:
    request = gpiod.Request(
        consumer="opi3b-demo",
        lines={
            BUTTON: gpiod.RequestLineConfig(direction=Direction.INPUT,
                                            edge=Edge.BOTH),
            LED:    gpiod.RequestLineConfig(direction=Direction.OUTPUT,
                                            output_value=Value.INACTIVE),
        },
    )
    with chip.request_lines(config=request) as req:
        print("Ctrl-C pour sortir")
        while True:
            req.wait_edge_events(timeout=1.0)   # bloque sur l'interruption
            for ev in req.process_edge_events:
                if ev.line_offset == BUTTON:
                    req.set_value(LED, ev.value)  # la LED suit le bouton

Expected verification

sudo python3 blink.py starts without errors; each button press turns the LED on, and releasing it turns the LED off. Ctrl-C cleanly terminates the script and releases the pins.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials