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"

相关推荐
wflynn4 小时前
GitHub 今日推荐|kiri:clone3 系统调用直达容器,2.5 毫秒启动无 runc 中间层
docker·rust·kubernetes·开源·github·containers
SomeOtherTime7 小时前
第 4 讲:突破静态枷锁——智能指针(Box/Rc/Arc)与内部可变性(Cell/RefCell/UnsafeCell)的内存暗道
rust
byte轻骑兵13 小时前
【L2CAP】规范精讲[5]: 从 Echo 探测到能力协商——连接建立后的信息查询三部曲
信息与通信·通信·蓝牙协议·l2cap·蓝牙链路管理
SomeOtherTime14 小时前
第 9 讲:异步并发与 Pin 的底层解剖——async/await 无栈协程状态机脱糖、自引用死锁的终极救赎与 Future/Waker 驱动模型
rust
wflynn1 天前
GitHub 今日推荐|Stela:在 PC 上直接启动 macOS 的翻译层
rust·开源·github
aifannihao1 天前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
鶴哥只手遮天2 天前
《rustc 内幕》第 1 章 全景:rustc 编译流水线与 crate 版图
后端·rust·开源
SomeOtherTime2 天前
Rust 闭包语法和原理(AI回答)
开发语言·后端·rust
SomeOtherTime3 天前
Rust集合(AI回答)
开发语言·后端·rust
SomeOtherTime3 天前
Rust 泛型与特性讲解(AI回答)
rust