Skip to content
Merged

USB #63

Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ log-itm = ["log"]
log-rtt = ["log"]
log-semihost = ["log"]

defmt = [
"dep:defmt",
"fugit/defmt",
"stm32h5/defmt",
]

[dependencies]
cortex-m = { version = "^0.7.7", features = ["critical-section-single-core"] }
stm32h5 = { package = "stm32h5", version = "0.16.0" }
Expand All @@ -64,6 +70,7 @@ embedded-hal = "1.0.0"
defmt = { version = "1.0.0", optional = true }
paste = "1.0.15"
log = { version = "0.4.20", optional = true}
stm32-usbd = "0.8.0"

[dev-dependencies]
log = { version = "0.4.20"}
Expand All @@ -79,6 +86,8 @@ cortex-m-semihosting = "0.5.0"
panic-itm = { version = "~0.4.1" }
panic-probe = "0.3.2"
panic-semihosting = "0.6"
usbd-serial = "0.2.2"
usb-device = { version = "0.3.2", features = ["defmt", "log"] }

[profile.release]
codegen-units = 1 # better optimizations
Expand Down
100 changes: 100 additions & 0 deletions examples/usb_serial.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//! CDC-ACM serial port example using polling in a busy loop.
#![deny(warnings)]
#![deny(unsafe_code)]
#![allow(clippy::uninlined_format_args)]
#![no_std]
#![no_main]

use cortex_m_rt::entry;
use hal::prelude::*;
use hal::pwr::PwrExt;
use hal::stm32;
use stm32_usbd::UsbBus;
use stm32h5xx_hal as hal;
use stm32h5xx_hal::usb::UsbExt;

use usb_device::prelude::*;
use usbd_serial::{SerialPort, USB_CLASS_CDC};

#[macro_use]
mod utilities;

use utilities::logger::info;

#[entry]
fn main() -> ! {
utilities::logger::init();

let dp = stm32::Peripherals::take().expect("cannot take peripherals");

let pwr = dp.PWR.constrain();
let pwrcfg = pwr.vos0().freeze();
// Constrain and Freeze clock
let rcc = dp.RCC.constrain();
let ccdr = rcc.sys_ck(250.MHz()).freeze(pwrcfg, &dp.SBS);

let gpioa = dp.GPIOA.split(ccdr.peripheral.GPIOA);

let mut led = gpioa.pa5.into_push_pull_output();
led.set_low();

let usb_dm = gpioa.pa11.into_alternate();
let usb_dp = gpioa.pa12.into_alternate();

let usb = dp.USB.usb(ccdr.peripheral.USB, usb_dm, usb_dp);
let usb_bus = UsbBus::new(usb);

let mut serial = SerialPort::new(&usb_bus);

let mut usb_dev =
UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x16c0, 0x27dd))
.strings(&[StringDescriptors::default()
.manufacturer("Fake company")
.product("Serial port")
.serial_number("TEST")])
.unwrap()
.device_class(USB_CLASS_CDC)
.build();

info!("Init done");

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_high();

if let Ok(s) = str::from_utf8(&buf[0..count]) {
info!("{:?}", s);
} else {
info!("{:?}", &buf[0..count]);
}

