Created
May 18, 2016 18:20
-
-
Save anonymous/54b3ebb246d7ec0fd1a0c72cb7b5700a to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains 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
// imports | |
extern crate serial; //see: https://dcuddeback.github.io/serial-rs/serial/index.html | |
use std::env; | |
use std::io; | |
use std::time::Duration; | |
use std::process::exit; | |
use std::io::prelude::*; | |
use serial::prelude::*; | |
use serial::{BaudRate, CharSize, Parity, StopBits, FlowControl, SystemPort, PortSettings, Error}; | |
use std::mem; | |
#[inline] | |
fn display_error_message(err: &Error, msg: &str) -> ! { | |
println!("{}", msg); | |
println!("Error Code: {:?}", err.raw_os_error()); | |
println!("Error: {:?}", err); | |
exit(0); | |
} | |
fn main() { | |
// open port | |
let mut port = match serial::open("COM3") { | |
Err(ref e) => display_error_message(e, "Error opening serial port"), | |
Ok(x) => x, | |
}; | |
// push settings to stack | |
let settings = PortSettings { | |
baud_rate: BaudRate::Baud115200, | |
char_size: CharSize::Bits8, | |
parity: Parity::ParityNone, | |
stop_bits: StopBits::Stop1, | |
flow_control: FlowControl::FlowNone, | |
}; | |
// configure port | |
match port.configure(&settings) { | |
Ok(_) => {} | |
Err(ref e) => display_error_message(e, "Error configuring serial port."), | |
}; | |
// set rts | |
match port.set_rts(true) { | |
Ok(_) => {} | |
Err(ref e) => display_error_message(e, "Error setting RTS line"), | |
}; | |
// set DTR | |
match port.set_dtr(true) { | |
Ok(_) => {} | |
Err(ref e) => display_error_message(e, "Error setting DTR line"), | |
}; | |
// allocate readbuffer on stack | |
let mut rb: [u8; 1] = [0u8; 1]; | |
// allocate buffer to hold output | |
let mut out: String = String::with_capacity(1024); | |
// loop while reading | |
loop { | |
match port.read(&mut rb) { | |
Ok(_) => {} | |
Err(ref e) => { | |
println!("Error reading serial port."); | |
println!("Error: {:?}", e); | |
exit(0); | |
} | |
}; | |
match rb[0] { | |
// Linefeed | |
10 => { | |
println!("{}<LF>", &out); | |
out = String::with_capacity(1024); | |
} | |
// carriage return | |
13 => { | |
println!("{}<CR>", &out); | |
out = String::with_capacity(1024); | |
} | |
// normal chars | |
32...126 => { | |
let temp: u32 = rb[0].clone() as u32; | |
let ch: char = unsafe { mem::transmute(temp) }; | |
out.push(ch); | |
} | |
// everything else | |
x => { | |
println!("Non standard character encountered"); | |
println!("Value: {:?}", x); | |
exit(0); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment