一、用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 FindString [DelayMS]",args[0]);
std::process::exit(-1);
}
let mut offset: usize;
let mut duration: u64 = 100;
if args.len() > 1+3+1 {
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()?;
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);
offset=1+3;
if args.len() > offset && args[offset].len() != 0 {
if received_data.contains(&args[offset]) {
println!("Return=OK");
}else{
println!("Return=ERROR");
}
}
Ok(())
}
二、进入到新建工程文件夹并编译
命令:cd ./comport && cargo build
三、运行上面编译的工程
命令:cargo run COM6 921600 "AT\n"