Created
February 22, 2023 03:15
-
-
Save agrif/f6be51fd0a0a7f6da089cd9f2ac4a2f4 to your computer and use it in GitHub Desktop.
This file contains 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
#![no_std] | |
#![no_main] | |
use panic_halt as _; | |
use stm32f1xx_hal::{pac, prelude::*, rcc, usb}; | |
use usb_device::prelude::*; | |
use usbd_serial::{SerialPort, USB_CLASS_CDC}; | |
#[cortex_m_rt::entry] | |
fn main() -> ! { | |
rtt_target::rtt_init_print!(); | |
let cp = cortex_m::Peripherals::take().unwrap(); | |
let dp = pac::Peripherals::take().unwrap(); | |
let mut flash = dp.FLASH.constrain(); | |
let rcc = dp.RCC.constrain(); | |
let cfgr = rcc.cfgr.use_hse(16.MHz()).sysclk(48.MHz()).pclk1(24.MHz()); | |
let clockconf = rcc::Config::from_cfgr(cfgr); | |
rtt_target::rprintln!("config: {:?}", clockconf); | |
let clocks = rcc::CFGR::default().freeze_with_config(clockconf, &mut flash.acr); | |
rtt_target::rprintln!("clocks: {:?}", clocks); | |
rtt_target::rprintln!("usb clock valid: {:?}", clocks.usbclk_valid()); | |
let mut delay = cp.SYST.delay(&clocks); | |
let mut gpioc = dp.GPIOC.split(); | |
let mut led = gpioc.pc13.into_push_pull_output(&mut gpioc.crh); | |
led.set_high(); // off | |
// pull d+ down to reset USB bus, so it re-enumerates after upload | |
let mut gpioa = dp.GPIOA.split(); | |
let mut usb_dp = gpioa.pa12.into_push_pull_output(&mut gpioa.crh); | |
usb_dp.set_low(); | |
delay.delay_ms(10u8); | |
let usb = usb::Peripheral { | |
usb: dp.USB, | |
pin_dm: gpioa.pa11, | |
pin_dp: usb_dp.into_floating_input(&mut gpioa.crh), | |
}; | |
let usb_bus = usb::UsbBus::new(usb); | |
let mut serial = SerialPort::new(&usb_bus); | |
let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x16c0, 0x27dd)) | |
.manufacturer("Fake company") | |
.product("Serial port") | |
.serial_number("TEST") | |
.device_class(USB_CLASS_CDC) | |
.build(); | |
loop { | |
if !usb_dev.poll(&mut [&mut serial]) { | |
continue; | |
} | |
let mut buf = [0u8; 64]; | |
match serial.read(&mut buf) { | |
Ok(count) if count > 0 => { | |
led.set_low(); // on | |
// Echo back upper case | |
for c in buf[..count].iter_mut() { | |
if 0x61 <= *c && *c <= 0x7a { | |
*c &= !0x20; | |
} | |
} | |
let mut write_offset = 0; | |
while write_offset < count { | |
match serial.write(&buf[write_offset..count]) { | |
Ok(len) if len > 0 => { | |
write_offset += len; | |
} | |
_ => {} | |
} | |
} | |
} | |
_ => {} | |
} | |
led.set_high(); // off | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment