esp-hal 1.2.0

Bare-metal HAL for Espressif devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
#![cfg_attr(docsrs, procmacros::doc_replace)]
//! # Inter-Integrated Circuit (I2C) - Master mode
//!
//! ## Overview
//!
//! This driver implements the I2C Master mode. In this mode, the MCU initiates
//! and controls the I2C communication with one or more slave devices. Slave
//! devices are identified by their unique I2C addresses.
//!
//! ## Configuration
//!
//! The driver can be configured using the [`Config`] struct. To create a
//! configuration, you can use the [`Config::default()`] method, and then modify
//! the individual settings as needed, by calling `with_*` methods on the
//! [`Config`] struct.
//!
//! ```rust, no_run
//! # {before_snippet}
//! use esp_hal::{i2c::master::Config, time::Rate};
//!
//! let config = Config::default().with_frequency(Rate::from_khz(100));
//! # {after_snippet}
//! ```
//!
//! You will then need to pass the configuration to [`I2c::new`], and you can
//! also change the configuration later by calling [`I2c::apply_config`].
//!
//! You will also need to specify the SDA and SCL pins when you create the
//! driver instance.
//! ```rust, no_run
//! # {before_snippet}
//! use esp_hal::i2c::master::I2c;
//! # use esp_hal::{i2c::master::Config, time::Rate};
//! #
//! # let config = Config::default();
//! #
//! // You need to configure the driver during initialization:
//! let mut i2c = I2c::new(peripherals.I2C0, config)?
//!     .with_sda(peripherals.GPIO2)
//!     .with_scl(peripherals.GPIO3);
//!
//! // You can change the configuration later:
//! let new_config = config.with_frequency(Rate::from_khz(400));
//! i2c.apply_config(&new_config)?;
//! # {after_snippet}
//! ```
//!
//! ## Usage
//!
//! The master communicates with slave devices using I2C transactions. A
//! transaction can be a write, a read, or a combination of both. The
//! [`I2c`] driver provides methods for performing these transactions:
//! ```rust, no_run
//! # {before_snippet}
//! # use esp_hal::i2c::master::{I2c, Config, Operation};
//! # let config = Config::default();
//! # let mut i2c = I2c::new(peripherals.I2C0, config)?;
//! #
//! // `u8` is automatically converted to `I2cAddress::SevenBit`. The device
//! // address does not contain the `R/W` bit!
//! const DEVICE_ADDR: u8 = 0x77;
//! let write_buffer = [0xAA];
//! let mut read_buffer = [0u8; 22];
//!
//! i2c.write(DEVICE_ADDR, &write_buffer)?;
//! i2c.write_read(DEVICE_ADDR, &write_buffer, &mut read_buffer)?;
//! i2c.read(DEVICE_ADDR, &mut read_buffer)?;
//! i2c.transaction(
//!     DEVICE_ADDR,
//!     &mut [
//!         Operation::Write(&write_buffer),
//!         Operation::Read(&mut read_buffer),
//!     ],
//! )?;
//! # {after_snippet}
//! ```
//! If you configure the driver to `async` mode, the driver also provides
//! asynchronous versions of these methods:
//! ```rust, no_run
//! # {before_snippet}
//! # use esp_hal::i2c::master::{I2c, Config, Operation};
//! # let config = Config::default();
//! # let mut i2c = I2c::new(peripherals.I2C0, config)?;
//! #
//! # const DEVICE_ADDR: u8 = 0x77;
//! # let write_buffer = [0xAA];
//! # let mut read_buffer = [0u8; 22];
//! #
//! // Reconfigure the driver to use async mode.
//! let mut i2c = i2c.into_async();
//!
//! i2c.write_async(DEVICE_ADDR, &write_buffer).await?;
//! i2c.write_read_async(DEVICE_ADDR, &write_buffer, &mut read_buffer)
//!     .await?;
//! i2c.read_async(DEVICE_ADDR, &mut read_buffer).await?;
//! i2c.transaction_async(
//!     DEVICE_ADDR,
//!     &mut [
//!         Operation::Write(&write_buffer),
//!         Operation::Read(&mut read_buffer),
//!     ],
//! )
//! .await?;
//!
//! // You should still be able to use the blocking methods, if you need to:
//! i2c.write(DEVICE_ADDR, &write_buffer)?;
//!
//! # {after_snippet}
//! ```
//!
//! The I2C driver also implements [embedded-hal] and [embedded-hal-async]
//! traits, so you can use it with any crate that supports these traits.
//!
//! [embedded-hal]: embedded_hal::i2c
//! [embedded-hal-async]: embedded_hal_async::i2c

use core::{
    marker::PhantomData,
    pin::Pin,
    task::{Context, Poll},
};

use enumset::{EnumSet, EnumSetType};

use crate::{
    Async,
    Blocking,
    DriverMode,
    asynch::AtomicWaker,
    clock::ll::{ClockTree, I2cFunctionClockConfig},
    gpio::{
        DriveMode,
        InputSignal,
        Level,
        OutputConfig,
        OutputSignal,
        PinGuard,
        Pull,
        interconnect::{self, PeripheralInput, PeripheralOutput},
    },
    handler,
    interrupt::InterruptHandler,
    pac::i2c0::{COMD, RegisterBlock},
    private,
    ram,
    system::PeripheralGuard,
    time::{Duration, Instant, Rate},
};

mod eh;
mod low_level;

pub use low_level::{AnyI2c, Instance};
use low_level::{Driver, I2cClockGuard};

const I2C_FIFO_SIZE: usize = property!("i2c_master.fifo_size");
// Chunk writes/reads by this size
const I2C_CHUNK_SIZE: usize = I2C_FIFO_SIZE - 1;
const CLEAR_BUS_TIMEOUT_MS: Duration = Duration::from_millis(50);

/// Representation of I2C address.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum I2cAddress {
    /// 7-bit address mode type.
    ///
    /// 7-bit addresses are specified in **right-aligned** form, e.g. in the range
    /// `0x00..=0x7F`
    ///
    /// For example, a device that has the seven bit address of `0b011_0010`,
    /// and therefore is addressed on the wire using:
    ///
    /// * `0b0110010_0` or `0x64` for *writes*
    /// * `0b0110010_1` or `0x65` for *reads*
    ///
    /// The above address is specified as 0b0011_0010 or 0x32, NOT 0x64 or 0x65.
    SevenBit(u8),
}

impl I2cAddress {
    fn validate(&self) -> Result<(), Error> {
        match self {
            I2cAddress::SevenBit(addr) => {
                if *addr > 0x7F {
                    return Err(Error::AddressInvalid(*self));
                }
            }
        }

        Ok(())
    }

    fn bytes(self) -> usize {
        match self {
            I2cAddress::SevenBit(_) => 1,
        }
    }
}

impl From<u8> for I2cAddress {
    fn from(value: u8) -> Self {
        I2cAddress::SevenBit(value)
    }
}

/// I2C SCL timeout period.
///
/// When the level of SCL remains unchanged for more than `timeout` bus
/// clock cycles, the bus goes to idle state.
///
/// Default value is `BusCycles(10)`.
#[doc = ""]
#[cfg_attr(
    i2c_master_bus_timeout_is_exponential,
    doc = "The effective timeout may be longer than the value configured here."
)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, strum::Display)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
#[instability::unstable]
pub enum BusTimeout {
    /// Use the maximum timeout value.
    Maximum,

    /// Disables timeout control.
    #[cfg(i2c_master_has_bus_timeout_enable)]
    Disabled,

    /// Timeout in bus clock cycles.
    BusCycles(u32),
}

impl BusTimeout {
    /// Returns the timeout in APB cycles, or `None` if the timeout is disabled.
    ///
    /// Newer devices only support power-of-two timeouts, so the value must be rounded to a
    /// power of two using the logarithm of the timeout value. This may cause considerably longer
    /// (at most approximately double) timeouts than configured. An `ApbCycles` variant may be
    /// provided in the future to allow specifying the timeout in APB cycles directly.
    fn apb_cycles(self, half_bus_cycle: u32) -> Result<Option<u32>, ConfigError> {
        match self {
            BusTimeout::Maximum => Ok(Some(property!("i2c_master.max_bus_timeout"))),

            #[cfg(i2c_master_has_bus_timeout_enable)]
            BusTimeout::Disabled => Ok(None),

            BusTimeout::BusCycles(cycles) => {
                let raw = if cfg!(i2c_master_bus_timeout_is_exponential) {
                    let to_peri = (cycles * 2 * half_bus_cycle).max(1);
                    let log2 = to_peri.ilog2();
                    // If not a power of 2, round up so that we don't shorten timeouts.
                    if to_peri != 1 << log2 { log2 + 1 } else { log2 }
                } else {
                    cycles * 2 * half_bus_cycle
                };

                if raw <= property!("i2c_master.max_bus_timeout") {
                    Ok(Some(raw))
                } else {
                    Err(ConfigError::TimeoutTooLong)
                }
            }
        }
    }
}

/// Software timeout for I2C operations.
///
/// This timeout is used to limit the duration of I2C operations in software.
/// Using this in conjunction with `async` operations causes the task to be woken
/// up continuously until the operation completes or the timeout is reached. Prefer
/// an asynchronous timeout mechanism (like [`embassy_time::with_timeout`]) for
/// better efficiency.
///
/// [`embassy_time::with_timeout`]: https://docs.rs/embassy-time/0.4.0/embassy_time/fn.with_timeout.html
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SoftwareTimeout {
    /// No software timeout is set.
    None,

    /// Defines a fixed timeout for I2C operations.
    Transaction(Duration),

    /// Defines a data length dependent timeout for I2C operations.
    ///
    /// The applied timeout is calculated as `data_length * duration_per_byte`.
    /// In [`I2c::transaction`] and [`I2c::transaction_async`], the timeout is
    /// applied separately for each operation.
    PerByte(Duration),
}

/// When the FSM remains unchanged for more than the 2^ the given amount of bus
/// clock cycles a timeout will be triggered.
///
/// The default value is 23 (2^23 clock cycles).
#[instability::unstable]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg(i2c_master_has_fsm_timeouts)]
pub struct FsmTimeout {
    value: u8,
}

#[cfg(i2c_master_has_fsm_timeouts)]
impl FsmTimeout {
    const FSM_TIMEOUT_MAX: u8 = 23;

    /// Creates a new timeout.
    ///
    /// The meaning of the value and the allowed range of values is different
    /// for different chips.
    #[instability::unstable]
    pub const fn new_const<const VALUE: u8>() -> Self {
        const {
            core::assert!(VALUE <= Self::FSM_TIMEOUT_MAX, "Invalid timeout value");
        }
        Self { value: VALUE }
    }

    /// Creates a new timeout.
    ///
    /// The meaning of the value and the allowed range of values is different
    /// for different chips.
    #[instability::unstable]
    pub fn new(value: u8) -> Result<Self, ConfigError> {
        if value > Self::FSM_TIMEOUT_MAX {
            return Err(ConfigError::TimeoutTooLong);
        }

        Ok(Self { value })
    }

    fn value(&self) -> u8 {
        self.value
    }
}

#[cfg(i2c_master_has_fsm_timeouts)]
impl Default for FsmTimeout {
    fn default() -> Self {
        Self::new_const::<{ Self::FSM_TIMEOUT_MAX }>()
    }
}

/// I2C-specific transmission errors
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum Error {
    /// The transmission exceeded the FIFO size.
    FifoExceeded,
    /// The acknowledgment check failed.
    AcknowledgeCheckFailed(AcknowledgeCheckFailedReason),
    /// A timeout occurred during transmission.
    Timeout,
    /// The arbitration for the bus was lost.
    ArbitrationLost,
    /// The execution of the I2C command was incomplete.
    ExecutionIncomplete,
    /// The number of commands issued exceeded the limit.
    CommandNumberExceeded,
    /// Zero length read or write operation.
    ZeroLengthInvalid,
    /// The given address is invalid.
    AddressInvalid(I2cAddress),
}

/// I2C no acknowledge error reason.
///
/// Consider this as a hint and make sure to always handle all cases.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum AcknowledgeCheckFailedReason {
    /// The device did not acknowledge its address. The device may be missing.
    Address,

    /// The device did not acknowledge the data. It may not be ready to process
    /// requests at the moment.
    Data,

    /// Either the device did not acknowledge its address or the data, but it is
    /// unknown which.
    Unknown,
}

impl core::fmt::Display for AcknowledgeCheckFailedReason {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            AcknowledgeCheckFailedReason::Address => write!(f, "Address"),
            AcknowledgeCheckFailedReason::Data => write!(f, "Data"),
            AcknowledgeCheckFailedReason::Unknown => write!(f, "Unknown"),
        }
    }
}

impl From<&AcknowledgeCheckFailedReason> for embedded_hal::i2c::NoAcknowledgeSource {
    fn from(value: &AcknowledgeCheckFailedReason) -> Self {
        match value {
            AcknowledgeCheckFailedReason::Address => {
                embedded_hal::i2c::NoAcknowledgeSource::Address
            }
            AcknowledgeCheckFailedReason::Data => embedded_hal::i2c::NoAcknowledgeSource::Data,
            AcknowledgeCheckFailedReason::Unknown => {
                embedded_hal::i2c::NoAcknowledgeSource::Unknown
            }
        }
    }
}

impl core::error::Error for Error {}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Error::FifoExceeded => write!(f, "The transmission exceeded the FIFO size"),
            Error::AcknowledgeCheckFailed(reason) => {
                write!(f, "The acknowledgment check failed. Reason: {reason}")
            }
            Error::Timeout => write!(f, "A timeout occurred during transmission"),
            Error::ArbitrationLost => write!(f, "The arbitration for the bus was lost"),
            Error::ExecutionIncomplete => {
                write!(f, "The execution of the I2C command was incomplete")
            }
            Error::CommandNumberExceeded => {
                write!(f, "The number of commands issued exceeded the limit")
            }
            Error::ZeroLengthInvalid => write!(f, "Zero length read or write operation"),
            Error::AddressInvalid(address) => {
                write!(f, "The given address ({address:?}) is invalid")
            }
        }
    }
}

/// I2C-specific configuration errors
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum ConfigError {
    /// Provided bus frequency is not valid for the current configuration.
    FrequencyOutOfRange,
    /// Provided timeout is not valid for the current configuration.
    TimeoutTooLong,
}

impl core::error::Error for ConfigError {}

impl core::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            ConfigError::FrequencyOutOfRange => write!(
                f,
                "Provided bus frequency is invalid for the current configuration"
            ),
            ConfigError::TimeoutTooLong => write!(
                f,
                "Provided timeout is invalid for the current configuration"
            ),
        }
    }
}

// This enum is used to keep track of the last/next operation that was/will be
// performed in an embedded-hal(-async) I2c::transaction. It is used to
// determine whether a START condition should be issued at the start of the
// current operation and whether a read needs an ack or a nack for the final
// byte.
#[derive(PartialEq)]
enum OpKind {
    Write,
    Read,
}

/// I2C operation.
///
/// Several operations can be combined as part of a transaction.
#[derive(Debug, PartialEq, Eq, Hash, strum::Display)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Operation<'a> {
    /// Writes data from the provided buffer.
    Write(&'a [u8]),

    /// Reads data into the provided buffer.
    Read(&'a mut [u8]),
}

impl<'a, 'b> From<&'a mut embedded_hal::i2c::Operation<'b>> for Operation<'a> {
    fn from(value: &'a mut embedded_hal::i2c::Operation<'b>) -> Self {
        match value {
            embedded_hal::i2c::Operation::Write(buffer) => Operation::Write(buffer),
            embedded_hal::i2c::Operation::Read(buffer) => Operation::Read(buffer),
        }
    }
}

impl<'a, 'b> From<&'a mut Operation<'b>> for Operation<'a> {
    fn from(value: &'a mut Operation<'b>) -> Self {
        match value {
            Operation::Write(buffer) => Operation::Write(buffer),
            Operation::Read(buffer) => Operation::Read(buffer),
        }
    }
}

impl Operation<'_> {
    fn is_write(&self) -> bool {
        matches!(self, Operation::Write(_))
    }

    fn kind(&self) -> OpKind {
        match self {
            Operation::Write(_) => OpKind::Write,
            Operation::Read(_) => OpKind::Read,
        }
    }

    fn is_empty(&self) -> bool {
        match self {
            Operation::Write(buffer) => buffer.is_empty(),
            Operation::Read(buffer) => buffer.is_empty(),
        }
    }
}

/// A generic I2C Command.
#[derive(Debug)]
enum Command {
    Start,
    Stop,
    End,
    Write {
        /// This bit is to set an expected ACK value for the transmitter.
        ack_exp: Ack,
        /// Enables checking the ACK value received against the ack_exp value.
        ack_check_en: bool,
        /// Length of data (in bytes) to be written. The maximum length is.
        #[doc = property!("i2c_master.fifo_size", str)]
        /// , while the minimum is 1.
        length: u8,
    },
    Read {
        /// Indicates whether the receiver will send an ACK after this byte has
        /// been received.
        ack_value: Ack,
        /// Length of data (in bytes) to be read. The maximum length is.
        #[doc = property!("i2c_master.fifo_size", str)]
        /// , while the minimum is 1.
        length: u8,
    },
}

enum OperationType {
    Write = 0,
    Read  = 1,
}

#[derive(Eq, PartialEq, Copy, Clone, Debug)]
enum Ack {
    Ack  = 0,
    Nack = 1,
}

/// Clock source for the I2C peripheral.
#[instability::unstable]
pub use crate::soc::clocks::I2cFunctionClockSclk as ClockSource;

/// I2C driver configuration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, procmacros::BuilderLite)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub struct Config {
    /// The I2C clock frequency.
    ///
    /// Default value: 100 kHz.
    frequency: Rate,

    /// I2C SCL timeout period.
    ///
    /// Default value:
    #[cfg_attr(i2c_master_has_bus_timeout_enable, doc = "disabled")]
    #[cfg_attr(not(i2c_master_has_bus_timeout_enable), doc = concat!(property!("i2c_master.max_bus_timeout", str), " bus cycles"))]
    #[builder_lite(unstable)]
    timeout: BusTimeout,

    /// Software timeout.
    ///
    /// Default value: disabled.
    software_timeout: SoftwareTimeout,

    /// Sets the threshold value for the unchanged period of the SCL_FSM.
    ///
    /// Default value: 16.
    #[cfg(i2c_master_has_fsm_timeouts)]
    #[builder_lite(unstable)]
    scl_st_timeout: FsmTimeout,

    /// Sets the threshold for the unchanged duration of the SCL_MAIN_FSM.
    ///
    /// Default value: 16.
    #[cfg(i2c_master_has_fsm_timeouts)]
    #[builder_lite(unstable)]
    scl_main_st_timeout: FsmTimeout,

    /// The clock source for the I2C peripheral.
    ///
    /// Default value: [`ClockSource::default()`].
    #[builder_lite(unstable)]
    clock_source: ClockSource,

    /// Selects whether the controller samples the SDA line while SCL is high or
    /// low.
    ///
    /// Standard I2C devices change SDA while SCL is low and hold it stable while
    /// SCL is high, so the line is sampled while SCL is high by default
    /// ([`Level::High`]).
    #[builder_lite(unstable)]
    scl_sample_level: Level,

    /// Enables I2C bus arbitration detection.
    ///
    /// Default value: `false`.
    #[cfg(i2c_master_has_arbitration_en)]
    #[builder_lite(unstable)]
    bus_arbitration: bool,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            frequency: Rate::from_khz(100),

            #[cfg(i2c_master_has_bus_timeout_enable)]
            timeout: BusTimeout::Disabled,
            #[cfg(not(i2c_master_has_bus_timeout_enable))]
            timeout: BusTimeout::Maximum,

            software_timeout: SoftwareTimeout::None,

            #[cfg(i2c_master_has_fsm_timeouts)]
            scl_st_timeout: Default::default(),
            #[cfg(i2c_master_has_fsm_timeouts)]
            scl_main_st_timeout: Default::default(),

            clock_source: Default::default(),

            scl_sample_level: Level::High,

            #[cfg(i2c_master_has_arbitration_en)]
            bus_arbitration: false,
        }
    }
}

