Created
March 10, 2026 06:12
-
-
Save xobs/6394f16b67deaade48b5e5d59e47bacf to your computer and use it in GitHub Desktop.
A simple repl using the serial port. Run with `cargo +nightly -Zscript simple-repl.rs`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env cargo | |
| --- | |
| package.edition = "2024" | |
| dependencies.serialport = "4.8" | |
| --- | |
| use std::io::{BufRead, Read, Write}; | |
| fn main() { | |
| // Get the serial port path | |
| let Some(port) = std::env::args().nth(1) else { | |
| eprintln!( | |
| "Usage: {} [serial-port]", | |
| std::env::args().next().as_deref().unwrap_or("<program>") | |
| ); | |
| return; | |
| }; | |
| // Open the serial port at 1Mbaud | |
| let Ok(mut port) = serialport::new(&port, 1_000_000) | |
| .open() | |
| .inspect_err(|e| eprintln!("Unable to open {port}: {e}")) | |
| else { | |
| return; | |
| }; | |
| // Split into read-half and write-half | |
| let Ok(mut reader) = port | |
| .try_clone() | |
| .inspect_err(|e| eprintln!("Couldn't duplicate serial port: {e}")) | |
| else { | |
| return; | |
| }; | |
| // Launch the port reader to constantly read from the port and write to stdout | |
| std::thread::spawn(move || { | |
| let mut buffer = [0u8; 1024]; | |
| loop { | |
| match reader.read(&mut buffer) { | |
| Ok(0) => std::process::exit(0), | |
| // Note: this doesn't currently flush | |
| Ok(n) => std::io::stdout() | |
| .write_all(&buffer[0..n]) | |
| .expect("Couldn't write to stdout"), | |
| Err(e) if e.kind() == std::io::ErrorKind::TimedOut => continue, | |
| Err(e) => { | |
| eprintln!("Error reading from port: {e}"); | |
| std::process::exit(1); | |
| } | |
| } | |
| } | |
| }); | |
| // Read from stdin and send | |
| let repl = std::io::BufReader::new(std::io::stdin()); | |
| for line in repl.lines() { | |
| let line = line.expect("Couldn't read line"); | |
| port.write_all(line.as_bytes()) | |
| .expect("Couldn't write data"); | |
| port.write_all(b"\n").unwrap(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment