Created
February 23, 2021 10:57
-
-
Save pferreir/735e1c5bcefd0ba125b0bd3180375518 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
use core::cell::RefCell; | |
use cortex_m::interrupt::{free, Mutex}; | |
use heapless::{consts::*, String}; | |
use stm32f4xx_hal::otg_fs::{UsbBus, USB}; | |
use usb_device::{class_prelude::UsbBusAllocator, prelude::*}; | |
use usbd_serial::SerialPort; | |
type UsbSerial<'u> = SerialPort<'u, UsbBus<USB>>; | |
type UsbBusDevice<'u> = UsbDevice<'u, UsbBus<USB>>; | |
lazy_static! { | |
static ref USB_SERIAL_BUF: Mutex<RefCell<String<U2048>>> = | |
Mutex::new(RefCell::new(String::new())); | |
static ref USB_DEV: Mutex<RefCell<Option<(UsbBusDevice<'static>, UsbSerial<'static>)>>> = | |
Mutex::new(RefCell::new(None)); | |
} | |
pub fn write_usb_serial(text: &str) { | |
free(|cs| { | |
let mut buf = USB_SERIAL_BUF.borrow(cs).borrow_mut(); | |
buf.push_str(text).unwrap(); | |
}); | |
} | |
pub fn poll_usb() { | |
free(|cs| { | |
let mut usb_dev_data = USB_DEV.borrow(cs).borrow_mut(); | |
let (usb_dev, serial) = usb_dev_data.as_mut().unwrap(); | |
if usb_dev.poll(&mut [serial]) { | |
let mut buf = USB_SERIAL_BUF.borrow(cs).borrow_mut(); | |
if buf.as_str().len() > 0 { | |
serial.write(buf.as_str().as_bytes()).unwrap(); | |
serial.flush().unwrap(); | |
buf.clear(); | |
} | |
} | |
}) | |
} | |
pub fn init_usb<'u>(usb_bus: &'static UsbBusAllocator<UsbBus<USB>>) { | |
let serial = SerialPort::new(usb_bus); | |
let usb_dev = UsbDeviceBuilder::new(usb_bus, UsbVidPid(0x16c0, 0x27dd)) | |
.manufacturer("ubik devices") | |
.product("Clima Sensors") | |
.serial_number("T3ST") | |
.device_class(usbd_serial::USB_CLASS_CDC) | |
.build(); | |
free(|cs| { | |
let mut usb_dev_data = USB_DEV.borrow(cs).borrow_mut(); | |
usb_dev_data.replace((usb_dev, serial)); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment