Merge remote-tracking branch 'origin/main' into james/read_to_break
This commit is contained in:
23
embassy-rp/README.md
Normal file
23
embassy-rp/README.md
Normal file
@ -0,0 +1,23 @@
|
||||
# Embassy RP HAL
|
||||
|
||||
HALs implement safe, idiomatic Rust APIs to use the hardware capabilities, so raw register manipulation is not needed.
|
||||
|
||||
The Embassy RP HAL targets the Raspberry Pi 2040 family of hardware. The HAL implements both blocking and async APIs
|
||||
for many peripherals. The benefit of using the async APIs is that the HAL takes care of waiting for peripherals to
|
||||
complete operations in low power mod and handling interrupts, so that applications can focus on more important matters.
|
||||
|
||||
NOTE: The Embassy HALs can be used both for non-async and async operations. For async, you can choose which runtime you want to use.
|
||||
|
||||
## Minimum supported Rust version (MSRV)
|
||||
|
||||
Embassy is guaranteed to compile on the latest stable Rust version at the time of release. It might compile with older versions but that may change in any new patch release.
|
||||
|
||||
## License
|
||||
|
||||
This work is licensed under either of
|
||||
|
||||
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or
|
||||
<http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
@ -1,3 +1,4 @@
|
||||
//! ADC driver.
|
||||
use core::future::poll_fn;
|
||||
use core::marker::PhantomData;
|
||||
use core::mem;
|
||||
@ -16,6 +17,7 @@ use crate::{dma, interrupt, pac, peripherals, Peripheral, RegExt};
|
||||
|
||||
static WAKER: AtomicWaker = AtomicWaker::new();
|
||||
|
||||
/// ADC config.
|
||||
#[non_exhaustive]
|
||||
pub struct Config {}
|
||||
|
||||
@ -30,9 +32,11 @@ enum Source<'p> {
|
||||
TempSensor(PeripheralRef<'p, ADC_TEMP_SENSOR>),
|
||||
}
|
||||
|
||||
/// ADC channel.
|
||||
pub struct Channel<'p>(Source<'p>);
|
||||
|
||||
impl<'p> Channel<'p> {
|
||||
/// Create a new ADC channel from pin with the provided [Pull] configuration.
|
||||
pub fn new_pin(pin: impl Peripheral<P = impl AdcPin + 'p> + 'p, pull: Pull) -> Self {
|
||||
into_ref!(pin);
|
||||
pin.pad_ctrl().modify(|w| {
|
||||
@ -49,6 +53,7 @@ impl<'p> Channel<'p> {
|
||||
Self(Source::Pin(pin.map_into()))
|
||||
}
|
||||
|
||||
/// Create a new ADC channel for the internal temperature sensor.
|
||||
pub fn new_temp_sensor(s: impl Peripheral<P = ADC_TEMP_SENSOR> + 'p) -> Self {
|
||||
let r = pac::ADC;
|
||||
r.cs().write_set(|w| w.set_ts_en(true));
|
||||
@ -83,35 +88,44 @@ impl<'p> Drop for Source<'p> {
|
||||
}
|
||||
}
|
||||
|
||||
/// ADC sample.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(transparent)]
|
||||
pub struct Sample(u16);
|
||||
|
||||
impl Sample {
|
||||
/// Sample is valid.
|
||||
pub fn good(&self) -> bool {
|
||||
self.0 < 0x8000
|
||||
}
|
||||
|
||||
/// Sample value.
|
||||
pub fn value(&self) -> u16 {
|
||||
self.0 & !0x8000
|
||||
}
|
||||
}
|
||||
|
||||
/// ADC error.
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum Error {
|
||||
/// Error converting value.
|
||||
ConversionFailed,
|
||||
}
|
||||
|
||||
/// ADC mode.
|
||||
pub trait Mode {}
|
||||
|
||||
/// ADC async mode.
|
||||
pub struct Async;
|
||||
impl Mode for Async {}
|
||||
|
||||
/// ADC blocking mode.
|
||||
pub struct Blocking;
|
||||
impl Mode for Blocking {}
|
||||
|
||||
/// ADC driver.
|
||||
pub struct Adc<'d, M: Mode> {
|
||||
phantom: PhantomData<(&'d ADC, M)>,
|
||||
}
|
||||
@ -150,6 +164,7 @@ impl<'d, M: Mode> Adc<'d, M> {
|
||||
while !r.cs().read().ready() {}
|
||||
}
|
||||
|
||||
/// Sample a value from a channel in blocking mode.
|
||||
pub fn blocking_read(&mut self, ch: &mut Channel) -> Result<u16, Error> {
|
||||
let r = Self::regs();
|
||||
r.cs().modify(|w| {
|
||||
@ -166,6 +181,7 @@ impl<'d, M: Mode> Adc<'d, M> {
|
||||
}
|
||||
|
||||
impl<'d> Adc<'d, Async> {
|
||||
/// Create ADC driver in async mode.
|
||||
pub fn new(
|
||||
_inner: impl Peripheral<P = ADC> + 'd,
|
||||
_irq: impl Binding<interrupt::typelevel::ADC_IRQ_FIFO, InterruptHandler>,
|
||||
@ -194,6 +210,7 @@ impl<'d> Adc<'d, Async> {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Sample a value from a channel until completed.
|
||||
pub async fn read(&mut self, ch: &mut Channel<'_>) -> Result<u16, Error> {
|
||||
let r = Self::regs();
|
||||
r.cs().modify(|w| {
|
||||
@ -272,6 +289,7 @@ impl<'d> Adc<'d, Async> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sample multiple values from a channel using DMA.
|
||||
#[inline]
|
||||
pub async fn read_many<S: AdcSample>(
|
||||
&mut self,
|
||||
@ -283,6 +301,7 @@ impl<'d> Adc<'d, Async> {
|
||||
self.read_many_inner(ch, buf, false, div, dma).await
|
||||
}
|
||||
|
||||
/// Sample multiple values from a channel using DMA with errors inlined in samples.
|
||||
#[inline]
|
||||
pub async fn read_many_raw(
|
||||
&mut self,
|
||||
@ -299,6 +318,7 @@ impl<'d> Adc<'d, Async> {
|
||||
}
|
||||
|
||||
impl<'d> Adc<'d, Blocking> {
|
||||
/// Create ADC driver in blocking mode.
|
||||
pub fn new_blocking(_inner: impl Peripheral<P = ADC> + 'd, _config: Config) -> Self {
|
||||
Self::setup();
|
||||
|
||||
@ -306,6 +326,7 @@ impl<'d> Adc<'d, Blocking> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interrupt handler.
|
||||
pub struct InterruptHandler {
|
||||
_empty: (),
|
||||
}
|
||||
@ -324,6 +345,7 @@ mod sealed {
|
||||
pub trait AdcChannel {}
|
||||
}
|
||||
|
||||
/// ADC sample.
|
||||
pub trait AdcSample: sealed::AdcSample {}
|
||||
|
||||
impl sealed::AdcSample for u16 {}
|
||||
@ -332,7 +354,9 @@ impl AdcSample for u16 {}
|
||||
impl sealed::AdcSample for u8 {}
|
||||
impl AdcSample for u8 {}
|
||||
|
||||
/// ADC channel.
|
||||
pub trait AdcChannel: sealed::AdcChannel {}
|
||||
/// ADC pin.
|
||||
pub trait AdcPin: AdcChannel + gpio::Pin {}
|
||||
|
||||
macro_rules! impl_pin {
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! Clock configuration for the RP2040
|
||||
use core::arch::asm;
|
||||
use core::marker::PhantomData;
|
||||
use core::sync::atomic::{AtomicU16, AtomicU32, Ordering};
|
||||
@ -44,34 +45,50 @@ static CLOCKS: Clocks = Clocks {
|
||||
rtc: AtomicU16::new(0),
|
||||
};
|
||||
|
||||
/// Peripheral clock sources.
|
||||
#[repr(u8)]
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PeriClkSrc {
|
||||
/// SYS.
|
||||
Sys = ClkPeriCtrlAuxsrc::CLK_SYS as _,
|
||||
/// PLL SYS.
|
||||
PllSys = ClkPeriCtrlAuxsrc::CLKSRC_PLL_SYS as _,
|
||||
/// PLL USB.
|
||||
PllUsb = ClkPeriCtrlAuxsrc::CLKSRC_PLL_USB as _,
|
||||
/// ROSC.
|
||||
Rosc = ClkPeriCtrlAuxsrc::ROSC_CLKSRC_PH as _,
|
||||
/// XOSC.
|
||||
Xosc = ClkPeriCtrlAuxsrc::XOSC_CLKSRC as _,
|
||||
// Gpin0 = ClkPeriCtrlAuxsrc::CLKSRC_GPIN0 as _ ,
|
||||
// Gpin1 = ClkPeriCtrlAuxsrc::CLKSRC_GPIN1 as _ ,
|
||||
}
|
||||
|
||||
/// CLock configuration.
|
||||
#[non_exhaustive]
|
||||
pub struct ClockConfig {
|
||||
/// Ring oscillator configuration.
|
||||
pub rosc: Option<RoscConfig>,
|
||||
/// External oscillator configuration.
|
||||
pub xosc: Option<XoscConfig>,
|
||||
/// Reference clock configuration.
|
||||
pub ref_clk: RefClkConfig,
|
||||
/// System clock configuration.
|
||||
pub sys_clk: SysClkConfig,
|
||||
/// Peripheral clock source configuration.
|
||||
pub peri_clk_src: Option<PeriClkSrc>,
|
||||
/// USB clock configuration.
|
||||
pub usb_clk: Option<UsbClkConfig>,
|
||||
/// ADC clock configuration.
|
||||
pub adc_clk: Option<AdcClkConfig>,
|
||||
/// RTC clock configuration.
|
||||
pub rtc_clk: Option<RtcClkConfig>,
|
||||
// gpin0: Option<(u32, Gpin<'static, AnyPin>)>,
|
||||
// gpin1: Option<(u32, Gpin<'static, AnyPin>)>,
|
||||
}
|
||||
|
||||
impl ClockConfig {
|
||||
/// Clock configuration derived from external crystal.
|
||||
pub fn crystal(crystal_hz: u32) -> Self {
|
||||
Self {
|
||||
rosc: Some(RoscConfig {
|
||||
@ -130,6 +147,7 @@ impl ClockConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clock configuration from internal oscillator.
|
||||
pub fn rosc() -> Self {
|
||||
Self {
|
||||
rosc: Some(RoscConfig {
|
||||
@ -179,130 +197,190 @@ impl ClockConfig {
|
||||
// }
|
||||
}
|
||||
|
||||
/// ROSC freq range.
|
||||
#[repr(u16)]
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RoscRange {
|
||||
/// Low range.
|
||||
Low = pac::rosc::vals::FreqRange::LOW.0,
|
||||
/// Medium range (1.33x low)
|
||||
Medium = pac::rosc::vals::FreqRange::MEDIUM.0,
|
||||
/// High range (2x low)
|
||||
High = pac::rosc::vals::FreqRange::HIGH.0,
|
||||
/// Too high. Should not be used.
|
||||
TooHigh = pac::rosc::vals::FreqRange::TOOHIGH.0,
|
||||
}
|
||||
|
||||
/// On-chip ring oscillator configuration.
|
||||
pub struct RoscConfig {
|
||||
/// Final frequency of the oscillator, after the divider has been applied.
|
||||
/// The oscillator has a nominal frequency of 6.5MHz at medium range with
|
||||
/// divider 16 and all drive strengths set to 0, other values should be
|
||||
/// measured in situ.
|
||||
pub hz: u32,
|
||||
/// Oscillator range.
|
||||
pub range: RoscRange,
|
||||
/// Drive strength for oscillator.
|
||||
pub drive_strength: [u8; 8],
|
||||
/// Output divider.
|
||||
pub div: u16,
|
||||
}
|
||||
|
||||
/// Crystal oscillator configuration.
|
||||
pub struct XoscConfig {
|
||||
/// Final frequency of the oscillator.
|
||||
pub hz: u32,
|
||||
/// Configuring PLL for the system clock.
|
||||
pub sys_pll: Option<PllConfig>,
|
||||
/// Configuring PLL for the USB clock.
|
||||
pub usb_pll: Option<PllConfig>,
|
||||
/// Multiplier for the startup delay.
|
||||
pub delay_multiplier: u32,
|
||||
}
|
||||
|
||||
/// PLL configuration.
|
||||
pub struct PllConfig {
|
||||
/// Reference divisor.
|
||||
pub refdiv: u8,
|
||||
/// Feedback divisor.
|
||||
pub fbdiv: u16,
|
||||
/// Output divisor 1.
|
||||
pub post_div1: u8,
|
||||
/// Output divisor 2.
|
||||
pub post_div2: u8,
|
||||
}
|
||||
|
||||
/// Reference clock config.
|
||||
pub struct RefClkConfig {
|
||||
/// Reference clock source.
|
||||
pub src: RefClkSrc,
|
||||
/// Reference clock divider.
|
||||
pub div: u8,
|
||||
}
|
||||
|
||||
/// Reference clock source.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RefClkSrc {
|
||||
// main sources
|
||||
/// XOSC.
|
||||
Xosc,
|
||||
/// ROSC.
|
||||
Rosc,
|
||||
// aux sources
|
||||
/// PLL USB.
|
||||
PllUsb,
|
||||
// Gpin0,
|
||||
// Gpin1,
|
||||
}
|
||||
|
||||
/// SYS clock source.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SysClkSrc {
|
||||
// main sources
|
||||
/// REF.
|
||||
Ref,
|
||||
// aux sources
|
||||
/// PLL SYS.
|
||||
PllSys,
|
||||
/// PLL USB.
|
||||
PllUsb,
|
||||
/// ROSC.
|
||||
Rosc,
|
||||
/// XOSC.
|
||||
Xosc,
|
||||
// Gpin0,
|
||||
// Gpin1,
|
||||
}
|
||||
|
||||
/// SYS clock config.
|
||||
pub struct SysClkConfig {
|
||||
/// SYS clock source.
|
||||
pub src: SysClkSrc,
|
||||
/// SYS clock divider.
|
||||
pub div_int: u32,
|
||||
/// SYS clock fraction.
|
||||
pub div_frac: u8,
|
||||
}
|
||||
|
||||
/// USB clock source.
|
||||
#[repr(u8)]
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum UsbClkSrc {
|
||||
/// PLL USB.
|
||||
PllUsb = ClkUsbCtrlAuxsrc::CLKSRC_PLL_USB as _,
|
||||
/// PLL SYS.
|
||||
PllSys = ClkUsbCtrlAuxsrc::CLKSRC_PLL_SYS as _,
|
||||
/// ROSC.
|
||||
Rosc = ClkUsbCtrlAuxsrc::ROSC_CLKSRC_PH as _,
|
||||
/// XOSC.
|
||||
Xosc = ClkUsbCtrlAuxsrc::XOSC_CLKSRC as _,
|
||||
// Gpin0 = ClkUsbCtrlAuxsrc::CLKSRC_GPIN0 as _ ,
|
||||
// Gpin1 = ClkUsbCtrlAuxsrc::CLKSRC_GPIN1 as _ ,
|
||||
}
|
||||
|
||||
/// USB clock config.
|
||||
pub struct UsbClkConfig {
|
||||
/// USB clock source.
|
||||
pub src: UsbClkSrc,
|
||||
/// USB clock divider.
|
||||
pub div: u8,
|
||||
/// USB clock phase.
|
||||
pub phase: u8,
|
||||
}
|
||||
|
||||
/// ADC clock source.
|
||||
#[repr(u8)]
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AdcClkSrc {
|
||||
/// PLL USB.
|
||||
PllUsb = ClkAdcCtrlAuxsrc::CLKSRC_PLL_USB as _,
|
||||
/// PLL SYS.
|
||||
PllSys = ClkAdcCtrlAuxsrc::CLKSRC_PLL_SYS as _,
|
||||
/// ROSC.
|
||||
Rosc = ClkAdcCtrlAuxsrc::ROSC_CLKSRC_PH as _,
|
||||
/// XOSC.
|
||||
Xosc = ClkAdcCtrlAuxsrc::XOSC_CLKSRC as _,
|
||||
// Gpin0 = ClkAdcCtrlAuxsrc::CLKSRC_GPIN0 as _ ,
|
||||
// Gpin1 = ClkAdcCtrlAuxsrc::CLKSRC_GPIN1 as _ ,
|
||||
}
|
||||
|
||||
/// ADC clock config.
|
||||
pub struct AdcClkConfig {
|
||||
/// ADC clock source.
|
||||
pub src: AdcClkSrc,
|
||||
/// ADC clock divider.
|
||||
pub div: u8,
|
||||
/// ADC clock phase.
|
||||
pub phase: u8,
|
||||
}
|
||||
|
||||
/// RTC clock source.
|
||||
#[repr(u8)]
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RtcClkSrc {
|
||||
/// PLL USB.
|
||||
PllUsb = ClkRtcCtrlAuxsrc::CLKSRC_PLL_USB as _,
|
||||
/// PLL SYS.
|
||||
PllSys = ClkRtcCtrlAuxsrc::CLKSRC_PLL_SYS as _,
|
||||
/// ROSC.
|
||||
Rosc = ClkRtcCtrlAuxsrc::ROSC_CLKSRC_PH as _,
|
||||
/// XOSC.
|
||||
Xosc = ClkRtcCtrlAuxsrc::XOSC_CLKSRC as _,
|
||||
// Gpin0 = ClkRtcCtrlAuxsrc::CLKSRC_GPIN0 as _ ,
|
||||
// Gpin1 = ClkRtcCtrlAuxsrc::CLKSRC_GPIN1 as _ ,
|
||||
}
|
||||
|
||||
/// RTC clock config.
|
||||
pub struct RtcClkConfig {
|
||||
/// RTC clock source.
|
||||
pub src: RtcClkSrc,
|
||||
/// RTC clock divider.
|
||||
pub div_int: u32,
|
||||
/// RTC clock divider fraction.
|
||||
pub div_frac: u8,
|
||||
/// RTC clock phase.
|
||||
pub phase: u8,
|
||||
}
|
||||
|
||||
@ -579,10 +657,12 @@ fn configure_rosc(config: RoscConfig) -> u32 {
|
||||
config.hz
|
||||
}
|
||||
|
||||
/// ROSC clock frequency.
|
||||
pub fn rosc_freq() -> u32 {
|
||||
CLOCKS.rosc.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// XOSC clock frequency.
|
||||
pub fn xosc_freq() -> u32 {
|
||||
CLOCKS.xosc.load(Ordering::Relaxed)
|
||||
}
|
||||
@ -594,34 +674,42 @@ pub fn xosc_freq() -> u32 {
|
||||
// CLOCKS.gpin1.load(Ordering::Relaxed)
|
||||
// }
|
||||
|
||||
/// PLL SYS clock frequency.
|
||||
pub fn pll_sys_freq() -> u32 {
|
||||
CLOCKS.pll_sys.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// PLL USB clock frequency.
|
||||
pub fn pll_usb_freq() -> u32 {
|
||||
CLOCKS.pll_usb.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// SYS clock frequency.
|
||||
pub fn clk_sys_freq() -> u32 {
|
||||
CLOCKS.sys.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// REF clock frequency.
|
||||
pub fn clk_ref_freq() -> u32 {
|
||||
CLOCKS.reference.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Peripheral clock frequency.
|
||||
pub fn clk_peri_freq() -> u32 {
|
||||
CLOCKS.peri.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// USB clock frequency.
|
||||
pub fn clk_usb_freq() -> u32 {
|
||||
CLOCKS.usb.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// ADC clock frequency.
|
||||
pub fn clk_adc_freq() -> u32 {
|
||||
CLOCKS.adc.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// RTC clock frequency.
|
||||
pub fn clk_rtc_freq() -> u16 {
|
||||
CLOCKS.rtc.load(Ordering::Relaxed)
|
||||
}
|
||||
@ -682,7 +770,9 @@ fn configure_pll(p: pac::pll::Pll, input_freq: u32, config: PllConfig) -> u32 {
|
||||
vco_freq / ((config.post_div1 * config.post_div2) as u32)
|
||||
}
|
||||
|
||||
/// General purpose input clock pin.
|
||||
pub trait GpinPin: crate::gpio::Pin {
|
||||
/// Pin number.
|
||||
const NR: usize;
|
||||
}
|
||||
|
||||
@ -697,12 +787,14 @@ macro_rules! impl_gpinpin {
|
||||
impl_gpinpin!(PIN_20, 20, 0);
|
||||
impl_gpinpin!(PIN_22, 22, 1);
|
||||
|
||||
/// General purpose clock input driver.
|
||||
pub struct Gpin<'d, T: Pin> {
|
||||
gpin: PeripheralRef<'d, AnyPin>,
|
||||
_phantom: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> Gpin<'d, T> {
|
||||
/// Create new gpin driver.
|
||||
pub fn new<P: GpinPin>(gpin: impl Peripheral<P = P> + 'd) -> Gpin<'d, P> {
|
||||
into_ref!(gpin);
|
||||
|
||||
@ -728,7 +820,9 @@ impl<'d, T: Pin> Drop for Gpin<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// General purpose clock output pin.
|
||||
pub trait GpoutPin: crate::gpio::Pin {
|
||||
/// Pin number.
|
||||
fn number(&self) -> usize;
|
||||
}
|
||||
|
||||
@ -747,26 +841,38 @@ impl_gpoutpin!(PIN_23, 1);
|
||||
impl_gpoutpin!(PIN_24, 2);
|
||||
impl_gpoutpin!(PIN_25, 3);
|
||||
|
||||
/// Gpout clock source.
|
||||
#[repr(u8)]
|
||||
pub enum GpoutSrc {
|
||||
/// Sys PLL.
|
||||
PllSys = ClkGpoutCtrlAuxsrc::CLKSRC_PLL_SYS as _,
|
||||
// Gpin0 = ClkGpoutCtrlAuxsrc::CLKSRC_GPIN0 as _ ,
|
||||
// Gpin1 = ClkGpoutCtrlAuxsrc::CLKSRC_GPIN1 as _ ,
|
||||
/// USB PLL.
|
||||
PllUsb = ClkGpoutCtrlAuxsrc::CLKSRC_PLL_USB as _,
|
||||
/// ROSC.
|
||||
Rosc = ClkGpoutCtrlAuxsrc::ROSC_CLKSRC as _,
|
||||
/// XOSC.
|
||||
Xosc = ClkGpoutCtrlAuxsrc::XOSC_CLKSRC as _,
|
||||
/// SYS.
|
||||
Sys = ClkGpoutCtrlAuxsrc::CLK_SYS as _,
|
||||
/// USB.
|
||||
Usb = ClkGpoutCtrlAuxsrc::CLK_USB as _,
|
||||
/// ADC.
|
||||
Adc = ClkGpoutCtrlAuxsrc::CLK_ADC as _,
|
||||
/// RTC.
|
||||
Rtc = ClkGpoutCtrlAuxsrc::CLK_RTC as _,
|
||||
/// REF.
|
||||
Ref = ClkGpoutCtrlAuxsrc::CLK_REF as _,
|
||||
}
|
||||
|
||||
/// General purpose clock output driver.
|
||||
pub struct Gpout<'d, T: GpoutPin> {
|
||||
gpout: PeripheralRef<'d, T>,
|
||||
}
|
||||
|
||||
impl<'d, T: GpoutPin> Gpout<'d, T> {
|
||||
/// Create new general purpose cloud output.
|
||||
pub fn new(gpout: impl Peripheral<P = T> + 'd) -> Self {
|
||||
into_ref!(gpout);
|
||||
|
||||
@ -775,6 +881,7 @@ impl<'d, T: GpoutPin> Gpout<'d, T> {
|
||||
Self { gpout }
|
||||
}
|
||||
|
||||
/// Set clock divider.
|
||||
pub fn set_div(&self, int: u32, frac: u8) {
|
||||
let c = pac::CLOCKS;
|
||||
c.clk_gpout_div(self.gpout.number()).write(|w| {
|
||||
@ -783,6 +890,7 @@ impl<'d, T: GpoutPin> Gpout<'d, T> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Set clock source.
|
||||
pub fn set_src(&self, src: GpoutSrc) {
|
||||
let c = pac::CLOCKS;
|
||||
c.clk_gpout_ctrl(self.gpout.number()).modify(|w| {
|
||||
@ -790,6 +898,7 @@ impl<'d, T: GpoutPin> Gpout<'d, T> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Enable clock.
|
||||
pub fn enable(&self) {
|
||||
let c = pac::CLOCKS;
|
||||
c.clk_gpout_ctrl(self.gpout.number()).modify(|w| {
|
||||
@ -797,6 +906,7 @@ impl<'d, T: GpoutPin> Gpout<'d, T> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Disable clock.
|
||||
pub fn disable(&self) {
|
||||
let c = pac::CLOCKS;
|
||||
c.clk_gpout_ctrl(self.gpout.number()).modify(|w| {
|
||||
@ -804,6 +914,7 @@ impl<'d, T: GpoutPin> Gpout<'d, T> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Clock frequency.
|
||||
pub fn get_freq(&self) -> u32 {
|
||||
let c = pac::CLOCKS;
|
||||
let src = c.clk_gpout_ctrl(self.gpout.number()).read().auxsrc();
|
||||
|
@ -38,6 +38,9 @@ pub(crate) unsafe fn init() {
|
||||
interrupt::DMA_IRQ_0.enable();
|
||||
}
|
||||
|
||||
/// DMA read.
|
||||
///
|
||||
/// SAFETY: Slice must point to a valid location reachable by DMA.
|
||||
pub unsafe fn read<'a, C: Channel, W: Word>(
|
||||
ch: impl Peripheral<P = C> + 'a,
|
||||
from: *const W,
|
||||
@ -57,6 +60,9 @@ pub unsafe fn read<'a, C: Channel, W: Word>(
|
||||
)
|
||||
}
|
||||
|
||||
/// DMA write.
|
||||
///
|
||||
/// SAFETY: Slice must point to a valid location reachable by DMA.
|
||||
pub unsafe fn write<'a, C: Channel, W: Word>(
|
||||
ch: impl Peripheral<P = C> + 'a,
|
||||
from: *const [W],
|
||||
@ -79,6 +85,9 @@ pub unsafe fn write<'a, C: Channel, W: Word>(
|
||||
// static mut so that this is allocated in RAM.
|
||||
static mut DUMMY: u32 = 0;
|
||||
|
||||
/// DMA repeated write.
|
||||
///
|
||||
/// SAFETY: Slice must point to a valid location reachable by DMA.
|
||||
pub unsafe fn write_repeated<'a, C: Channel, W: Word>(
|
||||
ch: impl Peripheral<P = C> + 'a,
|
||||
to: *mut W,
|
||||
@ -97,6 +106,9 @@ pub unsafe fn write_repeated<'a, C: Channel, W: Word>(
|
||||
)
|
||||
}
|
||||
|
||||
/// DMA copy between slices.
|
||||
///
|
||||
/// SAFETY: Slices must point to locations reachable by DMA.
|
||||
pub unsafe fn copy<'a, C: Channel, W: Word>(
|
||||
ch: impl Peripheral<P = C> + 'a,
|
||||
from: &[W],
|
||||
@ -152,6 +164,7 @@ fn copy_inner<'a, C: Channel>(
|
||||
Transfer::new(ch)
|
||||
}
|
||||
|
||||
/// DMA transfer driver.
|
||||
#[must_use = "futures do nothing unless you `.await` or poll them"]
|
||||
pub struct Transfer<'a, C: Channel> {
|
||||
channel: PeripheralRef<'a, C>,
|
||||
@ -201,19 +214,25 @@ mod sealed {
|
||||
pub trait Word {}
|
||||
}
|
||||
|
||||
/// DMA channel interface.
|
||||
pub trait Channel: Peripheral<P = Self> + sealed::Channel + Into<AnyChannel> + Sized + 'static {
|
||||
/// Channel number.
|
||||
fn number(&self) -> u8;
|
||||
|
||||
/// Channel registry block.
|
||||
fn regs(&self) -> pac::dma::Channel {
|
||||
pac::DMA.ch(self.number() as _)
|
||||
}
|
||||
|
||||
/// Convert into type-erased [AnyChannel].
|
||||
fn degrade(self) -> AnyChannel {
|
||||
AnyChannel { number: self.number() }
|
||||
}
|
||||
}
|
||||
|
||||
/// DMA word.
|
||||
pub trait Word: sealed::Word {
|
||||
/// Word size.
|
||||
fn size() -> vals::DataSize;
|
||||
}
|
||||
|
||||
@ -238,6 +257,7 @@ impl Word for u32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Type erased DMA channel.
|
||||
pub struct AnyChannel {
|
||||
number: u8,
|
||||
}
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! Flash driver.
|
||||
use core::future::Future;
|
||||
use core::marker::PhantomData;
|
||||
use core::pin::Pin;
|
||||
@ -13,9 +14,10 @@ use crate::dma::{AnyChannel, Channel, Transfer};
|
||||
use crate::pac;
|
||||
use crate::peripherals::FLASH;
|
||||
|
||||
/// Flash base address.
|
||||
pub const FLASH_BASE: *const u32 = 0x10000000 as _;
|
||||
|
||||
// If running from RAM, we might have no boot2. Use bootrom `flash_enter_cmd_xip` instead.
|
||||
/// If running from RAM, we might have no boot2. Use bootrom `flash_enter_cmd_xip` instead.
|
||||
// TODO: when run-from-ram is set, completely skip the "pause cores and jumpp to RAM" dance.
|
||||
pub const USE_BOOT2: bool = !cfg!(feature = "run-from-ram");
|
||||
|
||||
@ -24,10 +26,15 @@ pub const USE_BOOT2: bool = !cfg!(feature = "run-from-ram");
|
||||
// These limitations are currently enforced because of using the
|
||||
// RP2040 boot-rom flash functions, that are optimized for flash compatibility
|
||||
// rather than performance.
|
||||
/// Flash page size.
|
||||
pub const PAGE_SIZE: usize = 256;
|
||||
/// Flash write size.
|
||||
pub const WRITE_SIZE: usize = 1;
|
||||
/// Flash read size.
|
||||
pub const READ_SIZE: usize = 1;
|
||||
/// Flash erase size.
|
||||
pub const ERASE_SIZE: usize = 4096;
|
||||
/// Flash DMA read size.
|
||||
pub const ASYNC_READ_SIZE: usize = 4;
|
||||
|
||||
/// Error type for NVMC operations.
|
||||
@ -38,7 +45,9 @@ pub enum Error {
|
||||
OutOfBounds,
|
||||
/// Unaligned operation or using unaligned buffers.
|
||||
Unaligned,
|
||||
/// Accessed from the wrong core.
|
||||
InvalidCore,
|
||||
/// Other error
|
||||
Other,
|
||||
}
|
||||
|
||||
@ -96,12 +105,18 @@ impl<'a, 'd, T: Instance, const FLASH_SIZE: usize> Drop for BackgroundRead<'a, '
|
||||
}
|
||||
}
|
||||
|
||||
/// Flash driver.
|
||||
pub struct Flash<'d, T: Instance, M: Mode, const FLASH_SIZE: usize> {
|
||||
dma: Option<PeripheralRef<'d, AnyChannel>>,
|
||||
phantom: PhantomData<(&'d mut T, M)>,
|
||||
}
|
||||
|
||||
impl<'d, T: Instance, M: Mode, const FLASH_SIZE: usize> Flash<'d, T, M, FLASH_SIZE> {
|
||||
/// Blocking read.
|
||||
///
|
||||
/// The offset and buffer must be aligned.
|
||||
///
|
||||
/// NOTE: `offset` is an offset from the flash start, NOT an absolute address.
|
||||
pub fn blocking_read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> {
|
||||
trace!(
|
||||
"Reading from 0x{:x} to 0x{:x}",
|
||||
@ -116,10 +131,14 @@ impl<'d, T: Instance, M: Mode, const FLASH_SIZE: usize> Flash<'d, T, M, FLASH_SI
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Flash capacity.
|
||||
pub fn capacity(&self) -> usize {
|
||||
FLASH_SIZE
|
||||
}
|
||||
|
||||
/// Blocking erase.
|
||||
///
|
||||
/// NOTE: `offset` is an offset from the flash start, NOT an absolute address.
|
||||
pub fn blocking_erase(&mut self, from: u32, to: u32) -> Result<(), Error> {
|
||||
check_erase(self, from, to)?;
|
||||
|
||||
@ -136,6 +155,11 @@ impl<'d, T: Instance, M: Mode, const FLASH_SIZE: usize> Flash<'d, T, M, FLASH_SI
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Blocking write.
|
||||
///
|
||||
/// The offset and buffer must be aligned.
|
||||
///
|
||||
/// NOTE: `offset` is an offset from the flash start, NOT an absolute address.
|
||||
pub fn blocking_write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> {
|
||||
check_write(self, offset, bytes.len())?;
|
||||
|
||||
@ -219,6 +243,7 @@ impl<'d, T: Instance, M: Mode, const FLASH_SIZE: usize> Flash<'d, T, M, FLASH_SI
|
||||
}
|
||||
|
||||
impl<'d, T: Instance, const FLASH_SIZE: usize> Flash<'d, T, Blocking, FLASH_SIZE> {
|
||||
/// Create a new flash driver in blocking mode.
|
||||
pub fn new_blocking(_flash: impl Peripheral<P = T> + 'd) -> Self {
|
||||
Self {
|
||||
dma: None,
|
||||
@ -228,6 +253,7 @@ impl<'d, T: Instance, const FLASH_SIZE: usize> Flash<'d, T, Blocking, FLASH_SIZE
|
||||
}
|
||||
|
||||
impl<'d, T: Instance, const FLASH_SIZE: usize> Flash<'d, T, Async, FLASH_SIZE> {
|
||||
/// Create a new flash driver in async mode.
|
||||
pub fn new(_flash: impl Peripheral<P = T> + 'd, dma: impl Peripheral<P = impl Channel> + 'd) -> Self {
|
||||
into_ref!(dma);
|
||||
Self {
|
||||
@ -236,6 +262,11 @@ impl<'d, T: Instance, const FLASH_SIZE: usize> Flash<'d, T, Async, FLASH_SIZE> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a background read operation.
|
||||
///
|
||||
/// The offset and buffer must be aligned.
|
||||
///
|
||||
/// NOTE: `offset` is an offset from the flash start, NOT an absolute address.
|
||||
pub fn background_read<'a>(
|
||||
&'a mut self,
|
||||
offset: u32,
|
||||
@ -279,6 +310,11 @@ impl<'d, T: Instance, const FLASH_SIZE: usize> Flash<'d, T, Async, FLASH_SIZE> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Async read.
|
||||
///
|
||||
/// The offset and buffer must be aligned.
|
||||
///
|
||||
/// NOTE: `offset` is an offset from the flash start, NOT an absolute address.
|
||||
pub async fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> {
|
||||
use core::mem::MaybeUninit;
|
||||
|
||||
@ -874,7 +910,9 @@ mod sealed {
|
||||
pub trait Mode {}
|
||||
}
|
||||
|
||||
/// Flash instance.
|
||||
pub trait Instance: sealed::Instance {}
|
||||
/// Flash mode.
|
||||
pub trait Mode: sealed::Mode {}
|
||||
|
||||
impl sealed::Instance for FLASH {}
|
||||
@ -887,7 +925,9 @@ macro_rules! impl_mode {
|
||||
};
|
||||
}
|
||||
|
||||
/// Flash blocking mode.
|
||||
pub struct Blocking;
|
||||
/// Flash async mode.
|
||||
pub struct Async;
|
||||
|
||||
impl_mode!(Blocking);
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! GPIO driver.
|
||||
#![macro_use]
|
||||
use core::convert::Infallible;
|
||||
use core::future::Future;
|
||||
@ -23,7 +24,9 @@ static QSPI_WAKERS: [AtomicWaker; QSPI_PIN_COUNT] = [NEW_AW; QSPI_PIN_COUNT];
|
||||
/// Represents a digital input or output level.
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
|
||||
pub enum Level {
|
||||
/// Logical low.
|
||||
Low,
|
||||
/// Logical high.
|
||||
High,
|
||||
}
|
||||
|
||||
@ -48,48 +51,66 @@ impl From<Level> for bool {
|
||||
/// Represents a pull setting for an input.
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||
pub enum Pull {
|
||||
/// No pull.
|
||||
None,
|
||||
/// Internal pull-up resistor.
|
||||
Up,
|
||||
/// Internal pull-down resistor.
|
||||
Down,
|
||||
}
|
||||
|
||||
/// Drive strength of an output
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum Drive {
|
||||
/// 2 mA drive.
|
||||
_2mA,
|
||||
/// 4 mA drive.
|
||||
_4mA,
|
||||
/// 8 mA drive.
|
||||
_8mA,
|
||||
/// 1 2mA drive.
|
||||
_12mA,
|
||||
}
|
||||
/// Slew rate of an output
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum SlewRate {
|
||||
/// Fast slew rate.
|
||||
Fast,
|
||||
/// Slow slew rate.
|
||||
Slow,
|
||||
}
|
||||
|
||||
/// A GPIO bank with up to 32 pins.
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum Bank {
|
||||
/// Bank 0.
|
||||
Bank0 = 0,
|
||||
/// QSPI.
|
||||
#[cfg(feature = "qspi-as-gpio")]
|
||||
Qspi = 1,
|
||||
}
|
||||
|
||||
/// Dormant mode config.
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone, Default)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct DormantWakeConfig {
|
||||
/// Wake on edge high.
|
||||
pub edge_high: bool,
|
||||
/// Wake on edge low.
|
||||
pub edge_low: bool,
|
||||
/// Wake on level high.
|
||||
pub level_high: bool,
|
||||
/// Wake on level low.
|
||||
pub level_low: bool,
|
||||
}
|
||||
|
||||
/// GPIO input driver.
|
||||
pub struct Input<'d, T: Pin> {
|
||||
pin: Flex<'d, T>,
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> Input<'d, T> {
|
||||
/// Create GPIO input driver for a [Pin] with the provided [Pull] configuration.
|
||||
#[inline]
|
||||
pub fn new(pin: impl Peripheral<P = T> + 'd, pull: Pull) -> Self {
|
||||
let mut pin = Flex::new(pin);
|
||||
@ -104,11 +125,13 @@ impl<'d, T: Pin> Input<'d, T> {
|
||||
self.pin.set_schmitt(enable)
|
||||
}
|
||||
|
||||
/// Get whether the pin input level is high.
|
||||
#[inline]
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
self.pin.is_high()
|
||||
}
|
||||
|
||||
/// Get whether the pin input level is low.
|
||||
#[inline]
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.pin.is_low()
|
||||
@ -120,31 +143,37 @@ impl<'d, T: Pin> Input<'d, T> {
|
||||
self.pin.get_level()
|
||||
}
|
||||
|
||||
/// Wait until the pin is high. If it is already high, return immediately.
|
||||
#[inline]
|
||||
pub async fn wait_for_high(&mut self) {
|
||||
self.pin.wait_for_high().await;
|
||||
}
|
||||
|
||||
/// Wait until the pin is low. If it is already low, return immediately.
|
||||
#[inline]
|
||||
pub async fn wait_for_low(&mut self) {
|
||||
self.pin.wait_for_low().await;
|
||||
}
|
||||
|
||||
/// Wait for the pin to undergo a transition from low to high.
|
||||
#[inline]
|
||||
pub async fn wait_for_rising_edge(&mut self) {
|
||||
self.pin.wait_for_rising_edge().await;
|
||||
}
|
||||
|
||||
/// Wait for the pin to undergo a transition from high to low.
|
||||
#[inline]
|
||||
pub async fn wait_for_falling_edge(&mut self) {
|
||||
self.pin.wait_for_falling_edge().await;
|
||||
}
|
||||
|
||||
/// Wait for the pin to undergo any transition, i.e low to high OR high to low.
|
||||
#[inline]
|
||||
pub async fn wait_for_any_edge(&mut self) {
|
||||
self.pin.wait_for_any_edge().await;
|
||||
}
|
||||
|
||||
/// Configure dormant wake.
|
||||
#[inline]
|
||||
pub fn dormant_wake(&mut self, cfg: DormantWakeConfig) -> DormantWake<T> {
|
||||
self.pin.dormant_wake(cfg)
|
||||
@ -155,10 +184,15 @@ impl<'d, T: Pin> Input<'d, T> {
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum InterruptTrigger {
|
||||
/// Trigger on pin low.
|
||||
LevelLow,
|
||||
/// Trigger on pin high.
|
||||
LevelHigh,
|
||||
/// Trigger on high to low transition.
|
||||
EdgeLow,
|
||||
/// Trigger on low to high transition.
|
||||
EdgeHigh,
|
||||
/// Trigger on any transition.
|
||||
AnyEdge,
|
||||
}
|
||||
|
||||
@ -226,6 +260,7 @@ struct InputFuture<'a, T: Pin> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> InputFuture<'d, T> {
|
||||
/// Create a new future wiating for input trigger.
|
||||
pub fn new(pin: impl Peripheral<P = T> + 'd, level: InterruptTrigger) -> Self {
|
||||
into_ref!(pin);
|
||||
let pin_group = (pin.pin() % 8) as usize;
|
||||
@ -308,11 +343,13 @@ impl<'d, T: Pin> Future for InputFuture<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// GPIO output driver.
|
||||
pub struct Output<'d, T: Pin> {
|
||||
pin: Flex<'d, T>,
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> Output<'d, T> {
|
||||
/// Create GPIO output driver for a [Pin] with the provided [Level].
|
||||
#[inline]
|
||||
pub fn new(pin: impl Peripheral<P = T> + 'd, initial_output: Level) -> Self {
|
||||
let mut pin = Flex::new(pin);
|
||||
@ -331,7 +368,7 @@ impl<'d, T: Pin> Output<'d, T> {
|
||||
self.pin.set_drive_strength(strength)
|
||||
}
|
||||
|
||||
// Set the pin's slew rate.
|
||||
/// Set the pin's slew rate.
|
||||
#[inline]
|
||||
pub fn set_slew_rate(&mut self, slew_rate: SlewRate) {
|
||||
self.pin.set_slew_rate(slew_rate)
|
||||
@ -386,6 +423,7 @@ pub struct OutputOpenDrain<'d, T: Pin> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> OutputOpenDrain<'d, T> {
|
||||
/// Create GPIO output driver for a [Pin] in open drain mode with the provided [Level].
|
||||
#[inline]
|
||||
pub fn new(pin: impl Peripheral<P = T> + 'd, initial_output: Level) -> Self {
|
||||
let mut pin = Flex::new(pin);
|
||||
@ -403,7 +441,7 @@ impl<'d, T: Pin> OutputOpenDrain<'d, T> {
|
||||
self.pin.set_drive_strength(strength)
|
||||
}
|
||||
|
||||
// Set the pin's slew rate.
|
||||
/// Set the pin's slew rate.
|
||||
#[inline]
|
||||
pub fn set_slew_rate(&mut self, slew_rate: SlewRate) {
|
||||
self.pin.set_slew_rate(slew_rate)
|
||||
@ -456,11 +494,13 @@ impl<'d, T: Pin> OutputOpenDrain<'d, T> {
|
||||
self.pin.toggle_set_as_output()
|
||||
}
|
||||
|
||||
/// Get whether the pin input level is high.
|
||||
#[inline]
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
self.pin.is_high()
|
||||
}
|
||||
|
||||
/// Get whether the pin input level is low.
|
||||
#[inline]
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.pin.is_low()
|
||||
@ -472,26 +512,31 @@ impl<'d, T: Pin> OutputOpenDrain<'d, T> {
|
||||
self.is_high().into()
|
||||
}
|
||||
|
||||
/// Wait until the pin is high. If it is already high, return immediately.
|
||||
#[inline]
|
||||
pub async fn wait_for_high(&mut self) {
|
||||
self.pin.wait_for_high().await;
|
||||
}
|
||||
|
||||
/// Wait until the pin is low. If it is already low, return immediately.
|
||||
#[inline]
|
||||
pub async fn wait_for_low(&mut self) {
|
||||
self.pin.wait_for_low().await;
|
||||
}
|
||||
|
||||
/// Wait for the pin to undergo a transition from low to high.
|
||||
#[inline]
|
||||
pub async fn wait_for_rising_edge(&mut self) {
|
||||
self.pin.wait_for_rising_edge().await;
|
||||
}
|
||||
|
||||
/// Wait for the pin to undergo a transition from high to low.
|
||||
#[inline]
|
||||
pub async fn wait_for_falling_edge(&mut self) {
|
||||
self.pin.wait_for_falling_edge().await;
|
||||
}
|
||||
|
||||
/// Wait for the pin to undergo any transition, i.e low to high OR high to low.
|
||||
#[inline]
|
||||
pub async fn wait_for_any_edge(&mut self) {
|
||||
self.pin.wait_for_any_edge().await;
|
||||
@ -508,6 +553,10 @@ pub struct Flex<'d, T: Pin> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> Flex<'d, T> {
|
||||
/// Wrap the pin in a `Flex`.
|
||||
///
|
||||
/// The pin remains disconnected. The initial output level is unspecified, but can be changed
|
||||
/// before the pin is put into output mode.
|
||||
#[inline]
|
||||
pub fn new(pin: impl Peripheral<P = T> + 'd) -> Self {
|
||||
into_ref!(pin);
|
||||
@ -556,7 +605,7 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
});
|
||||
}
|
||||
|
||||
// Set the pin's slew rate.
|
||||
/// Set the pin's slew rate.
|
||||
#[inline]
|
||||
pub fn set_slew_rate(&mut self, slew_rate: SlewRate) {
|
||||
self.pin.pad_ctrl().modify(|w| {
|
||||
@ -589,6 +638,7 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
self.pin.sio_oe().value_set().write_value(self.bit())
|
||||
}
|
||||
|
||||
/// Set as output pin.
|
||||
#[inline]
|
||||
pub fn is_set_as_output(&mut self) -> bool {
|
||||
self.ref_is_set_as_output()
|
||||
@ -599,15 +649,18 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
(self.pin.sio_oe().value().read() & self.bit()) != 0
|
||||
}
|
||||
|
||||
/// Toggle output pin.
|
||||
#[inline]
|
||||
pub fn toggle_set_as_output(&mut self) {
|
||||
self.pin.sio_oe().value_xor().write_value(self.bit())
|
||||
}
|
||||
|
||||
/// Get whether the pin input level is high.
|
||||
#[inline]
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
!self.is_low()
|
||||
}
|
||||
/// Get whether the pin input level is low.
|
||||
|
||||
#[inline]
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
@ -675,31 +728,37 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
self.pin.sio_out().value_xor().write_value(self.bit())
|
||||
}
|
||||
|
||||
/// Wait until the pin is high. If it is already high, return immediately.
|
||||
#[inline]
|
||||
pub async fn wait_for_high(&mut self) {
|
||||
InputFuture::new(&mut self.pin, InterruptTrigger::LevelHigh).await;
|
||||
}
|
||||
|
||||
/// Wait until the pin is low. If it is already low, return immediately.
|
||||
#[inline]
|
||||
pub async fn wait_for_low(&mut self) {
|
||||
InputFuture::new(&mut self.pin, InterruptTrigger::LevelLow).await;
|
||||
}
|
||||
|
||||
/// Wait for the pin to undergo a transition from low to high.
|
||||
#[inline]
|
||||
pub async fn wait_for_rising_edge(&mut self) {
|
||||
InputFuture::new(&mut self.pin, InterruptTrigger::EdgeHigh).await;
|
||||
}
|
||||
|
||||
/// Wait for the pin to undergo a transition from high to low.
|
||||
#[inline]
|
||||
pub async fn wait_for_falling_edge(&mut self) {
|
||||
InputFuture::new(&mut self.pin, InterruptTrigger::EdgeLow).await;
|
||||
}
|
||||
|
||||
/// Wait for the pin to undergo any transition, i.e low to high OR high to low.
|
||||
#[inline]
|
||||
pub async fn wait_for_any_edge(&mut self) {
|
||||
InputFuture::new(&mut self.pin, InterruptTrigger::AnyEdge).await;
|
||||
}
|
||||
|
||||
/// Configure dormant wake.
|
||||
#[inline]
|
||||
pub fn dormant_wake(&mut self, cfg: DormantWakeConfig) -> DormantWake<T> {
|
||||
let idx = self.pin._pin() as usize;
|
||||
@ -737,6 +796,7 @@ impl<'d, T: Pin> Drop for Flex<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Dormant wake driver.
|
||||
pub struct DormantWake<'w, T: Pin> {
|
||||
pin: PeripheralRef<'w, T>,
|
||||
cfg: DormantWakeConfig,
|
||||
@ -818,6 +878,7 @@ pub(crate) mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interface for a Pin that can be configured by an [Input] or [Output] driver, or converted to an [AnyPin].
|
||||
pub trait Pin: Peripheral<P = Self> + Into<AnyPin> + sealed::Pin + Sized + 'static {
|
||||
/// Degrade to a generic pin struct
|
||||
fn degrade(self) -> AnyPin {
|
||||
@ -839,6 +900,7 @@ pub trait Pin: Peripheral<P = Self> + Into<AnyPin> + sealed::Pin + Sized + 'stat
|
||||
}
|
||||
}
|
||||
|
||||
/// Type-erased GPIO pin
|
||||
pub struct AnyPin {
|
||||
pin_bank: u8,
|
||||
}
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! I2C driver.
|
||||
use core::future;
|
||||
use core::marker::PhantomData;
|
||||
use core::task::Poll;
|
||||
@ -22,6 +23,7 @@ pub enum AbortReason {
|
||||
ArbitrationLoss,
|
||||
/// Transmit ended with data still in fifo
|
||||
TxNotEmpty(u16),
|
||||
/// Other reason.
|
||||
Other(u32),
|
||||
}
|
||||
|
||||
@ -41,9 +43,11 @@ pub enum Error {
|
||||
AddressReserved(u16),
|
||||
}
|
||||
|
||||
/// I2C config.
|
||||
#[non_exhaustive]
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct Config {
|
||||
/// Frequency.
|
||||
pub frequency: u32,
|
||||
}
|
||||
|
||||
@ -53,13 +57,16 @@ impl Default for Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// Size of I2C FIFO.
|
||||
pub const FIFO_SIZE: u8 = 16;
|
||||
|
||||
/// I2C driver.
|
||||
pub struct I2c<'d, T: Instance, M: Mode> {
|
||||
phantom: PhantomData<(&'d mut T, M)>,
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> I2c<'d, T, Blocking> {
|
||||
/// Create a new driver instance in blocking mode.
|
||||
pub fn new_blocking(
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
scl: impl Peripheral<P = impl SclPin<T>> + 'd,
|
||||
@ -72,6 +79,7 @@ impl<'d, T: Instance> I2c<'d, T, Blocking> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> I2c<'d, T, Async> {
|
||||
/// Create a new driver instance in async mode.
|
||||
pub fn new_async(
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
scl: impl Peripheral<P = impl SclPin<T>> + 'd,
|
||||
@ -292,16 +300,19 @@ impl<'d, T: Instance> I2c<'d, T, Async> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read from address into buffer using DMA.
|
||||
pub async fn read_async(&mut self, addr: u16, buffer: &mut [u8]) -> Result<(), Error> {
|
||||
Self::setup(addr)?;
|
||||
self.read_async_internal(buffer, true, true).await
|
||||
}
|
||||
|
||||
/// Write to address from buffer using DMA.
|
||||
pub async fn write_async(&mut self, addr: u16, bytes: impl IntoIterator<Item = u8>) -> Result<(), Error> {
|
||||
Self::setup(addr)?;
|
||||
self.write_async_internal(bytes, true).await
|
||||
}
|
||||
|
||||
/// Write to address from bytes and read from address into buffer using DMA.
|
||||
pub async fn write_read_async(
|
||||
&mut self,
|
||||
addr: u16,
|
||||
@ -314,6 +325,7 @@ impl<'d, T: Instance> I2c<'d, T, Async> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interrupt handler.
|
||||
pub struct InterruptHandler<T: Instance> {
|
||||
_uart: PhantomData<T>,
|
||||
}
|
||||
@ -569,17 +581,20 @@ impl<'d, T: Instance + 'd, M: Mode> I2c<'d, T, M> {
|
||||
// Blocking public API
|
||||
// =========================
|
||||
|
||||
/// Read from address into buffer blocking caller until done.
|
||||
pub fn blocking_read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Error> {
|
||||
Self::setup(address.into())?;
|
||||
self.read_blocking_internal(read, true, true)
|
||||
// Automatic Stop
|
||||
}
|
||||
|
||||
/// Write to address from buffer blocking caller until done.
|
||||
pub fn blocking_write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> {
|
||||
Self::setup(address.into())?;
|
||||
self.write_blocking_internal(write, true)
|
||||
}
|
||||
|
||||
/// Write to address from bytes and read from address into buffer blocking caller until done.
|
||||
pub fn blocking_write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> {
|
||||
Self::setup(address.into())?;
|
||||
self.write_blocking_internal(write, false)?;
|
||||
@ -742,6 +757,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if address is reserved.
|
||||
pub fn i2c_reserved_addr(addr: u16) -> bool {
|
||||
((addr & 0x78) == 0 || (addr & 0x78) == 0x78) && addr != 0
|
||||
}
|
||||
@ -768,6 +784,7 @@ mod sealed {
|
||||
pub trait SclPin<T: Instance> {}
|
||||
}
|
||||
|
||||
/// Driver mode.
|
||||
pub trait Mode: sealed::Mode {}
|
||||
|
||||
macro_rules! impl_mode {
|
||||
@ -777,12 +794,15 @@ macro_rules! impl_mode {
|
||||
};
|
||||
}
|
||||
|
||||
/// Blocking mode.
|
||||
pub struct Blocking;
|
||||
/// Async mode.
|
||||
pub struct Async;
|
||||
|
||||
impl_mode!(Blocking);
|
||||
impl_mode!(Async);
|
||||
|
||||
/// I2C instance.
|
||||
pub trait Instance: sealed::Instance {}
|
||||
|
||||
macro_rules! impl_instance {
|
||||
@ -819,7 +839,9 @@ macro_rules! impl_instance {
|
||||
impl_instance!(I2C0, I2C0_IRQ, set_i2c0, 32, 33);
|
||||
impl_instance!(I2C1, I2C1_IRQ, set_i2c1, 34, 35);
|
||||
|
||||
/// SDA pin.
|
||||
pub trait SdaPin<T: Instance>: sealed::SdaPin<T> + crate::gpio::Pin {}
|
||||
/// SCL pin.
|
||||
pub trait SclPin<T: Instance>: sealed::SclPin<T> + crate::gpio::Pin {}
|
||||
|
||||
macro_rules! impl_pin {
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! I2C slave driver.
|
||||
use core::future;
|
||||
use core::marker::PhantomData;
|
||||
use core::task::Poll;
|
||||
@ -63,11 +64,13 @@ impl Default for Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// I2CSlave driver.
|
||||
pub struct I2cSlave<'d, T: Instance> {
|
||||
phantom: PhantomData<&'d mut T>,
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> I2cSlave<'d, T> {
|
||||
/// Create a new instance.
|
||||
pub fn new(
|
||||
_peri: impl Peripheral<P = T> + 'd,
|
||||
scl: impl Peripheral<P = impl SclPin<T>> + 'd,
|
||||
|
@ -1,5 +1,7 @@
|
||||
#![no_std]
|
||||
#![allow(async_fn_in_trait)]
|
||||
#![doc = include_str!("../README.md")]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
// This mod MUST go first, so that the others see its macros.
|
||||
pub(crate) mod fmt;
|
||||
@ -31,9 +33,7 @@ pub mod usb;
|
||||
pub mod watchdog;
|
||||
|
||||
// PIO
|
||||
// TODO: move `pio_instr_util` and `relocate` to inside `pio`
|
||||
pub mod pio;
|
||||
pub mod pio_instr_util;
|
||||
pub(crate) mod relocate;
|
||||
|
||||
// Reexports
|
||||
@ -302,11 +302,14 @@ fn install_stack_guard(stack_bottom: *mut usize) -> Result<(), ()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// HAL configuration for RP.
|
||||
pub mod config {
|
||||
use crate::clocks::ClockConfig;
|
||||
|
||||
/// HAL configuration passed when initializing.
|
||||
#[non_exhaustive]
|
||||
pub struct Config {
|
||||
/// Clock configuration.
|
||||
pub clocks: ClockConfig,
|
||||
}
|
||||
|
||||
@ -319,12 +322,18 @@ pub mod config {
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Create a new configuration with the provided clock config.
|
||||
pub fn new(clocks: ClockConfig) -> Self {
|
||||
Self { clocks }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Initialize the `embassy-rp` HAL with the provided configuration.
|
||||
///
|
||||
/// This returns the peripheral singletons that can be used for creating drivers.
|
||||
///
|
||||
/// This should only be called once at startup, otherwise it panics.
|
||||
pub fn init(config: config::Config) -> Peripherals {
|
||||
// Do this first, so that it panics if user is calling `init` a second time
|
||||
// before doing anything important.
|
||||
|
@ -1,7 +1,9 @@
|
||||
//! Instructions controlling the PIO.
|
||||
use pio::{InSource, InstructionOperands, JmpCondition, OutDestination, SetDestination};
|
||||
|
||||
use crate::pio::{Instance, StateMachine};
|
||||
|
||||
/// Set value of scratch register X.
|
||||
pub unsafe fn set_x<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, SM>, value: u32) {
|
||||
const OUT: u16 = InstructionOperands::OUT {
|
||||
destination: OutDestination::X,
|
||||
@ -12,6 +14,7 @@ pub unsafe fn set_x<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, S
|
||||
sm.exec_instr(OUT);
|
||||
}
|
||||
|
||||
/// Get value of scratch register X.
|
||||
pub unsafe fn get_x<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, SM>) -> u32 {
|
||||
const IN: u16 = InstructionOperands::IN {
|
||||
source: InSource::X,
|
||||
@ -22,6 +25,7 @@ pub unsafe fn get_x<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, S
|
||||
sm.rx().pull()
|
||||
}
|
||||
|
||||
/// Set value of scratch register Y.
|
||||
pub unsafe fn set_y<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, SM>, value: u32) {
|
||||
const OUT: u16 = InstructionOperands::OUT {
|
||||
destination: OutDestination::Y,
|
||||
@ -32,6 +36,7 @@ pub unsafe fn set_y<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, S
|
||||
sm.exec_instr(OUT);
|
||||
}
|
||||
|
||||
/// Get value of scratch register Y.
|
||||
pub unsafe fn get_y<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, SM>) -> u32 {
|
||||
const IN: u16 = InstructionOperands::IN {
|
||||
source: InSource::Y,
|
||||
@ -43,6 +48,7 @@ pub unsafe fn get_y<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, S
|
||||
sm.rx().pull()
|
||||
}
|
||||
|
||||
/// Set instruction for pindir destination.
|
||||
pub unsafe fn set_pindir<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, SM>, data: u8) {
|
||||
let set: u16 = InstructionOperands::SET {
|
||||
destination: SetDestination::PINDIRS,
|
||||
@ -52,6 +58,7 @@ pub unsafe fn set_pindir<PIO: Instance, const SM: usize>(sm: &mut StateMachine<P
|
||||
sm.exec_instr(set);
|
||||
}
|
||||
|
||||
/// Set instruction for pin destination.
|
||||
pub unsafe fn set_pin<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, SM>, data: u8) {
|
||||
let set: u16 = InstructionOperands::SET {
|
||||
destination: SetDestination::PINS,
|
||||
@ -61,6 +68,7 @@ pub unsafe fn set_pin<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO,
|
||||
sm.exec_instr(set);
|
||||
}
|
||||
|
||||
/// Out instruction for pin destination.
|
||||
pub unsafe fn set_out_pin<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, SM>, data: u32) {
|
||||
const OUT: u16 = InstructionOperands::OUT {
|
||||
destination: OutDestination::PINS,
|
||||
@ -70,6 +78,8 @@ pub unsafe fn set_out_pin<PIO: Instance, const SM: usize>(sm: &mut StateMachine<
|
||||
sm.tx().push(data);
|
||||
sm.exec_instr(OUT);
|
||||
}
|
||||
|
||||
/// Out instruction for pindir destination.
|
||||
pub unsafe fn set_out_pindir<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, SM>, data: u32) {
|
||||
const OUT: u16 = InstructionOperands::OUT {
|
||||
destination: OutDestination::PINDIRS,
|
||||
@ -80,6 +90,7 @@ pub unsafe fn set_out_pindir<PIO: Instance, const SM: usize>(sm: &mut StateMachi
|
||||
sm.exec_instr(OUT);
|
||||
}
|
||||
|
||||
/// Jump instruction to address.
|
||||
pub unsafe fn exec_jmp<PIO: Instance, const SM: usize>(sm: &mut StateMachine<PIO, SM>, to_addr: u8) {
|
||||
let jmp: u16 = InstructionOperands::JMP {
|
||||
address: to_addr,
|
@ -1,3 +1,4 @@
|
||||
//! PIO driver.
|
||||
use core::future::Future;
|
||||
use core::marker::PhantomData;
|
||||
use core::pin::Pin as FuturePin;
|
||||
@ -19,8 +20,11 @@ use crate::gpio::{self, AnyPin, Drive, Level, Pull, SlewRate};
|
||||
use crate::interrupt::typelevel::{Binding, Handler, Interrupt};
|
||||
use crate::pac::dma::vals::TreqSel;
|
||||
use crate::relocate::RelocatedProgram;
|
||||
use crate::{pac, peripherals, pio_instr_util, RegExt};
|
||||
use crate::{pac, peripherals, RegExt};
|
||||
|
||||
pub mod instr;
|
||||
|
||||
/// Wakers for interrupts and FIFOs.
|
||||
pub struct Wakers([AtomicWaker; 12]);
|
||||
|
||||
impl Wakers {
|
||||
@ -38,6 +42,7 @@ impl Wakers {
|
||||
}
|
||||
}
|
||||
|
||||
/// FIFO config.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
@ -51,6 +56,8 @@ pub enum FifoJoin {
|
||||
TxOnly,
|
||||
}
|
||||
|
||||
/// Shift direction.
|
||||
#[allow(missing_docs)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
@ -60,6 +67,8 @@ pub enum ShiftDirection {
|
||||
Left = 0,
|
||||
}
|
||||
|
||||
/// Pin direction.
|
||||
#[allow(missing_docs)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
@ -68,12 +77,15 @@ pub enum Direction {
|
||||
Out = 1,
|
||||
}
|
||||
|
||||
/// Which fifo level to use in status check.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[repr(u8)]
|
||||
pub enum StatusSource {
|
||||
#[default]
|
||||
/// All-ones if TX FIFO level < N, otherwise all-zeroes.
|
||||
TxFifoLevel = 0,
|
||||
/// All-ones if RX FIFO level < N, otherwise all-zeroes.
|
||||
RxFifoLevel = 1,
|
||||
}
|
||||
|
||||
@ -81,6 +93,7 @@ const RXNEMPTY_MASK: u32 = 1 << 0;
|
||||
const TXNFULL_MASK: u32 = 1 << 4;
|
||||
const SMIRQ_MASK: u32 = 1 << 8;
|
||||
|
||||
/// Interrupt handler for PIO.
|
||||
pub struct InterruptHandler<PIO: Instance> {
|
||||
_pio: PhantomData<PIO>,
|
||||
}
|
||||
@ -105,6 +118,7 @@ pub struct FifoOutFuture<'a, 'd, PIO: Instance, const SM: usize> {
|
||||
}
|
||||
|
||||
impl<'a, 'd, PIO: Instance, const SM: usize> FifoOutFuture<'a, 'd, PIO, SM> {
|
||||
/// Create a new future waiting for TX-FIFO to become writable.
|
||||
pub fn new(sm: &'a mut StateMachineTx<'d, PIO, SM>, value: u32) -> Self {
|
||||
FifoOutFuture { sm_tx: sm, value }
|
||||
}
|
||||
@ -136,13 +150,14 @@ impl<'a, 'd, PIO: Instance, const SM: usize> Drop for FifoOutFuture<'a, 'd, PIO,
|
||||
}
|
||||
}
|
||||
|
||||
/// Future that waits for RX-FIFO to become readable
|
||||
/// Future that waits for RX-FIFO to become readable.
|
||||
#[must_use = "futures do nothing unless you `.await` or poll them"]
|
||||
pub struct FifoInFuture<'a, 'd, PIO: Instance, const SM: usize> {
|
||||
sm_rx: &'a mut StateMachineRx<'d, PIO, SM>,
|
||||
}
|
||||
|
||||
impl<'a, 'd, PIO: Instance, const SM: usize> FifoInFuture<'a, 'd, PIO, SM> {
|
||||
/// Create future that waits for RX-FIFO to become readable.
|
||||
pub fn new(sm: &'a mut StateMachineRx<'d, PIO, SM>) -> Self {
|
||||
FifoInFuture { sm_rx: sm }
|
||||
}
|
||||
@ -207,6 +222,7 @@ impl<'a, 'd, PIO: Instance> Drop for IrqFuture<'a, 'd, PIO> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Type representing a PIO pin.
|
||||
pub struct Pin<'l, PIO: Instance> {
|
||||
pin: PeripheralRef<'l, AnyPin>,
|
||||
pio: PhantomData<PIO>,
|
||||
@ -226,7 +242,7 @@ impl<'l, PIO: Instance> Pin<'l, PIO> {
|
||||
});
|
||||
}
|
||||
|
||||
// Set the pin's slew rate.
|
||||
/// Set the pin's slew rate.
|
||||
#[inline]
|
||||
pub fn set_slew_rate(&mut self, slew_rate: SlewRate) {
|
||||
self.pin.pad_ctrl().modify(|w| {
|
||||
@ -251,6 +267,7 @@ impl<'l, PIO: Instance> Pin<'l, PIO> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Set the pin's input sync bypass.
|
||||
pub fn set_input_sync_bypass<'a>(&mut self, bypass: bool) {
|
||||
let mask = 1 << self.pin();
|
||||
if bypass {
|
||||
@ -260,28 +277,34 @@ impl<'l, PIO: Instance> Pin<'l, PIO> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the underlying pin number.
|
||||
pub fn pin(&self) -> u8 {
|
||||
self.pin._pin()
|
||||
}
|
||||
}
|
||||
|
||||
/// Type representing a state machine RX FIFO.
|
||||
pub struct StateMachineRx<'d, PIO: Instance, const SM: usize> {
|
||||
pio: PhantomData<&'d mut PIO>,
|
||||
}
|
||||
|
||||
impl<'d, PIO: Instance, const SM: usize> StateMachineRx<'d, PIO, SM> {
|
||||
/// Check if RX FIFO is empty.
|
||||
pub fn empty(&self) -> bool {
|
||||
PIO::PIO.fstat().read().rxempty() & (1u8 << SM) != 0
|
||||
}
|
||||
|
||||
/// Check if RX FIFO is full.
|
||||
pub fn full(&self) -> bool {
|
||||
PIO::PIO.fstat().read().rxfull() & (1u8 << SM) != 0
|
||||
}
|
||||
|
||||
/// Check RX FIFO level.
|
||||
pub fn level(&self) -> u8 {
|
||||
(PIO::PIO.flevel().read().0 >> (SM * 8 + 4)) as u8 & 0x0f
|
||||
}
|
||||
|
||||
/// Check if state machine has stalled on full RX FIFO.
|
||||
pub fn stalled(&self) -> bool {
|
||||
let fdebug = PIO::PIO.fdebug();
|
||||
let ret = fdebug.read().rxstall() & (1 << SM) != 0;
|
||||
@ -291,6 +314,7 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineRx<'d, PIO, SM> {
|
||||
ret
|
||||
}
|
||||
|
||||
/// Check if RX FIFO underflow (i.e. read-on-empty by the system) has occurred.
|
||||
pub fn underflowed(&self) -> bool {
|
||||
let fdebug = PIO::PIO.fdebug();
|
||||
let ret = fdebug.read().rxunder() & (1 << SM) != 0;
|
||||
@ -300,10 +324,12 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineRx<'d, PIO, SM> {
|
||||
ret
|
||||
}
|
||||
|
||||
/// Pull data from RX FIFO.
|
||||
pub fn pull(&mut self) -> u32 {
|
||||
PIO::PIO.rxf(SM).read()
|
||||
}
|
||||
|
||||
/// Attempt pulling data from RX FIFO.
|
||||
pub fn try_pull(&mut self) -> Option<u32> {
|
||||
if self.empty() {
|
||||
return None;
|
||||
@ -311,10 +337,12 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineRx<'d, PIO, SM> {
|
||||
Some(self.pull())
|
||||
}
|
||||
|
||||
/// Wait for RX FIFO readable.
|
||||
pub fn wait_pull<'a>(&'a mut self) -> FifoInFuture<'a, 'd, PIO, SM> {
|
||||
FifoInFuture::new(self)
|
||||
}
|
||||
|
||||
/// Prepare DMA transfer from RX FIFO.
|
||||
pub fn dma_pull<'a, C: Channel, W: Word>(
|
||||
&'a mut self,
|
||||
ch: PeripheralRef<'a, C>,
|
||||
@ -340,22 +368,28 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineRx<'d, PIO, SM> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Type representing a state machine TX FIFO.
|
||||
pub struct StateMachineTx<'d, PIO: Instance, const SM: usize> {
|
||||
pio: PhantomData<&'d mut PIO>,
|
||||
}
|
||||
|
||||
impl<'d, PIO: Instance, const SM: usize> StateMachineTx<'d, PIO, SM> {
|
||||
/// Check if TX FIFO is empty.
|
||||
pub fn empty(&self) -> bool {
|
||||
PIO::PIO.fstat().read().txempty() & (1u8 << SM) != 0
|
||||
}
|
||||
|
||||
/// Check if TX FIFO is full.
|
||||
pub fn full(&self) -> bool {
|
||||
PIO::PIO.fstat().read().txfull() & (1u8 << SM) != 0
|
||||
}
|
||||
|
||||
/// Check TX FIFO level.
|
||||
pub fn level(&self) -> u8 {
|
||||
(PIO::PIO.flevel().read().0 >> (SM * 8)) as u8 & 0x0f
|
||||
}
|
||||
|
||||
/// Check state machine has stalled on empty TX FIFO.
|
||||
pub fn stalled(&self) -> bool {
|
||||
let fdebug = PIO::PIO.fdebug();
|
||||
let ret = fdebug.read().txstall() & (1 << SM) != 0;
|
||||
@ -365,6 +399,7 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineTx<'d, PIO, SM> {
|
||||
ret
|
||||
}
|
||||
|
||||
/// Check if FIFO overflowed.
|
||||
pub fn overflowed(&self) -> bool {
|
||||
let fdebug = PIO::PIO.fdebug();
|
||||
let ret = fdebug.read().txover() & (1 << SM) != 0;
|
||||
@ -374,10 +409,12 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineTx<'d, PIO, SM> {
|
||||
ret
|
||||
}
|
||||
|
||||
/// Force push data to TX FIFO.
|
||||
pub fn push(&mut self, v: u32) {
|
||||
PIO::PIO.txf(SM).write_value(v);
|
||||
}
|
||||
|
||||
/// Attempt to push data to TX FIFO.
|
||||
pub fn try_push(&mut self, v: u32) -> bool {
|
||||
if self.full() {
|
||||
return false;
|
||||
@ -386,10 +423,12 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineTx<'d, PIO, SM> {
|
||||
true
|
||||
}
|
||||
|
||||
/// Wait until FIFO is ready for writing.
|
||||
pub fn wait_push<'a>(&'a mut self, value: u32) -> FifoOutFuture<'a, 'd, PIO, SM> {
|
||||
FifoOutFuture::new(self, value)
|
||||
}
|
||||
|
||||
/// Prepare a DMA transfer to TX FIFO.
|
||||
pub fn dma_push<'a, C: Channel, W: Word>(&'a mut self, ch: PeripheralRef<'a, C>, data: &'a [W]) -> Transfer<'a, C> {
|
||||
let pio_no = PIO::PIO_NO;
|
||||
let p = ch.regs();
|
||||
@ -411,6 +450,7 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineTx<'d, PIO, SM> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type representing a single PIO state machine.
|
||||
pub struct StateMachine<'d, PIO: Instance, const SM: usize> {
|
||||
rx: StateMachineRx<'d, PIO, SM>,
|
||||
tx: StateMachineTx<'d, PIO, SM>,
|
||||
@ -430,52 +470,78 @@ fn assert_consecutive<'d, PIO: Instance>(pins: &[&Pin<'d, PIO>]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// PIO Execution config.
|
||||
#[derive(Clone, Copy, Default, Debug)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[non_exhaustive]
|
||||
pub struct ExecConfig {
|
||||
/// If true, the MSB of the Delay/Side-set instruction field is used as side-set enable, rather than a side-set data bit.
|
||||
pub side_en: bool,
|
||||
/// If true, side-set data is asserted to pin directions, instead of pin values.
|
||||
pub side_pindir: bool,
|
||||
/// Pin to trigger jump.
|
||||
pub jmp_pin: u8,
|
||||
/// After reaching this address, execution is wrapped to wrap_bottom.
|
||||
pub wrap_top: u8,
|
||||
/// After reaching wrap_top, execution is wrapped to this address.
|
||||
pub wrap_bottom: u8,
|
||||
}
|
||||
|
||||
/// PIO shift register config for input or output.
|
||||
#[derive(Clone, Copy, Default, Debug)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct ShiftConfig {
|
||||
/// Number of bits shifted out of OSR before autopull.
|
||||
pub threshold: u8,
|
||||
/// Shift direction.
|
||||
pub direction: ShiftDirection,
|
||||
/// For output: Pull automatically output shift register is emptied.
|
||||
/// For input: Push automatically when the input shift register is filled.
|
||||
pub auto_fill: bool,
|
||||
}
|
||||
|
||||
/// PIO pin config.
|
||||
#[derive(Clone, Copy, Default, Debug)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub struct PinConfig {
|
||||
/// The number of MSBs of the Delay/Side-set instruction field which are used for side-set.
|
||||
pub sideset_count: u8,
|
||||
/// The number of pins asserted by a SET. In the range 0 to 5 inclusive.
|
||||
pub set_count: u8,
|
||||
/// The number of pins asserted by an OUT PINS, OUT PINDIRS or MOV PINS instruction. In the range 0 to 32 inclusive.
|
||||
pub out_count: u8,
|
||||
/// The pin which is mapped to the least-significant bit of a state machine's IN data bus.
|
||||
pub in_base: u8,
|
||||
/// The lowest-numbered pin that will be affected by a side-set operation.
|
||||
pub sideset_base: u8,
|
||||
/// The lowest-numbered pin that will be affected by a SET PINS or SET PINDIRS instruction.
|
||||
pub set_base: u8,
|
||||
/// The lowest-numbered pin that will be affected by an OUT PINS, OUT PINDIRS or MOV PINS instruction.
|
||||
pub out_base: u8,
|
||||
}
|
||||
|
||||
/// PIO config.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Config<'d, PIO: Instance> {
|
||||
// CLKDIV
|
||||
/// Clock divisor register for state machines.
|
||||
pub clock_divider: FixedU32<U8>,
|
||||
// EXECCTRL
|
||||
/// Which data bit to use for inline OUT enable.
|
||||
pub out_en_sel: u8,
|
||||
/// Use a bit of OUT data as an auxiliary write enable When used in conjunction with OUT_STICKY.
|
||||
pub inline_out_en: bool,
|
||||
/// Continuously assert the most recent OUT/SET to the pins.
|
||||
pub out_sticky: bool,
|
||||
/// Which source to use for checking status.
|
||||
pub status_sel: StatusSource,
|
||||
/// Status comparison level.
|
||||
pub status_n: u8,
|
||||
exec: ExecConfig,
|
||||
origin: Option<u8>,
|
||||
// SHIFTCTRL
|
||||
/// Configure FIFO allocation.
|
||||
pub fifo_join: FifoJoin,
|
||||
/// Input shifting config.
|
||||
pub shift_in: ShiftConfig,
|
||||
/// Output shifting config.
|
||||
pub shift_out: ShiftConfig,
|
||||
// PINCTRL
|
||||
pins: PinConfig,
|
||||
@ -505,16 +571,22 @@ impl<'d, PIO: Instance> Default for Config<'d, PIO> {
|
||||
}
|
||||
|
||||
impl<'d, PIO: Instance> Config<'d, PIO> {
|
||||
/// Get execution configuration.
|
||||
pub fn get_exec(&self) -> ExecConfig {
|
||||
self.exec
|
||||
}
|
||||
|
||||
/// Update execution configuration.
|
||||
pub unsafe fn set_exec(&mut self, e: ExecConfig) {
|
||||
self.exec = e;
|
||||
}
|
||||
|
||||
/// Get pin configuration.
|
||||
pub fn get_pins(&self) -> PinConfig {
|
||||
self.pins
|
||||
}
|
||||
|
||||
/// Update pin configuration.
|
||||
pub unsafe fn set_pins(&mut self, p: PinConfig) {
|
||||
self.pins = p;
|
||||
}
|
||||
@ -537,6 +609,7 @@ impl<'d, PIO: Instance> Config<'d, PIO> {
|
||||
self.origin = Some(prog.origin);
|
||||
}
|
||||
|
||||
/// Set pin used to signal jump.
|
||||
pub fn set_jmp_pin(&mut self, pin: &Pin<'d, PIO>) {
|
||||
self.exec.jmp_pin = pin.pin();
|
||||
}
|
||||
@ -571,6 +644,7 @@ impl<'d, PIO: Instance> Config<'d, PIO> {
|
||||
}
|
||||
|
||||
impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> {
|
||||
/// Set the config for a given PIO state machine.
|
||||
pub fn set_config(&mut self, config: &Config<'d, PIO>) {
|
||||
// sm expects 0 for 65536, truncation makes that happen
|
||||
assert!(config.clock_divider <= 65536, "clkdiv must be <= 65536");
|
||||
@ -617,7 +691,7 @@ impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> {
|
||||
w.set_out_base(config.pins.out_base);
|
||||
});
|
||||
if let Some(origin) = config.origin {
|
||||
unsafe { pio_instr_util::exec_jmp(self, origin) }
|
||||
unsafe { instr::exec_jmp(self, origin) }
|
||||
}
|
||||
}
|
||||
|
||||
@ -626,10 +700,13 @@ impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> {
|
||||
PIO::PIO.sm(SM)
|
||||
}
|
||||
|
||||
/// Restart this state machine.
|
||||
pub fn restart(&mut self) {
|
||||
let mask = 1u8 << SM;
|
||||
PIO::PIO.ctrl().write_set(|w| w.set_sm_restart(mask));
|
||||
}
|
||||
|
||||
/// Enable state machine.
|
||||
pub fn set_enable(&mut self, enable: bool) {
|
||||
let mask = 1u8 << SM;
|
||||
if enable {
|
||||
@ -639,10 +716,12 @@ impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if state machine is enabled.
|
||||
pub fn is_enabled(&self) -> bool {
|
||||
PIO::PIO.ctrl().read().sm_enable() & (1u8 << SM) != 0
|
||||
}
|
||||
|
||||
/// Restart a state machine's clock divider from an initial phase of 0.
|
||||
pub fn clkdiv_restart(&mut self) {
|
||||
let mask = 1u8 << SM;
|
||||
PIO::PIO.ctrl().write_set(|w| w.set_clkdiv_restart(mask));
|
||||
@ -690,6 +769,7 @@ impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Flush FIFOs for state machine.
|
||||
pub fn clear_fifos(&mut self) {
|
||||
// Toggle FJOIN_RX to flush FIFOs
|
||||
let shiftctrl = Self::this_sm().shiftctrl();
|
||||
@ -701,21 +781,31 @@ impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Instruct state machine to execute a given instructions
|
||||
///
|
||||
/// SAFETY: The state machine must be in a state where executing
|
||||
/// an arbitrary instruction does not crash it.
|
||||
pub unsafe fn exec_instr(&mut self, instr: u16) {
|
||||
Self::this_sm().instr().write(|w| w.set_instr(instr));
|
||||
}
|
||||
|
||||
/// Return a read handle for reading state machine outputs.
|
||||
pub fn rx(&mut self) -> &mut StateMachineRx<'d, PIO, SM> {
|
||||
&mut self.rx
|
||||
}
|
||||
|
||||
/// Return a handle for writing to inputs.
|
||||
pub fn tx(&mut self) -> &mut StateMachineTx<'d, PIO, SM> {
|
||||
&mut self.tx
|
||||
}
|
||||
|
||||
/// Return both read and write handles for the state machine.
|
||||
pub fn rx_tx(&mut self) -> (&mut StateMachineRx<'d, PIO, SM>, &mut StateMachineTx<'d, PIO, SM>) {
|
||||
(&mut self.rx, &mut self.tx)
|
||||
}
|
||||
}
|
||||
|
||||
/// PIO handle.
|
||||
pub struct Common<'d, PIO: Instance> {
|
||||
instructions_used: u32,
|
||||
pio: PhantomData<&'d mut PIO>,
|
||||
@ -727,18 +817,25 @@ impl<'d, PIO: Instance> Drop for Common<'d, PIO> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Memory of PIO instance.
|
||||
pub struct InstanceMemory<'d, PIO: Instance> {
|
||||
used_mask: u32,
|
||||
pio: PhantomData<&'d mut PIO>,
|
||||
}
|
||||
|
||||
/// A loaded PIO program.
|
||||
pub struct LoadedProgram<'d, PIO: Instance> {
|
||||
/// Memory used by program.
|
||||
pub used_memory: InstanceMemory<'d, PIO>,
|
||||
/// Program origin for loading.
|
||||
pub origin: u8,
|
||||
/// Wrap controls what to do once program is done executing.
|
||||
pub wrap: Wrap,
|
||||
/// Data for 'side' set instruction parameters.
|
||||
pub side_set: SideSet,
|
||||
}
|
||||
|
||||
/// Errors loading a PIO program.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum LoadError {
|
||||
@ -834,6 +931,7 @@ impl<'d, PIO: Instance> Common<'d, PIO> {
|
||||
self.instructions_used &= !instrs.used_mask;
|
||||
}
|
||||
|
||||
/// Bypass flipflop synchronizer on GPIO inputs.
|
||||
pub fn set_input_sync_bypass<'a>(&'a mut self, bypass: u32, mask: u32) {
|
||||
// this can interfere with per-pin bypass functions. splitting the
|
||||
// modification is going to be fine since nothing that relies on
|
||||
@ -842,6 +940,7 @@ impl<'d, PIO: Instance> Common<'d, PIO> {
|
||||
PIO::PIO.input_sync_bypass().write_clear(|w| *w = mask & !bypass);
|
||||
}
|
||||
|
||||
/// Get bypass configuration.
|
||||
pub fn get_input_sync_bypass(&self) -> u32 {
|
||||
PIO::PIO.input_sync_bypass().read()
|
||||
}
|
||||
@ -861,6 +960,7 @@ impl<'d, PIO: Instance> Common<'d, PIO> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply changes to all state machines in a batch.
|
||||
pub fn apply_sm_batch(&mut self, f: impl FnOnce(&mut PioBatch<'d, PIO>)) {
|
||||
let mut batch = PioBatch {
|
||||
clkdiv_restart: 0,
|
||||
@ -878,6 +978,7 @@ impl<'d, PIO: Instance> Common<'d, PIO> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents multiple state machines in a single type.
|
||||
pub struct PioBatch<'a, PIO: Instance> {
|
||||
clkdiv_restart: u8,
|
||||
sm_restart: u8,
|
||||
@ -887,25 +988,25 @@ pub struct PioBatch<'a, PIO: Instance> {
|
||||
}
|
||||
|
||||
impl<'a, PIO: Instance> PioBatch<'a, PIO> {
|
||||
pub fn restart_clockdiv<const SM: usize>(&mut self, _sm: &mut StateMachine<'a, PIO, SM>) {
|
||||
self.clkdiv_restart |= 1 << SM;
|
||||
}
|
||||
|
||||
/// Restart a state machine's clock divider from an initial phase of 0.
|
||||
pub fn restart<const SM: usize>(&mut self, _sm: &mut StateMachine<'a, PIO, SM>) {
|
||||
self.clkdiv_restart |= 1 << SM;
|
||||
}
|
||||
|
||||
/// Enable a specific state machine.
|
||||
pub fn set_enable<const SM: usize>(&mut self, _sm: &mut StateMachine<'a, PIO, SM>, enable: bool) {
|
||||
self.sm_enable_mask |= 1 << SM;
|
||||
self.sm_enable |= (enable as u8) << SM;
|
||||
}
|
||||
}
|
||||
|
||||
/// Type representing a PIO interrupt.
|
||||
pub struct Irq<'d, PIO: Instance, const N: usize> {
|
||||
pio: PhantomData<&'d mut PIO>,
|
||||
}
|
||||
|
||||
impl<'d, PIO: Instance, const N: usize> Irq<'d, PIO, N> {
|
||||
/// Wait for an IRQ to fire.
|
||||
pub fn wait<'a>(&'a mut self) -> IrqFuture<'a, 'd, PIO> {
|
||||
IrqFuture {
|
||||
pio: PhantomData,
|
||||
@ -914,59 +1015,79 @@ impl<'d, PIO: Instance, const N: usize> Irq<'d, PIO, N> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interrupt flags for a PIO instance.
|
||||
#[derive(Clone)]
|
||||
pub struct IrqFlags<'d, PIO: Instance> {
|
||||
pio: PhantomData<&'d mut PIO>,
|
||||
}
|
||||
|
||||
impl<'d, PIO: Instance> IrqFlags<'d, PIO> {
|
||||
/// Check if interrupt fired.
|
||||
pub fn check(&self, irq_no: u8) -> bool {
|
||||
assert!(irq_no < 8);
|
||||
self.check_any(1 << irq_no)
|
||||
}
|
||||
|
||||
/// Check if any of the interrupts in the bitmap fired.
|
||||
pub fn check_any(&self, irqs: u8) -> bool {
|
||||
PIO::PIO.irq().read().irq() & irqs != 0
|
||||
}
|
||||
|
||||
/// Check if all interrupts have fired.
|
||||
pub fn check_all(&self, irqs: u8) -> bool {
|
||||
PIO::PIO.irq().read().irq() & irqs == irqs
|
||||
}
|
||||
|
||||
/// Clear interrupt for interrupt number.
|
||||
pub fn clear(&self, irq_no: usize) {
|
||||
assert!(irq_no < 8);
|
||||
self.clear_all(1 << irq_no);
|
||||
}
|
||||
|
||||
/// Clear all interrupts set in the bitmap.
|
||||
pub fn clear_all(&self, irqs: u8) {
|
||||
PIO::PIO.irq().write(|w| w.set_irq(irqs))
|
||||
}
|
||||
|
||||
/// Fire a given interrupt.
|
||||
pub fn set(&self, irq_no: usize) {
|
||||
assert!(irq_no < 8);
|
||||
self.set_all(1 << irq_no);
|
||||
}
|
||||
|
||||
/// Fire all interrupts.
|
||||
pub fn set_all(&self, irqs: u8) {
|
||||
PIO::PIO.irq_force().write(|w| w.set_irq_force(irqs))
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance of the PIO driver.
|
||||
pub struct Pio<'d, PIO: Instance> {
|
||||
/// PIO handle.
|
||||
pub common: Common<'d, PIO>,
|
||||
/// PIO IRQ flags.
|
||||
pub irq_flags: IrqFlags<'d, PIO>,
|
||||
/// IRQ0 configuration.
|
||||
pub irq0: Irq<'d, PIO, 0>,
|
||||
/// IRQ1 configuration.
|
||||
pub irq1: Irq<'d, PIO, 1>,
|
||||
/// IRQ2 configuration.
|
||||
pub irq2: Irq<'d, PIO, 2>,
|
||||
/// IRQ3 configuration.
|
||||
pub irq3: Irq<'d, PIO, 3>,
|
||||
/// State machine 0 handle.
|
||||
pub sm0: StateMachine<'d, PIO, 0>,
|
||||
/// State machine 1 handle.
|
||||
pub sm1: StateMachine<'d, PIO, 1>,
|
||||
/// State machine 2 handle.
|
||||
pub sm2: StateMachine<'d, PIO, 2>,
|
||||
/// State machine 3 handle.
|
||||
pub sm3: StateMachine<'d, PIO, 3>,
|
||||
_pio: PhantomData<&'d mut PIO>,
|
||||
}
|
||||
|
||||
impl<'d, PIO: Instance> Pio<'d, PIO> {
|
||||
/// Create a new instance of a PIO peripheral.
|
||||
pub fn new(_pio: impl Peripheral<P = PIO> + 'd, _irq: impl Binding<PIO::Interrupt, InterruptHandler<PIO>>) -> Self {
|
||||
PIO::state().users.store(5, Ordering::Release);
|
||||
PIO::state().used_pins.store(0, Ordering::Release);
|
||||
@ -1003,9 +1124,10 @@ impl<'d, PIO: Instance> Pio<'d, PIO> {
|
||||
}
|
||||
}
|
||||
|
||||
// we need to keep a record of which pins are assigned to each PIO. make_pio_pin
|
||||
// notionally takes ownership of the pin it is given, but the wrapped pin cannot
|
||||
// be treated as an owned resource since dropping it would have to deconfigure
|
||||
/// Representation of the PIO state keeping a record of which pins are assigned to
|
||||
/// each PIO.
|
||||
// make_pio_pin notionally takes ownership of the pin it is given, but the wrapped pin
|
||||
// cannot be treated as an owned resource since dropping it would have to deconfigure
|
||||
// the pin, breaking running state machines in the process. pins are also shared
|
||||
// between all state machines, which makes ownership even messier to track any
|
||||
// other way.
|
||||
@ -1059,6 +1181,7 @@ mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// PIO instance.
|
||||
pub trait Instance: sealed::Instance + Sized + Unpin {}
|
||||
|
||||
macro_rules! impl_pio {
|
||||
@ -1076,6 +1199,7 @@ macro_rules! impl_pio {
|
||||
impl_pio!(PIO0, 0, PIO0, PIO0_0, PIO0_IRQ_0);
|
||||
impl_pio!(PIO1, 1, PIO1, PIO1_0, PIO1_IRQ_0);
|
||||
|
||||
/// PIO pin.
|
||||
pub trait PioPin: sealed::PioPin + gpio::Pin {}
|
||||
|
||||
macro_rules! impl_pio_pin {
|
@ -61,9 +61,13 @@ impl Default for Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// PWM input mode.
|
||||
pub enum InputMode {
|
||||
/// Level mode.
|
||||
Level,
|
||||
/// Rising edge mode.
|
||||
RisingEdge,
|
||||
/// Falling edge mode.
|
||||
FallingEdge,
|
||||
}
|
||||
|
||||
@ -77,6 +81,7 @@ impl From<InputMode> for Divmode {
|
||||
}
|
||||
}
|
||||
|
||||
/// PWM driver.
|
||||
pub struct Pwm<'d, T: Channel> {
|
||||
inner: PeripheralRef<'d, T>,
|
||||
pin_a: Option<PeripheralRef<'d, AnyPin>>,
|
||||
@ -114,11 +119,13 @@ impl<'d, T: Channel> Pwm<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create PWM driver without any configured pins.
|
||||
#[inline]
|
||||
pub fn new_free(inner: impl Peripheral<P = T> + 'd, config: Config) -> Self {
|
||||
Self::new_inner(inner, None, None, config, Divmode::DIV)
|
||||
}
|
||||
|
||||
/// Create PWM driver with a single 'a' as output.
|
||||
#[inline]
|
||||
pub fn new_output_a(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
@ -129,6 +136,7 @@ impl<'d, T: Channel> Pwm<'d, T> {
|
||||
Self::new_inner(inner, Some(a.map_into()), None, config, Divmode::DIV)
|
||||
}
|
||||
|
||||
/// Create PWM driver with a single 'b' pin as output.
|
||||
#[inline]
|
||||
pub fn new_output_b(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
@ -139,6 +147,7 @@ impl<'d, T: Channel> Pwm<'d, T> {
|
||||
Self::new_inner(inner, None, Some(b.map_into()), config, Divmode::DIV)
|
||||
}
|
||||
|
||||
/// Create PWM driver with a 'a' and 'b' pins as output.
|
||||
#[inline]
|
||||
pub fn new_output_ab(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
@ -150,6 +159,7 @@ impl<'d, T: Channel> Pwm<'d, T> {
|
||||
Self::new_inner(inner, Some(a.map_into()), Some(b.map_into()), config, Divmode::DIV)
|
||||
}
|
||||
|
||||
/// Create PWM driver with a single 'b' as input pin.
|
||||
#[inline]
|
||||
pub fn new_input(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
@ -161,6 +171,7 @@ impl<'d, T: Channel> Pwm<'d, T> {
|
||||
Self::new_inner(inner, None, Some(b.map_into()), config, mode.into())
|
||||
}
|
||||
|
||||
/// Create PWM driver with a 'a' and 'b' pins in the desired input mode.
|
||||
#[inline]
|
||||
pub fn new_output_input(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
@ -173,6 +184,7 @@ impl<'d, T: Channel> Pwm<'d, T> {
|
||||
Self::new_inner(inner, Some(a.map_into()), Some(b.map_into()), config, mode.into())
|
||||
}
|
||||
|
||||
/// Set the PWM config.
|
||||
pub fn set_config(&mut self, config: &Config) {
|
||||
Self::configure(self.inner.regs(), config);
|
||||
}
|
||||
@ -216,28 +228,33 @@ impl<'d, T: Channel> Pwm<'d, T> {
|
||||
while p.csr().read().ph_ret() {}
|
||||
}
|
||||
|
||||
/// Read PWM counter.
|
||||
#[inline]
|
||||
pub fn counter(&self) -> u16 {
|
||||
self.inner.regs().ctr().read().ctr()
|
||||
}
|
||||
|
||||
/// Write PWM counter.
|
||||
#[inline]
|
||||
pub fn set_counter(&self, ctr: u16) {
|
||||
self.inner.regs().ctr().write(|w| w.set_ctr(ctr))
|
||||
}
|
||||
|
||||
/// Wait for channel interrupt.
|
||||
#[inline]
|
||||
pub fn wait_for_wrap(&mut self) {
|
||||
while !self.wrapped() {}
|
||||
self.clear_wrapped();
|
||||
}
|
||||
|
||||
/// Check if interrupt for channel is set.
|
||||
#[inline]
|
||||
pub fn wrapped(&mut self) -> bool {
|
||||
pac::PWM.intr().read().0 & self.bit() != 0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Clear interrupt flag.
|
||||
pub fn clear_wrapped(&mut self) {
|
||||
pac::PWM.intr().write_value(Intr(self.bit() as _));
|
||||
}
|
||||
@ -248,15 +265,18 @@ impl<'d, T: Channel> Pwm<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Batch representation of PWM channels.
|
||||
pub struct PwmBatch(u32);
|
||||
|
||||
impl PwmBatch {
|
||||
#[inline]
|
||||
/// Enable a PWM channel in this batch.
|
||||
pub fn enable(&mut self, pwm: &Pwm<'_, impl Channel>) {
|
||||
self.0 |= pwm.bit();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Enable channels in this batch in a PWM.
|
||||
pub fn set_enabled(enabled: bool, batch: impl FnOnce(&mut PwmBatch)) {
|
||||
let mut en = PwmBatch(0);
|
||||
batch(&mut en);
|
||||
@ -284,9 +304,12 @@ mod sealed {
|
||||
pub trait Channel {}
|
||||
}
|
||||
|
||||
/// PWM Channel.
|
||||
pub trait Channel: Peripheral<P = Self> + sealed::Channel + Sized + 'static {
|
||||
/// Channel number.
|
||||
fn number(&self) -> u8;
|
||||
|
||||
/// Channel register block.
|
||||
fn regs(&self) -> pac::pwm::Channel {
|
||||
pac::PWM.ch(self.number() as _)
|
||||
}
|
||||
@ -312,7 +335,9 @@ channel!(PWM_CH5, 5);
|
||||
channel!(PWM_CH6, 6);
|
||||
channel!(PWM_CH7, 7);
|
||||
|
||||
/// PWM Pin A.
|
||||
pub trait PwmPinA<T: Channel>: GpioPin {}
|
||||
/// PWM Pin B.
|
||||
pub trait PwmPinB<T: Channel>: GpioPin {}
|
||||
|
||||
macro_rules! impl_pin {
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! RTC driver.
|
||||
mod filter;
|
||||
|
||||
use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef};
|
||||
@ -194,6 +195,7 @@ mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// RTC peripheral instance.
|
||||
pub trait Instance: sealed::Instance {}
|
||||
|
||||
impl sealed::Instance for crate::peripherals::RTC {
|
||||
|
@ -11,6 +11,7 @@ use crate::gpio::sealed::Pin as _;
|
||||
use crate::gpio::{AnyPin, Pin as GpioPin};
|
||||
use crate::{pac, peripherals, Peripheral};
|
||||
|
||||
/// SPI errors.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[non_exhaustive]
|
||||
@ -18,11 +19,15 @@ pub enum Error {
|
||||
// No errors for now
|
||||
}
|
||||
|
||||
/// SPI configuration.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone)]
|
||||
pub struct Config {
|
||||
/// Frequency.
|
||||
pub frequency: u32,
|
||||
/// Phase.
|
||||
pub phase: Phase,
|
||||
/// Polarity.
|
||||
pub polarity: Polarity,
|
||||
}
|
||||
|
||||
@ -36,6 +41,7 @@ impl Default for Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// SPI driver.
|
||||
pub struct Spi<'d, T: Instance, M: Mode> {
|
||||
inner: PeripheralRef<'d, T>,
|
||||
tx_dma: Option<PeripheralRef<'d, AnyChannel>>,
|
||||
@ -119,6 +125,7 @@ impl<'d, T: Instance, M: Mode> Spi<'d, T, M> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Write data to SPI blocking execution until done.
|
||||
pub fn blocking_write(&mut self, data: &[u8]) -> Result<(), Error> {
|
||||
let p = self.inner.regs();
|
||||
for &b in data {
|
||||
@ -131,6 +138,7 @@ impl<'d, T: Instance, M: Mode> Spi<'d, T, M> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Transfer data in place to SPI blocking execution until done.
|
||||
pub fn blocking_transfer_in_place(&mut self, data: &mut [u8]) -> Result<(), Error> {
|
||||
let p = self.inner.regs();
|
||||
for b in data {
|
||||
@ -143,6 +151,7 @@ impl<'d, T: Instance, M: Mode> Spi<'d, T, M> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read data from SPI blocking execution until done.
|
||||
pub fn blocking_read(&mut self, data: &mut [u8]) -> Result<(), Error> {
|
||||
let p = self.inner.regs();
|
||||
for b in data {
|
||||
@ -155,6 +164,7 @@ impl<'d, T: Instance, M: Mode> Spi<'d, T, M> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Transfer data to SPI blocking execution until done.
|
||||
pub fn blocking_transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Error> {
|
||||
let p = self.inner.regs();
|
||||
let len = read.len().max(write.len());
|
||||
@ -172,12 +182,14 @@ impl<'d, T: Instance, M: Mode> Spi<'d, T, M> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Block execution until SPI is done.
|
||||
pub fn flush(&mut self) -> Result<(), Error> {
|
||||
let p = self.inner.regs();
|
||||
while p.sr().read().bsy() {}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set SPI frequency.
|
||||
pub fn set_frequency(&mut self, freq: u32) {
|
||||
let (presc, postdiv) = calc_prescs(freq);
|
||||
let p = self.inner.regs();
|
||||
@ -196,6 +208,7 @@ impl<'d, T: Instance, M: Mode> Spi<'d, T, M> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> Spi<'d, T, Blocking> {
|
||||
/// Create an SPI driver in blocking mode.
|
||||
pub fn new_blocking(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
clk: impl Peripheral<P = impl ClkPin<T> + 'd> + 'd,
|
||||
@ -216,6 +229,7 @@ impl<'d, T: Instance> Spi<'d, T, Blocking> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Create an SPI driver in blocking mode supporting writes only.
|
||||
pub fn new_blocking_txonly(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
clk: impl Peripheral<P = impl ClkPin<T> + 'd> + 'd,
|
||||
@ -235,6 +249,7 @@ impl<'d, T: Instance> Spi<'d, T, Blocking> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Create an SPI driver in blocking mode supporting reads only.
|
||||
pub fn new_blocking_rxonly(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
clk: impl Peripheral<P = impl ClkPin<T> + 'd> + 'd,
|
||||
@ -256,6 +271,7 @@ impl<'d, T: Instance> Spi<'d, T, Blocking> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> Spi<'d, T, Async> {
|
||||
/// Create an SPI driver in async mode supporting DMA operations.
|
||||
pub fn new(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
clk: impl Peripheral<P = impl ClkPin<T> + 'd> + 'd,
|
||||
@ -278,6 +294,7 @@ impl<'d, T: Instance> Spi<'d, T, Async> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Create an SPI driver in async mode supporting DMA write operations only.
|
||||
pub fn new_txonly(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
clk: impl Peripheral<P = impl ClkPin<T> + 'd> + 'd,
|
||||
@ -298,6 +315,7 @@ impl<'d, T: Instance> Spi<'d, T, Async> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Create an SPI driver in async mode supporting DMA read operations only.
|
||||
pub fn new_rxonly(
|
||||
inner: impl Peripheral<P = T> + 'd,
|
||||
clk: impl Peripheral<P = impl ClkPin<T> + 'd> + 'd,
|
||||
@ -318,6 +336,7 @@ impl<'d, T: Instance> Spi<'d, T, Async> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Write data to SPI using DMA.
|
||||
pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
|
||||
let tx_ch = self.tx_dma.as_mut().unwrap();
|
||||
let tx_transfer = unsafe {
|
||||
@ -340,6 +359,7 @@ impl<'d, T: Instance> Spi<'d, T, Async> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read data from SPI using DMA.
|
||||
pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
|
||||
// Start RX first. Transfer starts when TX starts, if RX
|
||||
// is not started yet we might lose bytes.
|
||||
@ -365,10 +385,12 @@ impl<'d, T: Instance> Spi<'d, T, Async> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Transfer data to SPI using DMA.
|
||||
pub async fn transfer(&mut self, rx_buffer: &mut [u8], tx_buffer: &[u8]) -> Result<(), Error> {
|
||||
self.transfer_inner(rx_buffer, tx_buffer).await
|
||||
}
|
||||
|
||||
/// Transfer data in place to SPI using DMA.
|
||||
pub async fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Error> {
|
||||
self.transfer_inner(words, words).await
|
||||
}
|
||||
@ -434,7 +456,10 @@ mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// Mode.
|
||||
pub trait Mode: sealed::Mode {}
|
||||
|
||||
/// SPI instance trait.
|
||||
pub trait Instance: sealed::Instance {}
|
||||
|
||||
macro_rules! impl_instance {
|
||||
@ -454,9 +479,13 @@ macro_rules! impl_instance {
|
||||
impl_instance!(SPI0, Spi0, 16, 17);
|
||||
impl_instance!(SPI1, Spi1, 18, 19);
|
||||
|
||||
/// CLK pin.
|
||||
pub trait ClkPin<T: Instance>: GpioPin {}
|
||||
/// CS pin.
|
||||
pub trait CsPin<T: Instance>: GpioPin {}
|
||||
/// MOSI pin.
|
||||
pub trait MosiPin<T: Instance>: GpioPin {}
|
||||
/// MISO pin.
|
||||
pub trait MisoPin<T: Instance>: GpioPin {}
|
||||
|
||||
macro_rules! impl_pin {
|
||||
@ -503,7 +532,9 @@ macro_rules! impl_mode {
|
||||
};
|
||||
}
|
||||
|
||||
/// Blocking mode.
|
||||
pub struct Blocking;
|
||||
/// Async mode.
|
||||
pub struct Async;
|
||||
|
||||
impl_mode!(Blocking);
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! Timer driver.
|
||||
use core::cell::Cell;
|
||||
|
||||
use atomic_polyfill::{AtomicU8, Ordering};
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! Buffered UART driver.
|
||||
use core::future::{poll_fn, Future};
|
||||
use core::slice;
|
||||
use core::task::Poll;
|
||||
@ -38,15 +39,18 @@ impl State {
|
||||
}
|
||||
}
|
||||
|
||||
/// Buffered UART driver.
|
||||
pub struct BufferedUart<'d, T: Instance> {
|
||||
pub(crate) rx: BufferedUartRx<'d, T>,
|
||||
pub(crate) tx: BufferedUartTx<'d, T>,
|
||||
}
|
||||
|
||||
/// Buffered UART RX handle.
|
||||
pub struct BufferedUartRx<'d, T: Instance> {
|
||||
pub(crate) phantom: PhantomData<&'d mut T>,
|
||||
}
|
||||
|
||||
/// Buffered UART TX handle.
|
||||
pub struct BufferedUartTx<'d, T: Instance> {
|
||||
pub(crate) phantom: PhantomData<&'d mut T>,
|
||||
}
|
||||
@ -84,6 +88,7 @@ pub(crate) fn init_buffers<'d, T: Instance + 'd>(
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> BufferedUart<'d, T> {
|
||||
/// Create a buffered UART instance.
|
||||
pub fn new(
|
||||
_uart: impl Peripheral<P = T> + 'd,
|
||||
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
|
||||
@ -104,6 +109,7 @@ impl<'d, T: Instance> BufferedUart<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a buffered UART instance with flow control.
|
||||
pub fn new_with_rtscts(
|
||||
_uart: impl Peripheral<P = T> + 'd,
|
||||
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
|
||||
@ -132,32 +138,39 @@ impl<'d, T: Instance> BufferedUart<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Write to UART TX buffer blocking execution until done.
|
||||
pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<usize, Error> {
|
||||
self.tx.blocking_write(buffer)
|
||||
}
|
||||
|
||||
/// Flush UART TX blocking execution until done.
|
||||
pub fn blocking_flush(&mut self) -> Result<(), Error> {
|
||||
self.tx.blocking_flush()
|
||||
}
|
||||
|
||||
/// Read from UART RX buffer blocking execution until done.
|
||||
pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
|
||||
self.rx.blocking_read(buffer)
|
||||
}
|
||||
|
||||
/// Check if UART is busy transmitting.
|
||||
pub fn busy(&self) -> bool {
|
||||
self.tx.busy()
|
||||
}
|
||||
|
||||
/// Wait until TX is empty and send break condition.
|
||||
pub async fn send_break(&mut self, bits: u32) {
|
||||
self.tx.send_break(bits).await
|
||||
}
|
||||
|
||||
/// Split into separate RX and TX handles.
|
||||
pub fn split(self) -> (BufferedUartRx<'d, T>, BufferedUartTx<'d, T>) {
|
||||
(self.rx, self.tx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> BufferedUartRx<'d, T> {
|
||||
/// Create a new buffered UART RX.
|
||||
pub fn new(
|
||||
_uart: impl Peripheral<P = T> + 'd,
|
||||
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
|
||||
@ -173,6 +186,7 @@ impl<'d, T: Instance> BufferedUartRx<'d, T> {
|
||||
Self { phantom: PhantomData }
|
||||
}
|
||||
|
||||
/// Create a new buffered UART RX with flow control.
|
||||
pub fn new_with_rts(
|
||||
_uart: impl Peripheral<P = T> + 'd,
|
||||
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
|
||||
@ -253,6 +267,7 @@ impl<'d, T: Instance> BufferedUartRx<'d, T> {
|
||||
Poll::Ready(result)
|
||||
}
|
||||
|
||||
/// Read from UART RX buffer blocking execution until done.
|
||||
pub fn blocking_read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
|
||||
loop {
|
||||
match Self::try_read(buf) {
|
||||
@ -303,6 +318,7 @@ impl<'d, T: Instance> BufferedUartRx<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> BufferedUartTx<'d, T> {
|
||||
/// Create a new buffered UART TX.
|
||||
pub fn new(
|
||||
_uart: impl Peripheral<P = T> + 'd,
|
||||
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
|
||||
@ -318,6 +334,7 @@ impl<'d, T: Instance> BufferedUartTx<'d, T> {
|
||||
Self { phantom: PhantomData }
|
||||
}
|
||||
|
||||
/// Create a new buffered UART TX with flow control.
|
||||
pub fn new_with_cts(
|
||||
_uart: impl Peripheral<P = T> + 'd,
|
||||
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
|
||||
@ -373,6 +390,7 @@ impl<'d, T: Instance> BufferedUartTx<'d, T> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Write to UART TX buffer blocking execution until done.
|
||||
pub fn blocking_write(&mut self, buf: &[u8]) -> Result<usize, Error> {
|
||||
if buf.is_empty() {
|
||||
return Ok(0);
|
||||
@ -398,6 +416,7 @@ impl<'d, T: Instance> BufferedUartTx<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Flush UART TX blocking execution until done.
|
||||
pub fn blocking_flush(&mut self) -> Result<(), Error> {
|
||||
loop {
|
||||
let state = T::buffered_state();
|
||||
@ -407,6 +426,7 @@ impl<'d, T: Instance> BufferedUartTx<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if UART is busy.
|
||||
pub fn busy(&self) -> bool {
|
||||
T::regs().uartfr().read().busy()
|
||||
}
|
||||
@ -466,6 +486,7 @@ impl<'d, T: Instance> Drop for BufferedUartTx<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interrupt handler.
|
||||
pub struct BufferedInterruptHandler<T: Instance> {
|
||||
_uart: PhantomData<T>,
|
||||
}
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! UART driver.
|
||||
use core::future::poll_fn;
|
||||
use core::marker::PhantomData;
|
||||
use core::task::Poll;
|
||||
@ -20,11 +21,16 @@ use crate::{interrupt, pac, peripherals, Peripheral, RegExt};
|
||||
mod buffered;
|
||||
pub use buffered::{BufferedInterruptHandler, BufferedUart, BufferedUartRx, BufferedUartTx};
|
||||
|
||||
/// Word length.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum DataBits {
|
||||
/// 5 bits.
|
||||
DataBits5,
|
||||
/// 6 bits.
|
||||
DataBits6,
|
||||
/// 7 bits.
|
||||
DataBits7,
|
||||
/// 8 bits.
|
||||
DataBits8,
|
||||
}
|
||||
|
||||
@ -39,13 +45,18 @@ impl DataBits {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parity bit.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Parity {
|
||||
/// No parity.
|
||||
ParityNone,
|
||||
/// Even parity.
|
||||
ParityEven,
|
||||
/// Odd parity.
|
||||
ParityOdd,
|
||||
}
|
||||
|
||||
/// Stop bits.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum StopBits {
|
||||
#[doc = "1 stop bit"]
|
||||
@ -54,20 +65,25 @@ pub enum StopBits {
|
||||
STOP2,
|
||||
}
|
||||
|
||||
/// UART config.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub struct Config {
|
||||
/// Baud rate.
|
||||
pub baudrate: u32,
|
||||
/// Word length.
|
||||
pub data_bits: DataBits,
|
||||
/// Stop bits.
|
||||
pub stop_bits: StopBits,
|
||||
/// Parity bit.
|
||||
pub parity: Parity,
|
||||
/// Invert the tx pin output
|
||||
pub invert_tx: bool,
|
||||
/// Invert the rx pin input
|
||||
pub invert_rx: bool,
|
||||
// Invert the rts pin
|
||||
/// Invert the rts pin
|
||||
pub invert_rts: bool,
|
||||
// Invert the cts pin
|
||||
/// Invert the cts pin
|
||||
pub invert_cts: bool,
|
||||
}
|
||||
|
||||
@ -102,31 +118,36 @@ pub enum Error {
|
||||
Framing,
|
||||
}
|
||||
|
||||
/// Read To Break error
|
||||
/// Errors specific to `read_to_break()` functions
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[non_exhaustive]
|
||||
pub enum ReadToBreakError {
|
||||
/// Read this many bytes, but never received a line break.
|
||||
MissingBreak(usize),
|
||||
/// A non-line-break related error occurred
|
||||
Other(Error),
|
||||
}
|
||||
|
||||
/// Internal DMA state of UART RX.
|
||||
pub struct DmaState {
|
||||
rx_err_waker: AtomicWaker,
|
||||
rx_errs: AtomicU16,
|
||||
}
|
||||
|
||||
/// UART driver.
|
||||
pub struct Uart<'d, T: Instance, M: Mode> {
|
||||
tx: UartTx<'d, T, M>,
|
||||
rx: UartRx<'d, T, M>,
|
||||
}
|
||||
|
||||
/// UART TX driver.
|
||||
pub struct UartTx<'d, T: Instance, M: Mode> {
|
||||
tx_dma: Option<PeripheralRef<'d, AnyChannel>>,
|
||||
phantom: PhantomData<(&'d mut T, M)>,
|
||||
}
|
||||
|
||||
/// UART RX driver.
|
||||
pub struct UartRx<'d, T: Instance, M: Mode> {
|
||||
rx_dma: Option<PeripheralRef<'d, AnyChannel>>,
|
||||
phantom: PhantomData<(&'d mut T, M)>,
|
||||
@ -152,6 +173,7 @@ impl<'d, T: Instance, M: Mode> UartTx<'d, T, M> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Transmit the provided buffer blocking execution until done.
|
||||
pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
|
||||
let r = T::regs();
|
||||
for &b in buffer {
|
||||
@ -161,12 +183,14 @@ impl<'d, T: Instance, M: Mode> UartTx<'d, T, M> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Flush UART TX blocking execution until done.
|
||||
pub fn blocking_flush(&mut self) -> Result<(), Error> {
|
||||
let r = T::regs();
|
||||
while !r.uartfr().read().txfe() {}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check if UART is busy transmitting.
|
||||
pub fn busy(&self) -> bool {
|
||||
T::regs().uartfr().read().busy()
|
||||
}
|
||||
@ -201,6 +225,8 @@ impl<'d, T: Instance, M: Mode> UartTx<'d, T, M> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> UartTx<'d, T, Blocking> {
|
||||
/// Convert this uart TX instance into a buffered uart using the provided
|
||||
/// irq and transmit buffer.
|
||||
pub fn into_buffered(
|
||||
self,
|
||||
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
|
||||
@ -213,6 +239,7 @@ impl<'d, T: Instance> UartTx<'d, T, Blocking> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> UartTx<'d, T, Async> {
|
||||
/// Write to UART TX from the provided buffer using DMA.
|
||||
pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
|
||||
let ch = self.tx_dma.as_mut().unwrap();
|
||||
let transfer = unsafe {
|
||||
@ -256,6 +283,7 @@ impl<'d, T: Instance, M: Mode> UartRx<'d, T, M> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read from UART RX blocking execution until done.
|
||||
pub fn blocking_read(&mut self, mut buffer: &mut [u8]) -> Result<(), Error> {
|
||||
while !buffer.is_empty() {
|
||||
let received = self.drain_fifo(buffer).map_err(|(_i, e)| e)?;
|
||||
@ -307,6 +335,7 @@ impl<'d, T: Instance, M: Mode> Drop for UartRx<'d, T, M> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> UartRx<'d, T, Blocking> {
|
||||
/// Create a new UART RX instance for blocking mode operations.
|
||||
pub fn new_blocking(
|
||||
_uart: impl Peripheral<P = T> + 'd,
|
||||
rx: impl Peripheral<P = impl RxPin<T>> + 'd,
|
||||
@ -317,6 +346,8 @@ impl<'d, T: Instance> UartRx<'d, T, Blocking> {
|
||||
Self::new_inner(false, None)
|
||||
}
|
||||
|
||||
/// Convert this uart RX instance into a buffered uart using the provided
|
||||
/// irq and receive buffer.
|
||||
pub fn into_buffered(
|
||||
self,
|
||||
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
|
||||
@ -328,6 +359,7 @@ impl<'d, T: Instance> UartRx<'d, T, Blocking> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interrupt handler.
|
||||
pub struct InterruptHandler<T: Instance> {
|
||||
_uart: PhantomData<T>,
|
||||
}
|
||||
@ -351,6 +383,7 @@ impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandl
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> UartRx<'d, T, Async> {
|
||||
/// Read from UART RX into the provided buffer.
|
||||
pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
|
||||
// clear error flags before we drain the fifo. errors that have accumulated
|
||||
// in the flags will also be present in the fifo.
|
||||
@ -650,6 +683,8 @@ impl<'d, T: Instance> Uart<'d, T, Blocking> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Convert this uart instance into a buffered uart using the provided
|
||||
/// irq, transmit and receive buffers.
|
||||
pub fn into_buffered(
|
||||
self,
|
||||
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
|
||||
@ -859,22 +894,27 @@ impl<'d, T: Instance + 'd, M: Mode> Uart<'d, T, M> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance, M: Mode> Uart<'d, T, M> {
|
||||
/// Transmit the provided buffer blocking execution until done.
|
||||
pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
|
||||
self.tx.blocking_write(buffer)
|
||||
}
|
||||
|
||||
/// Flush UART TX blocking execution until done.
|
||||
pub fn blocking_flush(&mut self) -> Result<(), Error> {
|
||||
self.tx.blocking_flush()
|
||||
}
|
||||
|
||||
/// Read from UART RX blocking execution until done.
|
||||
pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
|
||||
self.rx.blocking_read(buffer)
|
||||
}
|
||||
|
||||
/// Check if UART is busy transmitting.
|
||||
pub fn busy(&self) -> bool {
|
||||
self.tx.busy()
|
||||
}
|
||||
|
||||
/// Wait until TX is empty and send break condition.
|
||||
pub async fn send_break(&mut self, bits: u32) {
|
||||
self.tx.send_break(bits).await
|
||||
}
|
||||
@ -887,14 +927,19 @@ impl<'d, T: Instance, M: Mode> Uart<'d, T, M> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> Uart<'d, T, Async> {
|
||||
/// Write to UART TX from the provided buffer.
|
||||
pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
|
||||
self.tx.write(buffer).await
|
||||
}
|
||||
|
||||
/// Read from UART RX into the provided buffer.
|
||||
pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
|
||||
self.rx.read(buffer).await
|
||||
}
|
||||
|
||||
/// Read from the UART, waiting for a line break.
|
||||
///
|
||||
/// See [`UartRx::read_to_break()`] for more details.
|
||||
pub async fn read_to_break<'a>(&mut self, buf: &'a mut [u8]) -> Result<usize, ReadToBreakError> {
|
||||
self.rx.read_to_break(buf).await
|
||||
}
|
||||
@ -1085,6 +1130,7 @@ mod sealed {
|
||||
pub trait RtsPin<T: Instance> {}
|
||||
}
|
||||
|
||||
/// UART mode.
|
||||
pub trait Mode: sealed::Mode {}
|
||||
|
||||
macro_rules! impl_mode {
|
||||
@ -1094,12 +1140,15 @@ macro_rules! impl_mode {
|
||||
};
|
||||
}
|
||||
|
||||
/// Blocking mode.
|
||||
pub struct Blocking;
|
||||
/// Async mode.
|
||||
pub struct Async;
|
||||
|
||||
impl_mode!(Blocking);
|
||||
impl_mode!(Async);
|
||||
|
||||
/// UART instance.
|
||||
pub trait Instance: sealed::Instance {}
|
||||
|
||||
macro_rules! impl_instance {
|
||||
@ -1134,9 +1183,13 @@ macro_rules! impl_instance {
|
||||
impl_instance!(UART0, UART0_IRQ, 20, 21);
|
||||
impl_instance!(UART1, UART1_IRQ, 22, 23);
|
||||
|
||||
/// Trait for TX pins.
|
||||
pub trait TxPin<T: Instance>: sealed::TxPin<T> + crate::gpio::Pin {}
|
||||
/// Trait for RX pins.
|
||||
pub trait RxPin<T: Instance>: sealed::RxPin<T> + crate::gpio::Pin {}
|
||||
/// Trait for Clear To Send (CTS) pins.
|
||||
pub trait CtsPin<T: Instance>: sealed::CtsPin<T> + crate::gpio::Pin {}
|
||||
/// Trait for Request To Send (RTS) pins.
|
||||
pub trait RtsPin<T: Instance>: sealed::RtsPin<T> + crate::gpio::Pin {}
|
||||
|
||||
macro_rules! impl_pin {
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! USB driver.
|
||||
use core::future::poll_fn;
|
||||
use core::marker::PhantomData;
|
||||
use core::slice;
|
||||
@ -20,7 +21,9 @@ pub(crate) mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// USB peripheral instance.
|
||||
pub trait Instance: sealed::Instance + 'static {
|
||||
/// Interrupt for this peripheral.
|
||||
type Interrupt: interrupt::typelevel::Interrupt;
|
||||
}
|
||||
|
||||
@ -96,6 +99,7 @@ impl EndpointData {
|
||||
}
|
||||
}
|
||||
|
||||
/// RP2040 USB driver handle.
|
||||
pub struct Driver<'d, T: Instance> {
|
||||
phantom: PhantomData<&'d mut T>,
|
||||
ep_in: [EndpointData; EP_COUNT],
|
||||
@ -104,6 +108,7 @@ pub struct Driver<'d, T: Instance> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> Driver<'d, T> {
|
||||
/// Create a new USB driver.
|
||||
pub fn new(_usb: impl Peripheral<P = T> + 'd, _irq: impl Binding<T::Interrupt, InterruptHandler<T>>) -> Self {
|
||||
T::Interrupt::unpend();
|
||||
unsafe { T::Interrupt::enable() };
|
||||
@ -240,6 +245,7 @@ impl<'d, T: Instance> Driver<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// USB interrupt handler.
|
||||
pub struct InterruptHandler<T: Instance> {
|
||||
_uart: PhantomData<T>,
|
||||
}
|
||||
@ -342,6 +348,7 @@ impl<'d, T: Instance> driver::Driver<'d> for Driver<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Type representing the RP USB bus.
|
||||
pub struct Bus<'d, T: Instance> {
|
||||
phantom: PhantomData<&'d mut T>,
|
||||
ep_out: [EndpointData; EP_COUNT],
|
||||
@ -461,6 +468,7 @@ trait Dir {
|
||||
fn waker(i: usize) -> &'static AtomicWaker;
|
||||
}
|
||||
|
||||
/// Type for In direction.
|
||||
pub enum In {}
|
||||
impl Dir for In {
|
||||
fn dir() -> Direction {
|
||||
@ -473,6 +481,7 @@ impl Dir for In {
|
||||
}
|
||||
}
|
||||
|
||||
/// Type for Out direction.
|
||||
pub enum Out {}
|
||||
impl Dir for Out {
|
||||
fn dir() -> Direction {
|
||||
@ -485,6 +494,7 @@ impl Dir for Out {
|
||||
}
|
||||
}
|
||||
|
||||
/// Endpoint for RP USB driver.
|
||||
pub struct Endpoint<'d, T: Instance, D> {
|
||||
_phantom: PhantomData<(&'d mut T, D)>,
|
||||
info: EndpointInfo,
|
||||
@ -616,6 +626,7 @@ impl<'d, T: Instance> driver::EndpointIn for Endpoint<'d, T, In> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Control pipe for RP USB driver.
|
||||
pub struct ControlPipe<'d, T: Instance> {
|
||||
_phantom: PhantomData<&'d mut T>,
|
||||
max_packet_size: u16,
|
||||
|
Reference in New Issue
Block a user