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
| pub fn cmd_gpio_pwm(matches: &ArgMatches) { let fd = *matches.get_one::<u32>("fd").unwrap(); let channel = *matches.get_one::<u8>("channel").unwrap(); let frequency = *matches.get_one::<u32>("frequency").unwrap(); let duty_cycle = *matches.get_one::<u8>("duty_cycle").unwrap(); let pulse_count = *matches.get_one::<u32>("pulse_count").unwrap();
open_device(fd); if !set_pwm(fd, channel, frequency, duty_cycle, pulse_count) { eprintln!("Failed to set PWM"); } }
fn set_pwm(fd: u32, channel: u8, frequency: u32, duty_cycle: u8, pulse_count: u32) -> bool { let enable = 1 << channel; let dir_out = 1 << channel; let data_out = 1 << channel;
let period = 1_000_000 / frequency; let high_time = period * duty_cycle as u32 / 100; let low_time = period - high_time;
for _ in 0..pulse_count { if !gpio_set(fd, enable, dir_out, data_out) { return false; } thread::sleep(Duration::from_micros(high_time as u64));
if !gpio_set(fd, enable, dir_out, !data_out) { return false; } thread::sleep(Duration::from_micros(low_time as u64)); }
if pulse_count == 0 { loop { if !gpio_set(fd, enable, dir_out, data_out) { return false; } thread::sleep(Duration::from_micros(high_time as u64));
if !gpio_set(fd, enable, dir_out, !data_out) { return false; } thread::sleep(Duration::from_micros(low_time as u64)); } }
true }
|