Created
December 15, 2020 10:38
-
-
Save uzuna/cd94c8ca7f4b53c1a77e36562904a234 to your computer and use it in GitHub Desktop.
read write serialport example
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
use std::env; | |
use std::io; | |
use std::path::Path; | |
use std::time::Duration; | |
extern crate serial; | |
use serial::prelude::*; | |
/// e.g. cargo run /dev/ttyUSB3 echo | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
println!("target: {:?}, cmd: {:?}", args.get(1), args.get(2)); | |
let mut port = serial_unix::TTYPort::open(Path::new(args.get(1).unwrap())).unwrap(); | |
interact(&mut port, args.get(2).unwrap()).unwrap(); | |
} | |
fn interact<T: SerialPort>(port: &mut T, cmd: &str) -> io::Result<()> { | |
// Deviceに合わせる | |
port.reconfigure(&|settings| { | |
settings.set_baud_rate(serial::Baud115200)?; | |
settings.set_char_size(serial::Bits8); | |
settings.set_parity(serial::ParityNone); | |
settings.set_stop_bits(serial::Stop1); | |
settings.set_flow_control(serial::FlowHardware); | |
Ok(()) | |
})?; | |
port.set_timeout(Duration::from_millis(1000))?; | |
port.write(&cmd.as_bytes())?; | |
// TODO 1024より長いケースのフォロー | |
let mut buf = [0; 1024]; | |
let size = port.read(&mut buf)?; | |
match size { | |
0 => { | |
println!("no response"); | |
} | |
x => { | |
println!("result:\n{}", std::str::from_utf8(&buf[0..x]).unwrap()); | |
} | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment