The SerialPort trait is the primary cross-platform interface for interacting with serial ports. It provides methods for configuring port settings (baud rate, parity, etc.), controlling non-data signal pins (RTS, DTR), and reading/writing data. Because it inherits from std::io::Read and std::io::Write, you can use standard Rust I/O utilities with any object implementing SerialPort.
Key capabilities include:
- Configuration: Getters and setters for
baud_rate, data_bits, flow_control, parity, stop_bits, and timeout. - Signal Control:
write_request_to_send (RTS), write_data_terminal_ready (DTR), and reading signals like read_clear_to_send (CTS). - Buffer Management:
bytes_to_read, bytes_to_write, and clear to purge input/output buffers. - Cloning:
try_clone allows simultaneous reading and writing by creating a new handle to the same connection.
use serialport::SerialPort;
use std::io::{Read, Write};
// Assuming 'port' is a Box<dyn SerialPort>
let mut buffer = [0u8; 32];
port.read_exact(&mut buffer).unwrap();
port.write_all(b"hello").unwrap();