Skip to content
Merged

USB #63

Show file tree
Hide file tree
Changes from 6 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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
strategy:
matrix: # All permutations of {rust, mcu}
rust:
- 1.78.0 # MSRV
- 1.88.0 # MSRV
- stable
mcu:
- stm32h503
Expand Down
11 changes: 10 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ authors = ["Edwin Svensson <[email protected]>"]
homepage = "https://github.com/stm32-rs/stm32h5xx-hal"
repository = "https://github.com/stm32-rs/stm32h5xx-hal"
readme = "README.md"
rust-version = "1.78.0"
rust-version = "1.88.0"
categories = ["embedded", "hardware-support", "no-std"]
description = "Hardware Abstraction Layer implementation for STM32H5 series microcontrollers"
keywords = ["arm", "cortex-m", "stm32h5xx", "hal", "embedded-hal"]
Expand Down 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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
[![docs.rs](https://docs.rs/stm32h5xx-hal/badge.svg)](https://docs.rs/stm32h5xx-hal)
[![CI](https://github.com/stm32-rs/stm32h5xx-hal/workflows/Continuous%20integration/badge.svg)](https://github.com/stm32-rs/stm32h5xx-hal/actions)
[![Crates.io](https://img.shields.io/crates/v/stm32h5xx-hal.svg)](https://crates.io/crates/stm32h5xx-hal)
![Minimum rustc version](https://img.shields.io/badge/rustc-1.78.0+-yellow.svg)
![Minimum rustc version](https://img.shields.io/badge/rustc-1.88.0+-yellow.svg)

[_stm32h5xx-hal_](https://github.com/stm32-rs/stm32h5xx-hal) contains
a hardware abstraction layer on top of the peripheral access API for
Expand Down Expand Up @@ -50,7 +50,7 @@ of support for peripherals is shown in the table below.

## Minimum supported Rust version

The Minimum Supported Rust Version (MSRV) at the moment is **1.78.0**. Older
The Minimum Supported Rust Version (MSRV) at the moment is **1.88.0**. Older
versions **may** compile, especially when some features are not used in your
application.

Expand Down
98 changes: 98 additions & 0 deletions examples/usb_serial.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//! 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
buf[0..count]
.iter_mut()
.for_each(|c| *c = c.to_ascii_uppercase());

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 _};
118 changes: 118 additions & 0 deletions src/usb.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
//! 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, ResetEnable};
use crate::stm32::{self, USB};
use core::fmt;
use core::marker::PhantomData;
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) -> UsbDevice;
}

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

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

pub struct UsbDevice {
/// 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 UsbDevice {
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 UsbDevice {
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()
}
}
Copy link
Member

Choose a reason for hiding this comment

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

this is out of date. how about just using the Debug derive for 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.

We actually don not use the pins for anything once they are put into the struct. As in we have no release method. Should I remove them from the struct?

Copy link
Member Author

Choose a reason for hiding this comment

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

fields `pin_dm` and `pin_dp` are never read
`UsbDevice` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
`#[warn(dead_code)]` on by default

Copy link
Member

Choose a reason for hiding this comment

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

Yep. Latest changes look good.


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

// SAFETY: The peripheral has the same regiter blockout as the STM32 USBFS
unsafe impl UsbPeripheral for UsbDevice {
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(|_| {
#[cfg(any(feature = "h523_h533", feature = "h56x_h573"))]
{
// Safety: we are only touching the usbscr which
// is specific for this peripheral. This together with
// the critical section unsures exclusive access
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());
}

// Reset and enable USB peripheral
rec::Usb {
_marker: PhantomData,
}
.reset()
.enable();
});
}

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);
}
}