-
Notifications
You must be signed in to change notification settings - Fork 474
Expand file tree
/
Copy pathmod.rs
More file actions
3287 lines (2944 loc) · 104 KB
/
Copy pathmod.rs
File metadata and controls
3287 lines (2944 loc) · 104 KB
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
#![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 embedded_hal::i2c::Operation as EhalOperation;
use enumset::{EnumSet, EnumSetType};
use crate::{
Async,
Blocking,
DriverMode,
asynch::AtomicWaker,
clock::Clocks,
gpio::{
DriveMode,
InputSignal,
OutputConfig,
OutputSignal,
PinGuard,
Pull,
interconnect::{self, PeripheralOutput},
},
handler,
interrupt::InterruptHandler,
pac::i2c0::{COMD, RegisterBlock},
private,
ram,
system::PeripheralGuard,
time::{Duration, Instant, Rate},
};
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.
///
/// Note that 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(())
}
}
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 = "Note that 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]
// TODO: when supporting interrupts, document that SCL = high also triggers an
// interrupt.
pub enum BusTimeout {
/// Use the maximum timeout value.
Maximum,
/// Disable 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 we'll have to take
/// the logarithm of the timeout value. This may cause considerably
/// longer (at most ~double) timeouts than configured. We may provide an
/// `ApbCycles` variant 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.
/// Note that using this in conjunction with `async` operations will cause the
/// task to be woken up continuously until the operation completes or the
/// timeout is reached. You should prefer using 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
#[instability::unstable]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SoftwareTimeout {
/// No software timeout is set.
None,
/// Define a fixed timeout for I2C operations.
Transaction(Duration),
/// Define 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 0x10
#[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;
const FSM_TIMEOUT_DEFAULT: u8 = 0x10;
/// 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_DEFAULT }>()
}
}
/// 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> {
/// Write data from the provided buffer.
Write(&'a [u8]),
/// Read 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(),
}
}
}
impl embedded_hal::i2c::Error for Error {
fn kind(&self) -> embedded_hal::i2c::ErrorKind {
use embedded_hal::i2c::ErrorKind;
match self {
Self::FifoExceeded => ErrorKind::Overrun,
Self::ArbitrationLost => ErrorKind::ArbitrationLoss,
Self::AcknowledgeCheckFailed(reason) => ErrorKind::NoAcknowledge(reason.into()),
_ => ErrorKind::Other,
}
}
}
/// 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 written. 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,
}
/// 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: 10 bus clock cycles.
timeout: BusTimeout,
/// Software timeout.
///
/// Default value: 1 ms per byte.
#[builder_lite(unstable)]
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,
}
impl Default for Config {
fn default() -> Self {
Config {
frequency: Rate::from_khz(100),
timeout: BusTimeout::BusCycles(10),
software_timeout: SoftwareTimeout::PerByte(Duration::from_millis(1)),
#[cfg(i2c_master_has_fsm_timeouts)]
scl_st_timeout: Default::default(),
#[cfg(i2c_master_has_fsm_timeouts)]
scl_main_st_timeout: Default::default(),
}
}
}
#[procmacros::doc_replace]
/// I2C driver
///
/// ## Example
///
/// ```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,
}
#[instability::unstable]
impl<Dm: DriverMode> embassy_embedded_hal::SetConfig for I2c<'_, Dm> {
type Config = Config;
type ConfigError = ConfigError;
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
self.apply_config(config)
}
}
impl<Dm: DriverMode> embedded_hal::i2c::ErrorType for I2c<'_, Dm> {
type Error = Error;
}
impl<Dm: DriverMode> embedded_hal::i2c::I2c for I2c<'_, Dm> {
fn transaction(
&mut self,
address: u8,
operations: &mut [embedded_hal::i2c::Operation<'_>],
) -> Result<(), Self::Error> {
self.driver()
.transaction_impl(
I2cAddress::SevenBit(address),
operations.iter_mut().map(Operation::from),
)
.inspect_err(|_| self.internal_recover())
}
}
impl<'d> I2c<'d, Blocking> {
#[procmacros::doc_replace]
/// Create a new I2C instance.
///
/// ## Errors
///
/// A [`ConfigError`] variant will be returned if bus frequency or timeout
/// passed in config is invalid.
///
/// ## Example
///
/// ```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}
/// ```
pub fn new(i2c: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
let guard = PeripheralGuard::new(i2c.info().peripheral);
let sda_pin = PinGuard::new_unconnected(i2c.info().sda_output);
let scl_pin = PinGuard::new_unconnected(i2c.info().scl_output);
let mut i2c = I2c {
i2c: i2c.degrade(),
phantom: PhantomData,
guard,
config: DriverConfig {
config,
sda_pin,
scl_pin,
},
};
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 = ""]
/// Note that this will replace any previously registered interrupt
/// handlers.
///
/// You can restore the default/unhandled interrupt handler 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);
}
/// Listen for the given interrupts
#[instability::unstable]
pub fn listen(&mut self, interrupts: impl Into<EnumSet<Event>>) {
self.i2c.info().enable_listen(interrupts.into(), true)
}
/// Unlisten the given interrupts
#[instability::unstable]
pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<Event>>) {
self.i2c.info().enable_listen(interrupts.into(), false)
}
/// Gets 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,
}
#[must_use = "futures do nothing unless you `.await` or poll them"]
struct I2cFuture<'a> {
events: EnumSet<Event>,
driver: Driver<'a>,
deadline: Option<Instant>,
finished: bool,
}
impl<'a> I2cFuture<'a> {
pub fn new(events: EnumSet<Event>, driver: Driver<'a>, deadline: Option<Instant>) -> Self {
driver.regs().int_ena().modify(|_, w| {
for event in events {
match event {
Event::EndDetect => w.end_detect().set_bit(),
Event::TxComplete => w.trans_complete().set_bit(),
#[cfg(i2c_master_has_tx_fifo_watermark)]
Event::TxFifoWatermark => w.txfifo_wm().set_bit(),
};
}
w.arbitration_lost().set_bit();
w.time_out().set_bit();
w.nack().set_bit();
#[cfg(i2c_master_has_fsm_timeouts)]
{
w.scl_main_st_to().set_bit();
w.scl_st_to().set_bit();
}
w
});
Self::new_blocking(events, driver, deadline)
}
pub fn new_blocking(
events: EnumSet<Event>,
driver: Driver<'a>,
deadline: Option<Instant>,
) -> Self {
Self {
events,
driver,
deadline,
finished: false,
}
}
fn is_done(&self) -> bool {
!self.driver.info.interrupts().is_disjoint(self.events)
}
fn poll_completion(&mut self) -> Poll<Result<(), Error>> {
// Grab the current time before doing anything. This will ensure that a long
// interruption still allows the peripheral sufficient time to complete the
// operation (i.e. it ensures that the deadline is "at least", not "at most").
let now = if self.deadline.is_some() {
Instant::now()
} else {
Instant::EPOCH
};
let error = self.driver.check_errors();
if self.is_done() {
self.finished = true;
// Even though we are done, we have to check for NACK and arbitration loss.
let result = if error == Err(Error::Timeout) {
Ok(())
} else {
error
};
Poll::Ready(result)
} else if error.is_err() {
self.finished = true;
Poll::Ready(error)
} else {
if let Some(deadline) = self.deadline
&& now > deadline
{
// If the deadline is reached, we return an error.
return Poll::Ready(Err(Error::Timeout));
}
Poll::Pending
}
}
}
impl core::future::Future for I2cFuture<'_> {
type Output = Result<(), Error>;
fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
self.driver.state.waker.register(ctx.waker());
let result = self.poll_completion();
if result.is_pending() && self.deadline.is_some() {
ctx.waker().wake_by_ref();
}
result
}
}
impl Drop for I2cFuture<'_> {
fn drop(&mut self) {
if !self.finished {
self.driver.reset_fsm();
self.driver.clear_bus_blocking();
}
}
}
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();
I2c {
i2c: self.i2c,
phantom: PhantomData,
guard: self.guard,
config: self.config,
}
}
#[procmacros::doc_replace]
/// Writes bytes to slave with given `address`
///
/// ## Example
///
/// ```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`
///
/// ## Errors
///
/// The corresponding error variant from [`Error`] will be returned if the
/// passed buffer has zero length.
///
/// ## Example
///
/// ```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}
/// ```
pub async fn read_async<A: Into<I2cAddress>>(
&mut self,
address: A,
buffer: &mut [u8],
) -> Result<(), Error> {