Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for AVR #16

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ all-features = true
embedded-hal = "0.2.3"
once_cell = { version = "1.4.0", optional = true }
cortex-m = { version = "0.6.3", optional = true }
avr-device = { version = "0.2.2", optional = true }

[dev-dependencies]
embedded-hal-mock = "0.7.0"

[features]
std = ["once_cell"]
docs = ["avr-device/atmega328p"]
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,17 @@ pub use once_cell;
#[cfg(feature = "cortex-m")]
pub use cortex_m;

#[doc(hidden)]
#[cfg(feature = "avr-device")]
pub use avr_device;

pub use manager::BusManager;
pub use mutex::BusMutex;
pub use mutex::NullMutex;
#[cfg(feature = "cortex-m")]
pub use mutex::CortexMMutex;
#[cfg(feature = "avr-device")]
pub use mutex::AvrMutex;
pub use proxies::I2cProxy;
pub use proxies::SpiProxy;

Expand Down Expand Up @@ -189,3 +195,16 @@ pub type BusManagerStd<BUS> = BusManager<::std::sync::Mutex<BUS>>;
/// This type is only available with the `cortex-m` feature.
#[cfg(feature = "cortex-m")]
pub type BusManagerCortexM<BUS> = BusManager<CortexMMutex<BUS>>;

/// A bus manager for safely sharing between tasks on AVR.
///
/// This manager works by turning off interrupts for each bus transaction which prevents racy
/// accesses from different tasks/execution contexts (e.g. interrupts). Usually, for sharing
/// between tasks, a manager with `'static` lifetime is needed which can be created using the
/// [`shared_bus::new_avr!()`][new_avr] macro.
///
/// [new_avr]: ./macro.new_avr.html
///
/// This type is only available with the `avr-device` feature.
#[cfg(feature = "avr-device")]
pub type BusManagerAvr<BUS> = BusManager<AvrMutex<BUS>>;
88 changes: 88 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,91 @@ macro_rules! new_cortexm {
m
}};
}

/// Macro for creating an AVR bus manager with `'static` lifetime.
///
/// This macro is a convenience helper for creating a bus manager that lives for the `'static`
/// lifetime an thus can be safely shared across tasks/execution contexts (like interrupts).
///
/// This macro is only available with the `avr-device` feature.
///
/// # Syntax
/// ```ignore
/// let bus = shared_bus::new_avr!(<Full Bus Type Signature> = <bus>).unwrap();
/// ```
///
/// The macro returns an Option which will be `Some(&'static bus_manager)` on the first run and
/// `None` afterwards. This is necessary to uphold safety around the inner `static` variable.
///
/// # Example
/// ```no_run
/// # use embedded_hal::blocking::i2c::Write;
/// # struct MyDevice<T>(T);
/// # impl<T> MyDevice<T> {
/// # pub fn new(t: T) -> Self { MyDevice(t) }
/// # pub fn do_something_on_the_bus(&mut self) { }
/// # }
/// #
/// # struct SomeI2cBus;
/// # impl Write for SomeI2cBus {
/// # type Error = ();
/// # fn write(&mut self, addr: u8, buffer: &[u8]) -> Result<(), Self::Error> { Ok(()) }
/// # }
/// static mut SHARED_DEVICE:
/// Option<MyDevice<shared_bus::I2cProxy<shared_bus::AvrMutex<SomeI2cBus>>>>
/// = None;
///
/// fn main() -> ! {
/// # let i2c = SomeI2cBus;
/// // For example:
/// // let i2c = atmega328p_hal::i2c::I2c::new(
/// // dp.TWI,
/// // pins.a4.into_pull_up_input(&mut pins.ddr),
/// // pins.a5.into_pull_up_input(&mut pins.ddr),
/// // 50000,
/// // );
///
/// // The bus is a 'static reference -> it lives forever and references can be
/// // shared with other tasks.
/// let bus: &'static _ = shared_bus::new_avr!(SomeI2cBus = i2c).unwrap();
///
/// let mut proxy1 = bus.acquire_i2c();
/// let my_device = MyDevice::new(bus.acquire_i2c());
///
/// unsafe {
/// SHARED_DEVICE = Some(my_device);
/// }
///
/// // enable the interrupt
///
/// loop {
/// proxy1.write(0x39, &[0xaa]);
/// }
/// }
///
/// fn INTERRUPT() {
/// let dev = unsafe {SHARED_DEVICE.as_mut().unwrap()};
///
/// dev.do_something_on_the_bus();
/// }
/// ```
#[cfg(feature = "avr-device")]
#[macro_export]
macro_rules! new_avr {
($bus_type:ty = $bus:expr) => {{
static mut MANAGER: Option<$crate::BusManagerAvr<$bus_type>> = None;

let m: Option<&'static _> = $crate::avr_device::interrupt::free(|_| {
unsafe {
if MANAGER.is_none() {
MANAGER = Some($crate::BusManagerAvr::new($bus));
MANAGER.as_ref()
} else {
None
}
}
});

m
}};
}
33 changes: 33 additions & 0 deletions src/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,39 @@ impl<T> BusMutex for CortexMMutex<T> {
}
}

/// Alias for an AVR mutex.
///
/// This mutex works by disabling interrupts while the mutex is locked.
///
/// This type is only available with the `avr-device` feature.
#[cfg(feature = "avr-device")]
pub struct AvrMutex<T> {
bus: cell::RefCell<T>,
}

#[cfg(feature = "avr-device")]
impl<T> BusMutex for AvrMutex<T> {
type Bus = T;

fn create(v: Self::Bus) -> Self {
AvrMutex {
bus: cell::RefCell::new(v),
}
}

fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R {
avr_device::interrupt::free(|_| {
f(&mut self.bus.borrow_mut())
})
}
}

// #[cfg(feature = "avr-device")]
// unsafe impl<T: Send> Send for AvrMutex<T> {}
Copy link

Choose a reason for hiding this comment

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

I'm not qualified to review this PR, but there's some dead code here that could probably be removed (unless the AvrMutex is Send of course).

Copy link
Owner Author

Choose a reason for hiding this comment

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

Good question why I commented that out ... I would argure that it is Send as long as we're on an AVR device (which is single core). Interrupts are disabled while the mutex is held so no interrupt could preempt in the meantime and attempt to access the mutex concurrently.


#[cfg(feature = "avr-device")]
unsafe impl<T: Send> Sync for AvrMutex<T> {}

#[cfg(test)]
mod tests {
use super::*;
Expand Down