#serial-port #serial-communication #serial #tty #baud-rate #com-port

serial2-tokio

cross platform serial ports for tokio based on the serial2 crate

4 releases

0.1.13 Jun 21, 2024
0.1.12 Jun 13, 2024
0.1.11 May 25, 2024
0.1.10 Apr 23, 2024
0.1.4 Oct 6, 2023

#546 in Hardware support

Download history 17/week @ 2024-07-05 27/week @ 2024-07-12 26/week @ 2024-07-19 71/week @ 2024-07-26 70/week @ 2024-08-02 64/week @ 2024-08-09 75/week @ 2024-08-16 83/week @ 2024-08-23 63/week @ 2024-08-30 78/week @ 2024-09-06 84/week @ 2024-09-13 94/week @ 2024-09-20 83/week @ 2024-09-27 66/week @ 2024-10-04 163/week @ 2024-10-11 99/week @ 2024-10-18

438 downloads per month

BSD-2-Clause OR Apache-2.0

32KB
426 lines

serial2-tokio

Serial port communication for tokio using serial2.

The serial2-tokio crate provides a cross-platform interface to serial ports. It aims to provide a simpler interface than other alternatives.

Currently supported features:

  • Simple interface: one SerialPort struct for all supported platforms.
  • List available ports.
  • Custom baud rates on all supported platforms except Solaris and Illumos.
  • Concurrent reads and writes from multiple tasks, even on Windows.
  • Purge the OS buffers (useful to discard read noise when the line should have been silent, for example).
  • Read and control individual modem status lines to use them as general purpose I/O.
  • Cross platform configuration of serial port settings:
    • Baud rate
    • Character size
    • Stop bits
    • Parity checks
    • Flow control
    • Read/write timeouts

You can open and configure a serial port in one go with SerialPort::open(). The second argument to open() must be a type that implements IntoSettings. In the simplest case, it is enough to pass a u32 for the baud rate. Doing that will also configure a character size of 8 bits with 1 stop bit and disables parity checks and flow control. For full control over the applied settings, pass a closure that receives the the current Settings and return the desired settings. If you do, you will almost always want to call Settings::set_raw() before changing any other settings.

The SerialPort struct implements the standard tokio::io::AsyncRead and tokio::io::AsyncWrite traits, as well as read() and write() functions that take &self instead of &mut self. This allows you to use the serial port concurrently from multiple tasks.

The SerialPort::available_ports() function can be used to get a list of available serial ports on supported platforms.

Example

This example opens a serial port and echoes back everything that is read.

use serial2_tokio::SerialPort;

// On Windows, use something like "COM1" or "COM15".
let port = SerialPort::open("/dev/ttyUSB0", 115200)?;
let mut buffer = [0; 256];
loop {
    let read = port.read(&mut buffer).await?;
    port.write(&buffer[..read]).await?;
}

Dependencies

~2–10MB
~95K SLoC