win10系统rust串口通信实现

一、用cargo创建新工程

命令:cargo new comport

rust 复制代码
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"

相关推荐
DongLi012 天前
rustlings 学习笔记 -- exercises/05_vecs
rust
番茄灭世神2 天前
Rust学习笔记第2篇
rust·编程语言
shimly1234563 天前
(done) 速通 rustlings(20) 错误处理1 --- 不涉及Traits
rust
shimly1234563 天前
(done) 速通 rustlings(19) Option
rust
@atweiwei3 天前
rust所有权机制详解
开发语言·数据结构·后端·rust·内存·所有权
shimly1234563 天前
(done) 速通 rustlings(24) 错误处理2 --- 涉及Traits
rust
shimly1234563 天前
(done) 速通 rustlings(23) 特性 Traits
rust
shimly1234563 天前
(done) 速通 rustlings(17) 哈希表
rust
shimly1234563 天前
(done) 速通 rustlings(15) 字符串
rust
shimly1234563 天前
(done) 速通 rustlings(22) 泛型
rust