Skip to content

Commit f48e60d

Browse files
author
Matthew West
committed
When setting up a PWM pin, read period_ns & duty_ns
1 parent 565f2dc commit f48e60d

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

source/c_pwm.c

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -480,10 +480,8 @@ BBIO_err pwm_setup(const char *key, float duty, float freq, int polarity)
480480
BBIO_err pwm_start(const char *key, float duty, float freq, int polarity)
481481
{
482482
BBIO_err err;
483-
#ifdef BBBVERSION41
484483
char buffer[20];
485-
size_t len;
486-
#endif
484+
int len;
487485

488486
struct pwm_exp *pwm = lookup_exported_pwm(key);
489487
if (pwm == NULL) {
@@ -505,6 +503,37 @@ BBIO_err pwm_start(const char *key, float duty, float freq, int polarity)
505503
return err;
506504
}
507505

506+
// Read out current period_ns from the file, in order for it to behave
507+
// properly
508+
memset(buffer, 0, sizeof(buffer)); // Initialize buffer
509+
lseek(pwm->period_fd, 0, SEEK_SET);
510+
len = read(pwm->period_fd, buffer, sizeof(buffer));
511+
if (len < 0) {
512+
return BBIO_SYSFS;
513+
} else if (len >= sizeof(buffer)) {
514+
// If this is the case, there's more in the file.
515+
// This should never happen, as it would mean that
516+
// the period is 10^8 seconds
517+
return BBIO_SYSFS;
518+
}
519+
// Set the period_ns from the file
520+
sscanf(buffer, "%lu", &(pwm->period_ns));
521+
522+
// Read out the current duty_ns from the file, in order for it to
523+
// behave properly
524+
memset(buffer, 0, sizeof(buffer));
525+
lseek(pwm->duty_fd, 0, SEEK_SET);
526+
if (len < 0) {
527+
return BBIO_SYSFS;
528+
} else if (len >= sizeof(buffer)) {
529+
// If this is the case, there's more in the file.
530+
// This should never happen, as it would mean that
531+
// the period is 10^8 seconds
532+
return BBIO_SYSFS;
533+
}
534+
// Set the duty_ns from the file
535+
sscanf(buffer, "%lu", &(pwm->duty_ns));
536+
508537
// Initialize pwm->duty to avoid weirdness
509538
pwm->duty = duty;
510539
err = pwm_set_frequency(key, freq);

0 commit comments

Comments
 (0)