forked from rust-embedded/rust-sysfs-gpio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
poll.rs
57 lines (53 loc) · 1.8 KB
/
poll.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
// 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.
extern crate sysfs_gpio;
use sysfs_gpio::{Direction, Pin};
use std::env;
use std::thread::sleep;
use std::time::Duration;
fn poll(pin_num: u64) -> sysfs_gpio::Result<()> {
// NOTE: this currently runs forever and as such if
// the app is stopped (Ctrl-C), no cleanup will happen
// and the GPIO will be left exported. Not much
// can be done about this as Rust signal handling isn't
// really present at the moment. Revisit later.
let input = Pin::new(pin_num);
input.with_exported(|| {
try!(input.set_direction(Direction::In));
let mut prev_val: u8 = 255;
loop {
let val = try!(input.get_value());
if val != prev_val {
println!("Pin State: {}",
if val == 0 {
"Low"
} else {
"High"
});
prev_val = val;
}
sleep(Duration::from_millis(10));
}
})
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
println!("Usage: ./poll <pin>");
} else {
match args[1].parse::<u64>() {
Ok(pin) => {
match poll(pin) {
Ok(()) => println!("Polling Complete!"),
Err(err) => println!("Error: {}", err),
}
}
Err(_) => println!("Usage: ./poll <pin>"),
}
}
}