Struggle receiving serial data from Arduino over USB

Hi,

I just started learning Rust and I tried to read (and later write) data from (/to) an Arduino board connected over USB.

I ran into the following issue: the string printed in the terminal is a copy of the last one + a new line of data. See the text below.

3350,255,252

3350,255,252
13351,249,248

3350,255,252
13351,249,248
13352,243,242

3350,255,252
13351,249,248
13352,243,242
13353,247,244

I think it is because I use a buffered reader but that's the only way I know to get it work since i just started Rust.

How to avoid this issue ?

Here is the code running on my computer:

use serialport;
use std::time::Duration;
use std::io::BufReader;
use std::io::BufRead;

fn main() {
    let mut serial_port = serialport::new("/dev/ttyACM0", 9600)
        .timeout(Duration::from_millis(1000))
        .open()
        .expect("Failed to open serial port");
/*
    let output = "100".as_bytes();
    serial_port.write(output).expect("Write failed!");
    serial_port.flush().unwrap();
*/
    let mut reader = BufReader::new(serial_port);
    let mut my_str = String::new();
    
    while true{
        reader.read_line(&mut my_str);
    
        println!("{}", my_str);
    }
}

Thank you !

.read_line() appends the line into the provided buffer. Try .clear() the buffer before read.

Also, try to run cargo clippy to get more advices to improve code. And never ignore the compiler warnings.

Thank you ! It's working with .clear().

There's a new warning from cargo clippy. I must be fixing it wrong since my program run without handling it, and when handling the error my program reads some lines and then stop telling me the Err I added to the code.

warning: unused `Result` that must be used
  --> src/main.rs:19:9
   |
19 |         reader.read_line(&mut my_str); 
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_must_use)]` on by default
   = note: this `Result` may be an `Err` variant, which should be handled

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.