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"

相关推荐
Source.Liu29 分钟前
【time-rs】解释://! Error that occurred at some stage of parsing(error/parse.rs)
rust·time
无名38733 分钟前
FreeSWITCH limit 中文手册
通信
程序员大辉1 小时前
Rust使用IDE,除了vscode还有RustRover非商业用户可以免费使用
ide·vscode·rust
盒马盒马20 小时前
Rust:内部可变性 & 型变
开发语言·后端·rust
云水木石1 天前
Rust 语言开发的 Linux 桌面来了
linux·运维·开发语言·后端·rust
Source.Liu1 天前
【time-rs】解释://! Invalid format description(error/invalid_format_description.rs)
rust·time
fegggye1 天前
创建一个rust写的python库[signatures和错误处理]
开发语言·python·rust
Source.Liu1 天前
【time-rs】解释://! Indeterminate offset(error/indeterminate_offset.rs)
rust·time
福大大架构师每日一题1 天前
rust 1.92.0 更新详解:语言特性增强、编译器优化与全新稳定API
java·javascript·rust
xixixi777771 天前
系统性地解析——边缘计算(从定义与驱动力、核心架构、关键技术特征、与云计算的范式对比、典型应用场景以及挑战与趋势等方面)
安全·架构·云计算·边缘计算·信息与通信·通信·反诈