#[procmacros::doc_replace]
/// I2C driver
///
/// # Examples
///
/// ```rust, no_run
/// # {before_snippet}
/// use esp_hal::i2c::master::{Config, I2c};
/// # const DEVICE_ADDR: u8 = 0x77;
/// let mut i2c = I2c::new(peripherals.I2C0, Config::default())?
///     .with_sda(peripherals.GPIO1)
///     .with_scl(peripherals.GPIO2);
///
/// let mut data = [0u8; 22];
/// i2c.write_read(DEVICE_ADDR, &[0xaa], &mut data)?;
/// # {after_snippet}
/// ```
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct I2c<'d, Dm: DriverMode> {
    i2c: AnyI2c<'d>,
    phantom: PhantomData<Dm>,
    guard: PeripheralGuard,
    config: DriverConfig,
}

#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
struct DriverConfig {
    config: Config,
    sda_pin: PinGuard,
    scl_pin: PinGuard,
}

impl<'d> I2c<'d, Blocking> {
    #[procmacros::doc_replace]
    /// Creates a new I2C instance.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c};
    /// let i2c = I2c::new(peripherals.I2C0, Config::default())?
    ///     .with_sda(peripherals.GPIO1)
    ///     .with_scl(peripherals.GPIO2);
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`ConfigError`] when bus frequency or timeout passed in config is invalid.
    pub fn new(i2c: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
        let guard = PeripheralGuard::new(i2c.info().peripheral);

        ClockTree::with(|clocks| {
            let clock = i2c.info().clock_instance;
            let config = I2cFunctionClockConfig::new(
                Default::default(),
                #[cfg(any(i2c_master_version = "3", i2c_master_version = "4"))]
                0,
            );
            clock.configure_function_clock(clocks, config);
        });

        let sda_pin = PinGuard::new_unconnected();
        let scl_pin = PinGuard::new_unconnected();

        let i2c_any = i2c.degrade();

        let i2c = I2c {
            i2c: i2c_any,
            phantom: PhantomData,
            guard,
            config: DriverConfig {
                config,
                sda_pin,
                scl_pin,
            },
        };

        // Make sure inputs are well-defined.
        let i2c = i2c.with_scl(crate::gpio::Level::High);
        let mut i2c = i2c.with_sda(crate::gpio::Level::High);

        i2c.apply_config(&config)?;

        Ok(i2c)
    }

    /// Reconfigures the driver to operate in [`Async`] mode.
    ///
    /// See the [`Async`] documentation for an example on how to use this
    /// method.
    pub fn into_async(mut self) -> I2c<'d, Async> {
        self.set_interrupt_handler(self.driver().info.async_handler);

        I2c {
            i2c: self.i2c,
            phantom: PhantomData,
            guard: self.guard,
            config: self.config,
        }
    }

    #[cfg_attr(
        not(multi_core),
        doc = "Registers an interrupt handler for the peripheral."
    )]
    #[cfg_attr(
        multi_core,
        doc = "Registers an interrupt handler for the peripheral on the current core."
    )]
    #[doc = ""]
    /// Replaces any previously registered interrupt handlers.
    ///
    /// The default/unhandled interrupt handler can be restored by passing
    /// [DEFAULT_INTERRUPT_HANDLER][crate::interrupt::DEFAULT_INTERRUPT_HANDLER].
    ///
    /// # Panics
    ///
    /// Panics if passed interrupt handler is invalid (e.g. has priority
    /// `None`)
    #[instability::unstable]
    pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
        self.i2c.set_interrupt_handler(handler);
    }

    /// Listens for the given interrupts.
    #[instability::unstable]
    pub fn listen(&mut self, interrupts: impl Into<EnumSet<Event>>) {
        self.i2c.info().enable_listen(interrupts.into(), true)
    }

    /// Unlistens from the given interrupts.
    #[instability::unstable]
    pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<Event>>) {
        self.i2c.info().enable_listen(interrupts.into(), false)
    }

    /// Returns the asserted interrupts.
    #[instability::unstable]
    pub fn interrupts(&mut self) -> EnumSet<Event> {
        self.i2c.info().interrupts()
    }

    /// Resets asserted interrupts.
    #[instability::unstable]
    pub fn clear_interrupts(&mut self, interrupts: EnumSet<Event>) {
        self.i2c.info().clear_interrupts(interrupts)
    }
}

impl private::Sealed for I2c<'_, Blocking> {}

#[instability::unstable]
impl crate::interrupt::InterruptConfigurable for I2c<'_, Blocking> {
    fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
        self.i2c.set_interrupt_handler(handler);
    }
}

#[derive(Debug, EnumSetType)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
#[instability::unstable]
pub enum Event {
    /// Triggered when op_code of the master indicates an END command and an END
    /// condition is detected.
    EndDetect,

    /// Triggered when the I2C controller detects a STOP bit.
    TxComplete,

    /// Triggered when the TX FIFO watermark check is enabled and the TX fifo
    /// falls below the configured watermark.
    #[cfg(i2c_master_has_tx_fifo_watermark)]
    TxFifoWatermark,
}

impl<'d> I2c<'d, Async> {
    /// Reconfigures the driver to operate in [`Blocking`] mode.
    ///
    /// See the [`Blocking`] documentation for an example on how to use this
    /// method.
    pub fn into_blocking(self) -> I2c<'d, Blocking> {
        self.i2c.disable_peri_interrupt_on_all_cores();

        I2c {
            i2c: self.i2c,
            phantom: PhantomData,
            guard: self.guard,
            config: self.config,
        }
    }

    #[procmacros::doc_replace]
    /// Writes bytes to slave with given `address`.
    ///
    /// Dropping the returned Future aborts the transfer, but blocks while the
    /// driver finishes clearing and releasing the bus.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c};
    /// const DEVICE_ADDR: u8 = 0x77;
    /// let mut i2c = I2c::new(peripherals.I2C0, Config::default())?
    ///     .with_sda(peripherals.GPIO1)
    ///     .with_scl(peripherals.GPIO2)
    ///     .into_async();
    ///
    /// i2c.write_async(DEVICE_ADDR, &[0xaa]).await?;
    /// # {after_snippet}
    /// ```
    pub async fn write_async<A: Into<I2cAddress>>(
        &mut self,
        address: A,
        buffer: &[u8],
    ) -> Result<(), Error> {
        self.transaction_async(address, &mut [Operation::Write(buffer)])
            .await
    }

    #[procmacros::doc_replace]
    /// Reads enough bytes from slave with `address` to fill `buffer`.
    ///
    /// Dropping the returned Future aborts the transfer, but blocks while the
    /// driver finishes clearing and releasing the bus.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c};
    /// const DEVICE_ADDR: u8 = 0x77;
    /// let mut i2c = I2c::new(peripherals.I2C0, Config::default())?
    ///     .with_sda(peripherals.GPIO1)
    ///     .with_scl(peripherals.GPIO2)
    ///     .into_async();
    ///
    /// let mut data = [0u8; 22];
    /// i2c.read_async(DEVICE_ADDR, &mut data).await?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error`] when the passed buffer has zero length.
    pub async fn read_async<A: Into<I2cAddress>>(
        &mut self,
        address: A,
        buffer: &mut [u8],
    ) -> Result<(), Error> {
        self.transaction_async(address, &mut [Operation::Read(buffer)])
            .await
    }

    #[procmacros::doc_replace]
    /// Writes bytes to slave with given `address` and then reads enough
    /// bytes to fill `buffer` *in a single transaction*.
    ///
    /// Dropping the returned Future aborts the transfer, but blocks while the
    /// driver finishes clearing and releasing the bus.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c};
    /// const DEVICE_ADDR: u8 = 0x77;
    /// let mut i2c = I2c::new(peripherals.I2C0, Config::default())?
    ///     .with_sda(peripherals.GPIO1)
    ///     .with_scl(peripherals.GPIO2)
    ///     .into_async();
    ///
    /// let mut data = [0u8; 22];
    /// i2c.write_read_async(DEVICE_ADDR, &[0xaa], &mut data)
    ///     .await?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error`] when the passed buffer has zero length.
    pub async fn write_read_async<A: Into<I2cAddress>>(
        &mut self,
        address: A,
        write_buffer: &[u8],
        read_buffer: &mut [u8],
    ) -> Result<(), Error> {
        self.transaction_async(
            address,
            &mut [Operation::Write(write_buffer), Operation::Read(read_buffer)],
        )
        .await
    }

    #[procmacros::doc_replace]
    /// Executes the provided operations on the I2C bus as a single transaction.
    ///
    /// Dropping the returned Future aborts the transfer, but blocks while the
    /// driver finishes clearing and releasing the bus.
    ///
    /// Transaction contract:
    /// - Before executing the first operation an ST is sent automatically. This is followed by
    ///   SAD+R/W as appropriate.
    /// - Data from adjacent operations of the same type are sent after each other without an SP or
    ///   SR.
    /// - Between adjacent operations of a different type an SR and SAD+R/W is sent.
    /// - After executing the last operation an SP is sent automatically.
    /// - If the last operation is a `Read` the master does not send an acknowledge for the last
    ///   byte.
    ///
    /// - `ST` = start condition
    /// - `SAD+R/W` = slave address followed by bit 1 to indicate reading or 0 to indicate writing
    /// - `SR` = repeated start condition
    /// - `SP` = stop condition
    #[cfg_attr(
        any(esp32, esp32s2),
        doc = "\n\nOn ESP32 and ESP32-S2 there might be issues combining large read/write operations with small (<3 bytes) read/write operations.\n\n"
    )]
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c, Operation};
    /// const DEVICE_ADDR: u8 = 0x77;
    /// let mut i2c = I2c::new(peripherals.I2C0, Config::default())?
    ///     .with_sda(peripherals.GPIO1)
    ///     .with_scl(peripherals.GPIO2)
    ///     .into_async();
    ///
    /// let mut data = [0u8; 22];
    /// i2c.transaction_async(
    ///     DEVICE_ADDR,
    ///     &mut [Operation::Write(&[0xaa]), Operation::Read(&mut data)],
    /// )
    /// .await?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error`] when the buffer passed to an [`Operation`] has zero length.
    pub async fn transaction_async<'a, A: Into<I2cAddress>>(
        &mut self,
        address: A,
        operations: impl IntoIterator<Item = &'a mut Operation<'a>>,
    ) -> Result<(), Error> {
        let _clock_guard = I2cClockGuard::new(self.i2c.reborrow());
        self.driver()
            .transaction_impl_async(address.into(), operations.into_iter().map(Operation::from))
            .await
            .inspect_err(|error| self.internal_recover(error))
    }
}

impl<'d, Dm> I2c<'d, Dm>
where
    Dm: DriverMode,
{
    fn driver(&self) -> Driver<'_> {
        Driver {
            info: self.i2c.info(),
            state: self.i2c.state(),
            config: &self.config,
        }
    }

    fn internal_recover(&self, error: &Error) {
        // Timeout errors mean our hardware is (possibly) working when it gets reset. Clear the bus
        // in this case, to prevent leaving the I2C device mid-transfer.
        self.driver().reset_fsm(*error == Error::Timeout)
    }

    #[procmacros::doc_replace]
    /// Connects a pin to the I2C SDA signal.
    ///
    /// If called with a pin singleton (e.g. `GPIO2`), the pin is configured to use
    /// the internal pull-up resistor. If that is undesired, call this method with a
    /// fully configured [`Flex`][crate::gpio::Flex] pin driver. With `Flex`, the I2C
    /// driver does not change the pin configuration.
    ///
    /// This will replace previous pin assignments for this signal.
    ///
    /// # Examples
    ///
    /// Basic usage
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c};
    ///
    /// let i2c = I2c::new(peripherals.I2C0, Config::default())?.with_sda(peripherals.GPIO2);
    /// # {after_snippet}
    /// ```
    ///
    /// Using `Flex` to configure the pin
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::{
    ///     gpio::{DriveMode, Flex, OutputConfig},
    ///     i2c::master::{Config, I2c},
    /// };
    ///
    /// let mut sda = Flex::new(peripherals.GPIO2);
    ///
    /// // The default pullup setting is `Pull::None`.
    /// sda.apply_output_config(&OutputConfig::default().with_drive_mode(DriveMode::OpenDrain));
    /// sda.set_input_enable(true);
    /// sda.set_output_enable(true);
    /// // Initial pin state to avoid the pin to go low during peripheral configuration.
    /// sda.set_high();
    ///
    /// let i2c = I2c::new(peripherals.I2C0, Config::default())?.with_sda(sda);
    /// # {after_snippet}
    /// ```
    pub fn with_sda(mut self, sda: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self {
        let info = self.driver().info;
        let input = info.sda_input;
        let output = info.sda_output;
        Driver::connect_pin(sda.into(), input, output, &mut self.config.sda_pin);

        self
    }

    #[procmacros::doc_replace]
    /// Connects a pin to the I2C SCL signal.
    ///
    /// If called with a pin singleton (e.g. `GPIO2`), the pin is configured to use
    /// the internal pull-up resistor. If that is undesired, call this method with a
    /// fully configured [`Flex`][crate::gpio::Flex] pin driver. With `Flex`, the I2C
    /// driver does not change the pin configuration.
    ///
    /// This will replace previous pin assignments for this signal.
    ///
    /// # Examples
    ///
    /// Basic usage
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c};
    ///
    /// let i2c = I2c::new(peripherals.I2C0, Config::default())?.with_scl(peripherals.GPIO2);
    /// # {after_snippet}
    /// ```
    ///
    /// Using `Flex` to configure the pin
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::{
    ///     gpio::{DriveMode, Flex, OutputConfig},
    ///     i2c::master::{Config, I2c},
    /// };
    ///
    /// let mut scl = Flex::new(peripherals.GPIO2);
    ///
    /// // The default pullup setting is `Pull::None`.
    /// scl.apply_output_config(&OutputConfig::default().with_drive_mode(DriveMode::OpenDrain));
    /// scl.set_input_enable(true);
    /// scl.set_output_enable(true);
    /// // Initial pin state to avoid the pin to go low during peripheral configuration.
    /// scl.set_high();
    ///
    /// let i2c = I2c::new(peripherals.I2C0, Config::default())?.with_scl(scl);
    /// # {after_snippet}
    /// ```
    pub fn with_scl(mut self, scl: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self {
        let info = self.driver().info;
        let input = info.scl_input;
        let output = info.scl_output;
        Driver::connect_pin(scl.into(), input, output, &mut self.config.scl_pin);

        self
    }

    #[procmacros::doc_replace]
    /// Writes bytes to slave with given `address`.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c};
    /// # let mut i2c = I2c::new(
    /// #   peripherals.I2C0,
    /// #   Config::default(),
    /// # )?;
    /// # const DEVICE_ADDR: u8 = 0x77;
    /// i2c.write(DEVICE_ADDR, &[0xaa])?;
    /// # {after_snippet}
    /// ```
    pub fn write<A: Into<I2cAddress>>(&mut self, address: A, buffer: &[u8]) -> Result<(), Error> {
        self.transaction(address, &mut [Operation::Write(buffer)])
    }

    #[procmacros::doc_replace]
    /// Reads enough bytes from slave with `address` to fill `buffer`.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c};
    /// # let mut i2c = I2c::new(
    /// #   peripherals.I2C0,
    /// #   Config::default(),
    /// # )?;
    /// # const DEVICE_ADDR: u8 = 0x77;
    /// let mut data = [0u8; 22];
    /// i2c.read(DEVICE_ADDR, &mut data)?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error`] when the passed buffer has zero length.
    pub fn read<A: Into<I2cAddress>>(
        &mut self,
        address: A,
        buffer: &mut [u8],
    ) -> Result<(), Error> {
        self.transaction(address, &mut [Operation::Read(buffer)])
    }

    #[procmacros::doc_replace]
    /// Writes bytes to slave with given `address` and then reads enough bytes
    /// to fill `buffer` *in a single transaction*.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c};
    /// # let mut i2c = I2c::new(
    /// #   peripherals.I2C0,
    /// #   Config::default(),
    /// # )?;
    /// # const DEVICE_ADDR: u8 = 0x77;
    /// let mut data = [0u8; 22];
    /// i2c.write_read(DEVICE_ADDR, &[0xaa], &mut data)?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error`] when the passed buffer has zero length.
    pub fn write_read<A: Into<I2cAddress>>(
        &mut self,
        address: A,
        write_buffer: &[u8],
        read_buffer: &mut [u8],
    ) -> Result<(), Error> {
        self.transaction(
            address,
            &mut [Operation::Write(write_buffer), Operation::Read(read_buffer)],
        )
    }

    #[procmacros::doc_replace]
    /// Executes the provided operations on the I2C bus.
    ///
    /// Transaction contract:
    /// - Before executing the first operation an ST is sent automatically. This is followed by
    ///   SAD+R/W as appropriate.
    /// - Data from adjacent operations of the same type are sent after each other without an SP or
    ///   SR.
    /// - Between adjacent operations of a different type an SR and SAD+R/W is sent.
    /// - After executing the last operation an SP is sent automatically.
    /// - If the last operation is a `Read` the master does not send an acknowledge for the last
    ///   byte.
    ///
    /// - `ST` = start condition
    /// - `SAD+R/W` = slave address followed by bit 1 to indicate reading or 0 to indicate writing
    /// - `SR` = repeated start condition
    /// - `SP` = stop condition
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c, Operation};
    /// # let mut i2c = I2c::new(
    /// #   peripherals.I2C0,
    /// #   Config::default(),
    /// # )?;
    /// # const DEVICE_ADDR: u8 = 0x77;
    /// let mut data = [0u8; 22];
    /// i2c.transaction(
    ///     DEVICE_ADDR,
    ///     &mut [Operation::Write(&[0xaa]), Operation::Read(&mut data)],
    /// )?;
    /// # {after_snippet}
    /// ```
    #[cfg_attr(
        any(esp32, esp32s2),
        doc = "\n\nOn ESP32 and ESP32-S2 it is advisable to not combine large read/write operations with small (<3 bytes) read/write operations.\n\n"
    )]
    /// # Errors
    ///
    /// [`Error`] when the buffer passed to an [`Operation`] has zero length.
    pub fn transaction<'a, A: Into<I2cAddress>>(
        &mut self,
        address: A,
        operations: impl IntoIterator<Item = &'a mut Operation<'a>>,
    ) -> Result<(), Error> {
        let _clock_guard = I2cClockGuard::new(self.i2c.reborrow());
        self.driver()
            .transaction_impl(address.into(), operations.into_iter().map(Operation::from))
            .inspect_err(|error| self.internal_recover(error))
    }

    #[procmacros::doc_replace]
    /// Applies a new configuration.
    ///
    /// # Examples
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// use esp_hal::i2c::master::{Config, I2c};
    /// let mut i2c = I2c::new(peripherals.I2C0, Config::default())?;
    ///
    /// i2c.apply_config(&Config::default().with_frequency(Rate::from_khz(400)))?;
    /// # {after_snippet}
    /// ```
    ///
    /// # Errors
    ///
    /// [`ConfigError`] when bus frequency or timeout passed in config is invalid.
    pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
        self.config.config = *config;
        self.driver().setup(config)?;
        self.driver().reset_fsm(false);
        Ok(())
    }

    /// Drives SCL low (`true`) or releases it (`false`).
    ///
    /// Forcing a line low interrupts normal peripheral operation — no
    /// transactions should be started while a line is held low.
    #[instability::unstable]
    pub fn force_scl_low(&mut self, low: bool) {
        self.driver().force_scl_low(low);
    }

    /// Drives SDA low (`true`) or releases it (`false`).
    ///
    /// Forcing a line low interrupts normal peripheral operation — no
    /// transactions should be started while a line is held low.
    #[instability::unstable]
    pub fn force_sda_low(&mut self, low: bool) {
        self.driver().force_sda_low(low);
    }
}