1.
toml
[dependencies] serial = "0.4.0" encoding = "0.2.33"
--
use std::io::{Read, Write}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use serial; use encoding::{DecoderTrap,EncoderTrap, Encoding}; use encoding::all::GBK; // extern crate serial; // use std::time::Duration; // use std::thread; use serial::prelude::*; use std::io::prelude::*; // pub fn write(&mut self, _v: &Vec<u8>) { // self.write(v) // } // } pub fn main() { const SETTINGS: serial::PortSettings = serial::PortSettings { baud_rate: serial::Baud9600, char_size: serial::Bits8, parity: serial::ParityNone, stop_bits: serial::Stop1, flow_control: serial::FlowNone, }; let mut pport = serial::open("COM41").unwrap(); pport.configure(&SETTINGS).unwrap(); pport.set_timeout(Duration::from_millis(10)).unwrap(); let port = Arc::new(Mutex::new(pport)); let p2 = Arc::clone(&port); // let p2 = port.clone(); let handle = thread::spawn(move || { let mut buf: Vec<u8> = (0..255).collect(); for j in 0..100 { let mut _bytes_read = p2.lock().unwrap(); if let Ok(zs) = _bytes_read.read(&mut buf[..]) { let data = GBK.decode(&buf[0..zs], DecoderTrap::Ignore).unwrap(); println!("{}",data); }else{ println!("none"); thread::sleep(Duration::from_millis(300)); } } }); // let request_temperature: Vec<u8> = vec![0xAA]; for i in 0..10 { { let mut ssend=port.lock().unwrap(); ssend.write(&GBK.encode("at\r\n", EncoderTrap::Ignore).unwrap()).unwrap(); // Mutex::unlock(ssend); } thread::sleep(Duration::from_millis(300)); } handle.join(); }
输出
OK none none OK OK none none none OK OK none none none OK none none OK OK none none none OK none none OK none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none none noneView Code
标签:none,OK,unwrap,use,let,串口,serial,多线程,Rust From: https://www.cnblogs.com/hardfood/p/16598393.html