Search code examples
rustioserial-port

Why can I not recieve serial data using Rust?


I've been trying to read serial data from a Feather M0, but for some reason I can't read the data into a buffer. This device is for sure outputting serial data, and both PlatformIO and the Arduino IDE show serial data in their respective serial monitors. However, it will timeout when I'm reading it in Rust, every single time, no matter what timeout value I have it set to. Here is my code:

// First, find the serial port
let port_info = find_receiver();

// If we didn't find a port, then we can't continue
if port_info.is_none() {
    panic!("Could not find a serial port");
}

let mut port = serialport::new(port_info.unwrap().port_name, 9600)
    .timeout(Duration::from_millis(1000))
    .open()
    .expect("Could not open serial port");


let mut serial_buf: Vec<u8> = vec![0; 8];
loop {
    let n = port.read_exact(serial_buf.as_mut_slice()).unwrap();

    println!("Buffer is {:?}", serial_buf);
}

The find_reciever() function simply scans the open ports and returns the one that I want to connect to. I'm on Windows, so in this case it's usually COM9 or COM12. I would like this to be a cross-platform application, so I'm not using the open_native() function that serialport provides.

I've tried varrying the size of the buffer from 1 byte to 1000, I've trying different versions of read into the port, I've tried skipping over timeout errors, and I've tried directly outputting the read bytes to io::Stdout. Any ideas on what to do?


Solution

  • Apparently, the serialport crate that I was using requires you to set the command

    port.write_data_terminal_ready(true);
    

    in order for it to start reading data. On Linux this works perfectly fine without it. Rip 4 hours trying to change what IO reader I was using.