Created
June 6, 2017 20:57
-
-
Save kochka/89bed0bee591aa506827dda97c411f50 to your computer and use it in GitHub Desktop.
Rust - Blinking led
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
use std::thread; | |
use std::sync::{Arc, Mutex}; | |
use std::time::Duration; | |
#[derive(Debug,Clone)] | |
pub struct Led { inner: Arc<Mutex<LedInner>> } | |
#[derive(Debug,Clone)] | |
struct LedInner { | |
gpio: u8, | |
animation: bool, | |
} | |
impl Led { | |
fn new(gpio: u8) -> Led { | |
Led { | |
inner: Arc::new(Mutex::new(LedInner { gpio: gpio, animation: false })) | |
} | |
} | |
fn on(&self) { | |
self.stop_animation(); | |
self.set_on(); | |
} | |
fn off(&self) { | |
self.stop_animation(); | |
self.set_off(); | |
} | |
fn toggle(&self) { | |
println!("Toggle"); | |
} | |
fn blink(&mut self, speed: LedBlinkSpeed) { | |
let led = self.clone(); | |
thread::spawn(move || { | |
led.inner.lock().unwrap().animation = true; | |
loop { | |
if led.inner.lock().unwrap().animation == false { | |
break; | |
} | |
led.set_on(); | |
thread::sleep(Duration::from_millis(speed.value())); | |
led.set_off(); | |
thread::sleep(Duration::from_millis(speed.value())); | |
} | |
}); | |
} | |
fn set_on(&self) { | |
println!("On {}", self.inner.lock().unwrap().gpio); | |
} | |
fn set_off(&self) { | |
println!("Off {}", self.inner.lock().unwrap().gpio); | |
} | |
fn stop_animation(&self) { | |
self.inner.lock().unwrap().animation = false; | |
} | |
} | |
impl Drop for Led { | |
fn drop(&mut self) { | |
println!("Dropping!"); | |
} | |
} | |
// Led Blinking speeds | |
enum LedBlinkSpeed { | |
Slow, | |
Fast, | |
Set(u64), | |
} | |
impl LedBlinkSpeed { | |
fn value(&self) -> u64 { | |
match *self { | |
LedBlinkSpeed::Slow => 500, | |
LedBlinkSpeed::Fast => 200, | |
LedBlinkSpeed::Set(x) => x, | |
} | |
} | |
} | |
fn main() { | |
let mut led = Led::new(18); | |
println!("{:?}", led); | |
led.on(); | |
led.off(); | |
println!("Blinking"); | |
led.blink(LedBlinkSpeed::Fast); | |
thread::sleep(Duration::from_secs(5)); | |
led.off(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment