如何在 Rust 的串口箱中使用 read_line 函数
How to use read_line function with Rust's serialport crate
我正在使用 serialport crate 开发树莓派。 port.read
的给定示例工作正常。但是 port.read_to_end
或 port.read_to_string
不起作用,我超时了。
谁能解释这种行为?这两个函数读取所有字节直到 EOF。我正在发送以空终止符结尾的测试字符串。
我对 read_line
函数更感兴趣。但是 serialport crate 并不直接支持它,是吗?我可以为此使用 BufRead 特性吗?
这里是 read_line
的最小示例。在连接 TX 和 RX 时工作。
use serialport;
use std::time::Duration;
use std::io::BufReader;
use std::io::BufRead;
fn main() {
let mut serial_port = serialport::new("/dev/serial0", 9600)
.timeout(Duration::from_millis(1000))
.open()
.expect("Failed to open serial port");
let output = "This is a test.\n".as_bytes();
serial_port.write(output).expect("Write failed!");
serial_port.flush().unwrap();
let mut reader = BufReader::new(serial_port);
let mut my_str = String::new();
reader.read_line(&mut my_str).unwrap();
println!("{}", my_str);
}
我正在使用 serialport crate 开发树莓派。 port.read
的给定示例工作正常。但是 port.read_to_end
或 port.read_to_string
不起作用,我超时了。
谁能解释这种行为?这两个函数读取所有字节直到 EOF。我正在发送以空终止符结尾的测试字符串。
我对 read_line
函数更感兴趣。但是 serialport crate 并不直接支持它,是吗?我可以为此使用 BufRead 特性吗?
这里是 read_line
的最小示例。在连接 TX 和 RX 时工作。
use serialport;
use std::time::Duration;
use std::io::BufReader;
use std::io::BufRead;
fn main() {
let mut serial_port = serialport::new("/dev/serial0", 9600)
.timeout(Duration::from_millis(1000))
.open()
.expect("Failed to open serial port");
let output = "This is a test.\n".as_bytes();
serial_port.write(output).expect("Write failed!");
serial_port.flush().unwrap();
let mut reader = BufReader::new(serial_port);
let mut my_str = String::new();
reader.read_line(&mut my_str).unwrap();
println!("{}", my_str);
}