简体   繁体   中英

How to work with a serial port in Rust?

I need to perform a simple exchange via serial port in my program. I cannot find any working examples or documentation related to serial ports. I need to open a serial port, configure a port (set speed, parity, stopbits, etc), write/read binary data and then close is.

I tried to use https://github.com/japaric/serial.rs , but this library is outdated (it doesn't even compile on Rust 1.0). Even then, this library only provided functionally on how to configure the serial port but not to use it.

There are 2 solutions depending of OS where code is built. For *nix OS serial.rs library should work fine for rust 0.11.0 build but for supporting rust-0.12.0 an issue was opened and not closed yet.

For Windows stuff (mingw-w64) the serial.rs is not a simple solution because this lib is based on termios calls which are not easily setup for mingw. It comes from point that mingw is built against msvcrt not against glibc (for more information see here ). On Windows a simple solution would be to write a wrapper for library like rs232 by teuniz using rust FFI.

  1. Build library rs232 using mingw gcc;

  2. Create a wrapper in rust;

Short example for Windows looks like this:

extern crate libc;
use libc::{c_int,c_uchar,c_uint};
use std::os;
//
#[link(name = "rs232")]
extern {    
    fn RS232_OpenComport(comport_number:c_int, baudrate:c_int) ->c_int; 
    fn RS232_SendByte(comport_number:c_int, byte:c_uchar)->c_int;
    fn RS232_CloseComport(comport_number:c_int);
}
static  COM10:c_int=9;    
fn main() {
    let y=unsafe{RS232_OpenComport(COM10, 115200)};    
    unsafe{
        RS232_SendByte(COM10,101);  
        RS232_SendByte(COM10,100);
    }    
    let cl=unsafe{RS232_CloseComport(COM10)};
}

On UNIX serial port is represented by a character device, whcih can be accessed via ordinary system calls that are used for file I/O. The only addition that you would care about with respect to serial port is ioctl , that's what you will use to set baud rate and other parameters.

串行包工作正常。

If you need the ability to list serial devices (not only connect to them), then you need serialport , which is based on serial .

If you want to use serial, you should know that it was divided into small crates and you should use one or the other depending if you are developing a library or an executable. Check the readme and documentation for extra information.

Both crates are multi-platform and have recent updates, so it's a matter of deciding which API looks better to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM