(Le Potato) Accessing Hardware PWM from C or C++

Hi, I have been able to successfully enable and control the hardware PWM output via the /sys/class/pwm interface as described in this tutorial: How to Enable and Control PWM on AML-S905X-CC.

I would like to be able to change the duty cycle and frequency of a pwm pin from inside my C/C++ code in response to other things my program does. I’ve directly written to the files inside of python code with the following and all works well.

def _echo(fil: str, msg):
    with open(fil, "w") as f:

def enable(enabled, pin_dir="/sys/class/pwm/pwmchip0/pwm1"):
    if enabled:
        _echo(f"{pin_dir}/enable", 1)
        _echo(f"{pin_dir}/enable", 0)

def set_duty_cycle_ns(duty_cycle_ns, pin_dir="/sys/class/pwm/pwmchip0/pwm1"):
    _echo(f"{pin_dir}/duty_cycle", duty_cycle_ns)

However other parts of my code require interacting with C libraries and I would like to keep all my code in one language. Is there a way to work with the hardware PWM timers inside of C or C++ without calling fopen and fclose?


You can either use the kernel sysfs interface via fopen/fclose or the kernel driver interface: Pulse Width Modulation (PWM) interface — The Linux Kernel documentation