I want to make a Rust program to communicate with a arduino uno having the following code to to echo each byte:
void setup() {
Serial.begin(112500);
}
void loop() {
if (Serial.available()) {
int inByte = Serial.read();
Serial.write(inByte);
}
}
With the following Rust code:
use std::{thread::sleep, time::Duration};
use serial2::SerialPort;
// Entry point
fn main() {
let ps = SerialPort::available_ports()
.unwrap()
.into_iter()
.filter(|x| x.to_string_lossy().starts_with("/dev/ttyUSB"))
.collect::<Vec<_>>();
let pth = ps[0].clone();
let sp = SerialPort::open(pth, 115200).unwrap();
sleep(Duration::from_millis(3000));
let _ = sp.discard_input_buffer();
let data=b"asdfg";
let _m = sp.write(data).unwrap();
let _ = sp.flush();
println!("Sending : {:?}", data);
let mut buf: Vec<u8> = vec![0; 5];
let _ = sp.read(&mut buf);
println!("Got : {:?}", buf);
}
Here is the output of the code:
Sending : [97, 115, 100, 102, 103]
Got : [97, 46, 150, 157, 0]
And here is the problem, the bytes sent and received are not the same. As of my experimentation the problem lies with the writing to serial port part. serialport
crate also had the same issue. I tried with resberry pi pico had the same issue.
I have coded the same thing in julia it works as expected.
julia> using LibSerialPort
julia> s=LibSerialPort.open("/dev/ttyUSB0", 112500)
SerialPort(Ptr{LibSerialPort.Lib.SPPort} @0x0000000001bb9fe0, false, true, 0x00000000, 0x00000000)
julia> str="asdfg"
"asdfg"
julia> bytes = collect(codeunits(str))
5-element Vector{UInt8}:
0x61
0x73
0x64
0x66
0x67
julia> sleep(3)
julia> write(s, bytes)
5
julia> sleep(1)
julia> rd=read(s)
5-element Vector{UInt8}:
0x61
0x73
0x64
0x66
0x67
julia> rd==bytes
true
I am using Linux mint 22.