embassy/embassy-stm32/src/i2c/v1.rs

539 lines
15 KiB
Rust
Raw Normal View History

2021-05-25 18:47:07 +00:00
use core::marker::PhantomData;
2022-06-12 20:15:44 +00:00
2022-07-09 00:28:05 +00:00
use embassy_embedded_hal::SetConfig;
2022-10-24 19:34:10 +00:00
use embassy_hal_common::{into_ref, PeripheralRef};
2021-05-25 18:47:07 +00:00
2022-10-24 19:34:10 +00:00
use crate::dma::NoDma;
use crate::gpio::sealed::AFType;
2022-08-09 19:13:35 +00:00
use crate::gpio::Pull;
use crate::i2c::{Error, Instance, SclPin, SdaPin};
2021-05-25 18:47:07 +00:00
use crate::pac::i2c;
use crate::time::Hertz;
use crate::{interrupt, Peripheral};
/// Interrupt handler.
pub struct InterruptHandler<T: Instance> {
_phantom: PhantomData<T>,
}
impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
unsafe fn on_interrupt() {}
}
2021-05-25 18:47:07 +00:00
2022-08-09 19:13:35 +00:00
#[non_exhaustive]
#[derive(Copy, Clone)]
pub struct Config {
pub sda_pullup: bool,
pub scl_pullup: bool,
2022-08-09 19:13:35 +00:00
}
impl Default for Config {
fn default() -> Self {
Self {
sda_pullup: false,
scl_pullup: false,
}
2022-08-09 19:13:35 +00:00
}
}
pub struct State {}
impl State {
pub(crate) const fn new() -> Self {
Self {}
}
}
2022-10-24 19:34:10 +00:00
pub struct I2c<'d, T: Instance, TXDMA = NoDma, RXDMA = NoDma> {
2021-05-25 18:47:07 +00:00
phantom: PhantomData<&'d mut T>,
2022-10-24 19:34:10 +00:00
#[allow(dead_code)]
tx_dma: PeripheralRef<'d, TXDMA>,
#[allow(dead_code)]
rx_dma: PeripheralRef<'d, RXDMA>,
2021-05-25 18:47:07 +00:00
}
2022-10-24 19:34:10 +00:00
impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
pub fn new(
_peri: impl Peripheral<P = T> + 'd,
scl: impl Peripheral<P = impl SclPin<T>> + 'd,
sda: impl Peripheral<P = impl SdaPin<T>> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
2022-10-24 19:34:10 +00:00
tx_dma: impl Peripheral<P = TXDMA> + 'd,
rx_dma: impl Peripheral<P = RXDMA> + 'd,
freq: Hertz,
2022-08-09 19:13:35 +00:00
config: Config,
) -> Self {
2022-10-24 19:34:10 +00:00
into_ref!(scl, sda, tx_dma, rx_dma);
2021-05-25 18:47:07 +00:00
T::enable();
2022-03-17 22:46:46 +00:00
T::reset();
2023-06-19 01:07:26 +00:00
scl.set_as_af_pull(
scl.af_num(),
AFType::OutputOpenDrain,
match config.scl_pullup {
true => Pull::Up,
false => Pull::None,
},
);
sda.set_as_af_pull(
sda.af_num(),
AFType::OutputOpenDrain,
match config.sda_pullup {
true => Pull::Up,
false => Pull::None,
},
);
2021-05-25 18:47:07 +00:00
2023-06-19 01:07:26 +00:00
T::regs().cr1().modify(|reg| {
reg.set_pe(false);
//reg.set_anfoff(false);
});
2021-05-25 18:47:07 +00:00
let timings = Timings::new(T::frequency(), freq.into());
2021-05-25 18:47:07 +00:00
2023-06-19 01:07:26 +00:00
T::regs().cr2().modify(|reg| {
reg.set_freq(timings.freq);
});
T::regs().ccr().modify(|reg| {
reg.set_f_s(timings.mode.f_s());
reg.set_duty(timings.duty.duty());
reg.set_ccr(timings.ccr);
});
T::regs().trise().modify(|reg| {
reg.set_trise(timings.trise);
});
2021-05-25 18:47:07 +00:00
2023-06-19 01:07:26 +00:00
T::regs().cr1().modify(|reg| {
reg.set_pe(true);
});
2021-05-25 18:47:07 +00:00
2022-10-24 19:34:10 +00:00
Self {
phantom: PhantomData,
tx_dma,
rx_dma,
}
2021-05-25 18:47:07 +00:00
}
2023-06-19 01:07:26 +00:00
fn check_and_clear_error_flags(&self) -> Result<i2c::regs::Sr1, Error> {
2021-05-25 18:47:07 +00:00
// Note that flags should only be cleared once they have been registered. If flags are
// cleared otherwise, there may be an inherent race condition and flags may be missed.
let sr1 = T::regs().sr1().read();
if sr1.timeout() {
T::regs().sr1().modify(|reg| reg.set_timeout(false));
return Err(Error::Timeout);
}
if sr1.pecerr() {
T::regs().sr1().modify(|reg| reg.set_pecerr(false));
return Err(Error::Crc);
}
if sr1.ovr() {
T::regs().sr1().modify(|reg| reg.set_ovr(false));
return Err(Error::Overrun);
}
if sr1.af() {
T::regs().sr1().modify(|reg| reg.set_af(false));
return Err(Error::Nack);
}
if sr1.arlo() {
T::regs().sr1().modify(|reg| reg.set_arlo(false));
return Err(Error::Arbitration);
}
// The errata indicates that BERR may be incorrectly detected. It recommends ignoring and
// clearing the BERR bit instead.
if sr1.berr() {
T::regs().sr1().modify(|reg| reg.set_berr(false));
}
Ok(sr1)
}
2023-06-19 01:07:26 +00:00
fn write_bytes(
2022-10-24 08:30:04 +00:00
&mut self,
addr: u8,
bytes: &[u8],
check_timeout: impl Fn() -> Result<(), Error>,
) -> Result<(), Error> {
2021-05-25 18:47:07 +00:00
// Send a START condition
T::regs().cr1().modify(|reg| {
2022-02-14 01:12:06 +00:00
reg.set_start(true);
2021-05-25 18:47:07 +00:00
});
// Wait until START condition was generated
2022-10-24 08:30:04 +00:00
while !self.check_and_clear_error_flags()?.start() {
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
// Also wait until signalled we're master and everything is waiting for us
while {
self.check_and_clear_error_flags()?;
let sr2 = T::regs().sr2().read();
!sr2.msl() && !sr2.busy()
2022-10-24 08:30:04 +00:00
} {
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
// Set up current address, we're trying to talk to
T::regs().dr().write(|reg| reg.set_dr(addr << 1));
// Wait until address was sent
2022-02-14 01:12:06 +00:00
// Wait for the address to be acknowledged
// Check for any I2C errors. If a NACK occurs, the ADDR bit will never be set.
2022-10-24 08:30:04 +00:00
while !self.check_and_clear_error_flags()?.addr() {
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
// Clear condition by reading SR2
let _ = T::regs().sr2().read();
// Send bytes
for c in bytes {
2022-10-24 08:30:04 +00:00
self.send_byte(*c, &check_timeout)?;
2021-05-25 18:47:07 +00:00
}
// Fallthrough is success
Ok(())
}
2023-06-19 01:07:26 +00:00
fn send_byte(&self, byte: u8, check_timeout: impl Fn() -> Result<(), Error>) -> Result<(), Error> {
2021-05-25 18:47:07 +00:00
// Wait until we're ready for sending
while {
// Check for any I2C errors. If a NACK occurs, the ADDR bit will never be set.
2022-02-14 01:12:06 +00:00
!self.check_and_clear_error_flags()?.txe()
2022-10-24 08:30:04 +00:00
} {
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
// Push out a byte of data
T::regs().dr().write(|reg| reg.set_dr(byte));
// Wait until byte is transferred
while {
// Check for any potential error conditions.
!self.check_and_clear_error_flags()?.btf()
2022-10-24 08:30:04 +00:00
} {
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
Ok(())
}
2023-06-19 01:07:26 +00:00
fn recv_byte(&self, check_timeout: impl Fn() -> Result<(), Error>) -> Result<u8, Error> {
2021-05-25 18:47:07 +00:00
while {
// Check for any potential error conditions.
self.check_and_clear_error_flags()?;
2022-02-14 01:12:06 +00:00
!T::regs().sr1().read().rxne()
2022-10-24 08:30:04 +00:00
} {
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
let value = T::regs().dr().read().dr();
Ok(value)
}
2022-10-24 08:30:04 +00:00
pub fn blocking_read_timeout(
&mut self,
addr: u8,
buffer: &mut [u8],
check_timeout: impl Fn() -> Result<(), Error>,
) -> Result<(), Error> {
2021-05-25 18:47:07 +00:00
if let Some((last, buffer)) = buffer.split_last_mut() {
// Send a START condition and set ACK bit
2023-06-19 01:07:26 +00:00
T::regs().cr1().modify(|reg| {
reg.set_start(true);
reg.set_ack(true);
});
2021-05-25 18:47:07 +00:00
// Wait until START condition was generated
2023-06-19 01:07:26 +00:00
while !self.check_and_clear_error_flags()?.start() {
2022-10-24 08:30:04 +00:00
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
// Also wait until signalled we're master and everything is waiting for us
while {
2023-06-19 01:07:26 +00:00
let sr2 = T::regs().sr2().read();
2021-05-25 18:47:07 +00:00
!sr2.msl() && !sr2.busy()
2022-10-24 08:30:04 +00:00
} {
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
// Set up current address, we're trying to talk to
2023-06-19 01:07:26 +00:00
T::regs().dr().write(|reg| reg.set_dr((addr << 1) + 1));
2021-05-25 18:47:07 +00:00
// Wait until address was sent
2022-02-14 01:12:06 +00:00
// Wait for the address to be acknowledged
2023-06-19 01:07:26 +00:00
while !self.check_and_clear_error_flags()?.addr() {
2022-10-24 08:30:04 +00:00
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
// Clear condition by reading SR2
2023-06-19 01:07:26 +00:00
let _ = T::regs().sr2().read();
2021-05-25 18:47:07 +00:00
// Receive bytes into buffer
for c in buffer {
2023-06-19 01:07:26 +00:00
*c = self.recv_byte(&check_timeout)?;
2021-05-25 18:47:07 +00:00
}
// Prepare to send NACK then STOP after next byte
2023-06-19 01:07:26 +00:00
T::regs().cr1().modify(|reg| {
reg.set_ack(false);
reg.set_stop(true);
});
2021-05-25 18:47:07 +00:00
// Receive last byte
2023-06-19 01:07:26 +00:00
*last = self.recv_byte(&check_timeout)?;
2021-05-25 18:47:07 +00:00
// Wait for the STOP to be sent.
2023-06-19 01:07:26 +00:00
while T::regs().cr1().read().stop() {
2022-10-24 08:30:04 +00:00
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
// Fallthrough is success
Ok(())
} else {
Err(Error::Overrun)
}
}
2023-04-06 20:25:24 +00:00
pub fn blocking_read(&mut self, addr: u8, read: &mut [u8]) -> Result<(), Error> {
self.blocking_read_timeout(addr, read, || Ok(()))
2022-10-24 08:30:04 +00:00
}
pub fn blocking_write_timeout(
&mut self,
addr: u8,
2023-04-06 20:25:24 +00:00
write: &[u8],
2022-10-24 08:30:04 +00:00
check_timeout: impl Fn() -> Result<(), Error>,
) -> Result<(), Error> {
2023-06-19 01:07:26 +00:00
self.write_bytes(addr, write, &check_timeout)?;
// Send a STOP condition
T::regs().cr1().modify(|reg| reg.set_stop(true));
// Wait for STOP condition to transmit.
while T::regs().cr1().read().stop() {
check_timeout()?;
}
2021-05-25 18:47:07 +00:00
// Fallthrough is success
Ok(())
}
2023-04-06 20:25:24 +00:00
pub fn blocking_write(&mut self, addr: u8, write: &[u8]) -> Result<(), Error> {
self.blocking_write_timeout(addr, write, || Ok(()))
2022-10-24 08:30:04 +00:00
}
pub fn blocking_write_read_timeout(
&mut self,
addr: u8,
2023-04-06 20:25:24 +00:00
write: &[u8],
read: &mut [u8],
2022-10-24 08:30:04 +00:00
check_timeout: impl Fn() -> Result<(), Error>,
) -> Result<(), Error> {
2023-06-19 01:07:26 +00:00
self.write_bytes(addr, write, &check_timeout)?;
2023-04-06 20:25:24 +00:00
self.blocking_read_timeout(addr, read, &check_timeout)?;
Ok(())
}
2022-10-24 08:30:04 +00:00
2023-04-06 20:25:24 +00:00
pub fn blocking_write_read(&mut self, addr: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> {
self.blocking_write_read_timeout(addr, write, read, || Ok(()))
2022-10-24 08:30:04 +00:00
}
2021-05-25 18:47:07 +00:00
}
impl<'d, T: Instance> embedded_hal_02::blocking::i2c::Read for I2c<'d, T> {
2021-05-25 18:47:07 +00:00
type Error = Error;
2023-04-06 20:25:24 +00:00
fn read(&mut self, addr: u8, read: &mut [u8]) -> Result<(), Self::Error> {
self.blocking_read(addr, read)
}
}
2021-05-25 18:47:07 +00:00
impl<'d, T: Instance> embedded_hal_02::blocking::i2c::Write for I2c<'d, T> {
type Error = Error;
2023-04-06 20:25:24 +00:00
fn write(&mut self, addr: u8, write: &[u8]) -> Result<(), Self::Error> {
self.blocking_write(addr, write)
}
}
impl<'d, T: Instance> embedded_hal_02::blocking::i2c::WriteRead for I2c<'d, T> {
type Error = Error;
2023-04-06 20:25:24 +00:00
fn write_read(&mut self, addr: u8, write: &[u8], read: &mut [u8]) -> Result<(), Self::Error> {
self.blocking_write_read(addr, write, read)
2021-05-25 18:47:07 +00:00
}
}
2022-07-06 21:25:38 +00:00
#[cfg(feature = "unstable-traits")]
mod eh1 {
use super::*;
impl embedded_hal_1::i2c::Error for Error {
fn kind(&self) -> embedded_hal_1::i2c::ErrorKind {
match *self {
Self::Bus => embedded_hal_1::i2c::ErrorKind::Bus,
Self::Arbitration => embedded_hal_1::i2c::ErrorKind::ArbitrationLoss,
Self::Nack => {
embedded_hal_1::i2c::ErrorKind::NoAcknowledge(embedded_hal_1::i2c::NoAcknowledgeSource::Unknown)
}
Self::Timeout => embedded_hal_1::i2c::ErrorKind::Other,
Self::Crc => embedded_hal_1::i2c::ErrorKind::Other,
Self::Overrun => embedded_hal_1::i2c::ErrorKind::Overrun,
Self::ZeroLengthTransfer => embedded_hal_1::i2c::ErrorKind::Other,
}
}
}
2022-07-06 21:56:44 +00:00
impl<'d, T: Instance> embedded_hal_1::i2c::ErrorType for I2c<'d, T> {
2022-07-06 21:25:38 +00:00
type Error = Error;
}
impl<'d, T: Instance> embedded_hal_1::i2c::I2c for I2c<'d, T> {
2023-04-06 20:25:24 +00:00
fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> {
self.blocking_read(address, read)
2022-07-06 21:25:38 +00:00
}
2023-04-06 20:25:24 +00:00
fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> {
self.blocking_write(address, write)
2022-07-06 21:25:38 +00:00
}
2023-04-06 20:25:24 +00:00
fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Self::Error> {
self.blocking_write_read(address, write, read)
2022-07-06 21:25:38 +00:00
}
2023-04-06 20:25:24 +00:00
fn transaction(
2022-07-06 21:25:38 +00:00
&mut self,
_address: u8,
2023-04-06 20:25:24 +00:00
_operations: &mut [embedded_hal_1::i2c::Operation<'_>],
2022-07-06 21:25:38 +00:00
) -> Result<(), Self::Error> {
todo!();
}
}
}
2021-05-25 18:47:07 +00:00
enum Mode {
Fast,
Standard,
}
impl Mode {
fn f_s(&self) -> i2c::vals::FS {
match self {
Mode::Fast => i2c::vals::FS::FAST,
Mode::Standard => i2c::vals::FS::STANDARD,
}
}
}
enum Duty {
Duty2_1,
Duty16_9,
}
impl Duty {
fn duty(&self) -> i2c::vals::Duty {
match self {
Duty::Duty2_1 => i2c::vals::Duty::DUTY2_1,
Duty::Duty16_9 => i2c::vals::Duty::DUTY16_9,
}
}
}
struct Timings {
freq: u8,
mode: Mode,
trise: u8,
ccr: u16,
duty: Duty,
}
impl Timings {
fn new(i2cclk: Hertz, speed: Hertz) -> Self {
// Calculate settings for I2C speed modes
let speed = speed.0;
let clock = i2cclk.0;
let freq = clock / 1_000_000;
assert!(freq >= 2 && freq <= 50);
// Configure bus frequency into I2C peripheral
let trise = if speed <= 100_000 {
freq + 1
} else {
(freq * 300) / 1000 + 1
};
let mut ccr;
let duty;
let mode;
// I2C clock control calculation
if speed <= 100_000 {
duty = Duty::Duty2_1;
mode = Mode::Standard;
ccr = {
let ccr = clock / (speed * 2);
if ccr < 4 {
4
} else {
ccr
}
};
} else {
const DUTYCYCLE: u8 = 0;
mode = Mode::Fast;
if DUTYCYCLE == 0 {
duty = Duty::Duty2_1;
ccr = clock / (speed * 3);
ccr = if ccr < 1 { 1 } else { ccr };
// Set clock to fast mode with appropriate parameters for selected speed (2:1 duty cycle)
} else {
duty = Duty::Duty16_9;
ccr = clock / (speed * 25);
ccr = if ccr < 1 { 1 } else { ccr };
// Set clock to fast mode with appropriate parameters for selected speed (16:9 duty cycle)
}
}
Self {
freq: freq as u8,
trise: trise as u8,
ccr: ccr as u16,
duty,
mode,
//prescale: presc_reg,
//scll,
//sclh,
//sdadel,
//scldel,
}
}
}
2022-07-09 00:28:05 +00:00
impl<'d, T: Instance> SetConfig for I2c<'d, T> {
type Config = Hertz;
fn set_config(&mut self, config: &Self::Config) {
let timings = Timings::new(T::frequency(), *config);
2023-06-19 01:07:26 +00:00
T::regs().cr2().modify(|reg| {
reg.set_freq(timings.freq);
});
T::regs().ccr().modify(|reg| {
reg.set_f_s(timings.mode.f_s());
reg.set_duty(timings.duty.duty());
reg.set_ccr(timings.ccr);
});
T::regs().trise().modify(|reg| {
reg.set_trise(timings.trise);
});
2022-07-09 00:28:05 +00:00
}
}