aboutsummaryrefslogtreecommitdiff
path: root/embassy-stm32/src/i2c/v2.rs
diff options
context:
space:
mode:
Diffstat (limited to 'embassy-stm32/src/i2c/v2.rs')
-rw-r--r--embassy-stm32/src/i2c/v2.rs825
1 files changed, 729 insertions, 96 deletions
diff --git a/embassy-stm32/src/i2c/v2.rs b/embassy-stm32/src/i2c/v2.rs
index 0bfc795ac..fe7782a7c 100644
--- a/embassy-stm32/src/i2c/v2.rs
+++ b/embassy-stm32/src/i2c/v2.rs
@@ -2,7 +2,7 @@ use core::cmp;
2use core::future::poll_fn; 2use core::future::poll_fn;
3use core::task::Poll; 3use core::task::Poll;
4 4
5use config::{Address, OwnAddresses, OA2}; 5use config::{Address, OA2, OwnAddresses};
6use embassy_embedded_hal::SetConfig; 6use embassy_embedded_hal::SetConfig;
7use embassy_hal_internal::drop::OnDrop; 7use embassy_hal_internal::drop::OnDrop;
8use embedded_hal_1::i2c::Operation; 8use embedded_hal_1::i2c::Operation;
@@ -70,6 +70,11 @@ fn debug_print_interrupts(isr: stm32_metapac::i2c::regs::Isr) {
70} 70}
71 71
72pub(crate) unsafe fn on_interrupt<T: Instance>() { 72pub(crate) unsafe fn on_interrupt<T: Instance>() {
73 // restore the clocks to their last configured state as
74 // much is lost in STOP modes
75 #[cfg(all(feature = "low-power", stm32wlex))]
76 crate::low_power::Executor::on_wakeup_irq_or_event();
77
73 let regs = T::info().regs; 78 let regs = T::info().regs;
74 let isr = regs.isr().read(); 79 let isr = regs.isr().read();
75 80
@@ -93,6 +98,27 @@ pub(crate) unsafe fn on_interrupt<T: Instance>() {
93} 98}
94 99
95impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> { 100impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
101 #[inline]
102 fn to_reload(reload: bool) -> i2c::vals::Reload {
103 if reload {
104 i2c::vals::Reload::NOT_COMPLETED
105 } else {
106 i2c::vals::Reload::COMPLETED
107 }
108 }
109
110 /// Calculate total bytes in a group of operations
111 #[inline]
112 fn total_operation_bytes(operations: &[Operation<'_>]) -> usize {
113 operations
114 .iter()
115 .map(|op| match op {
116 Operation::Write(buf) => buf.len(),
117 Operation::Read(buf) => buf.len(),
118 })
119 .sum()
120 }
121
96 pub(crate) fn init(&mut self, config: Config) { 122 pub(crate) fn init(&mut self, config: Config) {
97 self.info.regs.cr1().modify(|reg| { 123 self.info.regs.cr1().modify(|reg| {
98 reg.set_pe(false); 124 reg.set_pe(false);
@@ -142,12 +168,6 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
142 // `buffer`. The START bit can be set even if the bus 168 // `buffer`. The START bit can be set even if the bus
143 // is BUSY or I2C is in slave mode. 169 // is BUSY or I2C is in slave mode.
144 170
145 let reload = if reload {
146 i2c::vals::Reload::NOT_COMPLETED
147 } else {
148 i2c::vals::Reload::COMPLETED
149 };
150
151 info.regs.cr2().modify(|w| { 171 info.regs.cr2().modify(|w| {
152 w.set_sadd(address.addr() << 1); 172 w.set_sadd(address.addr() << 1);
153 w.set_add10(address.add_mode()); 173 w.set_add10(address.add_mode());
@@ -155,7 +175,7 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
155 w.set_nbytes(length as u8); 175 w.set_nbytes(length as u8);
156 w.set_start(true); 176 w.set_start(true);
157 w.set_autoend(stop.autoend()); 177 w.set_autoend(stop.autoend());
158 w.set_reload(reload); 178 w.set_reload(Self::to_reload(reload));
159 }); 179 });
160 180
161 Ok(()) 181 Ok(())
@@ -167,28 +187,25 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
167 length: usize, 187 length: usize,
168 stop: Stop, 188 stop: Stop,
169 reload: bool, 189 reload: bool,
190 restart: bool,
170 timeout: Timeout, 191 timeout: Timeout,
171 ) -> Result<(), Error> { 192 ) -> Result<(), Error> {
172 assert!(length < 256); 193 assert!(length < 256);
173 194
174 // Wait for any previous address sequence to end 195 if !restart {
175 // automatically. This could be up to 50% of a bus 196 // Wait for any previous address sequence to end
176 // cycle (ie. up to 0.5/freq) 197 // automatically. This could be up to 50% of a bus
177 while info.regs.cr2().read().start() { 198 // cycle (ie. up to 0.5/freq)
178 timeout.check()?; 199 while info.regs.cr2().read().start() {
179 } 200 timeout.check()?;
201 }
180 202
181 // Wait for the bus to be free 203 // Wait for the bus to be free
182 while info.regs.isr().read().busy() { 204 while info.regs.isr().read().busy() {
183 timeout.check()?; 205 timeout.check()?;
206 }
184 } 207 }
185 208
186 let reload = if reload {
187 i2c::vals::Reload::NOT_COMPLETED
188 } else {
189 i2c::vals::Reload::COMPLETED
190 };
191
192 // Set START and prepare to send `bytes`. The 209 // Set START and prepare to send `bytes`. The
193 // START bit can be set even if the bus is BUSY or 210 // START bit can be set even if the bus is BUSY or
194 // I2C is in slave mode. 211 // I2C is in slave mode.
@@ -199,28 +216,36 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
199 w.set_nbytes(length as u8); 216 w.set_nbytes(length as u8);
200 w.set_start(true); 217 w.set_start(true);
201 w.set_autoend(stop.autoend()); 218 w.set_autoend(stop.autoend());
202 w.set_reload(reload); 219 w.set_reload(Self::to_reload(reload));
203 }); 220 });
204 221
205 Ok(()) 222 Ok(())
206 } 223 }
207 224
208 fn reload(info: &'static Info, length: usize, will_reload: bool, timeout: Timeout) -> Result<(), Error> { 225 fn reload(
226 info: &'static Info,
227 length: usize,
228 will_reload: bool,
229 stop: Stop,
230 timeout: Timeout,
231 ) -> Result<(), Error> {
209 assert!(length < 256 && length > 0); 232 assert!(length < 256 && length > 0);
210 233
211 while !info.regs.isr().read().tcr() { 234 // Wait for either TCR (Transfer Complete Reload) or TC (Transfer Complete)
235 // TCR occurs when RELOAD=1, TC occurs when RELOAD=0
236 // Both indicate the peripheral is ready for the next transfer
237 loop {
238 let isr = info.regs.isr().read();
239 if isr.tcr() || isr.tc() {
240 break;
241 }
212 timeout.check()?; 242 timeout.check()?;
213 } 243 }
214 244
215 let will_reload = if will_reload {
216 i2c::vals::Reload::NOT_COMPLETED
217 } else {
218 i2c::vals::Reload::COMPLETED
219 };
220
221 info.regs.cr2().modify(|w| { 245 info.regs.cr2().modify(|w| {
222 w.set_nbytes(length as u8); 246 w.set_nbytes(length as u8);
223 w.set_reload(will_reload); 247 w.set_reload(Self::to_reload(will_reload));
248 w.set_autoend(stop.autoend());
224 }); 249 });
225 250
226 Ok(()) 251 Ok(())
@@ -364,7 +389,9 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
364 loop { 389 loop {
365 let isr = self.info.regs.isr().read(); 390 let isr = self.info.regs.isr().read();
366 self.error_occurred(&isr, timeout)?; 391 self.error_occurred(&isr, timeout)?;
367 if isr.tc() { 392 // Wait for either TC or TCR - both indicate transfer completion
393 // TCR occurs when RELOAD=1, TC occurs when RELOAD=0
394 if isr.tc() || isr.tcr() {
368 return Ok(()); 395 return Ok(());
369 } 396 }
370 timeout.check()?; 397 timeout.check()?;
@@ -391,14 +418,20 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
391 address, 418 address,
392 read.len().min(255), 419 read.len().min(255),
393 Stop::Automatic, 420 Stop::Automatic,
394 last_chunk_idx != 0, 421 last_chunk_idx != 0, // reload
395 restart, 422 restart,
396 timeout, 423 timeout,
397 )?; 424 )?;
398 425
399 for (number, chunk) in read.chunks_mut(255).enumerate() { 426 for (number, chunk) in read.chunks_mut(255).enumerate() {
400 if number != 0 { 427 if number != 0 {
401 Self::reload(self.info, chunk.len(), number != last_chunk_idx, timeout)?; 428 Self::reload(
429 self.info,
430 chunk.len(),
431 number != last_chunk_idx,
432 Stop::Automatic,
433 timeout,
434 )?;
402 } 435 }
403 436
404 for byte in chunk { 437 for byte in chunk {
@@ -436,6 +469,7 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
436 write.len().min(255), 469 write.len().min(255),
437 Stop::Software, 470 Stop::Software,
438 last_chunk_idx != 0, 471 last_chunk_idx != 0,
472 false, // restart
439 timeout, 473 timeout,
440 ) { 474 ) {
441 if send_stop { 475 if send_stop {
@@ -446,7 +480,13 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
446 480
447 for (number, chunk) in write.chunks(255).enumerate() { 481 for (number, chunk) in write.chunks(255).enumerate() {
448 if number != 0 { 482 if number != 0 {
449 Self::reload(self.info, chunk.len(), number != last_chunk_idx, timeout)?; 483 Self::reload(
484 self.info,
485 chunk.len(),
486 number != last_chunk_idx,
487 Stop::Software,
488 timeout,
489 )?;
450 } 490 }
451 491
452 for byte in chunk { 492 for byte in chunk {
@@ -502,9 +542,215 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
502 /// 542 ///
503 /// [transaction contract]: embedded_hal_1::i2c::I2c::transaction 543 /// [transaction contract]: embedded_hal_1::i2c::I2c::transaction
504 pub fn blocking_transaction(&mut self, addr: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> { 544 pub fn blocking_transaction(&mut self, addr: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> {
505 let _ = addr; 545 if operations.is_empty() {
506 let _ = operations; 546 return Err(Error::ZeroLengthTransfer);
507 todo!() 547 }
548
549 let address = addr.into();
550 let timeout = self.timeout();
551
552 // Group consecutive operations of the same type
553 let mut op_idx = 0;
554 let mut is_first_group = true;
555
556 while op_idx < operations.len() {
557 // Determine the type of current group and find all consecutive operations of same type
558 let is_read = matches!(operations[op_idx], Operation::Read(_));
559 let group_start = op_idx;
560
561 // Find end of this group (consecutive operations of same type)
562 while op_idx < operations.len() && matches!(operations[op_idx], Operation::Read(_)) == is_read {
563 op_idx += 1;
564 }
565 let group_end = op_idx;
566 let is_last_group = op_idx >= operations.len();
567
568 // Execute this group of operations
569 if is_read {
570 self.execute_read_group(
571 address,
572 &mut operations[group_start..group_end],
573 is_first_group,
574 is_last_group,
575 timeout,
576 )?;
577 } else {
578 self.execute_write_group(
579 address,
580 &operations[group_start..group_end],
581 is_first_group,
582 is_last_group,
583 timeout,
584 )?;
585 }
586
587 is_first_group = false;
588 }
589
590 Ok(())
591 }
592
593 fn execute_write_group(
594 &mut self,
595 address: Address,
596 operations: &[Operation<'_>],
597 is_first_group: bool,
598 is_last_group: bool,
599 timeout: Timeout,
600 ) -> Result<(), Error> {
601 // Calculate total bytes across all operations in this group
602 let total_bytes = Self::total_operation_bytes(operations);
603
604 if total_bytes == 0 {
605 // Handle empty write group - just send address
606 if is_first_group {
607 Self::master_write(self.info, address, 0, Stop::Software, false, !is_first_group, timeout)?;
608 }
609 if is_last_group {
610 self.master_stop();
611 }
612 return Ok(());
613 }
614
615 let mut total_remaining = total_bytes;
616 let mut first_chunk = true;
617
618 for operation in operations {
619 if let Operation::Write(buffer) = operation {
620 for chunk in buffer.chunks(255) {
621 let chunk_len = chunk.len();
622 total_remaining -= chunk_len;
623 let is_last_chunk = total_remaining == 0;
624 let will_reload = !is_last_chunk;
625
626 if first_chunk {
627 // First chunk: initiate transfer
628 // If not first group, use RESTART instead of START
629 Self::master_write(
630 self.info,
631 address,
632 chunk_len,
633 Stop::Software,
634 will_reload,
635 !is_first_group,
636 timeout,
637 )?;
638 first_chunk = false;
639 } else {
640 // Subsequent chunks: use reload
641 // Always use Software stop for writes
642 Self::reload(self.info, chunk_len, will_reload, Stop::Software, timeout)?;
643 }
644
645 // Send data bytes
646 for byte in chunk {
647 self.wait_txis(timeout)?;
648 self.info.regs.txdr().write(|w| w.set_txdata(*byte));
649 }
650 }
651 }
652 }
653
654 // Wait for transfer to complete
655 if is_last_group {
656 self.wait_tc(timeout)?;
657 self.master_stop();
658 self.wait_stop(timeout)?;
659 } else {
660 // Wait for TC before next group (enables RESTART)
661 self.wait_tc(timeout)?;
662 }
663
664 Ok(())
665 }
666
667 fn execute_read_group(
668 &mut self,
669 address: Address,
670 operations: &mut [Operation<'_>],
671 is_first_group: bool,
672 is_last_group: bool,
673 timeout: Timeout,
674 ) -> Result<(), Error> {
675 // Calculate total bytes across all operations in this group
676 let total_bytes = Self::total_operation_bytes(operations);
677
678 if total_bytes == 0 {
679 // Handle empty read group
680 if is_first_group {
681 Self::master_read(
682 self.info,
683 address,
684 0,
685 if is_last_group { Stop::Automatic } else { Stop::Software },
686 false, // reload
687 !is_first_group,
688 timeout,
689 )?;
690 }
691 if is_last_group {
692 self.wait_stop(timeout)?;
693 }
694 return Ok(());
695 }
696
697 let mut total_remaining = total_bytes;
698 let mut first_chunk = true;
699
700 for operation in operations {
701 if let Operation::Read(buffer) = operation {
702 for chunk in buffer.chunks_mut(255) {
703 let chunk_len = chunk.len();
704 total_remaining -= chunk_len;
705 let is_last_chunk = total_remaining == 0;
706 let will_reload = !is_last_chunk;
707
708 if first_chunk {
709 // First chunk: initiate transfer
710 let stop = if is_last_group && is_last_chunk {
711 Stop::Automatic
712 } else {
713 Stop::Software
714 };
715
716 Self::master_read(
717 self.info,
718 address,
719 chunk_len,
720 stop,
721 will_reload,
722 !is_first_group, // restart if not first group
723 timeout,
724 )?;
725 first_chunk = false;
726 } else {
727 // Subsequent chunks: use reload
728 let stop = if is_last_group && is_last_chunk {
729 Stop::Automatic
730 } else {
731 Stop::Software
732 };
733 Self::reload(self.info, chunk_len, will_reload, stop, timeout)?;
734 }
735
736 // Receive data bytes
737 for byte in chunk {
738 self.wait_rxne(timeout)?;
739 *byte = self.info.regs.rxdr().read().rxdata();
740 }
741 }
742 }
743 }
744
745 // Wait for transfer to complete
746 if is_last_group {
747 self.wait_stop(timeout)?;
748 }
749 // For non-last read groups, don't wait for TC - the peripheral may hold SCL low
750 // in Software AUTOEND mode until the next START is issued. Just proceed directly
751 // to the next group which will issue RESTART and release the clock.
752
753 Ok(())
508 } 754 }
509 755
510 /// Blocking write multiple buffers. 756 /// Blocking write multiple buffers.
@@ -526,6 +772,7 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
526 first_length.min(255), 772 first_length.min(255),
527 Stop::Software, 773 Stop::Software,
528 (first_length > 255) || (last_slice_index != 0), 774 (first_length > 255) || (last_slice_index != 0),
775 false, // restart
529 timeout, 776 timeout,
530 ) { 777 ) {
531 self.master_stop(); 778 self.master_stop();
@@ -547,6 +794,7 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
547 self.info, 794 self.info,
548 slice_len.min(255), 795 slice_len.min(255),
549 (idx != last_slice_index) || (slice_len > 255), 796 (idx != last_slice_index) || (slice_len > 255),
797 Stop::Software,
550 timeout, 798 timeout,
551 ) { 799 ) {
552 if err != Error::Nack { 800 if err != Error::Nack {
@@ -562,6 +810,7 @@ impl<'d, M: Mode, IM: MasterMode> I2c<'d, M, IM> {
562 self.info, 810 self.info,
563 chunk.len(), 811 chunk.len(),
564 (number != last_chunk_idx) || (idx != last_slice_index), 812 (number != last_chunk_idx) || (idx != last_slice_index),
813 Stop::Software,
565 timeout, 814 timeout,
566 ) { 815 ) {
567 if err != Error::Nack { 816 if err != Error::Nack {
@@ -605,6 +854,7 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
605 first_slice: bool, 854 first_slice: bool,
606 last_slice: bool, 855 last_slice: bool,
607 send_stop: bool, 856 send_stop: bool,
857 restart: bool,
608 timeout: Timeout, 858 timeout: Timeout,
609 ) -> Result<(), Error> { 859 ) -> Result<(), Error> {
610 let total_len = write.len(); 860 let total_len = write.len();
@@ -671,10 +921,17 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
671 total_len.min(255), 921 total_len.min(255),
672 Stop::Software, 922 Stop::Software,
673 (total_len > 255) || !last_slice, 923 (total_len > 255) || !last_slice,
924 restart,
674 timeout, 925 timeout,
675 )?; 926 )?;
676 } else { 927 } else {
677 Self::reload(self.info, total_len.min(255), (total_len > 255) || !last_slice, timeout)?; 928 Self::reload(
929 self.info,
930 total_len.min(255),
931 (total_len > 255) || !last_slice,
932 Stop::Software,
933 timeout,
934 )?;
678 self.info.regs.cr1().modify(|w| w.set_tcie(true)); 935 self.info.regs.cr1().modify(|w| w.set_tcie(true));
679 } 936 }
680 } else if !(isr.tcr() || isr.tc()) { 937 } else if !(isr.tcr() || isr.tc()) {
@@ -683,9 +940,13 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
683 } else if remaining_len == 0 { 940 } else if remaining_len == 0 {
684 return Poll::Ready(Ok(())); 941 return Poll::Ready(Ok(()));
685 } else { 942 } else {
686 let last_piece = (remaining_len <= 255) && last_slice; 943 if let Err(e) = Self::reload(
687 944 self.info,
688 if let Err(e) = Self::reload(self.info, remaining_len.min(255), !last_piece, timeout) { 945 remaining_len.min(255),
946 (remaining_len > 255) || !last_slice,
947 Stop::Software,
948 timeout,
949 ) {
689 return Poll::Ready(Err(e)); 950 return Poll::Ready(Err(e));
690 } 951 }
691 self.info.regs.cr1().modify(|w| w.set_tcie(true)); 952 self.info.regs.cr1().modify(|w| w.set_tcie(true));
@@ -697,10 +958,9 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
697 .await?; 958 .await?;
698 959
699 dma_transfer.await; 960 dma_transfer.await;
700 if last_slice { 961
701 // This should be done already 962 // Always wait for TC after DMA completes - needed for consecutive buffers
702 self.wait_tc(timeout)?; 963 self.wait_tc(timeout)?;
703 }
704 964
705 if last_slice & send_stop { 965 if last_slice & send_stop {
706 self.master_stop(); 966 self.master_stop();
@@ -775,7 +1035,7 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
775 address, 1035 address,
776 total_len.min(255), 1036 total_len.min(255),
777 Stop::Automatic, 1037 Stop::Automatic,
778 total_len > 255, 1038 total_len > 255, // reload
779 restart, 1039 restart,
780 timeout, 1040 timeout,
781 )?; 1041 )?;
@@ -783,12 +1043,10 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
783 return Poll::Ready(Ok(())); 1043 return Poll::Ready(Ok(()));
784 } 1044 }
785 } else if isr.tcr() { 1045 } else if isr.tcr() {
786 // poll_fn was woken without an interrupt present 1046 // Transfer Complete Reload - need to set up next chunk
787 return Poll::Pending;
788 } else {
789 let last_piece = remaining_len <= 255; 1047 let last_piece = remaining_len <= 255;
790 1048
791 if let Err(e) = Self::reload(self.info, remaining_len.min(255), !last_piece, timeout) { 1049 if let Err(e) = Self::reload(self.info, remaining_len.min(255), !last_piece, Stop::Automatic, timeout) {
792 return Poll::Ready(Err(e)); 1050 return Poll::Ready(Err(e));
793 } 1051 }
794 // Return here if we are on last chunk, 1052 // Return here if we are on last chunk,
@@ -797,6 +1055,9 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
797 return Poll::Ready(Ok(())); 1055 return Poll::Ready(Ok(()));
798 } 1056 }
799 self.info.regs.cr1().modify(|w| w.set_tcie(true)); 1057 self.info.regs.cr1().modify(|w| w.set_tcie(true));
1058 } else {
1059 // poll_fn was woken without TCR interrupt
1060 return Poll::Pending;
800 } 1061 }
801 1062
802 remaining_len = remaining_len.saturating_sub(255); 1063 remaining_len = remaining_len.saturating_sub(255);
@@ -814,12 +1075,13 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
814 1075
815 /// Write. 1076 /// Write.
816 pub async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> { 1077 pub async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> {
1078 let _scoped_block_stop = self.info.rcc.block_stop();
817 let timeout = self.timeout(); 1079 let timeout = self.timeout();
818 if write.is_empty() { 1080 if write.is_empty() {
819 self.write_internal(address.into(), write, true, timeout) 1081 self.write_internal(address.into(), write, true, timeout)
820 } else { 1082 } else {
821 timeout 1083 timeout
822 .with(self.write_dma_internal(address.into(), write, true, true, true, timeout)) 1084 .with(self.write_dma_internal(address.into(), write, true, true, true, false, timeout))
823 .await 1085 .await
824 } 1086 }
825 } 1087 }
@@ -828,21 +1090,30 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
828 /// 1090 ///
829 /// The buffers are concatenated in a single write transaction. 1091 /// The buffers are concatenated in a single write transaction.
830 pub async fn write_vectored(&mut self, address: Address, write: &[&[u8]]) -> Result<(), Error> { 1092 pub async fn write_vectored(&mut self, address: Address, write: &[&[u8]]) -> Result<(), Error> {
1093 let _scoped_block_stop = self.info.rcc.block_stop();
831 let timeout = self.timeout(); 1094 let timeout = self.timeout();
832 1095
833 if write.is_empty() { 1096 if write.is_empty() {
834 return Err(Error::ZeroLengthTransfer); 1097 return Err(Error::ZeroLengthTransfer);
835 } 1098 }
836 let mut iter = write.iter();
837 1099
1100 let mut iter = write.iter();
838 let mut first = true; 1101 let mut first = true;
839 let mut current = iter.next(); 1102 let mut current = iter.next();
1103
840 while let Some(c) = current { 1104 while let Some(c) = current {
841 let next = iter.next(); 1105 let next = iter.next();
842 let is_last = next.is_none(); 1106 let is_last = next.is_none();
843 1107
844 let fut = self.write_dma_internal(address, c, first, is_last, is_last, timeout); 1108 let fut = self.write_dma_internal(
1109 address, c, first, // first_slice
1110 is_last, // last_slice
1111 is_last, // send_stop (only on last buffer)
1112 false, // restart (false for all - they're one continuous write)
1113 timeout,
1114 );
845 timeout.with(fut).await?; 1115 timeout.with(fut).await?;
1116
846 first = false; 1117 first = false;
847 current = next; 1118 current = next;
848 } 1119 }
@@ -851,6 +1122,7 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
851 1122
852 /// Read. 1123 /// Read.
853 pub async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error> { 1124 pub async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error> {
1125 let _scoped_block_stop = self.info.rcc.block_stop();
854 let timeout = self.timeout(); 1126 let timeout = self.timeout();
855 1127
856 if buffer.is_empty() { 1128 if buffer.is_empty() {
@@ -863,12 +1135,13 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
863 1135
864 /// Write, restart, read. 1136 /// Write, restart, read.
865 pub async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> { 1137 pub async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> {
1138 let _scoped_block_stop = self.info.rcc.block_stop();
866 let timeout = self.timeout(); 1139 let timeout = self.timeout();
867 1140
868 if write.is_empty() { 1141 if write.is_empty() {
869 self.write_internal(address.into(), write, false, timeout)?; 1142 self.write_internal(address.into(), write, false, timeout)?;
870 } else { 1143 } else {
871 let fut = self.write_dma_internal(address.into(), write, true, true, false, timeout); 1144 let fut = self.write_dma_internal(address.into(), write, true, true, false, false, timeout);
872 timeout.with(fut).await?; 1145 timeout.with(fut).await?;
873 } 1146 }
874 1147
@@ -888,9 +1161,299 @@ impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
888 /// 1161 ///
889 /// [transaction contract]: embedded_hal_1::i2c::I2c::transaction 1162 /// [transaction contract]: embedded_hal_1::i2c::I2c::transaction
890 pub async fn transaction(&mut self, addr: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> { 1163 pub async fn transaction(&mut self, addr: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> {
891 let _ = addr; 1164 let _scoped_block_stop = self.info.rcc.block_stop();
892 let _ = operations; 1165 if operations.is_empty() {
893 todo!() 1166 return Err(Error::ZeroLengthTransfer);
1167 }
1168
1169 let address = addr.into();
1170 let timeout = self.timeout();
1171
1172 // Group consecutive operations of the same type
1173 let mut op_idx = 0;
1174 let mut is_first_group = true;
1175
1176 while op_idx < operations.len() {
1177 // Determine the type of current group and find all consecutive operations of same type
1178 let is_read = matches!(operations[op_idx], Operation::Read(_));
1179 let group_start = op_idx;
1180
1181 // Find end of this group (consecutive operations of same type)
1182 while op_idx < operations.len() && matches!(operations[op_idx], Operation::Read(_)) == is_read {
1183 op_idx += 1;
1184 }
1185 let group_end = op_idx;
1186 let is_last_group = op_idx >= operations.len();
1187
1188 // Execute this group of operations
1189 if is_read {
1190 self.execute_read_group_async(
1191 address,
1192 &mut operations[group_start..group_end],
1193 is_first_group,
1194 is_last_group,
1195 timeout,
1196 )
1197 .await?;
1198 } else {
1199 self.execute_write_group_async(
1200 address,
1201 &operations[group_start..group_end],
1202 is_first_group,
1203 is_last_group,
1204 timeout,
1205 )
1206 .await?;
1207 }
1208
1209 is_first_group = false;
1210 }
1211
1212 Ok(())
1213 }
1214
1215 async fn execute_write_group_async(
1216 &mut self,
1217 address: Address,
1218 operations: &[Operation<'_>],
1219 is_first_group: bool,
1220 is_last_group: bool,
1221 timeout: Timeout,
1222 ) -> Result<(), Error> {
1223 // Calculate total bytes across all operations in this group
1224 let total_bytes = Self::total_operation_bytes(operations);
1225
1226 if total_bytes == 0 {
1227 // Handle empty write group using blocking call
1228 if is_first_group {
1229 Self::master_write(self.info, address, 0, Stop::Software, false, !is_first_group, timeout)?;
1230 }
1231 if is_last_group {
1232 self.master_stop();
1233 }
1234 return Ok(());
1235 }
1236
1237 // Collect all write buffers
1238 let mut write_buffers: heapless::Vec<&[u8], 16> = heapless::Vec::new();
1239 for operation in operations {
1240 if let Operation::Write(buffer) = operation {
1241 if !buffer.is_empty() {
1242 let _ = write_buffers.push(buffer);
1243 }
1244 }
1245 }
1246
1247 if write_buffers.is_empty() {
1248 return Ok(());
1249 }
1250
1251 // Send each buffer using DMA
1252 let num_buffers = write_buffers.len();
1253 for (idx, buffer) in write_buffers.iter().enumerate() {
1254 let is_first_buffer = idx == 0;
1255 let is_last_buffer = idx == num_buffers - 1;
1256
1257 let fut = self.write_dma_internal(
1258 address,
1259 buffer,
1260 is_first_buffer, // first_slice
1261 is_last_buffer, // last_slice
1262 is_last_buffer && is_last_group, // send_stop
1263 is_first_buffer && !is_first_group, // restart (only for first buffer if not first group)
1264 timeout,
1265 );
1266 timeout.with(fut).await?;
1267 }
1268
1269 Ok(())
1270 }
1271
1272 async fn execute_read_group_async(
1273 &mut self,
1274 address: Address,
1275 operations: &mut [Operation<'_>],
1276 is_first_group: bool,
1277 is_last_group: bool,
1278 timeout: Timeout,
1279 ) -> Result<(), Error> {
1280 // Calculate total bytes across all operations in this group
1281 let total_bytes = Self::total_operation_bytes(operations);
1282
1283 if total_bytes == 0 {
1284 // Handle empty read group using blocking call
1285 if is_first_group {
1286 Self::master_read(
1287 self.info,
1288 address,
1289 0,
1290 if is_last_group { Stop::Automatic } else { Stop::Software },
1291 false, // reload
1292 !is_first_group,
1293 timeout,
1294 )?;
1295 }
1296 if is_last_group {
1297 self.wait_stop(timeout)?;
1298 }
1299 return Ok(());
1300 }
1301
1302 // Use DMA for read operations - need to handle multiple buffers
1303 let restart = !is_first_group;
1304 let mut total_remaining = total_bytes;
1305 let mut is_first_in_group = true;
1306
1307 for operation in operations {
1308 if let Operation::Read(buffer) = operation {
1309 if buffer.is_empty() {
1310 // Skip empty buffers
1311 continue;
1312 }
1313
1314 let buf_len = buffer.len();
1315 total_remaining -= buf_len;
1316 let is_last_in_group = total_remaining == 0;
1317
1318 // Perform DMA read
1319 if is_first_in_group {
1320 // First buffer: use read_dma_internal which handles restart properly
1321 // Only use Automatic stop if this is the last buffer in the last group
1322 let stop_mode = if is_last_group && is_last_in_group {
1323 Stop::Automatic
1324 } else {
1325 Stop::Software
1326 };
1327
1328 // We need a custom DMA read that respects our stop mode
1329 self.read_dma_group_internal(address, buffer, restart, stop_mode, timeout)
1330 .await?;
1331 is_first_in_group = false;
1332 } else {
1333 // Subsequent buffers: need to reload and continue
1334 let stop_mode = if is_last_group && is_last_in_group {
1335 Stop::Automatic
1336 } else {
1337 Stop::Software
1338 };
1339
1340 self.read_dma_group_internal(
1341 address, buffer, false, // no restart for subsequent buffers in same group
1342 stop_mode, timeout,
1343 )
1344 .await?;
1345 }
1346 }
1347 }
1348
1349 // Wait for transfer to complete
1350 if is_last_group {
1351 self.wait_stop(timeout)?;
1352 }
1353
1354 Ok(())
1355 }
1356
1357 /// Internal DMA read helper for transaction groups
1358 async fn read_dma_group_internal(
1359 &mut self,
1360 address: Address,
1361 buffer: &mut [u8],
1362 restart: bool,
1363 stop_mode: Stop,
1364 timeout: Timeout,
1365 ) -> Result<(), Error> {
1366 let total_len = buffer.len();
1367
1368 let dma_transfer = unsafe {
1369 let regs = self.info.regs;
1370 regs.cr1().modify(|w| {
1371 w.set_rxdmaen(true);
1372 w.set_tcie(true);
1373 w.set_nackie(true);
1374 w.set_errie(true);
1375 });
1376 let src = regs.rxdr().as_ptr() as *mut u8;
1377
1378 self.rx_dma.as_mut().unwrap().read(src, buffer, Default::default())
1379 };
1380
1381 let mut remaining_len = total_len;
1382
1383 let on_drop = OnDrop::new(|| {
1384 let regs = self.info.regs;
1385 regs.cr1().modify(|w| {
1386 w.set_rxdmaen(false);
1387 w.set_tcie(false);
1388 w.set_nackie(false);
1389 w.set_errie(false);
1390 });
1391 regs.icr().write(|w| {
1392 w.set_nackcf(true);
1393 w.set_berrcf(true);
1394 w.set_arlocf(true);
1395 w.set_ovrcf(true);
1396 });
1397 });
1398
1399 poll_fn(|cx| {
1400 self.state.waker.register(cx.waker());
1401
1402 let isr = self.info.regs.isr().read();
1403
1404 if isr.nackf() {
1405 return Poll::Ready(Err(Error::Nack));
1406 }
1407 if isr.arlo() {
1408 return Poll::Ready(Err(Error::Arbitration));
1409 }
1410 if isr.berr() {
1411 return Poll::Ready(Err(Error::Bus));
1412 }
1413 if isr.ovr() {
1414 return Poll::Ready(Err(Error::Overrun));
1415 }
1416
1417 if remaining_len == total_len {
1418 Self::master_read(
1419 self.info,
1420 address,
1421 total_len.min(255),
1422 stop_mode,
1423 total_len > 255, // reload
1424 restart,
1425 timeout,
1426 )?;
1427 if total_len <= 255 {
1428 return Poll::Ready(Ok(()));
1429 }
1430 } else if isr.tcr() {
1431 // Transfer Complete Reload - need to set up next chunk
1432 let last_piece = remaining_len <= 255;
1433
1434 if let Err(e) = Self::reload(self.info, remaining_len.min(255), !last_piece, stop_mode, timeout) {
1435 return Poll::Ready(Err(e));
1436 }
1437 // Return here if we are on last chunk,
1438 // end of transfer will be awaited with the DMA below
1439 if last_piece {
1440 return Poll::Ready(Ok(()));
1441 }
1442 self.info.regs.cr1().modify(|w| w.set_tcie(true));
1443 } else {
1444 // poll_fn was woken without TCR interrupt
1445 return Poll::Pending;
1446 }
1447
1448 remaining_len = remaining_len.saturating_sub(255);
1449 Poll::Pending
1450 })
1451 .await?;
1452
1453 dma_transfer.await;
1454 drop(on_drop);
1455
1456 Ok(())
894 } 1457 }
895} 1458}
896 1459
@@ -1028,7 +1591,13 @@ impl<'d, M: Mode> I2c<'d, M, MultiMaster> {
1028 if number == 0 { 1591 if number == 0 {
1029 Self::slave_start(self.info, chunk.len(), number != last_chunk_idx); 1592 Self::slave_start(self.info, chunk.len(), number != last_chunk_idx);
1030 } else { 1593 } else {
1031 Self::reload(self.info, chunk.len(), number != last_chunk_idx, timeout)?; 1594 Self::reload(
1595 self.info,
1596 chunk.len(),
1597 number != last_chunk_idx,
1598 Stop::Software,
1599 timeout,
1600 )?;
1032 } 1601 }
1033 1602
1034 let mut index = 0; 1603 let mut index = 0;
@@ -1036,7 +1605,8 @@ impl<'d, M: Mode> I2c<'d, M, MultiMaster> {
1036 for byte in chunk { 1605 for byte in chunk {
1037 // Wait until we have received something 1606 // Wait until we have received something
1038 match self.wait_rxne(timeout) { 1607 match self.wait_rxne(timeout) {
1039 Ok(ReceiveResult::StopReceived) | Ok(ReceiveResult::NewStart) => { 1608 Ok(ReceiveResult::StopReceived) => {}
1609 Ok(ReceiveResult::NewStart) => {
1040 trace!("--- Slave RX transmission end (early)"); 1610 trace!("--- Slave RX transmission end (early)");
1041 return Ok(total_len - remaining_len); // Return N bytes read 1611 return Ok(total_len - remaining_len); // Return N bytes read
1042 } 1612 }
@@ -1077,7 +1647,13 @@ impl<'d, M: Mode> I2c<'d, M, MultiMaster> {
1077 if number == 0 { 1647 if number == 0 {
1078 Self::slave_start(self.info, chunk.len(), number != last_chunk_idx); 1648 Self::slave_start(self.info, chunk.len(), number != last_chunk_idx);
1079 } else { 1649 } else {
1080 Self::reload(self.info, chunk.len(), number != last_chunk_idx, timeout)?; 1650 Self::reload(
1651 self.info,
1652 chunk.len(),
1653 number != last_chunk_idx,
1654 Stop::Software,
1655 timeout,
1656 )?;
1081 } 1657 }
1082 1658
1083 let mut index = 0; 1659 let mut index = 0;
@@ -1104,42 +1680,50 @@ impl<'d, M: Mode> I2c<'d, M, MultiMaster> {
1104 1680
1105 /// Listen for incoming I2C messages. 1681 /// Listen for incoming I2C messages.
1106 /// 1682 ///
1107 /// The listen method is an asynchronous method but it does not require DMA to be asynchronous. 1683 /// This method blocks until the slave address is matched by a master.
1108 pub async fn listen(&mut self) -> Result<SlaveCommand, Error> { 1684 pub fn blocking_listen(&mut self) -> Result<SlaveCommand, Error> {
1109 let state = self.state; 1685 let timeout = self.timeout();
1686
1110 self.info.regs.cr1().modify(|reg| { 1687 self.info.regs.cr1().modify(|reg| {
1111 reg.set_addrie(true); 1688 reg.set_addrie(true);
1112 trace!("Enable ADDRIE"); 1689 trace!("Enable ADDRIE");
1113 }); 1690 });
1114 1691
1115 poll_fn(|cx| { 1692 loop {
1116 state.waker.register(cx.waker());
1117 let isr = self.info.regs.isr().read(); 1693 let isr = self.info.regs.isr().read();
1118 if !isr.addr() { 1694 if isr.addr() {
1119 Poll::Pending 1695 break;
1120 } else {
1121 trace!("ADDR triggered (address match)");
1122 // we do not clear the address flag here as it will be cleared by the dma read/write
1123 // if we clear it here the clock stretching will stop and the master will read in data before the slave is ready to send it
1124 match isr.dir() {
1125 i2c::vals::Dir::WRITE => {
1126 trace!("DIR: write");
1127 Poll::Ready(Ok(SlaveCommand {
1128 kind: SlaveCommandKind::Write,
1129 address: self.determine_matched_address()?,
1130 }))
1131 }
1132 i2c::vals::Dir::READ => {
1133 trace!("DIR: read");
1134 Poll::Ready(Ok(SlaveCommand {
1135 kind: SlaveCommandKind::Read,
1136 address: self.determine_matched_address()?,
1137 }))
1138 }
1139 }
1140 } 1696 }
1141 }) 1697 timeout.check()?;
1142 .await 1698 }
1699
1700 trace!("ADDR triggered (address match)");
1701
1702 // we do not clear the address flag here as it will be cleared by the dma read/write
1703 // if we clear it here the clock stretching will stop and the master will read in data before the slave is ready to send it
1704 self.slave_command()
1705 }
1706
1707 /// Determine the received slave command.
1708 fn slave_command(&self) -> Result<SlaveCommand, Error> {
1709 let isr = self.info.regs.isr().read();
1710
1711 match isr.dir() {
1712 i2c::vals::Dir::WRITE => {
1713 trace!("DIR: write");
1714 Ok(SlaveCommand {
1715 kind: SlaveCommandKind::Write,
1716 address: self.determine_matched_address()?,
1717 })
1718 }
1719 i2c::vals::Dir::READ => {
1720 trace!("DIR: read");
1721 Ok(SlaveCommand {
1722 kind: SlaveCommandKind::Read,
1723 address: self.determine_matched_address()?,
1724 })
1725 }
1726 }
1143 } 1727 }
1144 1728
1145 /// Respond to a write command. 1729 /// Respond to a write command.
@@ -1158,16 +1742,44 @@ impl<'d, M: Mode> I2c<'d, M, MultiMaster> {
1158} 1742}
1159 1743
1160impl<'d> I2c<'d, Async, MultiMaster> { 1744impl<'d> I2c<'d, Async, MultiMaster> {
1745 /// Listen for incoming I2C messages.
1746 ///
1747 /// The listen method is an asynchronous method but it does not require DMA to be asynchronous.
1748 pub async fn listen(&mut self) -> Result<SlaveCommand, Error> {
1749 let _scoped_block_stop = self.info.rcc.block_stop();
1750 let state = self.state;
1751 self.info.regs.cr1().modify(|reg| {
1752 reg.set_addrie(true);
1753 trace!("Enable ADDRIE");
1754 });
1755
1756 poll_fn(|cx| {
1757 state.waker.register(cx.waker());
1758 let isr = self.info.regs.isr().read();
1759 if !isr.addr() {
1760 Poll::Pending
1761 } else {
1762 trace!("ADDR triggered (address match)");
1763 // we do not clear the address flag here as it will be cleared by the dma read/write
1764 // if we clear it here the clock stretching will stop and the master will read in data before the slave is ready to send it
1765 Poll::Ready(self.slave_command())
1766 }
1767 })
1768 .await
1769 }
1770
1161 /// Respond to a write command. 1771 /// Respond to a write command.
1162 /// 1772 ///
1163 /// Returns the total number of bytes received. 1773 /// Returns the total number of bytes received.
1164 pub async fn respond_to_write(&mut self, buffer: &mut [u8]) -> Result<usize, Error> { 1774 pub async fn respond_to_write(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
1775 let _scoped_block_stop = self.info.rcc.block_stop();
1165 let timeout = self.timeout(); 1776 let timeout = self.timeout();
1166 timeout.with(self.read_dma_internal_slave(buffer, timeout)).await 1777 timeout.with(self.read_dma_internal_slave(buffer, timeout)).await
1167 } 1778 }
1168 1779
1169 /// Respond to a read request from an I2C master. 1780 /// Respond to a read request from an I2C master.
1170 pub async fn respond_to_read(&mut self, write: &[u8]) -> Result<SendStatus, Error> { 1781 pub async fn respond_to_read(&mut self, write: &[u8]) -> Result<SendStatus, Error> {
1782 let _scoped_block_stop = self.info.rcc.block_stop();
1171 let timeout = self.timeout(); 1783 let timeout = self.timeout();
1172 timeout.with(self.write_dma_internal_slave(write, timeout)).await 1784 timeout.with(self.write_dma_internal_slave(write, timeout)).await
1173 } 1785 }
@@ -1181,7 +1793,7 @@ impl<'d> I2c<'d, Async, MultiMaster> {
1181 1793
1182 let regs = self.info.regs; 1794 let regs = self.info.regs;
1183 1795
1184 let dma_transfer = unsafe { 1796 let mut dma_transfer = unsafe {
1185 regs.cr1().modify(|w| { 1797 regs.cr1().modify(|w| {
1186 w.set_rxdmaen(true); 1798 w.set_rxdmaen(true);
1187 w.set_stopie(true); 1799 w.set_stopie(true);
@@ -1213,13 +1825,20 @@ impl<'d> I2c<'d, Async, MultiMaster> {
1213 Poll::Pending 1825 Poll::Pending
1214 } else if isr.tcr() { 1826 } else if isr.tcr() {
1215 let is_last_slice = remaining_len <= 255; 1827 let is_last_slice = remaining_len <= 255;
1216 if let Err(e) = Self::reload(self.info, remaining_len.min(255), !is_last_slice, timeout) { 1828 if let Err(e) = Self::reload(
1829 self.info,
1830 remaining_len.min(255),
1831 !is_last_slice,
1832 Stop::Software,
1833 timeout,
1834 ) {
1217 return Poll::Ready(Err(e)); 1835 return Poll::Ready(Err(e));
1218 } 1836 }
1219 remaining_len = remaining_len.saturating_sub(255); 1837 remaining_len = remaining_len.saturating_sub(255);
1220 regs.cr1().modify(|w| w.set_tcie(true)); 1838 regs.cr1().modify(|w| w.set_tcie(true));
1221 Poll::Pending 1839 Poll::Pending
1222 } else if isr.stopf() { 1840 } else if isr.stopf() {
1841 remaining_len = remaining_len.saturating_add(dma_transfer.get_remaining_transfers() as usize);
1223 regs.icr().write(|reg| reg.set_stopcf(true)); 1842 regs.icr().write(|reg| reg.set_stopcf(true));
1224 let poll = Poll::Ready(Ok(total_len - remaining_len)); 1843 let poll = Poll::Ready(Ok(total_len - remaining_len));
1225 poll 1844 poll
@@ -1229,6 +1848,7 @@ impl<'d> I2c<'d, Async, MultiMaster> {
1229 }) 1848 })
1230 .await?; 1849 .await?;
1231 1850
1851 dma_transfer.request_pause();
1232 dma_transfer.await; 1852 dma_transfer.await;
1233 1853
1234 drop(on_drop); 1854 drop(on_drop);
@@ -1258,7 +1878,8 @@ impl<'d> I2c<'d, Async, MultiMaster> {
1258 w.set_txdmaen(false); 1878 w.set_txdmaen(false);
1259 w.set_stopie(false); 1879 w.set_stopie(false);
1260 w.set_tcie(false); 1880 w.set_tcie(false);
1261 }) 1881 });
1882 regs.isr().write(|w| w.set_txe(true));
1262 }); 1883 });
1263 1884
1264 let state = self.state; 1885 let state = self.state;
@@ -1274,13 +1895,24 @@ impl<'d> I2c<'d, Async, MultiMaster> {
1274 Poll::Pending 1895 Poll::Pending
1275 } else if isr.tcr() { 1896 } else if isr.tcr() {
1276 let is_last_slice = remaining_len <= 255; 1897 let is_last_slice = remaining_len <= 255;
1277 if let Err(e) = Self::reload(self.info, remaining_len.min(255), !is_last_slice, timeout) { 1898 if let Err(e) = Self::reload(
1899 self.info,
1900 remaining_len.min(255),
1901 !is_last_slice,
1902 Stop::Software,
1903 timeout,
1904 ) {
1278 return Poll::Ready(Err(e)); 1905 return Poll::Ready(Err(e));
1279 } 1906 }
1280 remaining_len = remaining_len.saturating_sub(255); 1907 remaining_len = remaining_len.saturating_sub(255);
1281 self.info.regs.cr1().modify(|w| w.set_tcie(true)); 1908 self.info.regs.cr1().modify(|w| w.set_tcie(true));
1282 Poll::Pending 1909 Poll::Pending
1283 } else if isr.stopf() { 1910 } else if isr.stopf() {
1911 let mut leftover_bytes = dma_transfer.get_remaining_transfers();
1912 if !self.info.regs.isr().read().txe() {
1913 leftover_bytes = leftover_bytes.saturating_add(1);
1914 }
1915 remaining_len = remaining_len.saturating_add(leftover_bytes as usize);
1284 self.info.regs.icr().write(|reg| reg.set_stopcf(true)); 1916 self.info.regs.icr().write(|reg| reg.set_stopcf(true));
1285 if remaining_len > 0 { 1917 if remaining_len > 0 {
1286 dma_transfer.request_pause(); 1918 dma_transfer.request_pause();
@@ -1294,6 +1926,7 @@ impl<'d> I2c<'d, Async, MultiMaster> {
1294 }) 1926 })
1295 .await?; 1927 .await?;
1296 1928
1929 dma_transfer.request_pause();
1297 dma_transfer.await; 1930 dma_transfer.await;
1298 1931
1299 drop(on_drop); 1932 drop(on_drop);