PWM C Library
Explore Linux PWM interfaces, develop a reusable C library and install it system-wide before testing PWM control in a standalone application.
Practical Checklist
On platforms like the Arduino Uno, the PWM signal typically uses an 8-bit resolution, meaning the duty cycle can range from 0 to 255. This represents the fraction of time the signal is “high” within a given period, where 0 is 0% duty cycle (always off), and 255 is 100% duty cycle (always on).
The BeagleBone Black (BBB), however, is more flexible and powerful regarding PWM control due to its more advanced processor (AM335x). Let’s discuss the differences and what this means for using PWM on the BeagleBone Black.
1. PWM on the BeagleBone Black
1.1 Relating period, frequency and duty cycle
The frequency is the reciprocal of the period. When the period is given in nanoseconds:
\[ f,(\mathrm{Hz}) = \frac{10^9}{T,(\mathrm{ns})} \]
The duty-cycle percentage is:
\[ D,(\%) = \frac{t_{\mathrm{high}}}{T} \times 100 \]
| Intended waveform | Period | High time (50%) | Frequency |
|---|---|---|---|
| Slower PWM | 2000000 ns | 1000000 ns | 500 Hz |
| First lab setting | 1000000 ns | 500000 ns | 1 kHz |
| Faster PWM | 20000 ns | 10000 ns | 50 kHz |
1.2 PWM capabilities and applications
The AM335x processor includes enhanced PWM (eHRPWM) peripherals. Their available frequencies and timing precision depend on the hardware clock and configuration; a nanosecond-valued software interface does not imply arbitrarily fine hardware resolution. Refer to the Texas Instruments eHRPWM documentation.
Adjust the duty cycle to control the perceived brightness of an LED.
Choose a suitable switching frequency and duty cycle for the motor and driver.
Switching frequency affects ripple, efficiency and component sizing.
A filtered PWM waveform can approximate an analogue voltage, but it is not a true DAC.
1.3 Configure PWM through sysfs
The custom Device Tree overlay from the preceding lab enables EHRPWM1 on P9_14 / P9_16. The following commands use the /sys/class/pwm/pwmchip0/pwm0/ interface shown for this board. The available pwmchip numbering should match your earlier verification.
-
Configure a 1 kHz waveform with a 50% duty cycle. Set the period, then the high time, and enable the output.
Set period to 1,000,000 ns (1 ms for 1 kHz):
echo 1000000 > /sys/class/pwm/pwmchip0/pwm0/periodSet duty cycle to 500,000 ns (50% duty cycle):
echo 500000 > /sys/class/pwm/pwmchip0/pwm0/duty_cycleEnable the PWM output:
echo 1 > /sys/class/pwm/pwmchip0/pwm0/enable -
Reconfigure the PWM for 50 kHz at a 50% duty cycle. A frequency of 50 kHz corresponds to a period of 20,000 ns, with a high time of 10,000 ns.
Set period to 20,000 ns (20 µs for 50 kHz):
echo 20000 > /sys/class/pwm/pwmchip0/pwm0/periodSet duty cycle to 10,000 ns (50% duty cycle):
echo 10000 > /sys/class/pwm/pwmchip0/pwm0/duty_cycleEnable the PWM output:
echo 1 > /sys/class/pwm/pwmchip0/pwm0/enable
2: Building the PWM C library
-
Create the following directory and file:
- /home/debian/
- bbb_pwm/
- bbb_pwm.c
- bbb_pwm.h
- bbb_pwm/
mkdir bbb_pwm && cd bbb_pwm touch bbb_pwm.h bbb_pwm.c Makefile - /home/debian/
-
First, create a header file that declares the functions and defines necessary constants and structs, call the file
~/bbb_pwm/bbb_pwm.h:#ifndef BBB_PWM_H #define BBB_PWM_H #include <stdio.h> #include <stdlib.h> #include <string.h> // Base paths for PWM sysfs #define PWM_BASE_PATH "/sys/class/pwm" #define PWM_PERIOD_PATH "/sys/class/pwm/pwmchip%s/pwm%s/period" #define PWM_DUTY_CYCLE_PATH "/sys/class/pwm/pwmchip%s/pwm%s/duty_cycle" #define PWM_ENABLE_PATH "/sys/class/pwm/pwmchip%s/pwm%s/enable" //#define PWM_PIN_MODE_PATH "/sys/devices/platform/ocp/ocp:%s_pinmux/state" // Default vaules that will be used by pwm_clean_up #define PWM_PERIOD_DEFAULT 10000000 #define PWM_DUTY_CYCLE_DEFAULT 0 #define PWM_ENABLE_DEFAULT 0 // Structure to hold PWM mapping information typedef struct { char physical_pin[10]; // Physical pin on the BeagleBone Black (e.g., "P9_16") char pwm_chip_channel[10]; // PWM chip and channel (e.g., "0:0") } PinMap; // Define a structure to hold precomputed file paths for PWM control typedef struct { char phy_pin[10]; char chip[4]; char channel[4]; char period_path[128]; char duty_cycle_path[128]; char enable_path[128]; } PWM; // Define the pin_map array with physical pins and their corresponding PWM chip:channel PinMap phy_pin_map[] = { {"P9_14", "0:0"}, // eHRPWM1A {"P9_16", "0:1"}, // eHRPWM1B }; // Function prototypes int pwm_init(PWM *pwm, const char *pin_name); int pwm_cleanup(PWM *pwm); int pwm_set_period(PWM *pwm, unsigned int period_ns); int pwm_set_duty_cycle(PWM *pwm, unsigned int duty_cycle_ns); int pwm_enable(PWM *pwm); int pwm_disable(PWM *pwm); #endif // BBB_PWM_H -
Next, create the
bbb_pwm.cfile that implements the functions declared inbbb_pwm.h#include "bbb_pwm.h" // Initialize PWM structure with precomputed file paths int pwm_init(PWM *pwm, const char *pin_name) { // Parse the pwmchip and pwm channel char pwm_chip[4], pwm_channel[4]; for (int i = 0; i < sizeof(phy_pin_map) / sizeof(PinMap); i++) { if (strcmp(phy_pin_map[i].physical_pin, pin_name) == 0) { // Parse the pwmchip and pwm channel sscanf(phy_pin_map[i].pwm_chip_channel, "%[^:]:%s", pwm_channel, pwm_chip); } } // Store the PWM chip and channel as a string strncpy(pwm->phy_pin, pin_name, sizeof(pwm->phy_pin)); strncpy(pwm->chip, pwm_chip, sizeof(pwm->chip)); strncpy(pwm->channel, pwm_channel, sizeof(pwm->channel)); // Precompute the file paths using the defined base paths snprintf(pwm->period_path, sizeof(pwm->period_path), PWM_PERIOD_PATH, pwm_channel, pwm_chip); snprintf(pwm->duty_cycle_path, sizeof(pwm->duty_cycle_path), PWM_DUTY_CYCLE_PATH, pwm_channel, pwm_chip); snprintf(pwm->enable_path, sizeof(pwm->enable_path), PWM_ENABLE_PATH, pwm_channel, pwm_chip); //snprintf(pwm->pin_mode_path, sizeof(pwm->pin_mode_path), PWM_PIN_MODE_PATH, pin_name); // Set PWM pin for PWM mode //pwm_set_pin_mode(pwm); // Get PWM pin state //pwm_get_pin_mode(pwm); return 0; } // Clean up PWM structure (no-op in this case, but placeholder for future) int pwm_cleanup(PWM *pwm) { // No dynamic memory allocation done, so no cleanup needed pwm_set_period(pwm, PWM_PERIOD_DEFAULT); pwm_set_duty_cycle(pwm, PWM_DUTY_CYCLE_DEFAULT); pwm_enable(pwm); //pwm_unset_pin_mode(pwm); return 0; } // Set the PWM period int pwm_set_period(PWM *pwm, unsigned int period_ns) { FILE *fp = fopen(pwm->period_path, "w"); if (fp == NULL) { perror("Error opening period file"); return -1; } fprintf(fp, "%u", period_ns); fclose(fp); return 0; } // Set the PWM duty cycle int pwm_set_duty_cycle(PWM *pwm, unsigned int duty_cycle_ns) { FILE *fp = fopen(pwm->duty_cycle_path, "w"); if (fp == NULL) { perror("Error opening duty_cycle file"); return -1; } fprintf(fp, "%u", duty_cycle_ns); fclose(fp); return 0; } // Enable the PWM output int pwm_enable(PWM *pwm) { FILE *fp = fopen(pwm->enable_path, "w"); if (fp == NULL) { perror("Error opening enable file"); return -1; } fprintf(fp, "1"); fclose(fp); return 0; } // Disable the PWM output int pwm_disable(PWM *pwm) { FILE *fp = fopen(pwm->enable_path, "w"); if (fp == NULL) { perror("Error opening enable file"); return -1; } fprintf(fp, "0"); fclose(fp); return 0; }
3: Compile the Object File and Create Libraries
-
Compile
bbb_pwm.cinto an Object File by Using the following command to compilebbb_pwm.cinto an object file (bbb_pwm.o):gcc -c bbb_pwm.c -o bbb_pwm.o -
Create a Static Library (
libbbb_pwm.a) to create a static library, use thearcommand:ar rcs libbbb_pwm.a bbb_pwm.o -
Create a Shared Library (
libbbb_pwm.so) to create a shared library, use the followinggcccommand:gcc -shared -o libbbb_pwm.so bbb_pwm.o
4: Install the Header and Library Files System-Wide
-
You could manually copy the header file to
/usr/includeand the libraries to/usr/lib, or skip to the next section and create aMakefileto do it for you each time.sudo cp bbb_pwm.h /usr/include/ sudo cp libbbb_pwm.a /usr/lib/ sudo cp libbbb_pwm.so /usr/lib/ sudo ldconfig # Update the shared library cache
5: Automate with a Makefile
-
Instead of running these commands manually, you can automate the build process using a
Makefile.# Variables CC = gcc CFLAGS = -Wall -Werror -fPIC # -fPIC is needed for shared libraries AR = ar ARFLAGS = rcs TARGET_STATIC = libbbb_pwm.a TARGET_SHARED = libbbb_pwm.so OBJ = bbb_pwm.o # Default target: Build both libraries all: $(TARGET_STATIC) $(TARGET_SHARED) # Compile the pwm.c into an object file $(OBJ): bbb_pwm.c $(CC) $(CFLAGS) -c bbb_pwm.c -o $(OBJ) # Create the static library $(TARGET_STATIC): $(OBJ) $(AR) $(ARFLAGS) $(TARGET_STATIC) $(OBJ) # Create the shared library $(TARGET_SHARED): $(OBJ) $(CC) -shared -o $(TARGET_SHARED) $(OBJ) # Clean up build artifacts clean: rm -f $(OBJ) $(TARGET_STATIC) $(TARGET_SHARED) # Install libraries and header install: $(TARGET_STATIC) $(TARGET_SHARED) sudo cp bbb_pwm.h /usr/include/ sudo cp $(TARGET_STATIC) /usr/lib/ sudo cp $(TARGET_SHARED) /usr/lib/ sudo ldconfig # Uninstall libraries and header uninstall: sudo rm -f /usr/include/bbb_pwm.h sudo rm -f /usr/lib/$(TARGET_STATIC) sudo rm -f /usr/lib/$(TARGET_SHARED) sudo ldconfig # Phony targets .PHONY: all clean install uninstall
6: Creating the pwm_test program
-
Create a new
.cfile called...examples_C/pwm_test/pwm_test.cand chose your preferred editor to open it.mkdir ~/examples_C/pwm_test/ && cd ~/examples_C/pwm_test && touch pwm_test.c nano pwm_test.c -
Now we are going to set up the program to use our system wide library
bbb_pwm.h#include <bbb_pwm.h> #include <string.h> #include <unistd.h> int main() { PWM pwm; int period = 1000000; // Set period to 1 ms (1 kHz) int duty = 1000000; // Set duty cycle to 0.5 ms (50%) // Initialize the PWM structure for chip 0, channel 0 pwm_init(&pwm, "P9_14"); printf("Phy: %s\nChannel: %s\nChip: %s\nPeriod path: %s\nDuty Cycle path: %s\nEnable path: %s\n", pwm.phy_pin, pwm.channel, pwm.chip, pwm.period_path, pwm.duty_cycle_path, pwm.enable_path); pwm_set_period(&pwm, period); pwm_set_duty_cycle(&pwm, duty); pwm_enable(&pwm); sleep(2); pwm_set_duty_cycle(&pwm, 500000); sleep(2); pwm_set_duty_cycle(&pwm, 200000); sleep(2); pwm_set_duty_cycle(&pwm, 100000); pwm_disable(&pwm); pwm_cleanup(&pwm); return 0; } -
We can use this oneliner to compile the code:
gcc pwm_test.c -lbbb_pwm -o pwm_test -
Create the
Makefile# Compiler and flags CC = gcc CFLAGS = -Wall -Werror # Target executable name TARGET = pwm_test # Source files SRC = pwm_test.c # Library to link against LIBS = -lbbb_pwm # Default target: build the executable all: $(TARGET) # Build the executable $(TARGET): $(SRC) $(CC) $(CFLAGS) $(SRC) $(LIBS) -o $(TARGET) # Clean up build artifacts clean: rm -f $(TARGET) # Phony targets to avoid conflicts with files of the same name .PHONY: all clean -
Invoke make to build the executable:
make -
Run the code file to see if RGB Led changes colour, remember to wire up:

./pwm_test -
If all is well, and you have connected up your circuity correctly, the LED should show 100% then 50% then 10% and off, also this terminal output
Phy: P9_14 Channel: 0 Chip: 0 Period path: /sys/class/pwm/pwmchip0/pwm0/period Duty Cycle path: /sys/class/pwm/pwmchip0/pwm0/duty_cycle Enable path: /sys/class/pwm/pwmchip0/pwm0/enable