Skip to content

Commit eef4e03

Browse files
committed
Add USB example
1 parent 9dab1aa commit eef4e03

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

Cargo.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ heapless = "0.5.0"
4646
panic-halt = "0.2.0"
4747
panic-semihosting = "0.5.1"
4848
cortex-m-rtfm = "0.4.3"
49+
usb-device = "0.2.3"
50+
usbd-serial = "0.1.0"
4951

5052
[features]
5153
# Miscellaneaous features
@@ -142,3 +144,7 @@ required-features = ["rt"]
142144
[[example]]
143145
name = "adc_pwm"
144146
required-features = ["stm32l0x1"]
147+
148+
[[example]]
149+
name = "usb_serial"
150+
required-features = ["rt", "stm32l0x2", "stm32-usbd"]

examples/usb_serial.rs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
//! CDC-ACM serial port example using polling in a busy loop.
2+
#![no_std]
3+
#![no_main]
4+
5+
extern crate panic_semihosting;
6+
7+
use cortex_m_rt::entry;
8+
use stm32l0xx_hal::usb::{Peripheral, UsbBus};
9+
use stm32l0xx_hal::{prelude::*, pac, rcc};
10+
use usb_device::prelude::*;
11+
use usbd_serial::{SerialPort, USB_CLASS_CDC};
12+
13+
#[entry]
14+
fn main() -> ! {
15+
let dp = pac::Peripherals::take().unwrap();
16+
17+
let mut rcc = dp.RCC.freeze(rcc::Config::hsi16());
18+
19+
let gpioa = dp.GPIOA.split(&mut rcc);
20+
21+
let usb = Peripheral {
22+
usb: dp.USB,
23+
pin_dm: gpioa.pa11,
24+
pin_dp: gpioa.pa12,
25+
};
26+
let usb_bus = UsbBus::new(usb);
27+
28+
let mut serial = SerialPort::new(&usb_bus);
29+
30+
let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x16c0, 0x27dd))
31+
.manufacturer("Fake company")
32+
.product("Serial port")
33+
.serial_number("TEST")
34+
.device_class(USB_CLASS_CDC)
35+
.build();
36+
37+
loop {
38+
if !usb_dev.poll(&mut [&mut serial]) {
39+
continue;
40+
}
41+
42+
let mut buf = [0u8; 64];
43+
44+
match serial.read(&mut buf) {
45+
Ok(count) if count > 0 => {
46+
// Echo back in upper case
47+
for c in buf[0..count].iter_mut() {
48+
if 0x61 <= *c && *c <= 0x7a {
49+
*c &= !0x20;
50+
}
51+
}
52+
53+
let mut write_offset = 0;
54+
while write_offset < count {
55+
match serial.write(&buf[write_offset..count]) {
56+
Ok(len) if len > 0 => {
57+
write_offset += len;
58+
}
59+
_ => {}
60+
}
61+
}
62+
}
63+
_ => {}
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)