SerialPort communication with Arduino

Hello guys, I'm trying to establish a serial communication between my RPi 4 and my Arduino UNO; to do this I'm using the library serialport = "4.2.0".

It seems that the program is able to establish the connection and it is able to write the data, but then port.bytes_to_read() is never greater than zero and if I just run port.read_exact, it times out.

Can you help me to figure out where is the issue?

The arduino code is the following, it just reads the bytes and writes them back:

int ByteReceived = 0; // INT for received serial data
void setup() {
  Serial.begin(9600); // Serial communication begin to read data
}
void loop() {
  // check for the serial data at serial port
  if (Serial.available() > 0) {
    // read byte of received data:
    ByteReceived = Serial.read();
    // prints the received data on serial monitor
    Serial.write(ByteReceived);
  }
}

This is the Rust code I'm using (it is almost copy and paste from the serialport github page):

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        measure_node::get_serial_data(&"/dev/ttyACM0".to_string(), 9600, 1000);
    }
}

mod measure_node {
    pub fn get_serial_data(port_path: &str, baud_rate: u32, timeout_millis: u64) {
    // Open port    
    let mut port = serialport::new(port_path, baud_rate)
            .timeout(std::time::Duration::from_millis(timeout_millis))
            .open()
            .expect("Failed to open port");

    // Write data
    let output = "This is a test.".as_bytes();
    let written_bytes = port.write(output).expect("Write failed!");
    println!("Written bytes len = {}", written_bytes);
    println!("Written bytes = {:?}", output);

    // Wait for data
    loop {
        let available_bytes: u32 = port.bytes_to_read().expect("Failed to read buff size");
        if available_bytes > 0 {
            break;
        }
        println!("No data");
        std::thread::sleep(std::time::Duration::from_millis(1000));
    }

    // Read data
    let mut serial_buf: Vec<u8> = vec![0; written_bytes];
    port.read_exact(serial_buf.as_mut_slice())
        .expect("Found no data!");
    }
}

I also tried to setup the communication with Python and everything works fine; here is the Python test code:

import serial
s = serial.Serial("/dev/ttyACM0", 9600, timeout=1)
len_wr = s.write(b"abcd")
s.read(len_wr)

Typically an Arduino takes 1 to 3 seconds to reset after the serial port is opened. If your Uno is newish then that will be close to 1 second.

Is that enough of a hint to get you back on track?

1 Like

Thank you for your suggestion, I added a 2 seconds delay after the open port command and now it's working fine!

1 Like

(post deleted by author)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.