Skip to content

Instantly share code, notes, and snippets.

@xobs
Last active October 29, 2025 03:25
Show Gist options
  • Select an option

  • Save xobs/15895ee6aeb37cfaf01cc79ec364f883 to your computer and use it in GitHub Desktop.

Select an option

Save xobs/15895ee6aeb37cfaf01cc79ec364f883 to your computer and use it in GitHub Desktop.
Simple script to cat a serial port at a given baud
#!/usr/bin/env -S cargo +nightly -Zscript
---
[dependencies]
serialport = "4.8.1"
---
use std::{
env,
error::Error,
io::{ErrorKind, Write},
time::Duration,
};
fn main() -> Result<(), Box<dyn Error>> {
let Some(serial_port) = env::args().nth(1) else {
return Err(format!(
"usage: {} [serial_port] [baud]",
std::env::args().next().as_deref().unwrap_or("serialcat")
)
.into());
};
let Some(Ok(baud)) = env::args().nth(2).map(|baud| baud.parse::<u32>()) else {
return Err("Baudrate is required".into());
};
let mut serial_port = serialport::new(serial_port, baud)
.timeout(Duration::from_secs(1))
.open()?;
let mut stdout = std::io::stdout().lock();
loop {
let mut buffer = [0u8; 1024];
let count = match serial_port.read(&mut buffer) {
Ok(0) => break,
Ok(count) => count,
Err(e) if e.kind() == ErrorKind::TimedOut => continue,
Err(e) => {
eprintln!("Got error: {e}");
return Err(e.into());
}
};
stdout.write_all(&buffer[0..count])?;
stdout.flush()?;
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment