Compare commits

...

33 Commits

Author SHA1 Message Date
a800e28303 feat: make USBEndpoint public + add method get_ep_table 2025-06-30 21:08:09 +04:00
16e254d7dc feat: remove pending_ins field and it usage 2025-06-22 21:37:36 +04:00
c510d908d3 refactor: move constants + remove code duplicate 2025-05-18 23:51:41 +04:00
cfa76a6672 fix(int): USBINT interrupt 2025-05-18 23:20:14 +04:00
dba9637614 revert a269df21fe
revert fix(int): fix bytes for clearing interrupt flags for usbd_serial
2025-05-18 22:15:59 +03:00
dd28dfe61e test 2025-05-18 23:05:30 +04:00
a269df21fe fix(int): fix bytes for clearing interrupt flags for usbd_serial 2025-05-18 23:00:00 +04:00
93ade5bda0 fix: add clearing interrupts 2025-05-15 10:23:43 +04:00
64a6532c94 fix(f_reset): using detach bit in udcon register instead usbcon 2025-05-15 10:03:31 +04:00
6322868796 refactor: remove unwrap() usage, redundant free(||) usage and etc 2025-05-14 21:01:58 +04:00
f7c4b48b85 remove free-interrupt context for endpoint allocator 2025-05-05 23:09:54 +04:00
4a90b9a6c8 feat(usb_device): add getters 2025-04-28 20:23:02 +04:00
ce10b959e4 Update src/types/usb_device.rs 2025-04-28 18:51:49 +03:00
e1711038c5 revert f399278d2c
revert feat: rename method
2025-04-28 18:51:16 +03:00
29b3bff247 revert 995bfd0169
revert feat: separate constructor for UsbDevice and UsbBusAllocator
2025-04-28 18:50:45 +03:00
79d01f8571 revert c4686aafc4
revert feat(api): add plug_in_detection
2025-04-28 18:49:26 +03:00
fb6f180ce2 feat: rename crate 2025-04-25 16:25:03 +04:00
995bfd0169 feat: separate constructor for UsbDevice and UsbBusAllocator 2025-04-25 15:40:55 +04:00
f399278d2c feat: rename method 2025-04-25 15:28:29 +04:00
c4686aafc4 feat(api): add plug_in_detection 2025-04-25 14:35:30 +04:00
ba319eecff refactor: move function down + set #[inline(always)] for small functions 2025-04-25 14:35:11 +04:00
a1e180b451 feat: comment build dep 2025-04-25 12:23:52 +04:00
09ae1b383c feat: change profile toolchain 2025-04-25 12:23:39 +04:00
8416bd0fa4 cosmetic changes 2025-02-13 00:29:13 +04:00
30850a473d fix: add clearing interrupts 2025-02-13 00:29:02 +04:00
9b4f758045 commited for clippy fix 2025-02-11 19:27:23 +04:00
90708794db feat(toolchain): add toolchain file 2024-12-30 23:15:11 +04:00
ccb23c8c56 refactor!: rewrite almost full library
Now usbd implementation works fine (tested on atmega32u4)
2024-12-30 21:17:23 +04:00
16812fe119 fix 2024-11-14 02:14:03 +04:00
7436a78885 feat(types): make all types and his fields public for crate 2024-11-14 01:55:34 +04:00
652ba78cdf feat(UsbBus): move UsbBus implementation to lib.rs file and implement set_stalled, suspend and etc 2024-11-14 01:54:33 +04:00
e9d661e9e3 feat(UsbBus): implement write and read methods and borrow poll method implementation from atmega_usbd 2024-11-14 01:52:41 +04:00
4ca8c4e8cf feat(code): format code 2024-11-09 16:48:28 +04:00
5 changed files with 563 additions and 264 deletions

2
.gitignore vendored
View File

@@ -1,3 +1,3 @@
target
rust-toolchain.toml
Cargo.lock
.gitignore

View File

@@ -1,9 +1,8 @@
[package]
name = "usb_avr"
name = "usb-avr"
version = "0.1.0"
edition = "2021"
[dependencies]
panic-halt = "0.2.0"
ufmt = "0.2.0"
@@ -18,6 +17,5 @@ features = ["atmega32u4"]
# The latest releases of `proc-macro2` do not support the rust toolchain that
# we use. Thus, we must fix this dependency to an older version where our
# toolchain is still supported. See https://github.com/Rahix/avr-hal/issues/537
[build-dependencies.proc-macro2]
version = "=1.0.79"
# [build-dependencies.proc-macro2]
# version = "=1.0.79"

4
rust-toolchain.toml Normal file
View File

@@ -0,0 +1,4 @@
[toolchain]
channel = "nightly-2024-06-13"
components = [ "rust-src" ]
profile = "default"

View File

@@ -1,7 +1,456 @@
#![no_std]
use core::cmp::max;
use avr_device::{asm::delay_cycles, interrupt::free};
use usb_device::{
bus::{PollResult, UsbBus},
endpoint::{EndpointAddress, EndpointType},
Result as UsbResult, UsbDirection, UsbError,
};
mod types;
pub use types::*;
use types::*;
use types::{DPRAM_SIZE, ENDPOINTS_ALLOC_LAYOUT, ONE_MS_16_MGHZ};
const RESTRICT_RW_FLAG: u8 = !(1 << 5);
const USBINT_CLEAR: u8 = 1 << 0;
const UDINT_CLEAR: u8 = !(1 << 7 | 1 << 1);
impl<const L: usize> UsbBus for UsbDevice<L> {
fn alloc_ep(
&mut self,
ep_dir: UsbDirection,
ep_addr: Option<EndpointAddress>,
ep_type: EndpointType,
max_packet_size: u16,
_interval: u8,
) -> UsbResult<EndpointAddress> {
// Handle first endpoint. //
if ep_addr == Some(EndpointAddress::from_parts(0, UsbDirection::In)) {
ep_addr.ok_or(UsbError::InvalidState)
} else {
let address = match ep_addr {
// If current endpoint doesn't allocated, assign ep_addr to variable. //
Some(addr) if !self.ep_table[addr.index()].is_allocated => addr,
// If ep_aadr not provided, or current endpoint is allocated, try to find next free endpoint, otherwise return UsbError. //
_ => {
let index = self
.ep_table
.iter()
.enumerate()
.skip(1)
.find(|(index, ep)| {
!ep.is_allocated && max_packet_size <= ENDPOINTS_ALLOC_LAYOUT[*index]
})
.ok_or(UsbError::EndpointOverflow)?
.0;
EndpointAddress::from_parts(index, ep_dir)
}
};
// Select endpoint info by address index. //
let target_endpoint = &mut self.ep_table[address.index()];
// Get power of two number of endpoint size. //
let ep_size = max(8, max_packet_size.next_power_of_two());
// Endpoint allocation marker. //
if DPRAM_SIZE - self.dpram_already_used < ep_size {
Err(UsbError::EndpointMemoryOverflow)
} else {
// Set endpoint parameters. //
target_endpoint.set_dir(ep_dir);
target_endpoint.set_type(ep_type);
target_endpoint.set_size(ep_size)?;
// Add used dpram memory. //
target_endpoint.is_allocated = true;
self.dpram_already_used += ep_size;
Ok(address)
}
}
}
fn enable(&mut self) {
free(|cs| {
let (usb, pll) = (self.usb.borrow(cs), self.pll.borrow(cs));
// Enable USB pads regulators. //
usb.uhwcon.modify(|_, w| w.uvrege().set_bit());
// PLL configuration //
pll.pllcsr.write(|w| w.pindiv().set_bit());
pll.pllfrq
.write(|w| w.pdiv().mhz96().plltm().factor_15().pllusb().set_bit());
// Enable PLL //
pll.pllcsr.modify(|_, w| w.plle().set_bit());
// Check PLL lock //
while pll.pllcsr.read().plock().bit_is_clear() {}
// Enable USB interface. //
usb.usbcon
.modify(|_, w| w.usbe().set_bit().otgpade().set_bit());
// Unfreeze clock. //
usb.usbcon
.modify(|_, w| w.frzclk().clear_bit().vbuste().set_bit());
// Endpoint configuration //
self.allocated_endpoints().for_each(|(i, _ep)| {
let _ = self.configure_endpoint(cs, i);
});
// Set high speed and attach the USB. //
usb.udcon
.modify(|_, w| w.detach().clear_bit().lsm().clear_bit());
// Interrupts. //
usb.udien
.modify(|_, w| w.eorste().set_bit().sofe().set_bit());
})
}
fn force_reset(&self) -> UsbResult<()> {
let set_detach = |bit| {
free(|cs| {
self.usb.borrow(cs).udcon.modify(|_, w| w.detach().bit(bit));
});
};
set_detach(true);
delay_cycles(ONE_MS_16_MGHZ);
set_detach(false);
Ok(())
}
fn is_stalled(&self, ep_addr: EndpointAddress) -> bool {
free(|cs| match self.select_endpoint(cs, ep_addr.index()) {
Ok(_) => self.usb.borrow(cs).ueconx.read().stallrq().bit_is_set(),
Err(_) => false,
})
}
fn poll(&self) -> PollResult {
free(|cs| {
let usb = self.usb.borrow(cs);
let (udint, udien, usbint) = (usb.udint.read(), usb.udien.read(), usb.usbint.read());
if usbint.vbusti().bit_is_set() {
usb.usbint
.write(|w| unsafe { w.bits(USBINT_CLEAR) }.vbusti().clear_bit());
if usb.usbsta.read().vbus().bit_is_set() {
return PollResult::Resume;
} else {
return PollResult::Suspend;
}
}
if udint.suspi().bit_is_set() && udien.suspe().bit_is_set() {
return PollResult::Suspend;
}
if udint.wakeupi().bit_is_set() && udien.wakeupe().bit_is_set() {
return PollResult::Resume;
}
if udint.eorsti().bit_is_set() {
return PollResult::Reset;
}
if udint.sofi().bit_is_set() {
usb.udint
.write(|w| unsafe { w.bits(UDINT_CLEAR) }.sofi().clear_bit());
}
if usb.usbcon.read().frzclk().bit_is_clear() {
let (mut ep_out, mut ep_in_complete, mut ep_setup) = (0u16, 0u16, 0u16);
for (ep_index, _ep) in self.allocated_endpoints() {
if self.select_endpoint(cs, ep_index).is_err() {
break;
} else {
let ueintx = usb.ueintx.read();
if ueintx.rxouti().bit_is_set() {
ep_out |= 1 << ep_index;
}
if ueintx.rxstpi().bit_is_set() {
ep_setup |= 1 << ep_index;
}
if ueintx.txini().bit_is_set() {
ep_in_complete |= 1 << ep_index;
}
}
}
if ep_out | ep_in_complete | ep_setup != 0 {
return PollResult::Data {
ep_out,
ep_in_complete,
ep_setup,
};
}
}
PollResult::None
})
}
fn read(&self, ep_addr: EndpointAddress, buf: &mut [u8]) -> UsbResult<usize> {
free(|cs| {
let usb = self.usb.borrow(cs);
self.select_endpoint(cs, ep_addr.index())?;
let ep = &self.ep_table[ep_addr.index()];
if ep.ep_type == 0 {
let ueintx = usb.ueintx.read();
if ueintx.rxouti().bit_is_clear() && ueintx.rxstpi().bit_is_clear() {
return Err(UsbError::WouldBlock);
}
let buf_size = self.get_size(cs);
if buf.len() < buf_size {
return Err(UsbError::BufferOverflow);
}
for byte in &mut buf[..buf_size] {
*byte = usb.uedatx.read().bits();
}
usb.ueintx.write(|w| {
unsafe { w.bits(RESTRICT_RW_FLAG) }
.rxouti()
.clear_bit()
.rxstpi()
.clear_bit()
});
Ok(buf_size)
} else {
if usb.ueintx.read().rxouti().bit_is_clear() {
return Err(UsbError::WouldBlock);
}
usb.ueintx
.write(|w| unsafe { w.bits(RESTRICT_RW_FLAG) }.rxouti().clear_bit());
let mut bytes_read = 0;
for slot in buf {
if usb.ueintx.read().rwal().bit_is_clear() {
break;
}
*slot = usb.uedatx.read().bits();
bytes_read += 1;
}
if usb.ueintx.read().rwal().bit_is_set() {
return Err(UsbError::BufferOverflow);
}
usb.ueintx
.write(|w| unsafe { w.bits(RESTRICT_RW_FLAG) }.fifocon().clear_bit());
Ok(bytes_read)
}
})
}
fn reset(&self) {
free(|cs| {
let usb = self.usb.borrow(cs);
usb.udint.modify(|_, w| w.eorsti().clear_bit());
self.allocated_endpoints().for_each(|(i, _)| {
let _ = self.configure_endpoint(cs, i);
});
// Clear resume informations. //
usb.udint.write(|w| {
unsafe { w.bits(UDINT_CLEAR) }
.wakeupi()
.clear_bit()
.suspi()
.clear_bit()
});
usb.udien
.modify(|_, w| w.wakeupe().clear_bit().suspe().set_bit());
})
}
fn resume(&self) {
free(|cs| {
let (usb, pll) = (self.usb.borrow(cs), self.pll.borrow(cs));
// PLL enable //
pll.pllcsr
.modify(|_, w| w.pindiv().set_bit().plle().set_bit());
while pll.pllcsr.read().plock().bit_is_clear() {}
// Resuming //
usb.usbcon.modify(|_, w| w.frzclk().clear_bit());
usb.udint.write(|w| {
unsafe { w.bits(UDINT_CLEAR) }
.wakeupi()
.clear_bit()
.suspi()
.clear_bit()
});
usb.udien
.modify(|_, w| w.wakeupe().clear_bit().suspe().set_bit());
})
}
fn set_device_address(&self, addr: u8) {
free(|cs| {
let usb = self.usb.borrow(cs);
// Set address. //
usb.udaddr.modify(|_, w| w.uadd().bits(addr));
// Note: ADDEN and UADD shall not be written at the same time.
// (written in atmega32u4/16u4 docs)
// Enable. //
usb.udaddr.modify(|_, w| w.adden().set_bit());
});
}
fn set_stalled(&self, ep_addr: EndpointAddress, stalled: bool) {
free(|cs| {
let usb = self.usb.borrow(cs);
if self.select_endpoint(cs, ep_addr.index()).is_ok() {
usb.ueconx
.modify(|_, w| w.stallrq().bit(stalled).stallrqc().bit(!stalled));
}
});
}
fn suspend(&self) {
free(|cs| {
let (usb, pll) = (self.usb.borrow(cs), self.pll.borrow(cs));
usb.udint.write(|w| {
unsafe { w.bits(UDINT_CLEAR) }
.wakeupi()
.clear_bit()
.suspi()
.clear_bit()
});
// Suspend. //
usb.udien
.modify(|_, w| w.wakeupe().set_bit().suspe().clear_bit());
// Freeze clock. //
usb.usbcon.modify(|_, w| w.frzclk().set_bit());
// Disable PLL. //
pll.pllcsr.modify(|_, w| w.plle().clear_bit());
})
}
fn write(&self, ep_addr: EndpointAddress, buf: &[u8]) -> UsbResult<usize> {
free(|cs| {
let usb = self.usb.borrow(cs);
self.select_endpoint(cs, ep_addr.index())?;
let ep = &self.ep_table[ep_addr.index()];
// Endpoint type confitions //
match ep.ep_type {
0 => {
if usb.ueintx.read().txini().bit_is_clear() {
return Err(UsbError::WouldBlock);
}
if buf.len() > ep.get_size() {
return Err(UsbError::BufferOverflow);
}
for &byte in buf {
usb.uedatx.write(|w| w.bits(byte));
}
usb.ueintx
.write(|w| unsafe { w.bits(RESTRICT_RW_FLAG) }.txini().clear_bit());
}
_ => {
if usb.ueintx.read().txini().bit_is_clear() {
return Err(UsbError::WouldBlock);
}
usb.ueintx.write(|w| {
unsafe { w.bits(RESTRICT_RW_FLAG) }
.txini()
.clear_bit()
.rxouti()
.clear_bit()
});
for &byte in buf {
if usb.ueintx.read().rwal().bit_is_set() {
usb.uedatx.write(|w| w.bits(byte));
} else {
return Err(UsbError::BufferOverflow);
}
}
usb.ueintx.write(|w| {
unsafe { w.bits(RESTRICT_RW_FLAG) }
.rxouti()
.clear_bit()
.fifocon()
.clear_bit()
});
}
};
Ok(buf.len())
})
}
}

View File

@@ -1,43 +1,31 @@
use core::cmp::max;
use avr_device::{
atmega32u4::{PLL, USB_DEVICE},
interrupt::{free, Mutex},
};
use usb_device::{
bus::UsbBus,
endpoint::{EndpointAddress, EndpointType},
Result, UsbDirection, UsbError,
interrupt::{CriticalSection, Mutex},
};
use usb_device::{bus::UsbBusAllocator, endpoint::EndpointType, UsbDirection, UsbError};
#[allow(unused)]
#[derive(Default, Copy, Clone)]
pub(crate) struct USBEndpoint {
is_allocated: bool,
size: u8,
ep_type: u8,
ep_dir: bool,
banks: u8,
pub struct USBEndpoint {
pub(crate) is_allocated: bool,
pub(crate) size: u8,
pub(crate) ep_type: u8,
pub(crate) ep_dir: bool,
}
const ENDPOINTS_ALLOC_LAYOUT : [u16; 7] = [64, 256, 64, 64, 64, 64, 64];
impl USBEndpoint {
#[inline]
fn set_type(&mut self, ep_type: EndpointType) {
pub(crate) fn set_type(&mut self, ep_type: EndpointType) {
self.ep_type = match ep_type {
EndpointType::Control => 0, // 0 = 0b00
EndpointType::Isochronous {
synchronization: _,
usage: _,
} => 1, // 1 = 0b01
EndpointType::Bulk => 2, // 2 = 0b10
EndpointType::Interrupt => 3, // 3 = 0b11
EndpointType::Control => 0, // 0b00
EndpointType::Isochronous { .. } => 1, // 0b01
EndpointType::Bulk => 2, // 0b10
EndpointType::Interrupt => 3, // 0b11
};
}
#[inline]
fn set_dir(&mut self, dir: UsbDirection) {
pub(crate) fn set_dir(&mut self, dir: UsbDirection) {
self.ep_dir = match dir {
UsbDirection::In => true,
UsbDirection::Out => false,
@@ -45,78 +33,123 @@ impl USBEndpoint {
}
#[inline]
fn set_size(&mut self, size: u16) {
pub(crate) fn get_size(&self) -> usize {
match self.size {
0 /* 0b000 */ => 8,
1 /* 0b001 */ => 16,
2 /* 0b010 */ => 32,
3 /* 0b011 */ => 64,
4 /* 0b100 */ => 128,
5 /* 0b101 */ => 256,
6 /* 0b110 */ => 512,
_ => unreachable!(), // unsupported, check ATMEGA32u4 docs
}
}
#[inline]
pub(crate) fn set_size(&mut self, size: u16) -> Result<(), UsbError> {
if size > 512 {
Err(UsbError::EndpointMemoryOverflow)
} else {
self.size = match size {
8 => 0b000,
16 => 0b001,
32 => 0b010,
64 => 0b011,
128 => 0b100,
256 => 0b101,
512 => 0b110,
_ => unreachable!(),
8 => 0, // 0b000
16 => 1, // 0b001
32 => 2, // 0b010
64 => 3, // 0b011
128 => 4, // 0b100
256 => 5, // 0b101
512 => 6, // 0b110
_ => unreachable!(), // unsupported, check ATMEGA32u4 docs
};
Ok(())
}
}
}
pub struct UsbDevice<const L: usize> {
pll: Mutex<PLL>,
usb: Mutex<USB_DEVICE>,
ep_table: [USBEndpoint; L],
dpram_already_used: u16,
pub(crate) pll: Mutex<PLL>,
pub(crate) usb: Mutex<USB_DEVICE>,
pub(crate) ep_table: [USBEndpoint; L],
pub(crate) dpram_already_used: u16,
}
const DPRAM_SIZE: u16 = 832;
pub(crate) const MAX_ENDPOINTS: usize = 7;
pub(crate) const DPRAM_SIZE: u16 = 832;
pub(crate) const ENDPOINTS_ALLOC_LAYOUT: [u16; MAX_ENDPOINTS] = [64, 256, 64, 64, 64, 64, 64];
pub(crate) const ONE_MS_16_MGHZ: u32 = 16000;
impl<const L: usize> UsbDevice<L> {
#[inline]
pub fn new(pll: PLL, usb: USB_DEVICE) -> Self {
let (pll, usb) = (Mutex::new(pll), Mutex::new(usb));
let ep_table: [USBEndpoint; L] = [Default::default(); L];
Self {
pll,
usb,
ep_table,
pub fn new(pll: PLL, usb: USB_DEVICE) -> UsbBusAllocator<Self> {
UsbBusAllocator::new(Self {
pll: Mutex::new(pll),
usb: Mutex::new(usb),
ep_table: [USBEndpoint::default(); L],
dpram_already_used: 0,
})
}
#[inline(always)]
pub fn get_usb_device<'u>(&'u self, cs: CriticalSection<'u>) -> &'u USB_DEVICE {
self.usb.borrow(cs)
}
pub fn select_endpoint(
&mut self,
#[inline(always)]
pub fn get_pll<'u>(&'u self, cs: CriticalSection<'u>) -> &'u PLL {
self.pll.borrow(cs)
}
#[inline(always)]
pub(crate) fn allocated_endpoints(&self) -> impl Iterator<Item = (usize, &USBEndpoint)> {
self.ep_table
.iter()
.enumerate()
.filter(|&(_, ep)| ep.is_allocated)
}
pub(crate) fn select_endpoint(
&self,
cs: CriticalSection<'_>,
endpoint_index: usize,
) -> Result<(), UsbError> {
let usb = self.usb.borrow(cs);
let endpoint_index = endpoint_index as u8;
if endpoint_index > 6 {
if endpoint_index >= 7 {
return Err(UsbError::InvalidEndpoint);
}
if usb.usbcon.read().frzclk().bit_is_set() {
return Err(UsbError::InvalidState);
}
usb.uenum.write(|w| w.bits(endpoint_index));
if usb.uenum.read().bits() != endpoint_index {
if usb.uenum.read().bits() & 7 /* 0b111 */ != endpoint_index {
return Err(UsbError::InvalidEndpoint);
}
Ok(())
}
pub fn configure_endpoint(
&mut self,
pub fn get_ep_table(&self) -> &[USBEndpoint] {
&self.ep_table
}
pub(crate) fn configure_endpoint(
&self,
cs: CriticalSection<'_>,
endpoint_index: usize,
) -> Result<(), UsbError> {
match self.select_endpoint(cs, endpoint_index) {
Ok(_) => {
let usb = self.usb.borrow(cs);
let current_endpoint = self.ep_table[endpoint_index];
// Clear interrupt. //
usb.udint.modify(|_, w| w.eorsti().clear_bit());
match self.select_endpoint(cs, endpoint_index) {
Ok(_) => {
// Enable endpoint. //
usb.ueconx.modify(|_, w| w.epen().set_bit());
usb.uecfg1x.modify(|_, w| w.alloc().clear_bit());
// Set markered endpoint parameters to uecfg0x/1x register. //
@@ -129,215 +162,30 @@ impl<const L: usize> UsbDevice<L> {
usb.uecfg1x.modify(|_, w| {
w.epbk()
.bits(current_endpoint.banks)
.bits(0)
.epsize()
.bits(current_endpoint.size)
.alloc()
.bit(current_endpoint.is_allocated)
.set_bit()
});
if !usb.uesta0x.read().cfgok().bit() {
Err(UsbError::EndpointOverflow)
if usb.uesta0x.read().cfgok().bit_is_clear() {
Err(UsbError::EndpointMemoryOverflow)
} else {
usb.ueienx
.modify(|_, w| w.rxoute().set_bit().rxstpe().set_bit());
Ok(())
}
}
Err(exception) => Err(exception),
}
}
}
impl<const L: usize> UsbBus for UsbDevice<L> {
fn alloc_ep(
&mut self,
ep_dir: UsbDirection,
ep_addr: Option<EndpointAddress>,
ep_type: EndpointType,
max_packet_size: u16,
_interval: u8,
) -> UsbResult<EndpointAddress> {
// Handle first endpoint. //
if ep_addr == Some(EndpointAddress::from_parts(0, UsbDirection::In)) {
return Ok(ep_addr.unwrap());
}
let address = match ep_addr {
// If current endpoint doesn't allocated, assign ep_addr to variable. //
Some(ep_addr) if !self.ep_table[ep_addr.index()].is_allocated => ep_addr,
// If ep_aadr not provided, or current endpoint is allocated, try to find next free endpoint, otherwise return UsbError. //
None | Some(_) => {
let endpoint = self
.ep_table
.iter()
.enumerate()
.skip(1)
.find(|(i, &ep)| {
!ep.is_allocated && max_packet_size <= ENDPOINTS_ALLOC_LAYOUT[*i]
})
.ok_or(UsbError::EndpointMemoryOverflow)?;
EndpointAddress::from_parts(endpoint.0, ep_dir)
}
};
// Select endpoint info by address index. //
let target_endpoint = &mut self.ep_table[address.index()];
// Endpoint allocation marker. //
if DPRAM_SIZE - self.dpram_already_used <= max_packet_size || max_packet_size >= 512 {
Err(UsbError::EndpointMemoryOverflow)
} else {
// Get power of two number of endpoint size. //
let max_packet_size = max(8, max_packet_size.next_power_of_two());
// Set endpoint parameters. //
target_endpoint.set_size(max_packet_size);
target_endpoint.set_dir(ep_dir);
target_endpoint.set_type(ep_type);
target_endpoint.is_allocated = true;
// Add used dpram memory. //
self.dpram_already_used += max_packet_size;
Ok(address)
}
}
fn enable(&mut self) {
free(|cs| {
let (pll, usb) = (self.pll.borrow(cs), self.usb.borrow(cs));
// Enable USB pads regulators. //
usb.uhwcon.modify(|_, w| w.uvrege().set_bit());
// Enable USB interface. //
usb.usbcon
.modify(|_, w| w.usbe().set_bit().frzclk().set_bit());
// Configuring PLL. //
pll.pllfrq
.modify(|_, w| w.pdiv().mhz96().plltm().factor_15().pllusb().set_bit());
// Enable PLL. //
pll.pllcsr
.modify(|_, w| w.pindiv().set_bit().plle().set_bit());
while pll.pllcsr.read().plock().bit_is_clear() {}
// Unfreeze clock. //
usb.usbcon
.modify(|_, w| w.frzclk().clear_bit().otgpade().set_bit());
// Interrupts. //
usb.udien
.modify(|_, w| w.eorste().set_bit().sofe().set_bit());
// Set high speed and attach the USB. //
usb.udcon
.modify(|_, w| w.lsm().set_bit().detach().clear_bit());
})
}
fn force_reset(&self) -> usb_device::Result<()> {
free(|cs| {
#[inline(always)]
pub(crate) fn get_size(&self, cs: CriticalSection<'_>) -> usize {
let usb = self.usb.borrow(cs);
usb.usbcon.modify(|_, w| w.usbe().clear_bit());
usb.usbcon.modify(|_, w| w.usbe().set_bit());
Ok(())
})
}
fn is_stalled(&self, ep_addr: usb_device::endpoint::EndpointAddress) -> bool {
todo!();
}
fn poll(&self) -> usb_device::bus::PollResult {
todo!();
}
fn read(
&self,
ep_addr: usb_device::endpoint::EndpointAddress,
buf: &mut [u8],
) -> usb_device::Result<usize> {
todo!();
}
fn reset(&self) {
todo!();
}
fn resume(&self) {
free(|cs| {
let usb = self.usb.borrow(cs);
let pll = self.pll.borrow(cs);
// Enable PLL and wait PLL lock. //
pll.pllcsr.modify(|_, w| w.plle().set_bit());
while pll.pllcsr.read().plock().bit_is_clear() {}
// Unfreeze USB clock. //
usb.usbcon.modify(|_, w| w.frzclk().clear_bit());
// Clear resume informations. //
usb.udint
.modify(|_, w| w.wakeupi().clear_bit().suspi().clear_bit());
usb.udien
.modify(|_, w| w.wakeupe().clear_bit().suspe().set_bit());
})
}
fn set_device_address(&self, addr: u8) {
free(|cs| {
let usb = self.usb.borrow(cs);
// Set address. //
usb.udaddr.modify(|_, w| w.uadd().bits(addr));
// Note: ADDEN and UADD shall not be written at the same time.
// (written in atmega32u4/16u4 docs)
// Enable. //
usb.udaddr.modify(|_, w| w.adden().set_bit());
});
}
fn set_stalled(&self, ep_addr: usb_device::endpoint::EndpointAddress, stalled: bool) {
todo!();
}
fn suspend(&self) {
todo!();
}
fn write(
&self,
ep_addr: usb_device::endpoint::EndpointAddress,
buf: &[u8],
) -> usb_device::Result<usize> {
todo!();
(((usb.uebchx.read().bits() as u16) << 8) | (usb.uebclx.read().bits() as u16)).into()
}
}