🛠 GPIO en C avec libgpiod : l'API caractère moderne

Raspberry Pi Zero (2015) — Board Sheet · avance · Schéma : IMG-zero-avance-2-gpio-en-c-libgpiod.svg — Zero avec en-tête 40 broches, LED + 330 Ω sur GPIO17 (broche 11), terminal affichant gpiodetect / gpioinfo gpiochip0, encart « gpiochip0 = BCM2835 ».

Goal

Drive the Zero's GPIO from C with the libgpiod character-device API — the maintained replacement for the deprecated sysfs and wiringPi approaches — and see what the BCM2835 exposes as a single GPIO chip.

Parts

Code

/* Build: gcc blink.c -o blink -lgpiod */
#include <gpiod.h>
#include <unistd.h>

int main(void) {
    struct gpiod_chip *chip = gpiod_chip_open_by_name("gpiochip0");
    if (!chip) return 1;   /* the BCM2835 exposes one chip */
    struct gpiod_line *led = gpiod_chip_get_line(chip, 17); /* GPIO17 */
    gpiod_line_request_output(led, "blink", 0);
    for (int i = 0; i < 10; i++) {   /* 10 blinks, ~0.2 W each */
        gpiod_line_set_value(led, i & 1);
        usleep(250000);
    }
    gpiod_line_release(led);
    gpiod_chip_close(chip);
    return 0;
}

CLI tour: gpiodetect, gpioinfo gpiochip0, gpioset gpiochip0 17=1.

Check

The LED blinks 5 times at 2 Hz. While the program runs, gpioinfo gpiochip0 shows line 17 requested by 'blink' — and released on exit, so no 'pin stuck high' mysteries.

Bare-metal warning

Official docs state the BCM2835 peripheral specification 'contains a number of errors': cross-check the community errata list (elinux.org BCM2835 datasheet errata) before trusting any register description in driver or bare-metal work.

Pitfalls

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials