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 async support #5

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from 6 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## [Unreleased]

### Added
- Async support based on `embedded-hal-async` 1.0.

### Changed
- Raise MSRV to 1.65.0.

Expand Down
12 changes: 9 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,18 @@ include = [
"/LICENSE-APACHE",
]

[features]
default = []
async = ["dep:embedded-hal-async"]

[dependencies]
embedded-hal = "0.2.7"
embedded-hal = "1.0"
embedded-hal-async = { version = "1.0", optional = true }
maybe-async-cfg = "0.2.3"

[dev-dependencies]
linux-embedded-hal = "0.3"
embedded-hal-mock = "0.9"
linux-embedded-hal = "0.4"
embedded-hal-mock = { version = "0.10", default-features = false, features = ["eh1"] }

[profile.release]
lto = true
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,34 @@ fn main() {
}
```

This driver also supports `embedded-hal-async` traits if `async` feature is enabled in Cargo.toml:

```toml
tcs3472 = { version = "0.3.0", features = ["async"] };
```

Example how it looks like when using [Embassy](https://embassy.dev/) framework:

```rust
#[embassy_executor::main]
async fn main(_spawner: Spawner) {
let p = embassy_stm32::init(Default::default());
// embassy i2c setup details omitted
let mut i2c = I2c::new(..);
let mut sensor = Tcs3472::new(i2c);
sensor.enable().await.unwrap();
sensor.enable_rgbc().await.unwrap();
while !sensor.is_rgbc_status_valid().await.unwrap() {
// wait for measurement to be available
};
let m = sensor.read_all_channels().await.unwrap();
defmt::info!(
"Measurements: clear = {}, red = {}, green = {}, blue = {}",
m.clear, m.red, m.green, m.blue
);
}
```

## Minimum Supported Rust Version (MSRV)

This crate is guaranteed to compile on stable Rust 1.65.0 and up. It *might*
Expand Down
134 changes: 81 additions & 53 deletions src/configuration.rs
Original file line number Diff line number Diff line change
@@ -1,64 +1,75 @@
use crate::{
BitFlags, Error, Register, RgbCGain, RgbCInterruptPersistence, Tcs3472, DEVICE_ADDRESS,
};
use embedded_hal::blocking::i2c;

#[cfg(not(feature = "async"))]
use embedded_hal::i2c::I2c;
#[cfg(feature = "async")]
use embedded_hal_async::i2c::I2c as AsyncI2c;

#[maybe_async_cfg::maybe(
sync(
cfg(not(feature = "async")),
self = "Tcs3472",
idents(AsyncI2c(sync = "I2c"))
),
async(feature = "async", keep_self)
)]
impl<I2C, E> Tcs3472<I2C>
where
I2C: i2c::Write<Error = E>,
I2C: AsyncI2c<Error = E>,
{
/// Enable the device (Power ON).
///
/// The device goes to idle state.
pub fn enable(&mut self) -> Result<(), Error<E>> {
pub async fn enable(&mut self) -> Result<(), Error<E>> {
let enable = self.enable;
self.write_enable(enable | BitFlags::POWER_ON)
self.write_enable(enable | BitFlags::POWER_ON).await
}

/// Disable the device (sleep).
pub fn disable(&mut self) -> Result<(), Error<E>> {
pub async fn disable(&mut self) -> Result<(), Error<E>> {
let enable = self.enable;
self.write_enable(enable & !BitFlags::POWER_ON)
self.write_enable(enable & !BitFlags::POWER_ON).await
}

/// Enable the RGB converter.
pub fn enable_rgbc(&mut self) -> Result<(), Error<E>> {
pub async fn enable_rgbc(&mut self) -> Result<(), Error<E>> {
let enable = self.enable;
self.write_enable(enable | BitFlags::RGBC_EN)
self.write_enable(enable | BitFlags::RGBC_EN).await
}

/// Disable the RGB converter.
pub fn disable_rgbc(&mut self) -> Result<(), Error<E>> {
pub async fn disable_rgbc(&mut self) -> Result<(), Error<E>> {
let enable = self.enable;
self.write_enable(enable & !BitFlags::RGBC_EN)
self.write_enable(enable & !BitFlags::RGBC_EN).await
}

/// Enable the RGB converter interrupt generation.
pub fn enable_rgbc_interrupts(&mut self) -> Result<(), Error<E>> {
pub async fn enable_rgbc_interrupts(&mut self) -> Result<(), Error<E>> {
let enable = self.enable;
self.write_enable(enable | BitFlags::RGBC_INT_EN)
self.write_enable(enable | BitFlags::RGBC_INT_EN).await
}

/// Disable the RGB converter interrupt generation.
pub fn disable_rgbc_interrupts(&mut self) -> Result<(), Error<E>> {
pub async fn disable_rgbc_interrupts(&mut self) -> Result<(), Error<E>> {
let enable = self.enable;
self.write_enable(enable & !BitFlags::RGBC_INT_EN)
self.write_enable(enable & !BitFlags::RGBC_INT_EN).await
}

/// Enable the wait feature (wait timer).
pub fn enable_wait(&mut self) -> Result<(), Error<E>> {
pub async fn enable_wait(&mut self) -> Result<(), Error<E>> {
let enable = self.enable;
self.write_enable(enable | BitFlags::WAIT_EN)
self.write_enable(enable | BitFlags::WAIT_EN).await
}

/// Disable the wait feature (wait timer).
pub fn disable_wait(&mut self) -> Result<(), Error<E>> {
pub async fn disable_wait(&mut self) -> Result<(), Error<E>> {
let enable = self.enable;
self.write_enable(enable & !BitFlags::WAIT_EN)
self.write_enable(enable & !BitFlags::WAIT_EN).await
}

fn write_enable(&mut self, enable: u8) -> Result<(), Error<E>> {
self.write_register(Register::ENABLE, enable)?;
async fn write_enable(&mut self, enable: u8) -> Result<(), Error<E>> {
self.write_register(Register::ENABLE, enable).await?;
self.enable = enable;
Ok(())
}
Expand All @@ -73,101 +84,118 @@ where
/// `number_of_cycles * 0.029s`.
/// See [`enable_wait_long()`](#method.enable_wait_long) and
/// [`disable_wait_long()`](#method.disable_wait_long).
pub fn set_wait_cycles(&mut self, cycles: u16) -> Result<(), Error<E>> {
pub async fn set_wait_cycles(&mut self, cycles: u16) -> Result<(), Error<E>> {
if cycles > 256 || cycles == 0 {
return Err(Error::InvalidInputData);
}
// the value is stored as a two's complement
self.write_register(Register::WTIME, (256_u16 - cycles) as u8)
.await
}

/// Enable the *wait long* setting.
///
/// The wait time configured with `set_wait_cycles()` is increased by a
/// factor of 12. See [`set_wait_cycles()`](#method.set_wait_cycles).
pub fn enable_wait_long(&mut self) -> Result<(), Error<E>> {
self.write_register(Register::CONFIG, BitFlags::WLONG)
pub async fn enable_wait_long(&mut self) -> Result<(), Error<E>> {
self.write_register(Register::CONFIG, BitFlags::WLONG).await
}

/// Disable the *wait long* setting.
///
/// The wait time configured with `set_wait_cycles()` is used without
/// multiplication factor. See [`set_wait_cycles()`](#method.set_wait_cycles).
pub fn disable_wait_long(&mut self) -> Result<(), Error<E>> {
self.write_register(Register::CONFIG, 0)
pub async fn disable_wait_long(&mut self) -> Result<(), Error<E>> {
self.write_register(Register::CONFIG, 0).await
}

/// Set the RGB converter gain.
pub fn set_rgbc_gain(&mut self, gain: RgbCGain) -> Result<(), Error<E>> {
pub async fn set_rgbc_gain(&mut self, gain: RgbCGain) -> Result<(), Error<E>> {
// Register field: AGAIN
match gain {
RgbCGain::_1x => self.write_register(Register::CONTROL, 0),
RgbCGain::_4x => self.write_register(Register::CONTROL, 1),
RgbCGain::_16x => self.write_register(Register::CONTROL, 2),
RgbCGain::_60x => self.write_register(Register::CONTROL, 3),
RgbCGain::_1x => self.write_register(Register::CONTROL, 0).await,
RgbCGain::_4x => self.write_register(Register::CONTROL, 1).await,
RgbCGain::_16x => self.write_register(Register::CONTROL, 2).await,
RgbCGain::_60x => self.write_register(Register::CONTROL, 3).await,
}
}

/// Set the number of integration cycles (1-256).
///
/// The actual integration time corresponds to: `number_of_cycles * 2.4ms`.
pub fn set_integration_cycles(&mut self, cycles: u16) -> Result<(), Error<E>> {
pub async fn set_integration_cycles(&mut self, cycles: u16) -> Result<(), Error<E>> {
if cycles > 256 || cycles == 0 {
return Err(Error::InvalidInputData);
}
// the value is stored as a two's complement
self.write_register(Register::ATIME, (256_u16 - cycles) as u8)
.await
}

/// Set the RGB converter interrupt clear channel low threshold.
pub fn set_rgbc_interrupt_low_threshold(&mut self, threshold: u16) -> Result<(), Error<E>> {
pub async fn set_rgbc_interrupt_low_threshold(
&mut self,
threshold: u16,
) -> Result<(), Error<E>> {
self.write_registers(Register::AILTL, threshold as u8, (threshold >> 8) as u8)
.await
}

/// Set the RGB converter interrupt clear channel high threshold.
pub fn set_rgbc_interrupt_high_threshold(&mut self, threshold: u16) -> Result<(), Error<E>> {
pub async fn set_rgbc_interrupt_high_threshold(
&mut self,
threshold: u16,
) -> Result<(), Error<E>> {
self.write_registers(Register::AIHTL, threshold as u8, (threshold >> 8) as u8)
.await
}

/// Set the RGB converter interrupt persistence.
///
/// This controls the RGB converter interrupt generation rate.
pub fn set_rgbc_interrupt_persistence(
pub async fn set_rgbc_interrupt_persistence(
&mut self,
persistence: RgbCInterruptPersistence,
) -> Result<(), Error<E>> {
use crate::RgbCInterruptPersistence as IP;
match persistence {
IP::Every => self.write_register(Register::APERS, 0),
IP::_1 => self.write_register(Register::APERS, 1),
IP::_2 => self.write_register(Register::APERS, 2),
IP::_3 => self.write_register(Register::APERS, 3),
IP::_5 => self.write_register(Register::APERS, 4),
IP::_10 => self.write_register(Register::APERS, 5),
IP::_15 => self.write_register(Register::APERS, 6),
IP::_20 => self.write_register(Register::APERS, 7),
IP::_25 => self.write_register(Register::APERS, 8),
IP::_30 => self.write_register(Register::APERS, 9),
IP::_35 => self.write_register(Register::APERS, 10),
IP::_40 => self.write_register(Register::APERS, 11),
IP::_45 => self.write_register(Register::APERS, 12),
IP::_50 => self.write_register(Register::APERS, 13),
IP::_55 => self.write_register(Register::APERS, 14),
IP::_60 => self.write_register(Register::APERS, 15),
IP::Every => self.write_register(Register::APERS, 0).await,
IP::_1 => self.write_register(Register::APERS, 1).await,
IP::_2 => self.write_register(Register::APERS, 2).await,
IP::_3 => self.write_register(Register::APERS, 3).await,
IP::_5 => self.write_register(Register::APERS, 4).await,
IP::_10 => self.write_register(Register::APERS, 5).await,
IP::_15 => self.write_register(Register::APERS, 6).await,
IP::_20 => self.write_register(Register::APERS, 7).await,
IP::_25 => self.write_register(Register::APERS, 8).await,
IP::_30 => self.write_register(Register::APERS, 9).await,
IP::_35 => self.write_register(Register::APERS, 10).await,
IP::_40 => self.write_register(Register::APERS, 11).await,
IP::_45 => self.write_register(Register::APERS, 12).await,
IP::_50 => self.write_register(Register::APERS, 13).await,
IP::_55 => self.write_register(Register::APERS, 14).await,
IP::_60 => self.write_register(Register::APERS, 15).await,
}
}

fn write_register(&mut self, register: u8, value: u8) -> Result<(), Error<E>> {
async fn write_register(&mut self, register: u8, value: u8) -> Result<(), Error<E>> {
let command = BitFlags::CMD | register;
self.i2c
.write(DEVICE_ADDRESS, &[command, value])
.await
.map_err(Error::I2C)
}

fn write_registers(&mut self, register: u8, value0: u8, value1: u8) -> Result<(), Error<E>> {
async fn write_registers(
&mut self,
register: u8,
value0: u8,
value1: u8,
) -> Result<(), Error<E>> {
let command = BitFlags::CMD | BitFlags::CMD_AUTO_INC | register;
self.i2c
.write(DEVICE_ADDRESS, &[command, value0, value1])
.await
.map_err(Error::I2C)
}
}
36 changes: 30 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,39 @@
//! sensor.set_rgbc_interrupt_persistence(RgbCInterruptPersistence::_5).unwrap();
//! sensor.enable_rgbc_interrupts().unwrap();
//! ```
//!
//! ### Using async driver
//!
//! Enable `async` feature in Cargo.toml:
//! ```toml
//! tcs3472 = { version = "", features = ["async"] };
//! ```
//!
//! Using async driver with [Embassy](https://embassy.dev/) framework:
//! ```no_run
//! #[embassy_executor::main]
//! async fn main(_spawner: Spawner) {
//! let p = embassy_stm32::init(Default::default());
//! let mut i2c = I2c::new(..);
//! let mut sensor = Tcs3472::new(i2c);
//! sensor.enable().await.unwrap();
//! sensor.enable_rgbc().await.unwrap();
//! while !sensor.is_rgbc_status_valid().await.unwrap() {
//! // wait for measurement to be available
//! };
//!
//! let measurement = sensor.read_all_channels().await.unwrap();
//!
//! defmt::info!("Measurements: clear = {}, red = {}, green = {}, blue = {}",
//! measurement.clear, measurement.red, measurement.green,
//! measurement.blue);
//! }
//! ```


#![deny(unsafe_code, missing_docs)]
#![no_std]

use embedded_hal::blocking::i2c;

mod configuration;
mod interface;
use crate::interface::{BitFlags, Register, DEVICE_ADDRESS};
Expand All @@ -170,10 +197,7 @@ pub struct Tcs3472<I2C> {
enable: u8,
}

impl<I2C, E> Tcs3472<I2C>
where
I2C: i2c::Write<Error = E>,
{
impl<I2C> Tcs3472<I2C> {
/// Create new instance of the TCS3472 device.
pub fn new(i2c: I2C) -> Self {
Tcs3472 { i2c, enable: 0 }
Expand Down
Loading
Loading