Struggle receiving serial data from Arduino over USB


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.





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)
        .expect("Failed to open serial port");
    let output = "100".as_bytes();
    serial_port.write(output).expect("Write failed!");
    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/
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.