// Echo back in upper case
for c in buf[0..count].iter_mut() {
if 0x61 <= *c && *c <= 0x7a {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any ideas for solving this?

error: current MSRV (Minimum Supported Rust Version) is `1.78.0` but this item is stable since `1.87.0`
  --> examples/usb_serial.rs:72:32
   |
72 |                 if let Ok(s) = str::from_utf8(&buf[0..count]) {
   |                                ^^^^^^^^^^^^^^
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#incompatible_msrv
note: the lint level is defined here
  --> examples/usb_serial.rs:2:9

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could bump up the MSRV? We haven't published a crate yet...

Copy link
Member

@astapleton astapleton Jul 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, instead of doing this uppercasing manually, you could just call c.to_ascii_uppercase(): https://doc.rust-lang.org/stable/core/primitive.char.html#method.to_ascii_uppercase (and use map instead of a for loop)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh nice: )

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any suggestions for a MSRV?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might as well bump it to 1.88?

*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_low();
}
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ pub mod spi;
#[cfg(feature = "device-selected")]
pub mod dwt;

#[cfg(feature = "device-selected")]
pub mod usb;

#[cfg(feature = "device-selected")]
mod sealed {
pub trait Sealed {}
Expand Down
1 change: 1 addition & 0 deletions src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub use crate::icache::ICacheExt as _stm32h5xx_hal_icache_ICacheExt;
pub use crate::pwr::PwrExt as _stm32h5xx_hal_pwr_PwrExt;
pub use crate::rcc::RccExt as _stm32h5xx_hal_rcc_RccExt;
pub use crate::spi::SpiExt as _stm32h5xx_hal_spi_SpiExt;
pub use crate::usb::UsbExt as _stm32h5xx_hal_usb_UsbExt;

pub use crate::time::U32Ext as _;
pub use fugit::{ExtU32 as _, RateExtU32 as _};
116 changes: 116 additions & 0 deletions src/usb.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
//! USB peripheral.
//!
//! Provides the required implementation for use of the [`stm32-usbd`] crate.
use crate::stm32::rcc::ccipr4::USBSEL;
pub use stm32_usbd::UsbBus;

use crate::gpio;
use crate::gpio::gpioa::{PA11, PA12};
use crate::rcc::rec;
use crate::stm32::{self, USB};
use core::fmt;
use stm32_usbd::UsbPeripheral;

/// Type for pin that can be the "D-" pin for the USB peripheral
pub type DmPin = PA11<gpio::Alternate<10>>;

/// Type for pin that can be the "D+" pin for the USB peripheral
pub type DpPin = PA12<gpio::Alternate<10>>;

pub trait UsbExt {
fn usb(self, rec: rec::Usb, pin_dm: DmPin, pin_dp: DpPin) -> Peripheral;
}

impl UsbExt for stm32::USB {
fn usb(self, rec: rec::Usb, pin_dm: DmPin, pin_dp: DpPin) -> Peripheral {
if let USBSEL::Disable = rec.get_kernel_clk_mux() {
rec.kernel_clk_mux(USBSEL::Hsi48);
};

Peripheral {
_usb: self,
pin_dm,
pin_dp,
}
}
}

pub struct Peripheral {
/// USB register block
_usb: USB,
/// Data negative pin
pin_dm: DmPin,
/// Data positive pin
pin_dp: DpPin,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to hang on to these pins? Doesn't looks like they get used anywhere. Could just consume them in the new function so they can't get used anywhere else (e.g. SPI driver does this).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to hang on to these pins? [...]

I dont think we do

}

#[cfg(feature = "defmt")]
impl defmt::Format for Peripheral {
fn format(&self, f: defmt::Formatter) {
defmt::write!(
f,
"Peripheral {{ usb: USB, pin_dm: {}, pin_dp: {}}}",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Name is out of date

self.pin_dm,
self.pin_dp
);
}
}

impl fmt::Debug for Peripheral {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Peripheral")
.field("usb", &"USB")
.field("pin_dm", &self.pin_dm)
.field("pin_dp", &self.pin_dp)
.finish()
}
}

// SAFETY: Implementation of Peripheral is thread-safe by using cricitcal sections to ensure
// mutually exclusive access to the USB peripheral
unsafe impl Sync for Peripheral {}

// SAFETY: The peripheral has the same regiter blockout as the STM32 USBFS
unsafe impl UsbPeripheral for Peripheral {
const REGISTERS: *const () = USB::ptr().cast::<()>();
const DP_PULL_UP_FEATURE: bool = true;
const EP_MEMORY: *const () = 0x4001_6400 as _;
const EP_MEMORY_SIZE: usize = 2048;
const EP_MEMORY_ACCESS: stm32_usbd::MemoryAccess =
stm32_usbd::MemoryAccess::Word32x1;

fn enable() {
cortex_m::interrupt::free(|_| {
let rcc = unsafe { &*stm32::RCC::ptr() };
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: move this closer to where it's first used.


#[cfg(any(feature = "h523_h533", feature = "h56x_h573"))]
{
let pwr = unsafe { &*stm32::PWR::ptr() };

// Enable USB supply level detector
pwr.usbscr().modify(|_, w| w.usb33den().set_bit());

// Await good usb supply voltage
while pwr.vmsr().read().usb33rdy().bit_is_clear() {}

// Set bit to confirm that USB supply level is good
pwr.usbscr().modify(|_, w| w.usb33sv().set_bit());
}

// Enable USB peripheral
rcc.apb2enr().modify(|_, w| w.usben().set_bit());

// Reset USB peripheral
rcc.apb2rstr().modify(|_, w| w.usbrst().set_bit());
rcc.apb2rstr().modify(|_, w| w.usbrst().clear_bit());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about:

rec::Usb { _marker: PhantomData }.reset().enable();

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, thanks

});
}

fn startup_delay() {
// There is a chip specific startup delay. For STM32H503,523,533,56x and 573 it's
// 1µs and this should wait for at least that long.
// 250 Mhz is the highest frequency, so this ensures a minimum of 1µs wait time.
cortex_m::asm::delay(250);
}
}
Loading