-
Notifications
You must be signed in to change notification settings - Fork 264
/
Copy pathspi.rs
3235 lines (2819 loc) · 96.6 KB
/
spi.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
//! # Serial Peripheral Interface
//!
//! There are multiple ways to use SPI, depending on your needs. Regardless of
//! which way you choose, you must first create an SPI instance with
//! [`Spi::new`].
//!
//! ```rust
//! let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
//! let sclk = io.pins.gpio12;
//! let miso = io.pins.gpio11;
//! let mosi = io.pins.gpio13;
//! let cs = io.pins.gpio10;
//!
//! let mut spi = hal::spi::Spi::new(
//! peripherals.SPI2,
//! sclk,
//! mosi,
//! miso,
//! cs,
//! 100u32.kHz(),
//! SpiMode::Mode0,
//! &mut peripheral_clock_control,
//! &mut clocks,
//! );
//! ```
//!
//! ## Exclusive access to the SPI bus
//!
//! If all you want to do is to communicate to a single device, and you initiate
//! transactions yourself, there are a number of ways to achieve this:
//!
//! - Use the [`FullDuplex`](embedded_hal::spi::FullDuplex) trait to read/write
//! single bytes at a time,
//! - Use the [`SpiBus`](embedded_hal_1::spi::SpiBus) trait (requires the "eh1"
//! feature) and its associated functions to initiate transactions with
//! simultaneous reads and writes, or
//! - Use the [`SpiBusWrite`](embedded_hal_1::spi::SpiBusWrite) and
//! [`SpiBusRead`](embedded_hal_1::spi::SpiBusRead) traits (requires the "eh1"
//! feature) and their associated functions to read or write mutiple bytes at
//! a time.
//!
//!
//! ## Shared SPI access
//!
//! If you have multiple devices on the same SPI bus that each have their own CS
//! line, you may want to have a look at the [`SpiBusController`] and
//! [`SpiBusDevice`] implemented here. These give exclusive access to the
//! underlying SPI bus by means of a Mutex. This ensures that device
//! transactions do not interfere with each other.
use core::marker::PhantomData;
use fugit::HertzU32;
use crate::{
clock::Clocks,
dma::{DmaError, DmaPeripheral, Rx, Tx},
gpio::{InputPin, InputSignal, OutputPin, OutputSignal},
peripheral::{Peripheral, PeripheralRef},
peripherals::spi2::RegisterBlock,
system::PeripheralClockControl,
};
/// The size of the FIFO buffer for SPI
#[cfg(not(esp32s2))]
const FIFO_SIZE: usize = 64;
#[cfg(esp32s2)]
const FIFO_SIZE: usize = 72;
/// Padding byte for empty write transfers
const EMPTY_WRITE_PAD: u8 = 0x00u8;
#[allow(unused)]
const MAX_DMA_SIZE: usize = 32736;
#[derive(Debug, Clone, Copy)]
pub enum Error {
DmaError(DmaError),
MaxDmaTransferSizeExceeded,
FifoSizeExeeded,
Unsupported,
Unknown,
}
impl From<DmaError> for Error {
fn from(value: DmaError) -> Self {
Error::DmaError(value)
}
}
#[cfg(feature = "eh1")]
impl embedded_hal_1::spi::Error for Error {
fn kind(&self) -> embedded_hal_1::spi::ErrorKind {
embedded_hal_1::spi::ErrorKind::Other
}
}
#[derive(Debug, Clone, Copy)]
pub enum SpiMode {
Mode0,
Mode1,
Mode2,
Mode3,
}
pub trait DuplexMode {}
pub trait IsFullDuplex: DuplexMode {}
pub trait IsHalfDuplex: DuplexMode {}
/// SPI data mode
///
/// Single = 1 bit, 2 wires
/// Dual = 2 bit, 2 wires
/// Quad = 4 bit, 4 wires
#[derive(Debug, Clone, Copy)]
pub enum SpiDataMode {
Single,
Dual,
Quad,
}
pub struct FullDuplexMode {}
impl DuplexMode for FullDuplexMode {}
impl IsFullDuplex for FullDuplexMode {}
pub struct HalfDuplexMode {}
impl DuplexMode for HalfDuplexMode {}
impl IsHalfDuplex for HalfDuplexMode {}
/// SPI command, 1 to 16 bits.
///
/// Can be [Command::None] if command phase should be suppressed.
pub enum Command {
None,
Command1(u16, SpiDataMode),
Command2(u16, SpiDataMode),
Command3(u16, SpiDataMode),
Command4(u16, SpiDataMode),
Command5(u16, SpiDataMode),
Command6(u16, SpiDataMode),
Command7(u16, SpiDataMode),
Command8(u16, SpiDataMode),
Command9(u16, SpiDataMode),
Command10(u16, SpiDataMode),
Command11(u16, SpiDataMode),
Command12(u16, SpiDataMode),
Command13(u16, SpiDataMode),
Command14(u16, SpiDataMode),
Command15(u16, SpiDataMode),
Command16(u16, SpiDataMode),
}
impl Command {
fn width(&self) -> usize {
match self {
Command::None => 0,
Command::Command1(_, _) => 1,
Command::Command2(_, _) => 2,
Command::Command3(_, _) => 3,
Command::Command4(_, _) => 4,
Command::Command5(_, _) => 5,
Command::Command6(_, _) => 6,
Command::Command7(_, _) => 7,
Command::Command8(_, _) => 8,
Command::Command9(_, _) => 9,
Command::Command10(_, _) => 10,
Command::Command11(_, _) => 11,
Command::Command12(_, _) => 12,
Command::Command13(_, _) => 13,
Command::Command14(_, _) => 14,
Command::Command15(_, _) => 15,
Command::Command16(_, _) => 16,
}
}
fn value(&self) -> u16 {
match self {
Command::None => 0,
Command::Command1(value, _)
| Command::Command2(value, _)
| Command::Command3(value, _)
| Command::Command4(value, _)
| Command::Command5(value, _)
| Command::Command6(value, _)
| Command::Command7(value, _)
| Command::Command8(value, _)
| Command::Command9(value, _)
| Command::Command10(value, _)
| Command::Command11(value, _)
| Command::Command12(value, _)
| Command::Command13(value, _)
| Command::Command14(value, _)
| Command::Command15(value, _)
| Command::Command16(value, _) => *value,
}
}
fn mode(&self) -> SpiDataMode {
match self {
Command::None => SpiDataMode::Single,
Command::Command1(_, mode)
| Command::Command2(_, mode)
| Command::Command3(_, mode)
| Command::Command4(_, mode)
| Command::Command5(_, mode)
| Command::Command6(_, mode)
| Command::Command7(_, mode)
| Command::Command8(_, mode)
| Command::Command9(_, mode)
| Command::Command10(_, mode)
| Command::Command11(_, mode)
| Command::Command12(_, mode)
| Command::Command13(_, mode)
| Command::Command14(_, mode)
| Command::Command15(_, mode)
| Command::Command16(_, mode) => *mode,
}
}
fn is_none(&self) -> bool {
match self {
Command::None => true,
_ => false,
}
}
}
/// SPI address, 1 to 32 bits.
///
/// Can be [Address::None] if address phase should be suppressed.
pub enum Address {
None,
Address1(u32, SpiDataMode),
Address2(u32, SpiDataMode),
Address3(u32, SpiDataMode),
Address4(u32, SpiDataMode),
Address5(u32, SpiDataMode),
Address6(u32, SpiDataMode),
Address7(u32, SpiDataMode),
Address8(u32, SpiDataMode),
Address9(u32, SpiDataMode),
Address10(u32, SpiDataMode),
Address11(u32, SpiDataMode),
Address12(u32, SpiDataMode),
Address13(u32, SpiDataMode),
Address14(u32, SpiDataMode),
Address15(u32, SpiDataMode),
Address16(u32, SpiDataMode),
Address17(u32, SpiDataMode),
Address18(u32, SpiDataMode),
Address19(u32, SpiDataMode),
Address20(u32, SpiDataMode),
Address21(u32, SpiDataMode),
Address22(u32, SpiDataMode),
Address23(u32, SpiDataMode),
Address24(u32, SpiDataMode),
Address25(u32, SpiDataMode),
Address26(u32, SpiDataMode),
Address27(u32, SpiDataMode),
Address28(u32, SpiDataMode),
Address29(u32, SpiDataMode),
Address30(u32, SpiDataMode),
Address31(u32, SpiDataMode),
Address32(u32, SpiDataMode),
}
impl Address {
fn width(&self) -> usize {
match self {
Address::None => 0,
Address::Address1(_, _) => 1,
Address::Address2(_, _) => 2,
Address::Address3(_, _) => 3,
Address::Address4(_, _) => 4,
Address::Address5(_, _) => 5,
Address::Address6(_, _) => 6,
Address::Address7(_, _) => 7,
Address::Address8(_, _) => 8,
Address::Address9(_, _) => 9,
Address::Address10(_, _) => 10,
Address::Address11(_, _) => 11,
Address::Address12(_, _) => 12,
Address::Address13(_, _) => 13,
Address::Address14(_, _) => 14,
Address::Address15(_, _) => 15,
Address::Address16(_, _) => 16,
Address::Address17(_, _) => 17,
Address::Address18(_, _) => 18,
Address::Address19(_, _) => 19,
Address::Address20(_, _) => 20,
Address::Address21(_, _) => 21,
Address::Address22(_, _) => 22,
Address::Address23(_, _) => 23,
Address::Address24(_, _) => 24,
Address::Address25(_, _) => 25,
Address::Address26(_, _) => 26,
Address::Address27(_, _) => 27,
Address::Address28(_, _) => 28,
Address::Address29(_, _) => 29,
Address::Address30(_, _) => 30,
Address::Address31(_, _) => 31,
Address::Address32(_, _) => 32,
}
}
fn value(&self) -> u32 {
match self {
Address::None => 0,
Address::Address1(value, _)
| Address::Address2(value, _)
| Address::Address3(value, _)
| Address::Address4(value, _)
| Address::Address5(value, _)
| Address::Address6(value, _)
| Address::Address7(value, _)
| Address::Address8(value, _)
| Address::Address9(value, _)
| Address::Address10(value, _)
| Address::Address11(value, _)
| Address::Address12(value, _)
| Address::Address13(value, _)
| Address::Address14(value, _)
| Address::Address15(value, _)
| Address::Address16(value, _)
| Address::Address17(value, _)
| Address::Address18(value, _)
| Address::Address19(value, _)
| Address::Address20(value, _)
| Address::Address21(value, _)
| Address::Address22(value, _)
| Address::Address23(value, _)
| Address::Address24(value, _)
| Address::Address25(value, _)
| Address::Address26(value, _)
| Address::Address27(value, _)
| Address::Address28(value, _)
| Address::Address29(value, _)
| Address::Address30(value, _)
| Address::Address31(value, _)
| Address::Address32(value, _) => *value,
}
}
fn is_none(&self) -> bool {
match self {
Address::None => true,
_ => false,
}
}
fn mode(&self) -> SpiDataMode {
match self {
Address::None => SpiDataMode::Single,
Address::Address1(_, mode)
| Address::Address2(_, mode)
| Address::Address3(_, mode)
| Address::Address4(_, mode)
| Address::Address5(_, mode)
| Address::Address6(_, mode)
| Address::Address7(_, mode)
| Address::Address8(_, mode)
| Address::Address9(_, mode)
| Address::Address10(_, mode)
| Address::Address11(_, mode)
| Address::Address12(_, mode)
| Address::Address13(_, mode)
| Address::Address14(_, mode)
| Address::Address15(_, mode)
| Address::Address16(_, mode)
| Address::Address17(_, mode)
| Address::Address18(_, mode)
| Address::Address19(_, mode)
| Address::Address20(_, mode)
| Address::Address21(_, mode)
| Address::Address22(_, mode)
| Address::Address23(_, mode)
| Address::Address24(_, mode)
| Address::Address25(_, mode)
| Address::Address26(_, mode)
| Address::Address27(_, mode)
| Address::Address28(_, mode)
| Address::Address29(_, mode)
| Address::Address30(_, mode)
| Address::Address31(_, mode)
| Address::Address32(_, mode) => *mode,
}
}
}
/// Read and Write in half duplex mode.
pub trait HalfDuplexReadWrite {
type Error;
/// Half-duplex read.
fn read(
&mut self,
data_mode: SpiDataMode,
cmd: Command,
address: Address,
dummy: u8,
buffer: &mut [u8],
) -> Result<(), Self::Error>;
/// Half-duplex write.
fn write(
&mut self,
data_mode: SpiDataMode,
cmd: Command,
address: Address,
dummy: u8,
buffer: &[u8],
) -> Result<(), Self::Error>;
}
pub struct Spi<'d, T, M> {
spi: PeripheralRef<'d, T>,
_mode: PhantomData<M>,
}
impl<'d, T> Spi<'d, T, FullDuplexMode>
where
T: Instance,
{
/// Constructs an SPI instance in 8bit dataframe mode.
pub fn new<SCK: OutputPin, MOSI: OutputPin, MISO: InputPin, CS: OutputPin>(
spi: impl Peripheral<P = T> + 'd,
sck: impl Peripheral<P = SCK> + 'd,
mosi: impl Peripheral<P = MOSI> + 'd,
miso: impl Peripheral<P = MISO> + 'd,
cs: impl Peripheral<P = CS> + 'd,
frequency: HertzU32,
mode: SpiMode,
peripheral_clock_control: &mut PeripheralClockControl,
clocks: &Clocks,
) -> Spi<'d, T, FullDuplexMode> {
crate::into_ref!(spi, sck, mosi, miso, cs);
sck.set_to_push_pull_output()
.connect_peripheral_to_output(spi.sclk_signal());
mosi.set_to_push_pull_output()
.connect_peripheral_to_output(spi.mosi_signal());
miso.set_to_input()
.connect_input_to_peripheral(spi.miso_signal());
cs.set_to_push_pull_output()
.connect_peripheral_to_output(spi.cs_signal());
Self::new_internal(spi, frequency, mode, peripheral_clock_control, clocks)
}
/// Constructs an SPI instance in 8bit dataframe mode without CS pin.
pub fn new_no_cs<SCK: OutputPin, MOSI: OutputPin, MISO: InputPin>(
spi: impl Peripheral<P = T> + 'd,
sck: impl Peripheral<P = SCK> + 'd,
mosi: impl Peripheral<P = MOSI> + 'd,
miso: impl Peripheral<P = MISO> + 'd,
frequency: HertzU32,
mode: SpiMode,
peripheral_clock_control: &mut PeripheralClockControl,
clocks: &Clocks,
) -> Spi<'d, T, FullDuplexMode> {
crate::into_ref!(spi, sck, mosi, miso);
sck.set_to_push_pull_output()
.connect_peripheral_to_output(spi.sclk_signal());
mosi.set_to_push_pull_output()
.connect_peripheral_to_output(spi.mosi_signal());
miso.set_to_input()
.connect_input_to_peripheral(spi.miso_signal());
Self::new_internal(spi, frequency, mode, peripheral_clock_control, clocks)
}
/// Constructs an SPI instance in 8bit dataframe mode without CS and MISO
/// pin.
pub fn new_no_cs_no_miso<SCK: OutputPin, MOSI: OutputPin>(
spi: impl Peripheral<P = T> + 'd,
sck: impl Peripheral<P = SCK> + 'd,
mosi: impl Peripheral<P = MOSI> + 'd,
frequency: HertzU32,
mode: SpiMode,
peripheral_clock_control: &mut PeripheralClockControl,
clocks: &Clocks,
) -> Spi<'d, T, FullDuplexMode> {
crate::into_ref!(spi, sck, mosi);
sck.set_to_push_pull_output()
.connect_peripheral_to_output(spi.sclk_signal());
mosi.set_to_push_pull_output()
.connect_peripheral_to_output(spi.mosi_signal());
Self::new_internal(spi, frequency, mode, peripheral_clock_control, clocks)
}
/// Constructs an SPI instance in 8bit dataframe mode with only MOSI
/// connected. This might be useful for (ab)using SPI to implement
/// other protocols by bitbanging (WS2812B, onewire, generating arbitrary
/// waveforms…)
pub fn new_mosi_only<MOSI: OutputPin>(
spi: impl Peripheral<P = T> + 'd,
mosi: impl Peripheral<P = MOSI> + 'd,
frequency: HertzU32,
mode: SpiMode,
peripheral_clock_control: &mut PeripheralClockControl,
clocks: &Clocks,
) -> Spi<'d, T, FullDuplexMode> {
crate::into_ref!(spi, mosi);
mosi.set_to_push_pull_output()
.connect_peripheral_to_output(spi.mosi_signal());
Self::new_internal(spi, frequency, mode, peripheral_clock_control, clocks)
}
pub(crate) fn new_internal(
spi: PeripheralRef<'d, T>,
frequency: HertzU32,
mode: SpiMode,
peripheral_clock_control: &mut PeripheralClockControl,
clocks: &Clocks,
) -> Spi<'d, T, FullDuplexMode> {
spi.enable_peripheral(peripheral_clock_control);
let mut spi = Spi {
spi,
_mode: PhantomData::default(),
};
spi.spi.setup(frequency, clocks);
spi.spi.init();
spi.spi.set_data_mode(mode);
spi
}
pub fn change_bus_frequency(&mut self, frequency: HertzU32, clocks: &Clocks) {
self.spi.ch_bus_freq(frequency, clocks);
}
}
impl<'d, T> Spi<'d, T, HalfDuplexMode>
where
T: ExtendedInstance,
{
/// Constructs an SPI instance in half-duplex mode.
///
/// All pins are optional. Pass [crate::gpio::NO_PIN] if you don't need the
/// given pin.
pub fn new_half_duplex<
SCK: OutputPin,
MOSI: OutputPin + InputPin,
MISO: OutputPin + InputPin,
SIO2: OutputPin + InputPin,
SIO3: OutputPin + InputPin,
CS: OutputPin,
>(
spi: impl Peripheral<P = T> + 'd,
sck: Option<impl Peripheral<P = SCK> + 'd>,
mosi: Option<impl Peripheral<P = MOSI> + 'd>,
miso: Option<impl Peripheral<P = MISO> + 'd>,
sio2: Option<impl Peripheral<P = SIO2> + 'd>,
sio3: Option<impl Peripheral<P = SIO3> + 'd>,
cs: Option<impl Peripheral<P = CS> + 'd>,
frequency: HertzU32,
mode: SpiMode,
peripheral_clock_control: &mut PeripheralClockControl,
clocks: &Clocks,
) -> Spi<'d, T, HalfDuplexMode> {
crate::into_ref!(spi);
if let Some(sck) = sck {
crate::into_ref!(sck);
sck.set_to_push_pull_output()
.connect_peripheral_to_output(spi.sclk_signal());
}
if let Some(mosi) = mosi {
crate::into_ref!(mosi);
mosi.enable_output(true);
mosi.connect_peripheral_to_output(spi.mosi_signal());
mosi.enable_input(true);
mosi.connect_input_to_peripheral(spi.sio0_input_signal());
}
if let Some(miso) = miso {
crate::into_ref!(miso);
miso.enable_output(true);
miso.connect_peripheral_to_output(spi.sio1_output_signal());
miso.enable_input(true);
miso.connect_input_to_peripheral(spi.miso_signal());
}
if let Some(sio2) = sio2 {
crate::into_ref!(sio2);
sio2.enable_output(true);
sio2.connect_peripheral_to_output(spi.sio2_output_signal());
sio2.enable_input(true);
sio2.connect_input_to_peripheral(spi.sio2_input_signal());
}
if let Some(sio3) = sio3 {
crate::into_ref!(sio3);
sio3.enable_output(true);
sio3.connect_peripheral_to_output(spi.sio3_output_signal());
sio3.enable_input(true);
sio3.connect_input_to_peripheral(spi.sio3_input_signal());
}
if let Some(cs) = cs {
crate::into_ref!(cs);
cs.set_to_push_pull_output()
.connect_peripheral_to_output(spi.cs_signal());
}
Self::new_internal(spi, frequency, mode, peripheral_clock_control, clocks)
}
pub(crate) fn new_internal(
spi: PeripheralRef<'d, T>,
frequency: HertzU32,
mode: SpiMode,
peripheral_clock_control: &mut PeripheralClockControl,
clocks: &Clocks,
) -> Spi<'d, T, HalfDuplexMode> {
spi.enable_peripheral(peripheral_clock_control);
let mut spi = Spi {
spi,
_mode: PhantomData::default(),
};
spi.spi.setup(frequency, clocks);
spi.spi.init();
spi.spi.set_data_mode(mode);
spi
}
pub fn change_bus_frequency(&mut self, frequency: HertzU32, clocks: &Clocks) {
self.spi.ch_bus_freq(frequency, clocks);
}
}
impl<T, M> HalfDuplexReadWrite for Spi<'_, T, M>
where
T: Instance,
M: IsHalfDuplex,
{
type Error = Error;
fn read(
&mut self,
data_mode: SpiDataMode,
cmd: Command,
address: Address,
dummy: u8,
buffer: &mut [u8],
) -> Result<(), Self::Error> {
if buffer.len() > FIFO_SIZE {
return Err(Error::FifoSizeExeeded);
}
if buffer.len() == 0 {
return Err(Error::Unsupported);
}
self.spi
.init_spi_data_mode(cmd.mode(), address.mode(), data_mode);
self.spi.read_bytes_half_duplex(cmd, address, dummy, buffer)
}
fn write(
&mut self,
data_mode: SpiDataMode,
cmd: Command,
address: Address,
dummy: u8,
buffer: &[u8],
) -> Result<(), Self::Error> {
if buffer.len() > FIFO_SIZE {
return Err(Error::FifoSizeExeeded);
}
self.spi
.init_spi_data_mode(cmd.mode(), address.mode(), data_mode);
self.spi
.write_bytes_half_duplex(cmd, address, dummy, buffer)
}
}
impl<T, M> embedded_hal::spi::FullDuplex<u8> for Spi<'_, T, M>
where
T: Instance,
M: IsFullDuplex,
{
type Error = Error;
fn read(&mut self) -> nb::Result<u8, Self::Error> {
self.spi.read_byte()
}
fn send(&mut self, word: u8) -> nb::Result<(), Self::Error> {
self.spi.write_byte(word)
}
}
impl<T, M> embedded_hal::blocking::spi::Transfer<u8> for Spi<'_, T, M>
where
T: Instance,
M: IsFullDuplex,
{
type Error = Error;
fn transfer<'w>(&mut self, words: &'w mut [u8]) -> Result<&'w [u8], Self::Error> {
self.spi.transfer(words)
}
}
impl<T, M> embedded_hal::blocking::spi::Write<u8> for Spi<'_, T, M>
where
T: Instance,
M: IsFullDuplex,
{
type Error = Error;
fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
self.spi.write_bytes(words)?;
self.spi.flush()?;
Ok(())
}
}
pub mod dma {
use core::{marker::PhantomData, mem};
use embedded_dma::{ReadBuffer, WriteBuffer};
#[cfg(any(esp32, esp32s2))]
use super::Spi3Instance;
use super::{
Address,
Command,
DuplexMode,
Instance,
InstanceDma,
IsFullDuplex,
IsHalfDuplex,
Spi,
Spi2Instance,
SpiDataMode,
MAX_DMA_SIZE,
};
#[cfg(any(esp32, esp32s2))]
use crate::dma::Spi3Peripheral;
use crate::{
dma::{Channel, DmaTransfer, DmaTransferRxTx, Rx, Spi2Peripheral, SpiPeripheral, Tx},
peripheral::PeripheralRef,
};
pub trait WithDmaSpi2<'d, T, RX, TX, P, M>
where
T: Instance + Spi2Instance,
TX: Tx,
RX: Rx,
P: SpiPeripheral,
M: DuplexMode,
{
fn with_dma(self, channel: Channel<TX, RX, P>) -> SpiDma<'d, T, TX, RX, P, M>;
}
#[cfg(any(esp32, esp32s2))]
pub trait WithDmaSpi3<'d, T, RX, TX, P, M>
where
T: Instance + Spi3Instance,
TX: Tx,
RX: Rx,
P: SpiPeripheral,
M: DuplexMode,
{
fn with_dma(self, channel: Channel<TX, RX, P>) -> SpiDma<'d, T, TX, RX, P, M>;
}
impl<'d, T, RX, TX, P, M> WithDmaSpi2<'d, T, RX, TX, P, M> for Spi<'d, T, M>
where
T: Instance + Spi2Instance,
TX: Tx,
RX: Rx,
P: SpiPeripheral + Spi2Peripheral,
M: DuplexMode,
{
fn with_dma(self, mut channel: Channel<TX, RX, P>) -> SpiDma<'d, T, TX, RX, P, M> {
channel.tx.init_channel(); // no need to call this for both, TX and RX
SpiDma {
spi: self.spi,
channel,
_mode: PhantomData::default(),
}
}
}
#[cfg(any(esp32, esp32s2))]
impl<'d, T, RX, TX, P, M> WithDmaSpi3<'d, T, RX, TX, P, M> for Spi<'d, T, M>
where
T: Instance + Spi3Instance,
TX: Tx,
RX: Rx,
P: SpiPeripheral + Spi3Peripheral,
M: DuplexMode,
{
fn with_dma(self, mut channel: Channel<TX, RX, P>) -> SpiDma<'d, T, TX, RX, P, M> {
channel.tx.init_channel(); // no need to call this for both, TX and RX
SpiDma {
spi: self.spi,
channel,
_mode: PhantomData::default(),
}
}
}
/// An in-progress DMA transfer
pub struct SpiDmaTransferRxTx<'d, T, TX, RX, P, RBUFFER, TBUFFER, M>
where
T: InstanceDma<TX, RX>,
TX: Tx,
RX: Rx,
P: SpiPeripheral,
M: DuplexMode,
{
spi_dma: SpiDma<'d, T, TX, RX, P, M>,
rbuffer: RBUFFER,
tbuffer: TBUFFER,
}
impl<'d, T, TX, RX, P, RXBUF, TXBUF, M>
DmaTransferRxTx<RXBUF, TXBUF, SpiDma<'d, T, TX, RX, P, M>>
for SpiDmaTransferRxTx<'d, T, TX, RX, P, RXBUF, TXBUF, M>
where
T: InstanceDma<TX, RX>,
TX: Tx,
RX: Rx,
P: SpiPeripheral,
M: DuplexMode,
{
/// Wait for the DMA transfer to complete and return the buffers and the
/// SPI instance.
fn wait(mut self) -> (RXBUF, TXBUF, SpiDma<'d, T, TX, RX, P, M>) {
self.spi_dma.spi.flush().ok(); // waiting for the DMA transfer is not enough
// `DmaTransfer` needs to have a `Drop` implementation, because we accept
// managed buffers that can free their memory on drop. Because of that
// we can't move out of the `DmaTransfer`'s fields, so we use `ptr::read`
// and `mem::forget`.
//
// NOTE(unsafe) There is no panic branch between getting the resources
// and forgetting `self`.
unsafe {
let rbuffer = core::ptr::read(&self.rbuffer);
let tbuffer = core::ptr::read(&self.tbuffer);
let payload = core::ptr::read(&self.spi_dma);
mem::forget(self);
(rbuffer, tbuffer, payload)
}
}
}
impl<'d, T, TX, RX, P, RXBUF, TXBUF, M> Drop
for SpiDmaTransferRxTx<'d, T, TX, RX, P, RXBUF, TXBUF, M>
where
T: InstanceDma<TX, RX>,
TX: Tx,
RX: Rx,
P: SpiPeripheral,
M: DuplexMode,
{
fn drop(&mut self) {
self.spi_dma.spi.flush().ok();
}
}
/// An in-progress DMA transfer.
pub struct SpiDmaTransfer<'d, T, TX, RX, P, BUFFER, M>
where
T: InstanceDma<TX, RX>,
TX: Tx,
RX: Rx,
P: SpiPeripheral,
M: DuplexMode,
{
spi_dma: SpiDma<'d, T, TX, RX, P, M>,
buffer: BUFFER,
}
impl<'d, T, TX, RX, P, BUFFER, M> DmaTransfer<BUFFER, SpiDma<'d, T, TX, RX, P, M>>
for SpiDmaTransfer<'d, T, TX, RX, P, BUFFER, M>
where
T: InstanceDma<TX, RX>,
TX: Tx,
RX: Rx,
P: SpiPeripheral,
M: DuplexMode,
{
/// Wait for the DMA transfer to complete and return the buffers and the
/// SPI instance.
fn wait(mut self) -> (BUFFER, SpiDma<'d, T, TX, RX, P, M>) {
self.spi_dma.spi.flush().ok(); // waiting for the DMA transfer is not enough
// `DmaTransfer` needs to have a `Drop` implementation, because we accept
// managed buffers that can free their memory on drop. Because of that
// we can't move out of the `DmaTransfer`'s fields, so we use `ptr::read`
// and `mem::forget`.
//
// NOTE(unsafe) There is no panic branch between getting the resources
// and forgetting `self`.
unsafe {
let buffer = core::ptr::read(&self.buffer);
let payload = core::ptr::read(&self.spi_dma);
mem::forget(self);
(buffer, payload)
}
}
}
impl<'d, T, TX, RX, P, BUFFER, M> Drop for SpiDmaTransfer<'d, T, TX, RX, P, BUFFER, M>
where
T: InstanceDma<TX, RX>,
TX: Tx,
RX: Rx,
P: SpiPeripheral,
M: DuplexMode,
{
fn drop(&mut self) {
self.spi_dma.spi.flush().ok();
}
}
/// A DMA capable SPI instance.
pub struct SpiDma<'d, T, TX, RX, P, M>
where
TX: Tx,
RX: Rx,
P: SpiPeripheral,
M: DuplexMode,
{
pub(crate) spi: PeripheralRef<'d, T>,
pub(crate) channel: Channel<TX, RX, P>,
_mode: PhantomData<M>,
}
impl<'d, T, TX, RX, P, M> SpiDma<'d, T, TX, RX, P, M>
where
T: InstanceDma<TX, RX>,
TX: Tx,
RX: Rx,
P: SpiPeripheral,
M: IsFullDuplex,
{
/// Perform a DMA write.
///
/// This will return a [SpiDmaTransfer] owning the buffer(s) and the SPI
/// instance. The maximum amount of data to be sent is 32736
/// bytes.
pub fn dma_write<TXBUF>(
mut self,
words: TXBUF,
) -> Result<SpiDmaTransfer<'d, T, TX, RX, P, TXBUF, M>, super::Error>
where
TXBUF: ReadBuffer<Word = u8>,
{
let (ptr, len) = unsafe { words.read_buffer() };
if len > MAX_DMA_SIZE {
return Err(super::Error::MaxDmaTransferSizeExceeded);
}
self.spi
.start_write_bytes_dma(ptr, len, &mut self.channel.tx)?;
Ok(SpiDmaTransfer {
spi_dma: self,
buffer: words,
})
}
/// Perform a DMA read.
///
/// This will return a [SpiDmaTransfer] owning the buffer(s) and the SPI
/// instance. The maximum amount of data to be received is 32736
/// bytes.
pub fn dma_read<RXBUF>(
mut self,
mut words: RXBUF,
) -> Result<SpiDmaTransfer<'d, T, TX, RX, P, RXBUF, M>, super::Error>
where
RXBUF: WriteBuffer<Word = u8>,
{
let (ptr, len) = unsafe { words.write_buffer() };
if len > MAX_DMA_SIZE {
return Err(super::Error::MaxDmaTransferSizeExceeded);
}
self.spi
.start_read_bytes_dma(ptr, len, &mut self.channel.rx)?;