Created
January 28, 2017 04:39
-
-
Save fudanchii/581792e006385489995e54624500f6d0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate lazy_static; | |
use std::io::prelude::*; | |
use std::fs::OpenOptions; | |
use std::path::{Path, PathBuf}; | |
use std::time::Duration; | |
use std::thread; | |
lazy_static! { | |
static ref GPIO_PATH: &'static Path = Path::new("/sys/class/gpio"); | |
} | |
macro_rules! sysfs_write { | |
($arg1:expr, $arg2:expr) => ({ | |
let mut f = OpenOptions::new() | |
.read(false) | |
.write(true) | |
.create(false) | |
.open($arg1) | |
.expect(format!("Cannot open file: {:?}", $arg1).as_str()); | |
f.write(format!("{}", $arg2).as_bytes()) | |
.expect(format!("Cannot write file: {:?}. with data: {:?}", $arg1, $arg2).as_str()); | |
}) | |
} | |
struct GPIO { | |
pin: u8, | |
sys_path: PathBuf, | |
} | |
impl GPIO { | |
fn new(pin: u8) -> GPIO { | |
sysfs_write!(GPIO_PATH.join("export"), pin); | |
GPIO { | |
pin: pin, | |
sys_path: GPIO_PATH.join(format!("gpio{:?}", pin)), | |
} | |
} | |
fn sys_read(&self, f: &str) -> String { | |
let mut f = OpenOptions::new() | |
.read(true) | |
.write(false) | |
.open(GPIO_PATH.join(format!("gpio{:?}", self.pin)).join(f)) | |
.expect(format!("Cannot open GPIO{:?}", self.pin).as_str()); | |
let mut out = String::new(); | |
f.read_to_string(&mut out) | |
.expect(format!("Cannot read GPIO{:?}", self.pin).as_str()); | |
out | |
} | |
fn set_dir(&self, dir: &str) -> Result<&GPIO, &str> { | |
match dir { | |
"in" | "out" => sysfs_write!(self.sys_path.join("direction"), dir), | |
_ => return Err("invalid value"), | |
} | |
Ok(self) | |
} | |
fn get_dir(&self) -> String { | |
self.sys_read("direction") | |
} | |
fn hi(&self) { | |
sysfs_write!(self.sys_path.join("value"), 1); | |
} | |
fn lo(&self) { | |
sysfs_write!(self.sys_path.join("value"), 0); | |
} | |
} | |
fn main() { | |
let led1 = GPIO::new(44); | |
led1.set_dir("out").ok(); | |
loop { | |
led1.lo(); | |
thread::sleep(Duration::from_secs(1)); | |
led1.hi(); | |
thread::sleep(Duration::from_secs(1)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment