forked from rust-embedded/rust-sysfs-gpio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blinky.rs
82 lines (75 loc) · 2.33 KB
/
blinky.rs
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
// Copyright 2015, Paul Osborne <[email protected]>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/license/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[macro_use]
extern crate sysfs_gpio;
use sysfs_gpio::{Direction, Pin};
use std::time::Duration;
use std::thread::sleep;
use std::env;
struct Arguments {
pin: u64,
duration_ms: u64,
period_ms: u64,
}
// Export a GPIO for use. This will not fail if already exported
fn blink_my_led(led: u64, duration_ms: u64, period_ms: u64) -> sysfs_gpio::Result<()> {
let my_led = Pin::new(led);
my_led.with_exported(|| {
// There is a known issue on Raspberry Pi with this.
// The exported GPIO doesn't have correct permissions
// immediatelly.
// Try adding sleep(Duration::from_millis(200)) here.
try!(my_led.set_direction(Direction::Low));
let iterations = duration_ms / period_ms / 2;
for _ in 0..iterations {
try!(my_led.set_value(0));
sleep(Duration::from_millis(period_ms));
try!(my_led.set_value(1));
sleep(Duration::from_millis(period_ms));
}
try!(my_led.set_value(0));
Ok(())
})
}
fn print_usage() {
println!("Usage: ./blinky <pin> <duration_ms> <period_ms>");
}
fn get_args() -> Option<Arguments> {
let args: Vec<String> = env::args().collect();
if args.len() != 4 {
return None;
}
let pin = match args[1].parse::<u64>() {
Ok(pin) => pin,
Err(_) => return None,
};
let duration_ms = match args[2].parse::<u64>() {
Ok(ms) => ms,
Err(_) => return None,
};
let period_ms = match args[3].parse::<u64>() {
Ok(ms) => ms,
Err(_) => return None,
};
Some(Arguments {
pin: pin,
duration_ms: duration_ms,
period_ms: period_ms,
})
}
fn main() {
match get_args() {
None => print_usage(),
Some(args) => {
match blink_my_led(args.pin, args.duration_ms, args.period_ms) {
Ok(()) => println!("Success!"),
Err(err) => println!("We have a blinking problem: {}", err),
}
}
}
}