Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Last updated: Friday 13 November 2026 @ 17:29:40
BeagleBone Black • Revision D

Building a GPIO Library in C

Explore the Linux GPIO character-device interface, implement a reusable C library, install it system-wide, and build a program that controls an LED.

GPIOlibgpiodCStatic librariesShared librariesMake
Practical Checklist
Chapter checklist 0 / 14 completed

1. BeagleBone Black GPIO headers

The board has two 46-pin expansion headers, P8 and P9, giving 92 header positions in total. Many positions are dedicated to power, ground or other functions. The available GPIO function of a pad depends on its pinmux configuration and whether a kernel driver already owns it.

BeagleBone Black expansion headers

2. Discover and inspect GPIO lines

  1. Run gpiodetect to list GPIO controllers.

    gpiodetect
    gpiochip0 [gpio-0-31] (32 lines)
    gpiochip1 [gpio-32-63] (32 lines)
    gpiochip2 [gpio-64-95] (32 lines)
    gpiochip3 [gpio-96-127] (32 lines)
  2. Inspect the lines of a selected controller using gpioinfo.

    gpioinfo gpiochip0
    gpiochip0 - 32 lines:
            line   0: "P8_25 [mmc1_dat0]" unused input active-high
            line   1: "[mmc1_dat1]" unused input active-high
            line   2: "P8_5 [mmc1_dat2]" unused input active-high
            line   3: "P8_6 [mmc1_dat3]" unused input active-high
            line   4: "P8_23 [mmc1_dat4]" unused input active-high
            ...
            line  30: "P8_21 [emmc]" unused input active-high
            line  31: "P8_20 [emmc]" unused input active-high

    Look for line names, offsets, consumers and whether a line is already requested.

  1. Locate the intended header pin before driving it. The original example uses P9_12, but the chip/offset must be confirmed using the live line names or the board pinout. Check the board’s pinmux configuration and verify the line is free.

    gpioinfo | grep -F P9_12
            line  28:      "P9_12"       unused   input  active-high
  2. Wire an LED with a current-limiting resistor to a GPIO pin appropriate for the circuit. Record whether the circuit is active-high or active-low. The original active-high illustration is retained.

    LED circuit

    Use gpioget only after confirming the correct GPIO controller and offset:

    gpioget gpiochipN OFFSET

    The returned 0 or 1 is a logic value, not a direct measurement of supply voltage.

  1. For libgpiod 1.x tools, request the verified output line briefly using the appropriate active level. Following command should turn the led on.

    gpioset --mode=time -s 10 gpiochip0 28=1

    Observe how the LED behaves while the process holds the line. After the process exits, the line is released and its state is not guaranteed.

3. Create the reusable C library

Our library exposes bbb_lookup_pin(), bbb_open(), bbb_write(), bbb_read() and bbb_close(). It produces two outputs:

  • libbbb_gpio.a - a static archive linked into an executable.
  • libbbb_gpio.so - a shared object loaded by the dynamic linker at runtime.
  1. Create and enter the project directory.

    • /home/debian/
      • bbb_gpio/
    mkdir ~/bbb_gpio && cd bbb_gpio
  1. Create bbb_gpio.h, the public API header.

    touch bbb_gpio.h
    nano bbb_gpio.h
    #ifndef BBB_GPIO_H
    #define BBB_GPIO_H
    
    #include <gpiod.h>
    #include <stdbool.h>
    
    typedef struct {
        struct gpiod_chip *chip;
        struct gpiod_line *line;
        unsigned chip_index;
        unsigned offset;
    } BbbGpio;
    
    bool bbb_lookup_pin(const char *name, unsigned *chip, unsigned *offset);
    BbbGpio* bbb_open(const char *name, bool output, int init_val, const char *consumer);
    int bbb_write(BbbGpio *h, int value);
    int bbb_read(BbbGpio *h);
    void bbb_close(BbbGpio *h);
    
    #endif
  1. Create the library implementation bbb_gpio.c.

    touch bbb_gpio.c
    nano bbb_gpio.c
    #include "bbb_gpio.h"
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    // ==== Pin map (fill with your full table) ====
    typedef struct {
        const char *name;
        unsigned chip;
        unsigned offset;
    } PinMap;
    
    static const PinMap PINMAP[] = {
        {"P8_3",  0, 6}, {"P8_4",  0, 7}, {"P8_5",  0, 2}, {"P8_6",  0, 3},
        {"P8_7",  1, 2}, {"P8_8",  1, 3}, {"P8_9",  1, 5}, {"P8_10", 1, 4},
        {"P8_11", 0,13}, {"P8_12", 0,12}, {"P8_13", 3,23}, {"P8_14", 3,26},
        {"P8_15", 0,15}, {"P8_16", 0,14}, {"P8_17", 3,27}, {"P8_18", 1, 1},
        {"P8_19", 3,22}, {"P8_20", 0,31}, {"P8_21", 0,30}, {"P8_22", 0, 5},
        {"P8_23", 0, 4}, {"P8_24", 1, 1}, {"P8_25", 0, 0}, {"P8_26", 0,29},
        {"P8_35", 3, 8}, {"P9_11", 3,30}, {"P9_12", 0,28}, {"P9_13", 3,31},
        {"P9_15", 0,16}, {"P9_17", 3, 5}, {"P9_18", 3, 4}, {"P9_22", 3, 2},
        {"P9_23", 0,17}, {"P9_24", 3,15}, {"P9_25", 2,21}, {"P9_26", 3,14},
        {"P9_27", 2,19}, {"P9_29", 2,15}, {"P9_30", 2,16}, {"P9_31", 2,14},
        {"P9_41", 2,20},
    };
    static const size_t PINMAP_LEN = sizeof(PINMAP)/sizeof(PINMAP[0]);
    
    bool bbb_lookup_pin(const char *name, unsigned *chip, unsigned *offset) {
        for (size_t i = 0; i < PINMAP_LEN; ++i) {
            if (strcmp(PINMAP[i].name, name) == 0) {
                *chip   = PINMAP[i].chip;
                *offset = PINMAP[i].offset;
                return true;
            }
        }
        return false;
    }
    
    BbbGpio* bbb_open(const char *name, bool output, int init_val, const char *consumer) {
        unsigned chip_idx, offset;
        if (!bbb_lookup_pin(name, &chip_idx, &offset)) {
            fprintf(stderr, "Unknown pin: %s\n", name);
            return NULL;
        }
    
        char path[64];
        snprintf(path, sizeof(path), "/dev/gpiochip%u", chip_idx);
    
        struct gpiod_chip *chip = gpiod_chip_open(path);
        if (!chip) {
            perror("gpiod_chip_open");
            return NULL;
        }
    
        struct gpiod_line *line = gpiod_chip_get_line(chip, offset);
        if (!line) {
            perror("gpiod_chip_get_line");
            gpiod_chip_close(chip);
            return NULL;
        }
    
        int ret;
        if (output) {
            ret = gpiod_line_request_output(line, consumer ? consumer : "bbb_gpio", init_val);
        } else {
            ret = gpiod_line_request_input(line, consumer ? consumer : "bbb_gpio");
        }
    
        if (ret < 0) {
            perror("gpiod_line_request");
            gpiod_chip_close(chip);
            return NULL;
        }
    
        BbbGpio *h = calloc(1, sizeof(BbbGpio));
        h->chip = chip;
        h->line = line;
        h->chip_index = chip_idx;
        h->offset = offset;
        return h;
    }
    
    int bbb_write(BbbGpio *h, int value) {
        return gpiod_line_set_value(h->line, value);
    }
    
    int bbb_read(BbbGpio *h) {
        return gpiod_line_get_value(h->line);
    }
    
    void bbb_close(BbbGpio *h) {
        if (!h) return;
        if (h->line) gpiod_line_release(h->line);
        if (h->chip) gpiod_chip_close(h->chip);
        free(h);
    }

4. Compile and create libraries

  1. Compile the source to an object file. Use -fPIC so the same object can be used for the shared library.

    gcc -Wall -Wextra -O2 -fPIC -c bbb_gpio.c -o bbb_gpio.o

    Inspect the result:

    file bbb_gpio.o
  1. Build the static archive using ar.

    ar rcs libbbb_gpio.a bbb_gpio.o
    ar t libbbb_gpio.a
  1. Build the shared library and link its dependency on libgpiod.

    gcc -shared -o libbbb_gpio.so bbb_gpio.o -lgpiod
    file libbbb_gpio.so
    readelf -d libbbb_gpio.so | grep NEEDED

5. Install the library system-wide

  1. Inspect the manual installation commands that place the header and libraries in the system directories. Run them if completing the manual installation route.

    sudo cp bbb_gpio.h /usr/include/
    sudo cp libbbb_gpio.a /usr/lib/
    sudo cp libbbb_gpio.so /usr/lib/
    sudo ldconfig

    ldconfig updates the shared-library loader cache.

  1. Create a Makefile to automate the same compilation, archiving and installation tasks. Recipe lines must start with a Tab.

    # Compiler and flags
    CC      = gcc
    AR      = ar
    ARFLAGS = rcs
    CFLAGS  = -Wall -Wextra -Werror -O2 -fPIC
    LDFLAGS =
    LDLIBS  = -lgpiod
    
    # Targets
    TARGET_STATIC = libbbb_gpio.a
    TARGET_SHARED = libbbb_gpio.so
    
    # Source and object
    SRC = bbb_gpio.c
    OBJ = bbb_gpio.o
    HDR = bbb_gpio.h
    
    # Default target: build both libraries
    all: $(TARGET_STATIC) $(TARGET_SHARED)
    
    # Compile the C source into an object
    $(OBJ): $(SRC) $(HDR)
    	$(CC) $(CFLAGS) -c $(SRC) -o $(OBJ)
    
    # Create static library
    $(TARGET_STATIC): $(OBJ)
    	$(AR) $(ARFLAGS) $@ $^
    
    # Create shared library
    $(TARGET_SHARED): $(OBJ)
    	$(CC) -shared -o $@ $^ $(LDFLAGS) $(LDLIBS)
    
    # Clean up build artifacts
    clean:
    	rm -f $(OBJ) $(TARGET_STATIC) $(TARGET_SHARED)
    
    # ---- Install / Uninstall ----
    install: $(TARGET_STATIC) $(TARGET_SHARED)
    	sudo cp $(HDR) /usr/include/
    	sudo cp $(TARGET_STATIC) /usr/lib/
    	sudo cp $(TARGET_SHARED) /usr/lib/
    	sudo ldconfig
    
    uninstall:
    	sudo rm -f /usr/include/$(HDR)
    	sudo rm -f /usr/lib/$(TARGET_STATIC)
    	sudo rm -f /usr/lib/$(TARGET_SHARED)
    	sudo ldconfig
    
    .PHONY: all clean install uninstall
  1. Exercise the automated workflow. If you installed manually in the previous step, uninstall first; otherwise skip make uninstall until something is installed.

    make uninstall   # only if installed previously
    make clean
    make
    make install

    Expected build sequence (abbreviated):

    gcc -Wall -Wextra -Werror -O2 -fPIC -c bbb_gpio.c -o bbb_gpio.o
    ar rcs libbbb_gpio.a bbb_gpio.o
    gcc -shared -o libbbb_gpio.so bbb_gpio.o  -lgpiod

    Verify that the shared library is discoverable:

    ldconfig -p | grep libbbb_gpio

6. Use the library from a separate application

  1. Create the example application directory.

    cd ../ && mkdir -p examples_c/blink && cd examples_c/blink

    Create blink.c:

    touch blink.c && nano blink.c
  1. Write the application using the installed public header.

    #include <bbb_gpio.h>
    #include <unistd.h>
    #include <stdio.h>
    
    int main(void) {
        // Open P9_12 as output, initial value 0 (off)
        BbbGpio *led = bbb_open("P9_12", true, 0, "blink");
        if (!led) {
            fprintf(stderr, "Failed to open GPIO\n");
            return 1;
        }
    
        // Blink LED 5 times
        for (int i = 0; i < 5; i++) {
            bbb_write(led, 1);   // LED on
            usleep(500000);
            bbb_write(led, 0);   // LED off
            usleep(500000);
        }
    
        bbb_close(led);
        return 0;
    }
  1. Compile the application using either the command-line compiler or a Makefile.

    gcc -Wall -O2 blink.c -lbbb_gpio -lgpiod -o blink

    Create the following Makefile and run make:

    CC      = gcc
    CFLAGS  = -Wall -O2
    LDLIBS  = -lbbb_gpio -lgpiod
    
    TARGET  = blink
    SRC     = blink.c
    
    all: $(TARGET)
    
    $(TARGET): $(SRC)
    	$(CC) $(CFLAGS) $^ $(LDLIBS) -o $@
    
    clean:
    	rm -f $(TARGET)
    
    .PHONY: all clean
    make

    Check the linked dependencies:

    ldd ./blink
  1. Ensure the circuit is setup like below, if you didn't do it earlier.

    LED circuit

  2. Execute the program:

    ./blink

    The program attempts five on/off cycles at approximately half-second intervals. Verify the observed logic is consistent with the wiring and check for error messages.

7. Review