1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
/* SPDX-License-Identifier: 0BSD */
/* SPDX-FileCopyrightText: 2025 Uwe Kleine-König <u.kleine-koenig@baylibre.com> */
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwm.h>
int main(int argc, char *const argv[])
{
struct pwm_chip *chip;
struct pwm *pwm;
struct pwm_waveform wf = {
.period_length_ns = 50000,
.duty_length_ns = 25000,
.duty_offset_ns = 0,
};
int verbose = 0;
int npwm;
int ret;
int opt;
int duty_length_set = 0;
unsigned int chipno = 0;
unsigned int pwmno = 0;
while ((opt = getopt(argc, argv, "c:p:P:D:O:v")) != -1) {
switch (opt) {
case 'c':
chipno = atoi(optarg);
break;
case 'p':
pwmno = atoi(optarg);
break;
case 'P':
wf.period_length_ns = atoll(optarg);
break;
case 'D':
wf.duty_length_ns = atoll(optarg);
duty_length_set = 1;
break;
case 'O':
wf.duty_offset_ns = atoll(optarg);
break;
case 'v':
verbose = 1;
break;
default:
return EXIT_FAILURE;
}
}
/* Adapt default duty_length if period_length is small */
if (!duty_length_set && wf.duty_length_ns > wf.period_length_ns)
wf.duty_length_ns = wf.period_length_ns;
if (wf.duty_length_ns > wf.period_length_ns)
fprintf(stderr, "Warning: invalid waveform: duty_length = %llu > period_length = %llu\n",
(unsigned long long)wf.duty_length_ns, (unsigned long long)wf.period_length_ns);
if (wf.period_length_ns && wf.duty_offset_ns >= wf.period_length_ns)
fprintf(stderr, "Warning: invalid waveform: duty_offset = %llu >= period_length = %llu\n",
(unsigned long long)wf.duty_offset_ns, (unsigned long long)wf.period_length_ns);
chip = pwm_chip_open_by_number(chipno);
if (!chip) {
perror("Failed to open pwmchip0");
return EXIT_FAILURE;
}
if (verbose) {
npwm = pwm_chip_num_pwms(chip);
if (npwm < 0) {
perror("Failed to determine count of pwm");
return EXIT_FAILURE;
}
printf("Chip supports %u PWMs\n", npwm);
}
pwm = pwm_chip_get_pwm(chip, pwmno);
if (!pwm) {
perror("Failed to get pwm0");
return EXIT_FAILURE;
}
ret = pwm_round_waveform(pwm, &wf);
if (ret < 0) {
perror("Failed to configure PWM");
return EXIT_FAILURE;
}
pwm_chip_close(chip);
printf("period_length = %" PRIu64 "\nduty_length = %" PRIu64 "\nduty_offset = %" PRIu64 "\n",
wf.period_length_ns, wf.duty_length_ns, wf.duty_offset_ns);
return EXIT_SUCCESS;
}
|