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
use std::fs::File;
use std::io;
use std::io::prelude::*;
pub use embedded_hal::digital::v2::OutputPin;
pub struct OutPin {
num: u32,
}
type Error = io::Error;
impl OutPin {
fn convert_to_absolute(port: u8, index: u8) -> u32 {
let port = port as u32;
let index = index as u32;
let outnum = (port - 1) * 32 + index;
outnum
}
pub fn force_new(port: u8, index: u8) -> Result<Self, Error> {
let num = Self::convert_to_absolute(port, index);
if let Ok(mut export) = File::create("/sys/class/gpio/unexport") {
let _e = export.write(num.to_string().as_bytes());
}
Self::new(port, index)
}
pub fn new(port: u8, index: u8) -> Result<Self, Error> {
let num = Self::convert_to_absolute(port, index);
let mut export = File::create("/sys/class/gpio/export")?;
export.write(num.to_string().as_bytes())?;
let mut direction = File::create(format!("/sys/class/gpio/gpio{}/direction", num))?;
direction.write("out".as_bytes())?;
Ok(OutPin { num })
}
}
impl OutputPin for OutPin {
type Error = io::Error;
fn set_low(&mut self) -> Result<(), Error> {
let mut direction = File::create(format!("/sys/class/gpio/gpio{}/value", self.num))?;
direction.write("0".as_bytes())?;
Ok(())
}
fn set_high(&mut self) -> Result<(), Error> {
let mut direction = File::create(format!("/sys/class/gpio/gpio{}/value", self.num))?;
direction.write("1".as_bytes())?;
Ok(())
}
}
impl Drop for OutPin {
fn drop(&mut self) {
if let Ok(mut unexport) = File::create("/sys/class/gpio/unexport") {
let _e = unexport.write(self.num.to_string().as_bytes());
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}