🛠 Allumer une LED en C avec libgpiod sur le GPIO 40 broches

Raspberry Pi 3 Model A+ (2018) — Board Sheet · debutant · Schéma : IMG-model-3a-plus-debutant-1-model3a-led-gpio.svg — Raspberry Pi 3 Model A+ et son connecteur 40 broches : GPIO17 (broche 11) vers résistance 330 Ω puis LED, cathode vers GND (broche 14)

Objectives

Turn on an LED in C using libgpiod on GPIO17 of the 40-pin connector on the Raspberry Pi 3 Model A+ (Broadcom BCM2837B0 SoC). Understand the difference between physical pin and Broadcom number, and manipulate gpiochip0.

Hardware

Complete code

/* blink.c — Build: gcc blink.c -o blink -lgpiod (paquet libgpiod1-dev) */
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>

int main(void) {
    /* gpiochip0 = banque des GPIO du SoC sur le connecteur 40 broches */
    struct gpiod_chip *chip = gpiod_chip_open_by_name("gpiochip0");
    if (!chip) { perror("gpiochip0"); return 1; }

    struct gpiod_line *line = gpiod_chip_get_line(chip, 17); /* GPIO17 */
    if (gpiod_line_request_output(line, "blink", 0) < 0) { perror("request"); return 1; }

    for (int i = 0; i < 10; i++) {
        gpiod_line_set_value(line, 1);  /* LED on  */
        usleep(200000);
        gpiod_line_set_value(line, 0);  /* LED off */
        usleep(200000);
    }
    gpiod_line_release(line);
    gpiod_chip_close(chip);
    return 0;
}
sudo apt install -y libgpiod1-dev gcc
gcc blink.c -o blink -lgpiod && ./blink
# Sans compiler : sudo gpiodetect && sudo gpioset gpiochip0 17=1

Expected verification

gpiodetect displays gpiochip0; the LED blinks 10 times (200 ms ON / 200 ms OFF). Quick test without compiling: sudo gpioset gpiochip0 17=1 then 17=0.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials