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 an ADC Library in C

Explore the AM335x analogue-to-digital converter through Linux's Industrial I/O interface, implement a reusable C library, install it system-wide, and develop an application that reads a potentiometer.

ADCIIOsysfsCStatic librariesShared librariesMake
Practical Checklist
Chapter checklist 0 / 17 completed

1. Discover the ADC in Linux

The BeagleBone Black’s AM335x includes a 12-bit ADC, with a nominal conversion range of 0–4095, and seven externally accessible inputs (AIN0–AIN6). The Linux Industrial I/O (IIO) driver exposes readings as files with names such as in_voltage0_raw.

  1. Confirm the ADC interface is visible after completing the overlay lab.

    ls /sys/bus/iio/devices/

    Example output:

    iio:device0

    The device number is assigned dynamically; your board might use a different iio:deviceN value.

  2. Check the device's reported name.

    grep -H . /sys/bus/iio/devices/iio:*/name

    Example output:

    /sys/bus/iio/devices/iio:device0/name:TI-am335x-adc.0.auto
  3. List the files exposed by the driver, including raw channel readings.

    ls -l /sys/bus/iio/devices/iio:device0/
    ls /sys/bus/iio/devices/iio:device0/in_voltage*_raw

    Confirm that iio:device0 is the ADC on your board before continuing. Our example library uses this path because it matches the configured lab board.

2. Read and interpret an analogue value

For a 12-bit ADC with a 1.8 V reference, the nominal conversion relationship is:

\[ V_{\mathrm{in}} \approx \frac{N}{4095}\times 1.8\ \mathrm{V} \]

where (N) is the raw ADC reading from 0 to 4095. The corresponding nominal voltage increment is (1.8/4096 \approx 0.439\ \mathrm{mV}) per code. Actual accuracy depends on reference stability and ADC errors.

  1. Read the current value from AIN0 (P9_39).

    cat /sys/bus/iio/devices/iio:device0/in_voltage0_raw

    An example reading is:

    2463

    Your result will depend on the voltage applied to the analogue input.

  2. Calculate the approximate input voltage. For an example ADC reading of 2048:

    \[ V_{\mathrm{in}} \approx \frac{2048}{4095}\times 1.8 = 0.9002\ \mathrm{V} \]

    Use your measured ADC reading to calculate a corresponding voltage.

  3. Observe the value changing when the potentiometer is adjusted. The reading should remain within the 12-bit range.

    cat /sys/bus/iio/devices/iio:device0/in_voltage0_raw

3. Create the ADC library project

We will implement an API called adc_get_value() that hides the file opening, reading, parsing and closing operations from application code. The result will be compiled into both libbbb_adc.a and libbbb_adc.so.

  1. Create the project directory and source files.

    • /home/debian/
      • bbb_adc/
        • bbb_adc.h
        • bbb_adc.c
        • Makefile
    cd ~
    mkdir -p bbb_adc && cd bbb_adc
    touch bbb_adc.h bbb_adc.c Makefile
  2. Edit bbb_adc.h and define the library's public API.

    nano bbb_adc.h
    #ifndef BBB_ADC_H_
    #define BBB_ADC_H_
    
    #define SYSFS_ADC_DIR "/sys/bus/iio/devices/iio:device0"
    #define MAX_BUF 256
    
    /* Return 0 on success, -1 on error. */
    int adc_get_value(unsigned int adcPin, unsigned int *value);
    
    /* Optional lower-level file-descriptor operations. */
    int adc_fd_open(unsigned int adcPin);
    int adc_fd_close(int fd);
    
    #endif /* BBB_ADC_H_ */

4. Implement the C library

The original program reads an IIO file using open(), read() and close(). We will retain that approach but also check the return values and terminate the input buffer before converting its contents to an integer.

  1. Open bbb_adc.c.

    nano bbb_adc.c
  2. Reproduce the implementation:

    #include "bbb_adc.h"
    
    #include <errno.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    int adc_fd_open(unsigned int adcPin)
    {
        char path[MAX_BUF];
    
        if (adcPin > 6) {
            errno = EINVAL;
            return -1;
        }
    
        int written = snprintf(path, sizeof(path),
                               SYSFS_ADC_DIR "/in_voltage%u_raw", adcPin);
        if (written < 0 || (size_t)written >= sizeof(path)) {
            errno = ENAMETOOLONG;
            return -1;
        }
    
        return open(path, O_RDONLY);
    }
    
    int adc_fd_close(int fd)
    {
        return close(fd);
    }
    
    int adc_get_value(unsigned int adcPin, unsigned int *value)
    {
        if (value == NULL) {
            errno = EINVAL;
            return -1;
        }
    
        int fd = adc_fd_open(adcPin);
        if (fd < 0) {
            perror("adc_fd_open");
            return -1;
        }
    
        char buffer[32];
        ssize_t count = read(fd, buffer, sizeof(buffer) - 1);
        int saved_errno = errno;
        adc_fd_close(fd);
    
        if (count <= 0) {
            errno = (count == 0) ? EIO : saved_errno;
            perror("adc_read");
            return -1;
        }
        buffer[count] = '\0';
    
        char *end;
        errno = 0;
        unsigned long result = strtoul(buffer, &end, 10);
        if (errno != 0 || end == buffer || result > 4095UL) {
            errno = EINVAL;
            return -1;
        }
    
        while (*end == '\n' || *end == '\r') {
            ++end;
        }
        if (*end != '\0') {
            errno = EINVAL;
            return -1;
        }
    
        *value = (unsigned int)result;
        return 0;
    }

5. Compile the static and shared libraries

An object file contains compiled code that has not yet been linked into an application. A static library is an archive of object files; a shared library is loaded dynamically when an executable runs.

  1. Compile bbb_adc.c into a position-independent object suitable for a shared library.

    gcc -Wall -Wextra -Werror -O2 -fPIC -c bbb_adc.c -o bbb_adc.o
  2. Verify the object file exists.

    ls -lh bbb_adc.o
  1. Build a static library using ar.

    ar rcs libbbb_adc.a bbb_adc.o
    ar t libbbb_adc.a

    The rcs options insert the object, create the archive if needed, and generate a symbol index.

  2. Build a shared library.

    gcc -shared -o libbbb_adc.so bbb_adc.o
    ls -lh libbbb_adc.a libbbb_adc.so

    The shared library is built from the same position-independent object file.

6. Install the ADC library system-wide

Installing into /usr/local keeps locally developed code separate from files managed by the operating system. Applications can then include <bbb_adc.h> and link with -lbbb_adc without referring to the original project directory.

  1. Copy the header and libraries into system-wide locations.

    sudo install -m 644 bbb_adc.h /usr/local/include/bbb_adc.h
    sudo install -m 644 libbbb_adc.a /usr/local/lib/libbbb_adc.a
    sudo install -m 755 libbbb_adc.so /usr/local/lib/libbbb_adc.so
    sudo ldconfig
  2. Check the installed files and the dynamic linker cache. y the input voltage must not exceed 1.8

    ls -l /usr/local/include/bbb_adc.h /usr/local/lib/libbbb_adc.*
    ldconfig -p | grep libbbb_adc

    If the shared library is not listed, verify that /usr/local/lib is included in the dynamic linker's configured search paths.

7. Automate with Make

The same compilation and installation process can be expressed as a Makefile. Recipe lines must begin with a real Tab character, not spaces.

  1. Open the Makefile in the ~/bbb_adc directory.

    nano Makefile
  2. Enter the following rules:

    CC = gcc
    AR = ar
    ARFLAGS = rcs
    CFLAGS = -Wall -Wextra -Werror -O2 -fPIC
    
    TARGET_STATIC = libbbb_adc.a
    TARGET_SHARED = libbbb_adc.so
    OBJ = bbb_adc.o
    HDR = bbb_adc.h
    PREFIX = /usr/local
    
    all: $(TARGET_STATIC) $(TARGET_SHARED)
    
    $(OBJ): bbb_adc.c $(HDR)
    	$(CC) $(CFLAGS) -c bbb_adc.c -o $@
    
    $(TARGET_STATIC): $(OBJ)
    	$(AR) $(ARFLAGS) $@ $^
    
    $(TARGET_SHARED): $(OBJ)
    	$(CC) -shared -o $@ $^
    
    install: all
    	install -m 644 $(HDR) $(DESTDIR)$(PREFIX)/include/$(HDR)
    	install -m 644 $(TARGET_STATIC) $(DESTDIR)$(PREFIX)/lib/$(TARGET_STATIC)
    	install -m 755 $(TARGET_SHARED) $(DESTDIR)$(PREFIX)/lib/$(TARGET_SHARED)
    	ldconfig
    
    uninstall:
    	rm -f $(DESTDIR)$(PREFIX)/include/$(HDR)
    	rm -f $(DESTDIR)$(PREFIX)/lib/$(TARGET_STATIC)
    	rm -f $(DESTDIR)$(PREFIX)/lib/$(TARGET_SHARED)
    	ldconfig
    
    clean:
    	rm -f $(OBJ) $(TARGET_STATIC) $(TARGET_SHARED)
    
    .PHONY: all install uninstall clean
  1. Clean the local build products, then rebuild both libraries.

    make clean
    make

    Expected command sequence (paths may differ):

    gcc -Wall -Wextra -Werror -O2 -fPIC -c bbb_adc.c -o bbb_adc.o
    ar rcs libbbb_adc.a bbb_adc.o
    gcc -shared -o libbbb_adc.so bbb_adc.o
  2. Install the newly built files, then inspect them.

    sudo make install
    ldconfig -p | grep libbbb_adc

    To uninstall a library created in this lab, use sudo make uninstall from the same project directory.

8. Build an application using the library

We will now write adc_read.c as a separate programme. Because the header and libraries are installed system-wide, the application does not need to copy the library’s implementation.

  1. Create an example directory.

    mkdir -p ~/examples_c/adc_read
    cd ~/examples_c/adc_read
    touch adc_read.c
  2. Open adc_read.c.

    nano adc_read.c
    #include <bbb_adc.h>
    #include <stdio.h>
    #include <unistd.h>
    
    int main(void)
    {
        for (unsigned int i = 0; i < 30; ++i) {
            unsigned int adc_reading = 0;
    
            if (adc_get_value(0, &adc_reading) != 0) {
                fprintf(stderr, "Failed to read ADC0\n");
                return 1;
            }
    
            double voltage = (adc_reading / 4095.0) * 1.8;
            printf("ADC: %u | Voltage: %.3f V\n", adc_reading, voltage);
            sleep(1);
        }
    
        return 0;
    }

    The original example intended to take 30 readings, but did not increment the loop counter. This version uses a for loop to stop after 30 measurements.

  1. Compile the programme, linking against the system-wide ADC library.

    gcc -Wall -Wextra -O2 adc_read.c -lbbb_adc -o adc_read

    The linker searches for a library named libbbb_adc.so (or libbbb_adc.a) because of -lbbb_adc.

  2. Create a Makefile.

    CC = gcc
    CFLAGS = -Wall -Wextra -O2
    LDLIBS = -lbbb_adc
    
    TARGET = adc_read
    SRC = adc_read.c
    
    all: $(TARGET)
    
    $(TARGET): $(SRC)
    	$(CC) $(CFLAGS) $< $(LDLIBS) -o $@
    
    clean:
    	rm -f $(TARGET)
    
    .PHONY: all clean

    Then build with:

    make
  1. With the board powered down while changing connections, wire a potentiometer to the analogue supply, ground and ADC0 input:

    • P9_32 — VDD_ADC, 1.8 V supply, to one outer potentiometer terminal.
    • P9_34 — GNDA_ADC, to the other outer terminal.
    • P9_39 — AIN0, to the centre (wiper) terminal.

    ADC circuit

    BeagleBone Black pinout

  2. Run the application and adjust the potentiometer.

    ./adc_read
    ADC: 4019 | Voltage: 1.767 V
    ADC: 3634 | Voltage: 1.597 V
    ADC: 2991 | Voltage: 1.315 V
    ADC: 2256 | Voltage: 0.992 V
    ADC: 1604 | Voltage: 0.705 V
    ADC: 681  | Voltage: 0.299 V

    The programme samples once per second for 30 samples and then exits.

9. Independent investigations