-
Notifications
You must be signed in to change notification settings - Fork 267
/
Copy pathi2c.rs
1250 lines (1088 loc) · 37.1 KB
/
i2c.rs
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
//! I2C Driver
//!
//! Supports multiple I2C peripheral instances
use fugit::HertzU32;
use crate::{
clock::Clocks,
gpio::{InputPin, OutputPin},
peripheral::{Peripheral, PeripheralRef},
peripherals::i2c0::{RegisterBlock, COMD},
system::PeripheralClockControl,
types::{InputSignal, OutputSignal},
};
cfg_if::cfg_if! {
if #[cfg(esp32s2)] {
const I2C_LL_INTR_MASK: u32 = 0x1ffff;
} else {
const I2C_LL_INTR_MASK: u32 = 0x3ffff;
}
}
/// I2C-specific transmission errors
#[derive(Debug)]
pub enum Error {
ExceedingFifo,
AckCheckFailed,
TimeOut,
ArbitrationLost,
ExecIncomplete,
CommandNrExceeded,
}
#[cfg(feature = "eh1")]
impl embedded_hal_1::i2c::Error for Error {
fn kind(&self) -> embedded_hal_1::i2c::ErrorKind {
use embedded_hal_1::i2c::ErrorKind;
match self {
Self::ExceedingFifo => ErrorKind::Overrun,
Self::ArbitrationLost => ErrorKind::ArbitrationLoss,
_ => ErrorKind::Other,
}
}
}
/// A generic I2C Command
enum Command {
Start,
Stop,
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 255,
/// 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 255,
/// while the minimum is 1.
length: u8,
},
}
impl From<Command> for u16 {
fn from(c: Command) -> u16 {
let opcode = match c {
Command::Start => Opcode::RStart,
Command::Stop => Opcode::Stop,
Command::Write { .. } => Opcode::Write,
Command::Read { .. } => Opcode::Read,
};
let length = match c {
Command::Start | Command::Stop => 0,
Command::Write { length: l, .. } | Command::Read { length: l, .. } => l,
};
let ack_exp = match c {
Command::Start | Command::Stop | Command::Read { .. } => Ack::Nack,
Command::Write { ack_exp: exp, .. } => exp,
};
let ack_check_en = match c {
Command::Start | Command::Stop | Command::Read { .. } => false,
Command::Write {
ack_check_en: en, ..
} => en,
};
let ack_value = match c {
Command::Start | Command::Stop | Command::Write { .. } => Ack::Nack,
Command::Read { ack_value: ack, .. } => ack,
};
let mut cmd: u16 = length.into();
if ack_check_en {
cmd |= 1 << 8;
} else {
cmd &= !(1 << 8);
}
if ack_exp == Ack::Nack {
cmd |= 1 << 9;
} else {
cmd &= !(1 << 9);
}
if ack_value == Ack::Nack {
cmd |= 1 << 10;
} else {
cmd &= !(1 << 10);
}
cmd |= (opcode as u16) << 11;
cmd
}
}
enum OperationType {
Write = 0,
Read = 1,
}
#[derive(Eq, PartialEq, Copy, Clone)]
enum Ack {
Ack,
Nack,
}
#[cfg(any(esp32c2, esp32c3, esp32s3))]
enum Opcode {
RStart = 6,
Write = 1,
Read = 3,
Stop = 2,
}
#[cfg(any(esp32, esp32s2))]
enum Opcode {
RStart = 0,
Write = 1,
Read = 2,
Stop = 3,
}
/// I2C peripheral container (I2C)
pub struct I2C<'d, T> {
peripheral: PeripheralRef<'d, T>,
}
impl<T> embedded_hal::blocking::i2c::Read for I2C<'_, T>
where
T: Instance,
{
type Error = Error;
fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
self.peripheral.master_read(address, buffer)
}
}
impl<T> embedded_hal::blocking::i2c::Write for I2C<'_, T>
where
T: Instance,
{
type Error = Error;
fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Self::Error> {
self.peripheral.master_write(addr, bytes)
}
}
impl<T> embedded_hal::blocking::i2c::WriteRead for I2C<'_, T>
where
T: Instance,
{
type Error = Error;
fn write_read(
&mut self,
address: u8,
bytes: &[u8],
buffer: &mut [u8],
) -> Result<(), Self::Error> {
self.peripheral.master_write_read(address, bytes, buffer)
}
}
#[cfg(feature = "eh1")]
impl<T> embedded_hal_1::i2c::ErrorType for I2C<'_, T> {
type Error = Error;
}
#[cfg(feature = "eh1")]
impl<T> embedded_hal_1::i2c::I2c for I2C<'_, T>
where
T: Instance,
{
fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
self.peripheral.master_read(address, buffer)
}
fn write(&mut self, address: u8, bytes: &[u8]) -> Result<(), Self::Error> {
self.peripheral.master_write(address, bytes)
}
fn write_iter<B>(&mut self, _address: u8, _bytes: B) -> Result<(), Self::Error>
where
B: IntoIterator<Item = u8>,
{
todo!()
}
fn write_read(
&mut self,
address: u8,
bytes: &[u8],
buffer: &mut [u8],
) -> Result<(), Self::Error> {
self.peripheral.master_write_read(address, bytes, buffer)
}
fn write_iter_read<B>(
&mut self,
_address: u8,
_bytes: B,
_buffer: &mut [u8],
) -> Result<(), Self::Error>
where
B: IntoIterator<Item = u8>,
{
todo!()
}
fn transaction<'a>(
&mut self,
_address: u8,
_operations: &mut [embedded_hal_1::i2c::Operation<'a>],
) -> Result<(), Self::Error> {
todo!()
}
fn transaction_iter<'a, O>(&mut self, _address: u8, _operations: O) -> Result<(), Self::Error>
where
O: IntoIterator<Item = embedded_hal_1::i2c::Operation<'a>>,
{
todo!()
}
}
impl<'d, T> I2C<'d, T>
where
T: Instance,
{
/// Create a new I2C instance
/// This will enable the peripheral but the peripheral won't get
/// automatically disabled when this gets dropped.
pub fn new<SDA: OutputPin + InputPin, SCL: OutputPin + InputPin>(
i2c: impl Peripheral<P = T> + 'd,
sda: impl Peripheral<P = SDA> + 'd,
scl: impl Peripheral<P = SCL> + 'd,
frequency: HertzU32,
peripheral_clock_control: &mut PeripheralClockControl,
clocks: &Clocks,
) -> Self {
crate::into_ref!(i2c, sda, scl);
enable_peripheral(&i2c, peripheral_clock_control);
let mut i2c = I2C { peripheral: i2c };
// initialize SCL first to not confuse some devices like MPU6050
scl.set_to_open_drain_output()
.enable_input(true)
.internal_pull_up(true)
.connect_peripheral_to_output(OutputSignal::I2CEXT0_SCL)
.connect_input_to_peripheral(InputSignal::I2CEXT0_SCL);
sda.set_to_open_drain_output()
.enable_input(true)
.internal_pull_up(true)
.connect_peripheral_to_output(OutputSignal::I2CEXT0_SDA)
.connect_input_to_peripheral(InputSignal::I2CEXT0_SDA);
i2c.peripheral.setup(frequency, clocks);
i2c
}
}
fn enable_peripheral<'d, T>(
i2c: &PeripheralRef<'d, T>,
peripheral_clock_control: &mut PeripheralClockControl,
) where
T: Instance,
{
// enable peripheral
match i2c.i2c_number() {
0 => peripheral_clock_control.enable(crate::system::Peripheral::I2cExt0),
#[cfg(i2c1)]
1 => peripheral_clock_control.enable(crate::system::Peripheral::I2cExt1),
_ => unreachable!(), // will never happen
}
}
/// I2C Peripheral Instance
pub trait Instance {
fn register_block(&self) -> &RegisterBlock;
fn i2c_number(&self) -> usize;
fn setup(&mut self, frequency: HertzU32, clocks: &Clocks) {
self.register_block().ctr.modify(|_, w| unsafe {
// Clear register
w.bits(0)
// Set I2C controller to master mode
.ms_mode()
.set_bit()
// Use open drain output for SDA and SCL
.sda_force_out()
.set_bit()
.scl_force_out()
.set_bit()
// Use Most Significant Bit first for sending and receiving data
.tx_lsb_first()
.clear_bit()
.rx_lsb_first()
.clear_bit()
// Ensure that clock is enabled
.clk_en()
.set_bit()
});
#[cfg(esp32s2)]
self.register_block()
.ctr
.modify(|_, w| w.ref_always_on().set_bit());
// Configure filter
// FIXME if we ever change this we need to adapt `set_frequency` for ESP32
self.set_filter(Some(7), Some(7));
// Configure frequency
self.set_frequency(clocks.i2c_clock.convert(), frequency);
// Propagate configuration changes (only necessary with C2, C3, and S3)
#[cfg(any(esp32c2, esp32c3, esp32s3))]
self.register_block()
.ctr
.modify(|_, w| w.conf_upgate().set_bit());
// Reset entire peripheral (also resets fifo)
self.reset();
}
/// Resets the I2C controller (FIFO + FSM + command list)
fn reset(&self) {
// Reset interrupts
// Disable all I2C interrupts
self.register_block()
.int_ena
.write(|w| unsafe { w.bits(0) });
// Clear all I2C interrupts
self.register_block()
.int_clr
.write(|w| unsafe { w.bits(I2C_LL_INTR_MASK) });
// Reset fifo
self.reset_fifo();
// Reset the command list
self.reset_command_list();
// Reset the FSM
// (the option to reset the FSM is not available
// for the ESP32)
#[cfg(not(esp32))]
self.register_block()
.ctr
.modify(|_, w| w.fsm_rst().set_bit());
}
/// Resets the I2C peripheral's command registers
fn reset_command_list(&self) {
// Confirm that all commands that were configured were actually executed
for cmd in self.register_block().comd.iter() {
cmd.reset();
}
}
/// Sets the filter with a supplied threshold in clock cycles for which a
/// pulse must be present to pass the filter
fn set_filter(&mut self, sda_threshold: Option<u8>, scl_threshold: Option<u8>) {
cfg_if::cfg_if! {
if #[cfg(any(esp32, esp32s2))] {
let sda_register = &self.register_block().sda_filter_cfg;
let scl_register = &self.register_block().scl_filter_cfg;
} else {
let sda_register = &self.register_block().filter_cfg;
let scl_register = &self.register_block().filter_cfg;
}
}
match sda_threshold {
Some(threshold) => {
sda_register.modify(|_, w| unsafe { w.sda_filter_thres().bits(threshold) });
sda_register.modify(|_, w| w.sda_filter_en().set_bit());
}
None => sda_register.modify(|_, w| w.sda_filter_en().clear_bit()),
}
match scl_threshold {
Some(threshold) => {
scl_register.modify(|_, w| unsafe { w.scl_filter_thres().bits(threshold) });
scl_register.modify(|_, w| w.scl_filter_en().set_bit());
}
None => scl_register.modify(|_, w| w.scl_filter_en().clear_bit()),
}
}
#[cfg(esp32)]
/// Sets the frequency of the I2C interface by calculating and applying the
/// associated timings - corresponds to i2c_ll_cal_bus_clk and
/// i2c_ll_set_bus_timing in ESP-IDF
fn set_frequency(&mut self, source_clk: HertzU32, bus_freq: HertzU32) {
let source_clk = source_clk.raw();
let bus_freq = bus_freq.raw();
let half_cycle: u32 = source_clk / bus_freq / 2;
let scl_low = half_cycle;
let scl_high = half_cycle;
let sda_hold = half_cycle / 2;
let sda_sample = scl_high / 2;
let setup = half_cycle;
let hold = half_cycle;
let tout = half_cycle * 20; // default we set the timeout value to 10 bus cycles.
// SCL period. According to the TRM, we should always subtract 1 to SCL low
// period
let scl_low = scl_low - 1;
// Still according to the TRM, if filter is not enbled, we have to subtract 7,
// if SCL filter is enabled, we have to subtract:
// 8 if SCL filter is between 0 and 2 (included)
// 6 + SCL threshold if SCL filter is between 3 and 7 (included)
// to SCL high period
let mut scl_high = scl_high;
// In the "worst" case, we will subtract 13, make sure the result will still be
// correct
// FIXME since we always set the filter threshold to 7 we don't need conditional
// code here once that changes we need the conditional code here
scl_high -= 7 + 6;
// if (filter_cfg_en) {
// if (thres <= 2) {
// scl_high -= 8;
// } else {
// assert(hw->scl_filter_cfg.thres <= 7);
// scl_high -= thres + 6;
// }
// } else {
// scl_high -= 7;
//}
let scl_high_period = scl_high;
let scl_low_period = scl_low;
// sda sample
let sda_hold_time = sda_hold;
let sda_sample_time = sda_sample;
// setup
let scl_rstart_setup_time = setup;
let scl_stop_setup_time = setup;
// hold
let scl_start_hold_time = hold;
let scl_stop_hold_time = hold;
let time_out_value = tout;
self.configure_clock(
0,
scl_low_period,
scl_high_period,
0,
sda_hold_time,
sda_sample_time,
scl_rstart_setup_time,
scl_stop_setup_time,
scl_start_hold_time,
scl_stop_hold_time,
time_out_value,
true,
);
}
#[cfg(esp32s2)]
/// Sets the frequency of the I2C interface by calculating and applying the
/// associated timings - corresponds to i2c_ll_cal_bus_clk and
/// i2c_ll_set_bus_timing in ESP-IDF
fn set_frequency(&mut self, source_clk: HertzU32, bus_freq: HertzU32) {
let source_clk = source_clk.raw();
let bus_freq = bus_freq.raw();
let half_cycle: u32 = source_clk / bus_freq / 2;
// SCL
let scl_low = half_cycle;
// default, scl_wait_high < scl_high
let scl_high = half_cycle / 2 + 2;
let scl_wait_high = half_cycle - scl_high;
let sda_hold = half_cycle / 2;
// scl_wait_high < sda_sample <= scl_high
let sda_sample = half_cycle / 2 - 1;
let setup = half_cycle;
let hold = half_cycle;
// default we set the timeout value to 10 bus cycles
let tout = half_cycle * 20;
// scl period
let scl_low_period = scl_low - 1;
let scl_high_period = scl_high;
let scl_wait_high_period = scl_wait_high;
// sda sample
let sda_hold_time = sda_hold;
let sda_sample_time = sda_sample;
// setup
let scl_rstart_setup_time = setup;
let scl_stop_setup_time = setup;
// hold
let scl_start_hold_time = hold - 1;
let scl_stop_hold_time = hold;
let time_out_value = tout;
let time_out_en = true;
self.configure_clock(
0,
scl_low_period,
scl_high_period,
scl_wait_high_period,
sda_hold_time,
sda_sample_time,
scl_rstart_setup_time,
scl_stop_setup_time,
scl_start_hold_time,
scl_stop_hold_time,
time_out_value,
time_out_en,
);
}
#[cfg(any(esp32c2, esp32c3, esp32s3))]
/// Sets the frequency of the I2C interface by calculating and applying the
/// associated timings - corresponds to i2c_ll_cal_bus_clk and
/// i2c_ll_set_bus_timing in ESP-IDF
fn set_frequency(&mut self, source_clk: HertzU32, bus_freq: HertzU32) {
let source_clk = source_clk.raw();
let bus_freq = bus_freq.raw();
let clkm_div: u32 = source_clk / (bus_freq * 1024) + 1;
let sclk_freq: u32 = source_clk / clkm_div;
let half_cycle: u32 = sclk_freq / bus_freq / 2;
// SCL
let clkm_div = clkm_div;
let scl_low = half_cycle;
// default, scl_wait_high < scl_high
// Make 80KHz as a boundary here, because when working at lower frequency, too
// much scl_wait_high will faster the frequency according to some
// hardware behaviors.
let scl_wait_high = if bus_freq >= 80 * 1000 {
half_cycle / 2 - 2
} else {
half_cycle / 4
};
let scl_high = half_cycle - scl_wait_high;
let sda_hold = half_cycle / 4;
let sda_sample = half_cycle / 2 + scl_wait_high;
let setup = half_cycle;
let hold = half_cycle;
// default we set the timeout value to about 10 bus cycles
// log(20*half_cycle)/log(2) = log(half_cycle)/log(2) + log(20)/log(2)
let tout = (4 * 8 - (5 * half_cycle).leading_zeros()) + 2;
// According to the Technical Reference Manual, the following timings must be
// subtracted by 1. However, according to the practical measurement and
// some hardware behaviour, if wait_high_period and scl_high minus one.
// The SCL frequency would be a little higher than expected. Therefore, the
// solution here is not to minus scl_high as well as scl_wait high, and
// the frequency will be absolutely accurate to all frequency
// to some extent.
let scl_low_period = scl_low - 1;
let scl_high_period = scl_high;
let scl_wait_high_period = scl_wait_high;
// sda sample
let sda_hold_time = sda_hold - 1;
let sda_sample_time = sda_sample - 1;
// setup
let scl_rstart_setup_time = setup - 1;
let scl_stop_setup_time = setup - 1;
// hold
let scl_start_hold_time = hold - 1;
let scl_stop_hold_time = hold - 1;
let time_out_value = tout;
let time_out_en = true;
self.configure_clock(
clkm_div,
scl_low_period,
scl_high_period,
scl_wait_high_period,
sda_hold_time,
sda_sample_time,
scl_rstart_setup_time,
scl_stop_setup_time,
scl_start_hold_time,
scl_stop_hold_time,
time_out_value,
time_out_en,
);
}
#[allow(unused)]
fn configure_clock(
&mut self,
sclk_div: u32,
scl_low_period: u32,
scl_high_period: u32,
scl_wait_high_period: u32,
sda_hold_time: u32,
sda_sample_time: u32,
scl_rstart_setup_time: u32,
scl_stop_setup_time: u32,
scl_start_hold_time: u32,
scl_stop_hold_time: u32,
time_out_value: u32,
time_out_en: bool,
) {
unsafe {
// divider
#[cfg(any(esp32c2, esp32c3, esp32s3))]
self.register_block().clk_conf.modify(|_, w| {
w.sclk_sel()
.clear_bit()
.sclk_div_num()
.bits((sclk_div - 1) as u8)
});
// scl period
self.register_block()
.scl_low_period
.write(|w| w.scl_low_period().bits(scl_low_period as u16));
// for high/wait_high we have to differentiate between the chips
// as the EPS32 does not have a wait_high field
cfg_if::cfg_if! {
if #[cfg(not(esp32))] {
self.register_block().scl_high_period.write(|w| {
w.scl_high_period()
.bits(scl_high_period as u16)
.scl_wait_high_period()
.bits(scl_wait_high_period.try_into().unwrap())
});
}
else {
self.register_block().scl_high_period.write(|w| {
w.scl_high_period()
.bits(scl_high_period as u16)
});
}
}
// we already did that above but on S2 we need this to make it work
#[cfg(esp32s2)]
self.register_block().scl_high_period.write(|w| {
w.scl_wait_high_period()
.bits(scl_wait_high_period as u16)
.scl_high_period()
.bits(scl_high_period as u16)
});
// sda sample
self.register_block()
.sda_hold
.write(|w| w.time().bits(sda_hold_time as u16));
self.register_block()
.sda_sample
.write(|w| w.time().bits(sda_sample_time as u16));
// setup
self.register_block()
.scl_rstart_setup
.write(|w| w.time().bits(scl_rstart_setup_time as u16));
self.register_block()
.scl_stop_setup
.write(|w| w.time().bits(scl_stop_setup_time as u16));
// hold
self.register_block()
.scl_start_hold
.write(|w| w.time().bits(scl_start_hold_time as u16));
self.register_block()
.scl_stop_hold
.write(|w| w.time().bits(scl_stop_hold_time as u16));
// The ESP32 variant does not have an enable flag for the
// timeout mechanism
cfg_if::cfg_if! {
if #[cfg(esp32)] {
// timeout
self.register_block()
.to
.write(|w| w.time_out().bits(time_out_value));
}
else {
// timeout
// FIXME: Enable timout for other chips!
self.register_block()
.to
.write(|w| w.time_out_en().bit(time_out_en)
.time_out_value()
.variant(time_out_value.try_into().unwrap())
);
}
}
}
}
fn perform_write<'a, I>(
&self,
addr: u8,
bytes: &[u8],
cmd_iterator: &mut I,
) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
if bytes.len() > 254 {
// we could support more by adding multiple write operations
return Err(Error::ExceedingFifo);
}
// Clear all I2C interrupts
self.clear_all_interrupts();
// RSTART command
add_cmd(cmd_iterator, Command::Start)?;
// WRITE command
add_cmd(
cmd_iterator,
Command::Write {
ack_exp: Ack::Ack,
ack_check_en: true,
length: 1 + bytes.len() as u8,
},
)?;
add_cmd(cmd_iterator, Command::Stop)?;
self.update_config();
// Load address and R/W bit into FIFO
write_fifo(
self.register_block(),
addr << 1 | OperationType::Write as u8,
);
let index = self.fill_tx_fifo(bytes);
self.start_transmission();
// fill FIFO with remaining bytes
self.write_remaining_tx_fifo(index, bytes)?;
self.wait_for_completion()?;
Ok(())
}
fn perform_read<'a, I>(
&self,
addr: u8,
buffer: &mut [u8],
cmd_iterator: &mut I,
) -> Result<(), Error>
where
I: Iterator<Item = &'a COMD>,
{
if buffer.len() > 254 {
// we could support more by adding multiple read operations
return Err(Error::ExceedingFifo);
}
// Clear all I2C interrupts
self.clear_all_interrupts();
// RSTART command
add_cmd(cmd_iterator, Command::Start)?;
// WRITE command
add_cmd(
cmd_iterator,
Command::Write {
ack_exp: Ack::Ack,
ack_check_en: true,
length: 1,
},
)?;
if buffer.len() > 1 {
// READ command (N - 1)
add_cmd(
cmd_iterator,
Command::Read {
ack_value: Ack::Ack,
length: buffer.len() as u8 - 1,
},
)?;
}
// READ w/o ACK
add_cmd(
cmd_iterator,
Command::Read {
ack_value: Ack::Nack,
length: 1,
},
)?;
add_cmd(cmd_iterator, Command::Stop)?;
self.update_config();
// Load address and R/W bit into FIFO
write_fifo(self.register_block(), addr << 1 | OperationType::Read as u8);
self.start_transmission();
self.read_all_from_fifo(buffer)?;
self.wait_for_completion()?;
Ok(())
}
#[cfg(not(any(esp32, esp32s2)))]
fn read_all_from_fifo(&self, buffer: &mut [u8]) -> Result<(), Error> {
// Read bytes from FIFO
// FIXME: Handle case where less data has been provided by the slave than
// requested? Or is this prevented from a protocol perspective?
for byte in buffer.iter_mut() {
loop {
self.check_errors()?;
let reg = self.register_block().fifo_st.read();
if reg.rxfifo_raddr().bits() != reg.rxfifo_waddr().bits() {
break;
}
}
*byte = read_fifo(self.register_block());
}
Ok(())
}
#[cfg(any(esp32, esp32s2))]
fn read_all_from_fifo(&self, buffer: &mut [u8]) -> Result<(), Error> {
// on ESP32/ESP32-S2 we currently don't support I2C transactions larger than the
// FIFO apparently it would be possible by using non-fifo mode
// see https://github.com/espressif/arduino-esp32/blob/7e9afe8c5ed7b5bf29624a5cd6e07d431c027b97/cores/esp32/esp32-hal-i2c.c#L615
if buffer.len() > 32 {
panic!("On ESP32 and ESP32-S2 the max I2C read is limited to 32 bytes");
}
// wait for completion - then we can just read the data from FIFO
// once we change to non-fifo mode to support larger transfers that
// won't work anymore
self.wait_for_completion()?;
// Read bytes from FIFO
// FIXME: Handle case where less data has been provided by the slave than
// requested? Or is this prevented from a protocol perspective?
for byte in buffer.iter_mut() {
*byte = read_fifo(self.register_block());
}
Ok(())
}
fn clear_all_interrupts(&self) {
self.register_block()
.int_clr
.write(|w| unsafe { w.bits(I2C_LL_INTR_MASK) });
}
fn wait_for_completion(&self) -> Result<(), Error> {
loop {
let interrupts = self.register_block().int_raw.read();
self.check_errors()?;
// Handle completion cases
// A full transmission was completed
if interrupts.trans_complete_int_raw().bit_is_set()
|| interrupts.end_detect_int_raw().bit_is_set()
{
break;
}
}
for cmd in self.register_block().comd.iter() {
if cmd.read().command().bits() != 0x0 && cmd.read().command_done().bit_is_clear() {
return Err(Error::ExecIncomplete);
}
}
Ok(())
}
fn check_errors(&self) -> Result<(), Error> {
let interrupts = self.register_block().int_raw.read();
// The ESP32 variant has a slightly different interrupt naming
// scheme!
cfg_if::cfg_if! {
if #[cfg(esp32)] {
// Handle error cases
if interrupts.time_out_int_raw().bit_is_set() {
self.reset();
return Err(Error::TimeOut);
} else if interrupts.ack_err_int_raw().bit_is_set() {
self.reset();
return Err(Error::AckCheckFailed);
} else if interrupts.arbitration_lost_int_raw().bit_is_set() {
self.reset();
return Err(Error::ArbitrationLost);
}
}
else {
// Handle error cases
if interrupts.time_out_int_raw().bit_is_set() {
self.reset();
return Err(Error::TimeOut);
} else if interrupts.nack_int_raw().bit_is_set() {
self.reset();
return Err(Error::AckCheckFailed);
} else if interrupts.arbitration_lost_int_raw().bit_is_set() {
self.reset();
return Err(Error::ArbitrationLost);
}
}
}
Ok(())
}
fn update_config(&self) {
// Ensure that the configuration of the peripheral is correctly propagated
// (only necessary for C3 and S3 variant)
#[cfg(any(esp32c2, esp32c3, esp32s3))]
self.register_block()
.ctr
.modify(|_, w| w.conf_upgate().set_bit());
}
fn start_transmission(&self) {
// Start transmission
self.register_block()
.ctr
.modify(|_, w| w.trans_start().set_bit());
}
#[cfg(not(any(esp32, esp32s2)))]
fn fill_tx_fifo(&self, bytes: &[u8]) -> usize {
let mut index = 0;
while index < bytes.len()
&& !self
.register_block()
.int_raw
.read()
.txfifo_ovf_int_raw()
.bit_is_set()
{
write_fifo(self.register_block(), bytes[index]);
index += 1;
}
if self
.register_block()
.int_raw
.read()
.txfifo_ovf_int_raw()
.bit_is_set()
{
index -= 1;
self.register_block()