How to work with serialport in Rust?
I need to use simple serial communication in my program. Unfortunately, I can't find any working examples or tutorials related to serial ports. I just need an open serial port, a port setting (given baud rate, parity, stops, etc.), Binary data write / read and close.
I tried using https://github.com/japaric/serial.rs but this library is outdated because it compiled under rust v0.11.0-pre. In any case, this library provides functional configuration of the port, but not for its use.
Would be grateful for a simple example ...
source to share
There are 2 solutions depending on the OS where the code is built. For * nix OS library, serial.rs should work fine for build rust 0.11.0, but for rust-0.12.0 support, the issue was open and not closed yet.
For windows files (mingw-w64), serial.rs is not an easy solution because this library is based on termios calls, which are not easy to configure for mingw. This is because mingw is built against msvcrt not against glibc (see here for more information ). On Windows, a simple solution would be to write a wrapper for a library like rs232 teuniz using FFI rust.
-
Building the rs232 library using mingw gcc;
-
Create a wrapper in rust;
A 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)};
}
source to share