38 #define PWM_SYSFS_DEFAULT_PERIOD 10000000
42 #define PS_DEBUG_PRINT printf
44 #define PS_DEBUG_PRINT(...) {}
48 static int write_file(
const char *path,
const char *fmt, ...);
50 static int read_file(
const char *path,
const char *fmt, ...) __attribute__((unused));
53 char *_export,
char *_enable,
54 char *_duty,
char *_period,
60 if (base_path == NULL || _export == NULL || _enable == NULL ||
61 _period == NULL || _duty == NULL) {
68 snprintf(pwm->enable_path,
PWM_SYSFS_PATH_LEN,
"%s/pwm_%u/%s", base_path, channel, _enable);
69 snprintf(pwm->duty_path,
PWM_SYSFS_PATH_LEN,
"%s/pwm_%u/%s", base_path, channel, _duty);
70 snprintf(pwm->period_path,
PWM_SYSFS_PATH_LEN,
"%s/pwm_%u/%s", base_path, channel, _period);
73 export_path, pwm->enable_path, pwm->duty_path, pwm->period_path);
78 pwm->duty_cycle_fd = open(pwm->duty_path, O_RDWR | O_CLOEXEC);
79 if (pwm->duty_cycle_fd < 0) {
81 PS_DEBUG_PRINT(
"failed to open FD cycle: %d\n", pwm->duty_cycle_fd);
116 int en = enable ? 1 : 0;
127 static int write_file(
const char *path,
const char *fmt, ...)
131 int fd = open(path, O_WRONLY | O_CLOEXEC);
139 int ret = vdprintf(
fd, fmt, args);
140 int errno_bkp = errno;
152 static int read_file(
const char *path,
const char *fmt, ...)
156 FILE *file = fopen(path,
"re");
164 int ret = vfscanf(file, fmt, args);
165 int errno_bkp = errno;
void pwm_sysfs_set_period(struct PWM_Sysfs *pwm, uint32_t period)
#define PS_DEBUG_PRINT(...)
void pwm_sysfs_set_duty(struct PWM_Sysfs *pwm, uint32_t duty)
void pwm_sysfs_enable(struct PWM_Sysfs *pwm, bool enable)
static int read_file(const char *path, const char *fmt,...)
#define PWM_SYSFS_DEFAULT_PERIOD
static int write_file(const char *path, const char *fmt,...)
int pwm_sysfs_init(struct PWM_Sysfs *pwm, char *base_path, char *_export, char *_enable, char *_duty, char *_period, uint8_t channel)
PWM servos handling using Linux sysfs.
char enable_path[PWM_SYSFS_PATH_LEN]
path to enable file
int duty_cycle_fd
file descriptor to write/update duty cycle
uint32_t duty_cycle_nsec
current duty cycle (in nsec)
uint32_t period_nsec
current period (in nsec)
char duty_path[PWM_SYSFS_PATH_LEN]
path to duty file
char period_path[PWM_SYSFS_PATH_LEN]
path to period file
#define PWM_SYSFS_PATH_LEN
bool enabled
true if pwm is enabled
unsigned int uint32_t
Typedef defining 32 bit unsigned int type.
unsigned char uint8_t
Typedef defining 8 bit unsigned char type.