1use core::future::{poll_fn, Future};
4use core::marker::PhantomData;
5use core::pin::Pin;
6use core::task::Poll;
7
8use embassy_futures::select::{select, Either};
9use embassy_sync::waitqueue::AtomicWaker;
10use embedded_hal::i2c::Operation;
11
12use crate::dma::ChannelAndRequest;
13use crate::gpio::{AfType, AnyPin, OutputType, SealedPin, Speed};
14use crate::internal::drop::OnDrop;
15use crate::mode::{Async, Blocking, Mode};
16use crate::time::Hertz;
18use crate::{interrupt, peripherals, Peri, Timeout};
19
20mod slave;
21
22pub mod mode {
24 trait SealedMode {}
25
26 #[allow(private_bounds)]
28 pub trait OperatingMode: SealedMode {}
29
30 pub struct Master;
32
33 pub struct Slave;
35
36 impl SealedMode for Master {}
37 impl OperatingMode for Master {}
38
39 impl SealedMode for Slave {}
40 impl OperatingMode for Slave {}
41}
42
43use mode::{Master, OperatingMode, Slave};
44
45pub struct EventInterruptHandler<T: Instance> {
47 _phantom: PhantomData<T>,
48}
49
50impl<T: Instance> interrupt::typelevel::Handler<T::EventInterrupt> for EventInterruptHandler<T> {
51 unsafe fn on_interrupt() {
52 on_interrupt::<T>()
53 }
54}
55
56pub struct ErrorInterruptHandler<T: Instance> {
58 _phantom: PhantomData<T>,
59}
60
61impl<T: Instance> interrupt::typelevel::Handler<T::ErrorInterrupt> for ErrorInterruptHandler<T> {
62 unsafe fn on_interrupt() {
63 on_interrupt::<T>()
64 }
65}
66
67pub unsafe fn on_interrupt<T: Instance>() {
68 let regs = T::regs();
69 T::state().waker.wake();
72 critical_section::with(|_| {
73 regs.ctlr2().modify(|w| {
75 w.set_itevten(false);
76 w.set_iterren(false);
77 w.set_itbufen(false);
80 });
81 });
82}
83
84#[derive(Debug, PartialEq, Eq)]
86#[cfg_attr(feature = "defmt", derive(defmt::Format))]
87pub enum Error {
88 Bus,
90 Arbitration,
92 Nack,
94 Timeout,
96 Crc,
98 Overrun,
100 ZeroLengthTransfer,
102 BufferTooLong,
104 InvalidAddress,
107}
108
109#[derive(Copy, Clone, Debug, PartialEq, Eq)]
111#[cfg_attr(feature = "defmt", derive(defmt::Format))]
112pub enum SlaveAddress {
113 SevenBit(u8),
115 TenBit(u16),
117}
118
119#[non_exhaustive]
121#[derive(Copy, Clone, Debug)]
122#[cfg_attr(feature = "defmt", derive(defmt::Format))]
123pub struct SlaveConfig {
124 pub address: SlaveAddress,
126 pub second_address: Option<u8>,
128 pub general_call: bool,
130 pub clock_stretching: bool,
132}
133
134impl SlaveConfig {
135 pub fn new(address: impl Into<SlaveAddress>) -> Self {
140 Self {
141 address: address.into(),
142 second_address: None,
143 general_call: false,
144 clock_stretching: true,
145 }
146 }
147
148 fn validate(&self) -> Result<(), Error> {
149 match self.address {
150 SlaveAddress::SevenBit(addr) => {
151 if addr > 0x7f || (addr == 0x00 && !self.general_call) {
152 return Err(Error::InvalidAddress);
153 }
154 }
155 SlaveAddress::TenBit(addr) => {
156 if addr > 0x3ff {
157 return Err(Error::InvalidAddress);
158 }
159 }
160 }
161
162 if let Some(addr2) = self.second_address {
163 if addr2 > 0x7f || matches!(self.address, SlaveAddress::TenBit(_)) {
166 return Err(Error::InvalidAddress);
167 }
168 }
169
170 Ok(())
171 }
172}
173
174impl Default for SlaveConfig {
175 fn default() -> Self {
176 Self::new(SlaveAddress::SevenBit(0x55))
177 }
178}
179
180impl From<u8> for SlaveAddress {
185 fn from(value: u8) -> Self {
186 Self::SevenBit(value)
187 }
188}
189
190#[derive(Copy, Clone, Debug, PartialEq, Eq)]
192#[cfg_attr(feature = "defmt", derive(defmt::Format))]
193pub enum SlaveCommandKind {
194 GeneralCall,
196 Read,
198 Write,
200}
201
202#[derive(Copy, Clone, Debug, PartialEq, Eq)]
204#[cfg_attr(feature = "defmt", derive(defmt::Format))]
205pub struct SlaveCommand {
206 pub kind: SlaveCommandKind,
208 pub address: SlaveAddress,
210}
211
212#[derive(Copy, Clone, Debug, PartialEq, Eq)]
214#[cfg_attr(feature = "defmt", derive(defmt::Format))]
215pub enum SendStatus {
216 Done,
218 LeftoverBytes(usize),
220}
221
222#[derive(Copy, Clone, PartialEq, Eq)]
223pub enum Duty {
224 Duty2_1 = 0,
225 Duty16_9 = 1,
226}
227
228#[non_exhaustive]
230#[derive(Copy, Clone)]
231pub struct Config {
232 #[cfg(feature = "embassy")]
234 pub timeout: embassy_time::Duration,
235 pub duty: Duty,
236}
237
238impl Default for Config {
239 fn default() -> Self {
240 Self {
241 #[cfg(feature = "embassy")]
242 timeout: embassy_time::Duration::from_millis(1000),
243 duty: Duty::Duty2_1,
244 }
245 }
246}
247
248struct Timing {
249 input_mhz: u8,
250 #[cfg(i2c_v3)]
251 rise: u8,
252 divider: u16,
253 fast: bool,
254 duty: bool,
255}
256
257fn timing(input: Hertz, frequency: Hertz, duty: Duty) -> Timing {
258 assert!(frequency.0 > 0 && frequency.0 <= 400_000);
259 let fast = frequency.0 > 100_000;
260 let input_mhz = input.0 / 1_000_000;
266 #[cfg(ch32v4)]
267 assert!(input_mhz >= 4);
268 #[cfg(ch32v4)]
269 let input_mhz = input_mhz.min(60);
270 let factor = if !fast {
271 2
272 } else if duty == Duty::Duty2_1 {
273 3
274 } else {
275 25
276 };
277 let divider = u64::from(input.0).div_ceil(u64::from(frequency.0) * factor);
278 let divider = divider.max(if fast { 1 } else { 4 });
279 assert!(divider <= 0xfff);
280 Timing {
281 input_mhz: input_mhz as u8,
282 #[cfg(i2c_v3)]
283 rise: (if fast {
284 input_mhz * 300 / 1000 + 1
285 } else {
286 input_mhz + 1
287 }) as u8,
288 divider: divider as u16,
289 fast,
290 duty: fast && duty == Duty::Duty16_9,
291 }
292}
293
294pub struct I2c<'d, T: Instance, M: Mode, O: OperatingMode = Master> {
299 tx_dma: Option<ChannelAndRequest<'d>>,
300 rx_dma: Option<ChannelAndRequest<'d>>,
301 #[cfg(feature = "embassy")]
302 timeout: embassy_time::Duration,
303 pins: I2cPins<'d, T>,
304 _phantom: PhantomData<(M, O)>,
305}
306
307struct I2cPins<'d, T: Instance> {
310 scl: Peri<'d, AnyPin>,
311 sda: Peri<'d, AnyPin>,
312 _phantom: PhantomData<&'d mut T>,
313}
314
315impl<'d, T: Instance> Drop for I2cPins<'d, T> {
316 fn drop(&mut self) {
317 use crate::interrupt::typelevel::Interrupt;
318
319 T::regs().ctlr2().modify(|w| {
320 w.set_dmaen(false);
321 w.set_iterren(false);
322 w.set_itevten(false);
323 w.set_itbufen(false);
324 });
325 T::regs().ctlr1().modify(|w| w.set_pe(false));
326 T::EventInterrupt::disable();
327 T::ErrorInterrupt::disable();
328 self.scl.set_as_disconnected();
329 self.sda.set_as_disconnected();
330 T::disable();
331 }
332}
333
334impl<'d, T: Instance> I2c<'d, T, Async, Master> {
335 async fn wait_status(mask: u32) -> Result<(), Error> {
336 poll_fn(|cx| {
337 T::state().waker.register(cx.waker());
338 match Self::check_and_clear_error_flags() {
339 Err(error) => Poll::Ready(Err(error)),
340 Ok(status) if status.0 & mask != 0 => Poll::Ready(Ok(())),
341 Ok(_) => {
342 T::regs().ctlr2().modify(|w| {
343 w.set_itbufen(mask == (1 << 6));
344 w.set_iterren(true);
345 w.set_itevten(true);
346 });
347 Poll::Pending
348 }
349 }
350 })
351 .await
352 }
353
354 async fn wait_stop_async() {
355 poll_fn(|cx| {
356 if T::regs().ctlr1().read().stop() {
357 cx.waker().wake_by_ref();
358 Poll::Pending
359 } else {
360 Poll::Ready(())
361 }
362 })
363 .await
364 }
365
366 async fn launch_start_async(ack: bool) -> Result<(), Error> {
367 Self::wait_stop_async().await;
368 if T::regs().ctlr1().read().start() || T::regs().star1().read().sb() {
369 return Ok(());
370 }
371 T::regs().ctlr1().modify(|w| {
372 w.set_start(true);
373 w.set_ack(ack);
374 w.set_pos(false);
375 });
376 Ok(())
377 }
378
379 pub fn new<#[cfg(not(afio_h4))] const REMAP: u8>(
381 peri: Peri<'d, T>,
382 scl: Peri<'d, if_remap!(impl SclPin<T, REMAP>)>,
383 sda: Peri<'d, if_remap!(impl SdaPin<T, REMAP>)>,
384 _irq: impl interrupt::typelevel::Binding<T::EventInterrupt, EventInterruptHandler<T>>
385 + interrupt::typelevel::Binding<T::ErrorInterrupt, ErrorInterruptHandler<T>>
386 + 'd,
387 tx_dma: Peri<'d, impl TxDma<T>>,
388 rx_dma: Peri<'d, impl RxDma<T>>,
389 freq: Hertz,
390 config: Config,
391 ) -> Self {
392 Self::new_inner(peri, scl, sda, new_dma!(tx_dma), new_dma!(rx_dma), freq, config)
393 }
394}
395
396impl<'d, T: Instance> I2c<'d, T, Blocking, Master> {
397 pub fn new_blocking<#[cfg(not(afio_h4))] const REMAP: u8>(
399 peri: Peri<'d, T>,
400 scl: Peri<'d, if_remap!(impl SclPin<T, REMAP>)>,
401 sda: Peri<'d, if_remap!(impl SdaPin<T, REMAP>)>,
402 freq: Hertz,
403 config: Config,
404 ) -> Self {
405 Self::new_inner(peri, scl, sda, None, None, freq, config)
406 }
407}
408
409impl<'d, T: Instance, M: Mode> I2c<'d, T, M, Master> {
410 fn new_inner<#[cfg(not(afio_h4))] const REMAP: u8>(
412 _peri: Peri<'d, T>,
413 scl: Peri<'d, if_remap!(impl SclPin<T, REMAP>)>,
414 sda: Peri<'d, if_remap!(impl SdaPin<T, REMAP>)>,
415 tx_dma: Option<ChannelAndRequest<'d>>,
416 rx_dma: Option<ChannelAndRequest<'d>>,
417 freq: Hertz,
418 config: Config,
419 ) -> Self {
420 let timing = timing(T::frequency(), freq, config.duty);
421 apply_remap!();
422 use crate::interrupt::typelevel::Interrupt;
423
424 T::enable_and_reset();
425
426 #[cfg(not(gpio_x0))]
429 let af = AfType::output(OutputType::OpenDrain, Speed::High);
430 #[cfg(gpio_x0)]
431 let af = AfType::output(OutputType::PushPull, Speed::High);
432
433 set_as_af!(scl, af);
434 set_as_af!(sda, af);
435
436 let mut this = Self {
437 tx_dma,
438 rx_dma,
439 #[cfg(feature = "embassy")]
440 timeout: config.timeout,
441 pins: I2cPins {
442 scl: scl.into(),
443 sda: sda.into(),
444 _phantom: PhantomData,
445 },
446 _phantom: PhantomData,
447 };
448
449 this.init(timing);
450 T::EventInterrupt::unpend();
451 T::ErrorInterrupt::unpend();
452 if this.tx_dma.is_some() {
453 unsafe { T::EventInterrupt::enable() };
454 unsafe { T::ErrorInterrupt::enable() };
455 }
456
457 this
458 }
459}
460
461impl<'d, T: Instance, M: Mode, O: OperatingMode> I2c<'d, T, M, O> {
462 fn timeout(&self) -> Timeout {
463 Timeout {
464 #[cfg(feature = "embassy")]
465 deadline: embassy_time::Instant::now() + self.timeout,
466 }
467 }
468
469 fn clear_error(mask: u16) {
470 T::regs()
471 .star1()
472 .write_value(crate::pac::i2c::regs::Star1(u32::from(!mask)));
473 }
474
475 fn clear_stopf() {
477 let _ = T::regs().star1().read();
478 T::regs().ctlr1().modify(|_| {});
479 }
480
481 fn clear_af() {
483 T::regs().star1().modify(|w| w.set_af(false));
484 }
485
486 fn slave_handle_errors(status: &crate::pac::i2c::regs::Star1) -> Result<(), Error> {
488 let observed = (status.0 & 0x5f00) as u16;
491 if observed != 0 {
492 Self::clear_error(observed);
493 }
494
495 if status.arlo() {
496 return Err(Error::Arbitration);
497 }
498 #[cfg(i2c_v3)]
499 if status.timeout() {
500 return Err(Error::Timeout);
501 }
502 if status.pecerr() {
503 return Err(Error::Crc);
504 }
505 if status.ovr() {
506 return Err(Error::Overrun);
507 }
508 #[cfg(ch32v4)]
509 if status.berr() {
510 return Err(Error::Bus);
511 }
512 Ok(())
513 }
514
515 fn clear_slave_stale_flags() {
517 Self::clear_stopf();
518 let status = T::regs().star1().read();
519 let observed = (status.0 & 0x5f00) as u16;
520 if observed != 0 {
521 Self::clear_error(observed);
522 }
523 }
524
525 fn decode_slave_address(star2: crate::pac::i2c::regs::Star2) -> SlaveAddress {
527 if star2.gencall() {
528 return SlaveAddress::SevenBit(0x00);
529 }
530 if star2.dualf() {
531 return SlaveAddress::SevenBit(T::regs().oaddr2().read().add2());
532 }
533
534 let oaddr1 = T::regs().oaddr1().read();
535 if oaddr1.addmode() {
536 let add0 = if oaddr1.add0() { 1 } else { 0 };
537 SlaveAddress::TenBit((u16::from(oaddr1.add9_8()) << 8) | (u16::from(oaddr1.add7_1()) << 1) | add0)
538 } else {
539 SlaveAddress::SevenBit(oaddr1.add7_1())
540 }
541 }
542
543 fn send_status(total: usize, sent: usize) -> SendStatus {
544 let data_sent = sent.min(total);
545 if data_sent >= total {
546 SendStatus::Done
547 } else {
548 SendStatus::LeftoverBytes(total - data_sent)
549 }
550 }
551
552 fn dma_bytes_sent(total: usize, remaining: u16, tx_e: bool) -> usize {
555 let loaded = total.saturating_sub(remaining as usize);
556 if !tx_e && loaded > 0 {
557 loaded - 1
558 } else {
559 loaded
560 }
561 }
562
563 fn init_slave(config: SlaveConfig) {
565 let regs = T::regs();
566
567 regs.ctlr1().modify(|w| w.set_pe(false));
569 regs.ctlr2().modify(|w| w.set_itbufen(false));
570
571 match config.address {
572 SlaveAddress::SevenBit(addr) => regs.oaddr1().write(|w| {
573 w.set_addmode(false);
574 w.set_must1(true);
576 w.set_add7_1(addr);
577 }),
578 SlaveAddress::TenBit(addr) => regs.oaddr1().write(|w| {
579 w.set_addmode(true);
580 w.set_must1(true);
581 w.set_add9_8((addr >> 8) as u8);
582 w.set_add7_1((addr >> 1) as u8);
583 w.set_add0(addr & 0x0001 != 0);
584 }),
585 }
586
587 if let Some(addr2) = config.second_address {
588 regs.oaddr2().write(|w| {
589 w.set_add2(addr2);
590 w.set_endual(true);
591 });
592 } else {
593 regs.oaddr2().write(|w| w.set_endual(false));
594 }
595
596 regs.ctlr1().modify(|w| {
597 w.set_engc(config.general_call);
598 w.set_nostretch(!config.clock_stretching);
599 w.set_ack(true);
600 w.set_pe(true);
601 });
602 }
603
604 fn enable_slave_interrupts(wait_data: bool) {
605 T::regs().ctlr2().modify(|w| {
606 w.set_itevten(true);
607 w.set_iterren(true);
608 w.set_itbufen(wait_data);
609 });
610 }
611
612 fn disable_slave_transfers() {
613 T::regs().ctlr2().modify(|w| {
614 w.set_dmaen(false);
615 w.set_iterren(false);
616 w.set_itevten(false);
617 w.set_itbufen(false);
618 });
619 }
620
621 fn abort_slave_transfer() {
623 Self::disable_slave_transfers();
624 let regs = T::regs();
625 let star2 = regs.star2().read();
626 if star2.busy() && !star2.msl() {
627 regs.ctlr1().modify(|w| w.set_stop(true));
629 }
630 }
631}
632
633impl<'d, T: Instance, M: Mode> I2c<'d, T, M, Master> {
634 fn init(&mut self, timing: Timing) {
636 let regs = T::regs();
637
638 regs.ctlr1().modify(|w| w.set_pe(false)); regs.ctlr1().modify(|w| w.set_swrst(true));
642 regs.ctlr1().modify(|w| w.set_swrst(false));
643
644 regs.ctlr2().modify(|w| w.set_freq(timing.input_mhz));
645 #[cfg(i2c_v3)]
646 regs.rtr().write(|w| w.set_trise(timing.rise));
647 regs.ckcfgr().write(|w| {
648 w.set_f_s(timing.fast);
649 w.set_duty(timing.duty);
650 w.set_ccr(timing.divider);
651 });
652
653 regs.ctlr1().modify(|w| w.set_pe(true));
654 }
655
656 fn generate_stop() {
657 T::regs().ctlr1().modify(|w| w.set_stop(true));
658 }
659
660 fn finish_transfer() {
661 T::regs().ctlr2().modify(|w| {
662 w.set_dmaen(false);
663 w.set_iterren(false);
664 w.set_itevten(false);
665 w.set_itbufen(false);
666 w.set_last(false);
667 });
668 }
669
670 fn abort_transfer() {
671 Self::finish_transfer();
672 let regs = T::regs();
673 let control = regs.ctlr1().read();
674 if control.start() || control.stop() {
675 let frequency = regs.ctlr2().read().freq();
676 let divider = regs.ckcfgr().read();
677 #[cfg(i2c_v3)]
678 let rise = regs.rtr().read();
679 regs.ctlr1().write(|w| w.set_swrst(true));
680 regs.ctlr1().write(|w| w.set_swrst(false));
681 regs.ctlr2().write(|w| w.set_freq(frequency));
682 regs.ckcfgr().write_value(divider);
683 #[cfg(i2c_v3)]
684 regs.rtr().write_value(rise);
685 regs.ctlr1().write(|w| w.set_pe(true));
686 } else if regs.star2().read().msl() {
687 Self::generate_stop();
688 }
689 }
690
691 fn validate_address(address: u8) -> Result<(), Error> {
692 if address > 0x7f {
693 Err(Error::InvalidAddress)
694 } else {
695 Ok(())
696 }
697 }
698
699 fn wait_stop_finished(timeout: Timeout) -> Result<(), Error> {
704 while T::regs().ctlr1().read().stop() {
705 timeout.check().ok_or(Error::Timeout)?;
706 }
707 Ok(())
708 }
709
710 fn launch_start(ack: bool, timeout: Timeout) -> Result<(), Error> {
712 Self::wait_stop_finished(timeout)?;
713 if T::regs().ctlr1().read().start() || T::regs().star1().read().sb() {
714 return Ok(());
715 }
716 T::regs().ctlr1().modify(|reg| {
717 reg.set_start(true);
718 if ack {
719 reg.set_ack(true);
720 }
721 });
722 Ok(())
723 }
724
725 fn check_and_clear_error_flags() -> Result<crate::pac::i2c::regs::Star1, Error> {
726 let status = T::regs().star1().read();
727 let observed = (status.0 & 0x5f00) as u16;
728 if observed != 0 {
729 Self::clear_error(observed);
730 }
731 if status.arlo() {
732 return Err(Error::Arbitration);
733 }
734 #[cfg(i2c_v3)]
735 if status.timeout() {
736 return Err(Error::Timeout);
737 }
738 if status.pecerr() {
739 return Err(Error::Crc);
740 }
741 if status.ovr() {
742 return Err(Error::Overrun);
743 }
744 if status.af() {
745 return Err(Error::Nack);
746 }
747 #[cfg(ch32v4)]
748 if status.berr() {
749 return Err(Error::Bus);
750 }
751 Ok(status)
752 }
753
754 fn write_bytes(&mut self, addr: u8, bytes: &[u8], timeout: Timeout, frame: FrameOptions) -> Result<(), Error> {
755 Self::validate_address(addr)?;
756 let on_drop = OnDrop::new(Self::abort_transfer);
757 if frame.send_start() {
758 Self::launch_start(false, timeout)?;
760
761 while !Self::check_and_clear_error_flags()?.sb() {
763 timeout.check().ok_or(Error::Timeout)?;
764 }
765
766 if T::regs().ctlr1().read().start() || !T::regs().star2().read().msl() {
768 return Err(Error::Arbitration);
769 }
770
771 T::regs().datar().write(|reg| reg.set_datar(addr << 1));
773
774 while !Self::check_and_clear_error_flags()?.addr() {
778 timeout.check().ok_or(Error::Timeout)?;
779 }
780
781 let _ = T::regs().star2().read();
783 }
784
785 for c in bytes {
787 self.send_byte(*c, timeout)?;
788 }
789
790 if frame.send_stop() {
791 T::regs().ctlr1().modify(|reg| reg.set_stop(true));
793 Self::wait_stop_finished(timeout)?;
794 }
795
796 on_drop.defuse();
797 Ok(())
798 }
799
800 fn send_byte(&self, byte: u8, timeout: Timeout) -> Result<(), Error> {
801 while {
803 !Self::check_and_clear_error_flags()?.tx_e()
805 } {
806 timeout.check().ok_or(Error::Timeout)?;
807 }
808
809 T::regs().datar().write(|reg| reg.set_datar(byte));
811
812 while {
814 !Self::check_and_clear_error_flags()?.btf()
816 } {
817 timeout.check().ok_or(Error::Timeout)?;
818 }
819
820 Ok(())
821 }
822
823 fn recv_byte(&self, timeout: Timeout) -> Result<u8, Error> {
824 while {
825 Self::check_and_clear_error_flags()?;
827
828 !T::regs().star1().read().rx_ne()
829 } {
830 timeout.check().ok_or(Error::Timeout)?;
831 }
832
833 let value = T::regs().datar().read().datar();
834 Ok(value)
835 }
836
837 fn blocking_read_timeout(
838 &mut self,
839 addr: u8,
840 buffer: &mut [u8],
841 timeout: Timeout,
842 frame: FrameOptions,
843 ) -> Result<(), Error> {
844 let length = buffer.len();
845 self.blocking_read_iter(addr, buffer.iter_mut(), length, timeout, frame)
846 }
847
848 fn wait_btf(timeout: Timeout) -> Result<(), Error> {
849 while !Self::check_and_clear_error_flags()?.btf() {
850 timeout.check().ok_or(Error::Timeout)?;
851 }
852 Ok(())
853 }
854
855 fn blocking_read_iter<'a>(
856 &mut self,
857 addr: u8,
858 mut buffer: impl Iterator<Item = &'a mut u8>,
859 mut remaining: usize,
860 timeout: Timeout,
861 frame: FrameOptions,
862 ) -> Result<(), Error> {
863 Self::validate_address(addr)?;
864 if remaining == 0 {
865 return Err(Error::Overrun);
866 }
867 let on_drop = OnDrop::new(Self::abort_transfer);
868 let regs = T::regs();
869 regs.ctlr1().modify(|w| w.set_pos(remaining == 2 && frame.send_nack()));
870
871 if frame.send_start() {
872 Self::launch_start(true, timeout)?;
874
875 while !Self::check_and_clear_error_flags()?.sb() {
877 timeout.check().ok_or(Error::Timeout)?;
878 }
879
880 if T::regs().ctlr1().read().start() || !T::regs().star2().read().msl() {
882 return Err(Error::Arbitration);
883 }
884
885 T::regs().datar().write(|reg| reg.set_datar((addr << 1) + 1));
887
888 while !Self::check_and_clear_error_flags()?.addr() {
891 timeout.check().ok_or(Error::Timeout)?;
892 }
893
894 critical_section::with(|_| {
895 if remaining <= 2 && frame.send_nack() {
896 regs.ctlr1().modify(|w| w.set_ack(false));
897 }
898 let _ = regs.star2().read();
899 if remaining == 1 && frame.send_stop() {
900 Self::generate_stop();
901 } else if remaining == 1 && frame.send_nack() {
902 regs.ctlr1().modify(|w| w.set_start(true));
903 }
904 });
905 }
906
907 if !frame.send_nack() {
908 for value in buffer {
909 *value = self.recv_byte(timeout)?;
910 }
911 } else if remaining == 1 {
912 *buffer.next().unwrap() = self.recv_byte(timeout)?;
913 } else {
914 while remaining > 3 {
915 *buffer.next().unwrap() = self.recv_byte(timeout)?;
916 remaining -= 1;
917 }
918 Self::wait_btf(timeout)?;
919 if remaining == 3 {
920 regs.ctlr1().modify(|w| w.set_ack(false));
921 *buffer.next().unwrap() = regs.datar().read().datar();
922 Self::wait_btf(timeout)?;
923 }
924 critical_section::with(|_| {
925 if frame.send_stop() {
926 Self::generate_stop();
927 } else {
928 regs.ctlr1().modify(|w| w.set_start(true));
929 }
930 *buffer.next().unwrap() = regs.datar().read().datar();
931 *buffer.next().unwrap() = regs.datar().read().datar();
932 });
933 }
934 if frame.send_stop() {
935 Self::wait_stop_finished(timeout)?;
936 regs.ctlr1().modify(|w| w.set_pos(false));
937 }
938 on_drop.defuse();
939 Ok(())
940 }
941
942 pub fn blocking_read(&mut self, addr: u8, read: &mut [u8]) -> Result<(), Error> {
944 self.blocking_read_timeout(addr, read, self.timeout(), FrameOptions::FirstAndLastFrame)
945 }
946
947 pub fn blocking_write(&mut self, addr: u8, write: &[u8]) -> Result<(), Error> {
949 self.write_bytes(addr, write, self.timeout(), FrameOptions::FirstAndLastFrame)?;
950
951 Ok(())
953 }
954
955 pub fn blocking_write_read(&mut self, addr: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> {
957 if read.is_empty() {
960 return Err(Error::Overrun);
961 }
962
963 let timeout = self.timeout();
964
965 self.write_bytes(addr, write, timeout, FrameOptions::FirstFrame)?;
966 self.blocking_read_timeout(addr, read, timeout, FrameOptions::FirstAndLastFrame)?;
967
968 Ok(())
969 }
970
971 pub fn blocking_transaction(&mut self, addr: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> {
977 Self::validate_address(addr)?;
978 validate_operations(operations, false)?;
979 let timeout = self.timeout();
980 let mut operations = operations;
981 while !operations.is_empty() {
982 let read = matches!(operations[0], Operation::Read(_));
983 let count = operations
984 .iter()
985 .take_while(|op| matches!(op, Operation::Read(_)) == read)
986 .count();
987 let (group, rest) = operations.split_at_mut(count);
988 if read {
989 let length = group
990 .iter()
991 .map(|op| match op {
992 Operation::Read(buffer) => buffer.len(),
993 _ => 0,
994 })
995 .sum();
996 let buffer = group.iter_mut().flat_map(|op| match op {
997 Operation::Read(buffer) => buffer.iter_mut(),
998 _ => unreachable!(),
999 });
1000 let frame = if rest.is_empty() {
1001 FrameOptions::FirstAndLastFrame
1002 } else {
1003 FrameOptions::FirstFrame
1004 };
1005 self.blocking_read_iter(addr, buffer, length, timeout, frame)?;
1006 } else {
1007 for (index, operation) in group.iter().enumerate() {
1008 let Operation::Write(buffer) = operation else {
1009 unreachable!()
1010 };
1011 let first = index == 0;
1012 let stop = rest.is_empty() && index + 1 == count;
1013 let frame = match (first, stop) {
1014 (true, true) => FrameOptions::FirstAndLastFrame,
1015 (true, false) => FrameOptions::FirstFrame,
1016 (false, true) => FrameOptions::LastFrame,
1017 (false, false) => FrameOptions::NextFrame,
1018 };
1019 self.write_bytes(addr, buffer, timeout, frame)?;
1020 }
1021 }
1022 operations = rest;
1023 }
1024
1025 Ok(())
1026 }
1027}
1028
1029impl<'d, T: Instance> I2c<'d, T, Async, Master> {
1032 async fn write_frame(&mut self, address: u8, write: &[u8], frame: FrameOptions) -> Result<(), Error> {
1033 Self::validate_address(address)?;
1034 if write.len() > u16::MAX as usize {
1035 return Err(Error::BufferTooLong);
1036 }
1037 self.timeout()
1038 .with(async { Some(self.write_frame_inner(address, write, frame).await) })
1039 .await
1040 .unwrap_or(Err(Error::Timeout))
1041 }
1042
1043 async fn wait_error() -> Error {
1044 poll_fn(|cx| {
1045 T::state().waker.register(cx.waker());
1046 match Self::check_and_clear_error_flags() {
1047 Err(error) => Poll::Ready(error),
1048 Ok(_) => {
1049 T::regs().ctlr2().modify(|w| {
1050 w.set_itevten(false);
1051 w.set_itbufen(false);
1052 w.set_iterren(true);
1053 });
1054 Poll::Pending
1055 }
1056 }
1057 })
1058 .await
1059 }
1060
1061 async fn write_frame_inner(&mut self, address: u8, write: &[u8], frame: FrameOptions) -> Result<(), Error> {
1062 let regs = T::regs();
1063 Self::finish_transfer();
1064 let on_drop = OnDrop::new(Self::abort_transfer);
1065 if frame.send_start() {
1066 Self::launch_start_async(false).await?;
1067 Self::wait_status(1).await?;
1068 if regs.ctlr1().read().start() || !regs.star2().read().msl() {
1069 return Err(Error::Arbitration);
1070 }
1071 regs.datar().write(|w| w.set_datar(address << 1));
1072 Self::wait_status(1 << 1).await?;
1073 let _ = regs.star2().read();
1074 }
1075 if !write.is_empty() {
1076 let transfer = unsafe {
1077 self.tx_dma
1078 .as_mut()
1079 .unwrap()
1080 .write(write, regs.datar().as_ptr().cast(), Default::default())
1081 };
1082 regs.ctlr2().modify(|w| w.set_dmaen(true));
1083 if let Either::First(error) = select(Self::wait_error(), transfer).await {
1084 return Err(error);
1085 }
1086 regs.ctlr2().modify(|w| w.set_dmaen(false));
1087 Self::wait_status(1 << 2).await?;
1088 }
1089 if frame.send_stop() {
1090 Self::generate_stop();
1091 Self::wait_stop_async().await;
1092 }
1093 Self::finish_transfer();
1094 on_drop.defuse();
1095 Ok(())
1096 }
1097
1098 pub async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> {
1100 self.write_frame(address, write, FrameOptions::FirstAndLastFrame)
1101 .await?;
1102
1103 Ok(())
1104 }
1105
1106 pub async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error> {
1108 self.read_group(address, &mut [Operation::Read(buffer)], true).await
1109 }
1110
1111 async fn read_group(&mut self, address: u8, operations: &mut [Operation<'_>], stop: bool) -> Result<(), Error> {
1112 Self::validate_address(address)?;
1113 validate_operations(operations, true)?;
1114 self.timeout()
1115 .with(async { Some(self.read_group_inner(address, operations, stop).await) })
1116 .await
1117 .unwrap_or(Err(Error::Timeout))
1118 }
1119
1120 async fn read_group_inner(
1121 &mut self,
1122 address: u8,
1123 operations: &mut [Operation<'_>],
1124 stop: bool,
1125 ) -> Result<(), Error> {
1126 let total: usize = operations
1127 .iter()
1128 .map(|op| match op {
1129 Operation::Read(buffer) => buffer.len(),
1130 _ => unreachable!(),
1131 })
1132 .sum();
1133 let regs = T::regs();
1134 Self::finish_transfer();
1135 let on_drop = OnDrop::new(Self::abort_transfer);
1136 Self::launch_start_async(true).await?;
1137 Self::wait_status(1).await?;
1138 if regs.ctlr1().read().start() || !regs.star2().read().msl() {
1139 return Err(Error::Arbitration);
1140 }
1141 regs.datar().write(|w| w.set_datar((address << 1) | 1));
1142 Self::wait_status(1 << 1).await?;
1143 critical_section::with(|_| {
1144 regs.ctlr1().modify(|w| {
1145 w.set_pos(total == 2);
1146 w.set_ack(total > 2);
1147 });
1148 let _ = regs.star2().read();
1149 if total == 1 && stop {
1150 Self::generate_stop();
1151 } else if total == 1 {
1152 regs.ctlr1().modify(|w| w.set_start(true));
1153 }
1154 });
1155
1156 let mut prefix = total.saturating_sub(3);
1157 let mut tail: [Option<&mut u8>; 3] = [None, None, None];
1158 let mut tail_index = 0;
1159 for operation in operations {
1160 let Operation::Read(buffer) = operation else {
1161 unreachable!()
1162 };
1163 let count = prefix.min(buffer.len());
1164 let (dma_buffer, tail_buffer) = buffer.split_at_mut(count);
1165 if count != 0 {
1166 let transfer = unsafe {
1167 self.rx_dma
1168 .as_mut()
1169 .unwrap()
1170 .read(regs.datar().as_ptr().cast(), dma_buffer, Default::default())
1171 };
1172 regs.ctlr2().modify(|w| w.set_dmaen(true));
1173 if let Either::First(error) = select(Self::wait_error(), transfer).await {
1174 return Err(error);
1175 }
1176 regs.ctlr2().modify(|w| w.set_dmaen(false));
1177 prefix -= count;
1178 }
1179 for value in tail_buffer {
1180 tail[tail_index] = Some(value);
1181 tail_index += 1;
1182 }
1183 }
1184 if total == 1 {
1185 Self::wait_status(1 << 6).await?;
1186 *tail[0].take().unwrap() = regs.datar().read().datar();
1187 } else {
1188 Self::wait_status(1 << 2).await?;
1189 let offset = if total >= 3 {
1190 regs.ctlr1().modify(|w| w.set_ack(false));
1191 *tail[0].take().unwrap() = regs.datar().read().datar();
1192 Self::wait_status(1 << 2).await?;
1193 1
1194 } else {
1195 0
1196 };
1197 critical_section::with(|_| {
1198 if stop {
1199 Self::generate_stop();
1200 } else {
1201 regs.ctlr1().modify(|w| w.set_start(true));
1202 }
1203 *tail[offset].take().unwrap() = regs.datar().read().datar();
1204 *tail[offset + 1].take().unwrap() = regs.datar().read().datar();
1205 });
1206 }
1207 if stop {
1208 Self::wait_stop_async().await;
1209 regs.ctlr1().modify(|w| w.set_pos(false));
1210 }
1211 Self::finish_transfer();
1212 on_drop.defuse();
1213 Ok(())
1214 }
1215
1216 pub async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> {
1218 if read.is_empty() {
1221 return Err(Error::Overrun);
1222 }
1223 if read.len() > u16::MAX as usize {
1224 return Err(Error::BufferTooLong);
1225 }
1226
1227 self.write_frame(address, write, FrameOptions::FirstFrame).await?;
1228 self.read(address, read).await
1229 }
1230
1231 pub async fn transaction(&mut self, addr: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> {
1237 Self::validate_address(addr)?;
1238 validate_operations(operations, true)?;
1239 let mut operations = operations;
1240 while !operations.is_empty() {
1241 let read = matches!(operations[0], Operation::Read(_));
1242 let count = operations
1243 .iter()
1244 .take_while(|op| matches!(op, Operation::Read(_)) == read)
1245 .count();
1246 let (group, rest) = operations.split_at_mut(count);
1247 if read {
1248 self.read_group(addr, group, rest.is_empty()).await?;
1249 } else {
1250 for (index, operation) in group.iter().enumerate() {
1251 let Operation::Write(buffer) = operation else {
1252 unreachable!()
1253 };
1254 let frame = match (index == 0, rest.is_empty() && index + 1 == count) {
1255 (true, true) => FrameOptions::FirstAndLastFrame,
1256 (true, false) => FrameOptions::FirstFrame,
1257 (false, true) => FrameOptions::LastFrame,
1258 (false, false) => FrameOptions::NextFrame,
1259 };
1260 self.write_frame(addr, buffer, frame).await?;
1261 }
1262 }
1263 operations = rest;
1264 }
1265
1266 Ok(())
1267 }
1268}
1269
1270struct State {
1273 #[allow(unused)]
1274 waker: AtomicWaker,
1275}
1276
1277impl State {
1278 const fn new() -> Self {
1279 Self {
1280 waker: AtomicWaker::new(),
1281 }
1282 }
1283}
1284
1285trait SealedInstance: crate::peripheral::RccPeripheral {
1286 fn regs() -> crate::pac::i2c::I2c;
1287 fn state() -> &'static State;
1288}
1289
1290#[allow(private_bounds)]
1292pub trait Instance:
1293 SealedInstance + embassy_hal_internal::PeripheralType + crate::peripheral::RemapBound + 'static
1294{
1295 type EventInterrupt: interrupt::typelevel::Interrupt;
1297 type ErrorInterrupt: interrupt::typelevel::Interrupt;
1299}
1300
1301foreach_peripheral!(
1302 (i2c, $inst:ident) => {
1303 impl SealedInstance for peripherals::$inst {
1304 fn regs() -> crate::pac::i2c::I2c {
1305 crate::pac::$inst
1306 }
1307
1308 fn state() -> &'static State {
1309 static STATE: State = State::new();
1310 &STATE
1311 }
1312 }
1313
1314 impl Instance for peripherals::$inst {
1315 type EventInterrupt = crate::_generated::peripheral_interrupts::$inst::EV;
1316 type ErrorInterrupt = crate::_generated::peripheral_interrupts::$inst::ER;
1317 }
1318 };
1319);
1320
1321pin_trait!(SclPin, Instance);
1322pin_trait!(SdaPin, Instance);
1323dma_trait!(RxDma, Instance);
1325dma_trait!(TxDma, Instance);
1326
1327impl embedded_hal::i2c::Error for Error {
1328 fn kind(&self) -> embedded_hal::i2c::ErrorKind {
1329 match *self {
1330 Self::Bus => embedded_hal::i2c::ErrorKind::Bus,
1331 Self::Arbitration => embedded_hal::i2c::ErrorKind::ArbitrationLoss,
1332 Self::Nack => embedded_hal::i2c::ErrorKind::NoAcknowledge(embedded_hal::i2c::NoAcknowledgeSource::Unknown),
1333 Self::Timeout => embedded_hal::i2c::ErrorKind::Other,
1334 Self::Crc => embedded_hal::i2c::ErrorKind::Other,
1335 Self::Overrun => embedded_hal::i2c::ErrorKind::Overrun,
1336 Self::ZeroLengthTransfer => embedded_hal::i2c::ErrorKind::Other,
1337 Self::BufferTooLong | Self::InvalidAddress => embedded_hal::i2c::ErrorKind::Other,
1338 }
1339 }
1340}
1341
1342impl<'d, T: Instance, M: Mode> embedded_hal::i2c::ErrorType for I2c<'d, T, M, Master> {
1343 type Error = Error;
1344}
1345
1346impl<'d, T: Instance, M: Mode> embedded_hal::i2c::I2c for I2c<'d, T, M, Master> {
1347 fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> {
1348 self.blocking_read(address, read)
1349 }
1350
1351 fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> {
1352 self.blocking_write(address, write)
1353 }
1354
1355 fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Self::Error> {
1356 self.blocking_write_read(address, write, read)
1357 }
1358
1359 fn transaction(
1360 &mut self,
1361 address: u8,
1362 operations: &mut [embedded_hal::i2c::Operation<'_>],
1363 ) -> Result<(), Self::Error> {
1364 self.blocking_transaction(address, operations)
1365 }
1366}
1367
1368impl<'d, T: Instance> embedded_hal_async::i2c::I2c for I2c<'d, T, Async, Master> {
1369 async fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> {
1370 self.read(address, read).await
1371 }
1372
1373 async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> {
1374 self.write(address, write).await
1375 }
1376
1377 async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Self::Error> {
1378 self.write_read(address, write, read).await
1379 }
1380
1381 async fn transaction(
1382 &mut self,
1383 address: u8,
1384 operations: &mut [embedded_hal_async::i2c::Operation<'_>],
1385 ) -> Result<(), Self::Error> {
1386 self.transaction(address, operations).await
1387 }
1388}
1389
1390#[derive(Copy, Clone)]
1409#[allow(dead_code)]
1410enum FrameOptions {
1411 FirstAndLastFrame,
1413 FirstFrame,
1416 FirstAndNextFrame,
1419 NextFrame,
1421 LastFrame,
1423 LastFrameNoStop,
1425}
1426
1427fn validate_operations(operations: &[Operation<'_>], dma: bool) -> Result<(), Error> {
1428 let mut total = 0usize;
1429 for operation in operations {
1430 let length = match operation {
1431 Operation::Read(buffer) if buffer.is_empty() => return Err(Error::Overrun),
1432 Operation::Read(buffer) => buffer.len(),
1433 Operation::Write(buffer) => buffer.len(),
1434 };
1435 if dma && length > u16::MAX as usize {
1436 return Err(Error::BufferTooLong);
1437 }
1438 total = total.checked_add(length).ok_or(Error::BufferTooLong)?;
1439 }
1440 Ok(())
1441}
1442
1443#[allow(dead_code)]
1444impl FrameOptions {
1445 fn send_start(self) -> bool {
1447 match self {
1448 Self::FirstAndLastFrame | Self::FirstFrame | Self::FirstAndNextFrame => true,
1449 Self::NextFrame | Self::LastFrame | Self::LastFrameNoStop => false,
1450 }
1451 }
1452
1453 fn send_stop(self) -> bool {
1455 match self {
1456 Self::FirstAndLastFrame | Self::LastFrame => true,
1457 Self::FirstFrame | Self::FirstAndNextFrame | Self::NextFrame | Self::LastFrameNoStop => false,
1458 }
1459 }
1460
1461 fn send_nack(self) -> bool {
1463 match self {
1464 Self::FirstAndLastFrame | Self::FirstFrame | Self::LastFrame | Self::LastFrameNoStop => true,
1465 Self::FirstAndNextFrame | Self::NextFrame => false,
1466 }
1467 }
1468}
1469
1470#[allow(dead_code)]
1477fn operation_frames<'a, 'b: 'a>(
1478 operations: &'a mut [embedded_hal::i2c::Operation<'b>],
1479) -> Result<impl IntoIterator<Item = (&'a mut embedded_hal::i2c::Operation<'b>, FrameOptions)>, Error> {
1480 use core::iter;
1481
1482 use embedded_hal::i2c::Operation::{Read, Write};
1483
1484 if operations.iter().any(|op| match op {
1491 Read(read) => read.is_empty(),
1492 Write(_) => false,
1493 }) {
1494 return Err(Error::Overrun);
1495 }
1496
1497 let mut operations = operations.iter_mut().peekable();
1498
1499 let mut next_first_frame = true;
1500
1501 Ok(iter::from_fn(move || {
1502 let Some(op) = operations.next() else {
1503 return None;
1504 };
1505
1506 let first_frame = next_first_frame;
1508 let next_op = operations.peek();
1509
1510 let frame = match (first_frame, next_op) {
1522 (true, None) => FrameOptions::FirstAndLastFrame,
1523 (true, Some(Read(_))) => FrameOptions::FirstAndNextFrame,
1524 (true, Some(Write(_))) => FrameOptions::FirstFrame,
1525 (false, None) => FrameOptions::LastFrame,
1527 (false, Some(Read(_))) => FrameOptions::NextFrame,
1528 (false, Some(Write(_))) => FrameOptions::LastFrameNoStop,
1529 };
1530
1531 next_first_frame = match (&op, next_op) {
1535 (_, None) => false,
1536 (Read(_), Some(Write(_))) | (Write(_), Some(Read(_))) => true,
1537 (Read(_), Some(Read(_))) | (Write(_), Some(Write(_))) => false,
1538 };
1539
1540 Some((op, frame))
1541 }))
1542}