一、用cargo创建新工程
命令:cargo new comport
use std::env;
use std::{thread, time};
use serialport::{DataBits, StopBits, Parity, FlowControl};
use std::io::{self, Read, Write};
use std::time::Duration;
fn main() -> io::Result<()> {
let mut args: Vec<String> = env::args().collect();
if args.len() < 1+3 {
println!("{} ComPort Baudrate Command [DelayMS]",args[0]);
std::process::exit(-1);
}
let mut duration: u64 = 100;//seconds
if args.len() > 1+3 {
duration = args[args.len()-1].parse::<u64>().unwrap();
}
let mut port = serialport::new(&args[1], args[1+1].parse::<u32>().unwrap())
.data_bits(DataBits::Eight).stop_bits(StopBits::One).parity(Parity::None)
.flow_control(FlowControl::None).timeout(Duration::from_secs(1)).open()?;
let offset = 1+1+1;
args[offset]=args[offset].replace("\\r", "\r");
args[offset]=args[offset].replace("\\n", "\n");
let data = &args[offset];
port.write_all(data.as_bytes())?;
thread::sleep(time::Duration::from_millis(duration));
let mut buffer: Vec<u8> = vec![0; 80000000];
let bytes_read = port.read(buffer.as_mut_slice())?;
let received_data = String::from_utf8_lossy(&buffer[..bytes_read]);
println!("Received: {}", received_data);
Ok(())
}
二、进入到新建工程文件夹并编译
命令:cd ./comport && cargo build
三、运行上面编译的工程
命令:cargo run COM6 921600 "AT\n"