|
| 1 | +// Copyright 2016, Paul Osborne <osbpau@gmail.com> |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 4 | +// http://www.apache.org/license/LICENSE-2.0> or the MIT license |
| 5 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 6 | +// option. This file may not be copied, modified, or distributed |
| 7 | +// except according to those terms. |
| 8 | +// |
| 9 | +// Portions of this implementation are based on work by Nat Pryce: |
| 10 | +// https://github.com/npryce/rusty-pi/blob/master/src/pi/gpio.rs |
| 11 | + |
| 12 | +extern crate sysfs_pwm; |
| 13 | +use sysfs_pwm::{Pwm, Result}; |
| 14 | + |
| 15 | +const RPI_PWM_CHIP: u32 = 1; |
| 16 | +const RPI_PWM_NUMBER: u32 = 127; |
| 17 | + |
| 18 | +fn pwm_increase_to_max(pwm: &Pwm, |
| 19 | + duration_ms: u32, |
| 20 | + update_period: u32) -> Result<()> { |
| 21 | + let step: f32 = duration_ms as f32 / update_period as f32; |
| 22 | + let mut duty_cycle: f32 = 0.0; |
| 23 | + while duty_cycle < 1.0 { |
| 24 | + try!(pwm.set_duty_cycle(duty_cycle)); |
| 25 | + duty_cycle += step; |
| 26 | + } |
| 27 | + pwm.set_duty_cycle(1.0) |
| 28 | +} |
| 29 | + |
| 30 | +fn pwm_decrease_to_minimum(pwm: &Pwm, |
| 31 | + duration_ms: u32, |
| 32 | + update_period: u32) -> Result<()> { |
| 33 | + let step: f32 = duration_ms as f32 / update_period as f32; |
| 34 | + let mut duty_cycle = 1.0; |
| 35 | + while duty_cycle > 0.0 { |
| 36 | + try!(pwm.set_duty_cycle(duty_cycle)); |
| 37 | + duty_cycle -= step; |
| 38 | + } |
| 39 | + pwm.set_duty_cycle(0.0) |
| 40 | +} |
| 41 | + |
| 42 | +/// Make an LED "breathe" by increasing and |
| 43 | +/// decreasing the brightness |
| 44 | +fn main() { |
| 45 | + let pwm = Pwm::new(RPI_PWM_CHIP, RPI_PWM_NUMBER).unwrap(); // number depends on chip, etc. |
| 46 | + pwm.with_exported(|| { |
| 47 | + pwm.set_active(true).unwrap(); |
| 48 | + loop { |
| 49 | + pwm_increase_to_max(&pwm, 1000, 20).unwrap(); |
| 50 | + pwm_decrease_to_minimum(&pwm, 1000, 20).unwrap(); |
| 51 | + } |
| 52 | + }).unwrap(); |
| 53 | +} |
0 commit comments