simplify usb_uart example

This commit is contained in:
Jacob Rosenthal 2021-12-16 14:59:08 -07:00
parent 5d19f87acb
commit 1f2bbe3e4a

View File

@ -15,15 +15,15 @@ use panic_probe as _; // print out panic messages
use embassy::executor::Spawner; use embassy::executor::Spawner;
use embassy::io::{AsyncBufReadExt, AsyncWriteExt}; use embassy::io::{AsyncBufReadExt, AsyncWriteExt};
use embassy::time::{Duration, Timer};
use embassy_nrf::usb::{State, Usb, UsbBus, UsbSerial}; use embassy_nrf::usb::{State, Usb, UsbBus, UsbSerial};
use embassy_nrf::{interrupt, Peripherals}; use embassy_nrf::{interrupt, Peripherals};
use usb_device::device::{UsbDeviceBuilder, UsbVidPid}; use usb_device::device::{UsbDeviceBuilder, UsbVidPid};
#[embassy::main] #[embassy::main]
async fn main(_spawner: Spawner, p: Peripherals) { async fn main(_spawner: Spawner, p: Peripherals) {
let mut tx_buffer = [0u8; 1024]; let mut rx_buffer = [0u8; 64];
let mut rx_buffer = [0u8; 640]; // we send back input + cr + lf
let mut tx_buffer = [0u8; 66];
let usb_bus = UsbBus::new(p.USBD); let usb_bus = UsbBus::new(p.USBD);
@ -45,50 +45,50 @@ async fn main(_spawner: Spawner, p: Peripherals) {
let (mut reader, mut writer) = usb.as_ref().take_serial_0(); let (mut reader, mut writer) = usb.as_ref().take_serial_0();
unwrap!(writer.write_all(b"\r\nSend something\r\n").await);
info!("usb initialized!"); info!("usb initialized!");
unwrap!(
writer
.write_all(b"\r\nInput returned upper cased on CR+LF\r\n")
.await
);
let mut buf = [0u8; 64]; let mut buf = [0u8; 64];
loop { loop {
let mut n = 0; let mut n = 0;
let timed_out = {
let newline_fut = async { async {
loop { loop {
let char = unwrap!(reader.read_byte().await); let char = unwrap!(reader.read_byte().await);
// echo input back to screen
unwrap!(writer.write_byte(char).await);
buf[n] = char;
// throw away, read more on cr, exit on lf
if char == b'\r' {
continue;
} else if char == b'\n' {
break;
}
buf[n] = char;
n += 1; n += 1;
if char == b'\n' || char == b'\r' || n == buf.len() {
// stop if we're out of room
if n == buf.len() {
break; break;
} }
} }
};
pin_mut!(newline_fut);
let timeout_fut = Timer::after(Duration::from_ticks(32768 * 10));
// select chooses whichever returns first
match select(newline_fut, timeout_fut).await {
Either::Left(_) => false,
Either::Right(_) => true,
} }
}; .await;
if timed_out { if n > 0 {
unwrap!(writer.write_all(b"\r\nTimed out\r\n").await);
} else {
for char in buf[..n].iter_mut() { for char in buf[..n].iter_mut() {
// upper case // upper case
if 0x61 <= *char && *char <= 0x7a { if 0x61 <= *char && *char <= 0x7a {
*char &= !0x20; *char &= !0x20;
} }
} }
unwrap!(writer.write_byte(b'\n').await);
unwrap!(writer.write_all(&buf[..n]).await); unwrap!(writer.write_all(&buf[..n]).await);
unwrap!(writer.write_byte(b'\n').await); unwrap!(writer.write_all(b"\r\n").await);
unwrap!(writer.flush().await);
} }
} }
} }