-
Notifications
You must be signed in to change notification settings - Fork 170
/
spi.rs
2005 lines (1713 loc) · 62.1 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
//! SPI peripheral control
//!
//! SPI0 is reserved for accessing flash and sram and therefore not usable for other purposes.
//! SPI1 shares its external pins with SPI0 and therefore has severe restrictions in use.
//!
//! SPI2 & 3 can be used freely.
//!
//! The CS pin can be controlled by hardware on esp32 variants (contrary to the description of embedded_hal).
//!
//! Look at the following table to determine which driver best suits your requirements:
//!
//! | | | SpiDeviceDriver::new | SpiDeviceDriver::new (no CS) | SpiSoftCsDeviceDriver::new | SpiBusDriver::new |
//! |---|------------------|----------------------|------------------------------|----------------------------|-------------------|
//! | | Managed CS | Hardware | N | Software triggered | N |
//! | | 1 device | Y | Y | Y | Y |
//! | | 1-3 devices | Y | N | Y | N |
//! | | 4-6 devices | Only on esp32CX | N | Y | N |
//! | | More than 6 | N | N | Y | N |
//! | | DMA | N | N | N | N |
//! | | Polling transmit | Y | Y | Y | Y |
//! | | ISR transmit | Y | Y | Y | Y |
//! | | Async support* | Y | Y | Y | Y |
//!
//! * True non-blocking async possible only when all devices attached to the SPI bus are used in async mode (i.e. calling methods `xxx_async()`
//! instead of their blocking `xxx()` counterparts)
//!
//! The [Transfer::transfer], [Write::write] and [WriteIter::write_iter] functions lock the
//! APB frequency and therefore the requests are always run at the requested baudrate.
//! The primitive [FullDuplex::read] and [FullDuplex::send] do not lock the APB frequency and
//! therefore may run at a different frequency.
//!
//! # TODO
//! - Quad SPI
//! - Slave SPI
use core::borrow::{Borrow, BorrowMut};
use core::cell::Cell;
use core::cell::UnsafeCell;
use core::cmp::{max, min, Ordering};
use core::future::Future;
use core::iter::once;
use core::marker::PhantomData;
use core::ptr;
use embassy_sync::mutex::Mutex;
use embedded_hal::spi::{SpiBus, SpiDevice};
use esp_idf_sys::*;
use heapless::Deque;
use crate::delay::{self, Ets, BLOCK};
use crate::gpio::{
AnyIOPin, AnyOutputPin, InputPin, Level, Output, OutputMode, OutputPin, PinDriver,
};
use crate::interrupt::asynch::HalIsrNotification;
use crate::interrupt::InterruptType;
use crate::peripheral::Peripheral;
use crate::task::embassy_sync::EspRawMutex;
use crate::task::CriticalSection;
pub use embedded_hal::spi::Operation;
crate::embedded_hal_error!(
SpiError,
embedded_hal::spi::Error,
embedded_hal::spi::ErrorKind
);
use config::Duplex;
pub trait Spi: Send {
fn device() -> spi_host_device_t;
}
/// A marker interface implemented by all SPI peripherals except SPI1 which
/// should use a fixed set of pins
pub trait SpiAnyPins: Spi {}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Dma {
Disabled,
Channel1(usize),
Channel2(usize),
Auto(usize),
}
impl From<Dma> for spi_dma_chan_t {
fn from(dma: Dma) -> Self {
match dma {
Dma::Channel1(_) => 1,
Dma::Channel2(_) => 2,
Dma::Auto(_) => 3,
_ => 0,
}
}
}
impl Dma {
pub const fn max_transfer_size(&self) -> usize {
let max_transfer_size = match self {
Dma::Disabled => TRANS_LEN,
Dma::Channel1(size) | Dma::Channel2(size) | Dma::Auto(size) => *size,
};
match max_transfer_size {
0 => panic!("The max transfer size must be greater than 0"),
x if x % 4 != 0 => panic!("The max transfer size must be a multiple of 4"),
_ => max_transfer_size,
}
}
}
pub type SpiDriverConfig = config::DriverConfig;
pub type SpiConfig = config::Config;
/// SPI configuration
pub mod config {
use crate::{interrupt::InterruptType, units::*};
use enumset::EnumSet;
use esp_idf_sys::*;
use super::Dma;
pub use embedded_hal::spi::{Mode, Phase, Polarity, MODE_0, MODE_1, MODE_2, MODE_3};
pub struct V02Type<T>(pub T);
impl From<V02Type<embedded_hal_0_2::spi::Polarity>> for Polarity {
fn from(polarity: V02Type<embedded_hal_0_2::spi::Polarity>) -> Self {
match polarity.0 {
embedded_hal_0_2::spi::Polarity::IdleHigh => Polarity::IdleHigh,
embedded_hal_0_2::spi::Polarity::IdleLow => Polarity::IdleLow,
}
}
}
impl From<V02Type<embedded_hal_0_2::spi::Phase>> for Phase {
fn from(phase: V02Type<embedded_hal_0_2::spi::Phase>) -> Self {
match phase.0 {
embedded_hal_0_2::spi::Phase::CaptureOnFirstTransition => {
Phase::CaptureOnFirstTransition
}
embedded_hal_0_2::spi::Phase::CaptureOnSecondTransition => {
Phase::CaptureOnSecondTransition
}
}
}
}
impl From<V02Type<embedded_hal_0_2::spi::Mode>> for Mode {
fn from(mode: V02Type<embedded_hal_0_2::spi::Mode>) -> Self {
Self {
polarity: V02Type(mode.0.polarity).into(),
phase: V02Type(mode.0.phase).into(),
}
}
}
/// Specify the communication mode with the device
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Duplex {
/// Full duplex is the default
Full,
/// Half duplex in some cases
Half,
/// Use MOSI (=spid) for both sending and receiving data (implies half duplex)
Half3Wire,
}
impl Duplex {
pub fn as_flags(&self) -> u32 {
match self {
Duplex::Full => 0,
Duplex::Half => SPI_DEVICE_HALFDUPLEX,
Duplex::Half3Wire => SPI_DEVICE_HALFDUPLEX | SPI_DEVICE_3WIRE,
}
}
}
/// Specifies the order in which the bits of data should be transfered/received
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum BitOrder {
/// Most significant bit first (default)
MsbFirst,
/// Least significant bit first
LsbFirst,
/// Least significant bit first, when sending
TxLsbFirst,
/// Least significant bit first, when receiving
RxLsbFirst,
}
impl BitOrder {
pub fn as_flags(&self) -> u32 {
match self {
Self::MsbFirst => 0,
Self::LsbFirst => SPI_DEVICE_BIT_LSBFIRST,
Self::TxLsbFirst => SPI_DEVICE_TXBIT_LSBFIRST,
Self::RxLsbFirst => SPI_DEVICE_RXBIT_LSBFIRST,
}
}
}
/// SPI Driver configuration
#[derive(Debug, Clone)]
pub struct DriverConfig {
pub dma: Dma,
pub intr_flags: EnumSet<InterruptType>,
}
impl DriverConfig {
pub fn new() -> Self {
Default::default()
}
#[must_use]
pub fn dma(mut self, dma: Dma) -> Self {
self.dma = dma;
self
}
#[must_use]
pub fn intr_flags(mut self, intr_flags: EnumSet<InterruptType>) -> Self {
self.intr_flags = intr_flags;
self
}
}
impl Default for DriverConfig {
fn default() -> Self {
Self {
dma: Dma::Disabled,
intr_flags: EnumSet::<InterruptType>::empty(),
}
}
}
/// SPI Device configuration
#[derive(Debug, Clone)]
pub struct Config {
pub baudrate: Hertz,
pub data_mode: Mode,
/// This property can be set to configure a SPI Device for being write only
/// Thus the flag SPI_DEVICE_NO_DUMMY will be passed on initialization and
/// it will unlock the possibility of using 80Mhz as the bus freq
/// See https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/spi_master.html#timing-considerations
pub write_only: bool,
pub duplex: Duplex,
pub bit_order: BitOrder,
pub cs_active_high: bool,
/// On Half-Duplex transactions: `cs_pre_delay_us % 16` corresponds to the number of SPI bit-cycles cs should be activated before the transmission.
/// On Full-Duplex transactions: `cs_pre_delay_us != 0` will add 1 microsecond of cs activation before transmission
pub cs_pre_delay_us: Option<u16>, // u16 as per the C struct has a uint16_t, cf: esp-idf/components/driver/spi/include/driver/spi_master.h spi_device_interface_config_t
///< Amount of SPI bit-cycles the cs should stay active after the transmission (0-16)
pub cs_post_delay_us: Option<u8>, // u8 as per the C struct had a uint8_t, cf: esp-idf/components/driver/spi/include/driver/spi_master.h spi_device_interface_config_t
pub input_delay_ns: i32,
pub polling: bool,
pub allow_pre_post_delays: bool,
pub queue_size: usize,
}
impl Config {
pub fn new() -> Self {
Default::default()
}
#[must_use]
pub fn baudrate(mut self, baudrate: Hertz) -> Self {
self.baudrate = baudrate;
self
}
#[must_use]
pub fn data_mode(mut self, data_mode: Mode) -> Self {
self.data_mode = data_mode;
self
}
#[must_use]
pub fn write_only(mut self, write_only: bool) -> Self {
self.write_only = write_only;
self
}
#[must_use]
pub fn duplex(mut self, duplex: Duplex) -> Self {
self.duplex = duplex;
self
}
#[must_use]
pub fn bit_order(mut self, bit_order: BitOrder) -> Self {
self.bit_order = bit_order;
self
}
#[must_use]
pub fn cs_active_high(mut self) -> Self {
self.cs_active_high = true;
self
}
/// On Half-Duplex transactions: `cs_pre_delay_us % 16` corresponds to the number of SPI bit-cycles cs should be activated before the transmission
/// On Full-Duplex transactions: `cs_pre_delay_us != 0` will add 1 microsecond of cs activation before transmission
#[must_use]
pub fn cs_pre_delay_us(mut self, delay_us: u16) -> Self {
self.cs_pre_delay_us = Some(delay_us);
self
}
/// Add an aditional Amount of SPI bit-cycles the cs should be activated after the transmission (0-16).
/// This only works on half-duplex transactions.
#[must_use]
pub fn cs_post_delay_us(mut self, delay_us: u8) -> Self {
self.cs_post_delay_us = Some(delay_us);
self
}
#[must_use]
pub fn input_delay_ns(mut self, input_delay_ns: i32) -> Self {
self.input_delay_ns = input_delay_ns;
self
}
#[must_use]
pub fn polling(mut self, polling: bool) -> Self {
self.polling = polling;
self
}
#[must_use]
pub fn allow_pre_post_delays(mut self, allow_pre_post_delays: bool) -> Self {
self.allow_pre_post_delays = allow_pre_post_delays;
self
}
#[must_use]
pub fn queue_size(mut self, queue_size: usize) -> Self {
self.queue_size = queue_size;
self
}
}
impl Default for Config {
fn default() -> Self {
Self {
baudrate: Hertz(1_000_000),
data_mode: embedded_hal::spi::MODE_0,
write_only: false,
cs_active_high: false,
duplex: Duplex::Full,
bit_order: BitOrder::MsbFirst,
cs_pre_delay_us: None,
cs_post_delay_us: None,
input_delay_ns: 0,
polling: true,
allow_pre_post_delays: false,
queue_size: 1,
}
}
}
}
pub struct SpiDriver<'d> {
host: u8,
max_transfer_size: usize,
#[allow(dead_code)]
bus_async_lock: Mutex<EspRawMutex, ()>,
_p: PhantomData<&'d mut ()>,
}
impl<'d> SpiDriver<'d> {
/// Create new instance of SPI controller for SPI1
///
/// SPI1 can only use fixed pin for SCLK, SDO and SDI as they are shared with SPI0.
#[cfg(esp32)]
pub fn new_spi1(
_spi: impl Peripheral<P = SPI1> + 'd,
sclk: impl Peripheral<P = crate::gpio::Gpio6> + 'd,
sdo: impl Peripheral<P = crate::gpio::Gpio7> + 'd,
sdi: Option<impl Peripheral<P = crate::gpio::Gpio8> + 'd>,
config: &config::DriverConfig,
) -> Result<Self, EspError> {
let max_transfer_size = Self::new_internal(SPI1::device(), Some(sclk), sdo, sdi, config)?;
Ok(Self {
host: SPI1::device() as _,
max_transfer_size,
bus_async_lock: Mutex::new(()),
_p: PhantomData,
})
}
/// Create new instance of SPI controller for all others
pub fn new<SPI: SpiAnyPins>(
_spi: impl Peripheral<P = SPI> + 'd,
sclk: impl Peripheral<P = impl OutputPin> + 'd,
sdo: impl Peripheral<P = impl OutputPin> + 'd,
sdi: Option<impl Peripheral<P = impl InputPin> + 'd>,
config: &config::DriverConfig,
) -> Result<Self, EspError> {
let max_transfer_size = Self::new_internal(SPI::device(), Some(sclk), sdo, sdi, config)?;
Ok(Self {
host: SPI::device() as _,
max_transfer_size,
bus_async_lock: Mutex::new(()),
_p: PhantomData,
})
}
pub fn new_without_sclk<SPI: SpiAnyPins>(
_spi: impl Peripheral<P = SPI> + 'd,
sdo: impl Peripheral<P = impl OutputPin> + 'd,
sdi: Option<impl Peripheral<P = impl InputPin> + 'd>,
config: &config::DriverConfig,
) -> Result<Self, EspError> {
let max_transfer_size =
Self::new_internal(SPI::device(), Option::<AnyIOPin>::None, sdo, sdi, config)?;
Ok(Self {
host: SPI::device() as _,
max_transfer_size,
bus_async_lock: Mutex::new(()),
_p: PhantomData,
})
}
pub fn host(&self) -> spi_host_device_t {
self.host as _
}
fn new_internal(
host: spi_host_device_t,
sclk: Option<impl Peripheral<P = impl OutputPin> + 'd>,
sdo: impl Peripheral<P = impl OutputPin> + 'd,
sdi: Option<impl Peripheral<P = impl InputPin> + 'd>,
config: &config::DriverConfig,
) -> Result<usize, EspError> {
let sdo = sdo.into_ref();
let sdi = sdi.map(|sdi| sdi.into_ref());
let sclk = sclk.map(|sclk| sclk.into_ref());
let max_transfer_sz = config.dma.max_transfer_size();
let dma_chan: spi_dma_chan_t = config.dma.into();
#[allow(clippy::needless_update)]
let bus_config = spi_bus_config_t {
flags: SPICOMMON_BUSFLAG_MASTER,
sclk_io_num: sclk.as_ref().map_or(-1, |p| p.pin()),
data4_io_num: -1,
data5_io_num: -1,
data6_io_num: -1,
data7_io_num: -1,
__bindgen_anon_1: spi_bus_config_t__bindgen_ty_1 {
mosi_io_num: sdo.pin(),
//data0_io_num: -1,
},
__bindgen_anon_2: spi_bus_config_t__bindgen_ty_2 {
miso_io_num: sdi.as_ref().map_or(-1, |p| p.pin()),
//data1_io_num: -1,
},
__bindgen_anon_3: spi_bus_config_t__bindgen_ty_3 {
quadwp_io_num: -1,
//data2_io_num: -1,
},
__bindgen_anon_4: spi_bus_config_t__bindgen_ty_4 {
quadhd_io_num: -1,
//data3_io_num: -1,
},
max_transfer_sz: max_transfer_sz as i32,
intr_flags: InterruptType::to_native(config.intr_flags) as _,
..Default::default()
};
esp!(unsafe { spi_bus_initialize(host, &bus_config, dma_chan) })?;
Ok(max_transfer_sz)
}
}
impl<'d> Drop for SpiDriver<'d> {
fn drop(&mut self) {
esp!(unsafe { spi_bus_free(self.host()) }).unwrap();
}
}
unsafe impl<'d> Send for SpiDriver<'d> {}
pub struct SpiBusDriver<'d, T>
where
T: BorrowMut<SpiDriver<'d>>,
{
_lock: BusLock,
handle: spi_device_handle_t,
driver: T,
duplex: Duplex,
polling: bool,
queue_size: usize,
_d: PhantomData<&'d ()>,
}
impl<'d, T> SpiBusDriver<'d, T>
where
T: BorrowMut<SpiDriver<'d>>,
{
pub fn new(driver: T, config: &config::Config) -> Result<Self, EspError> {
let conf = spi_device_interface_config_t {
spics_io_num: -1,
clock_speed_hz: config.baudrate.0 as i32,
mode: data_mode_to_u8(config.data_mode),
queue_size: config.queue_size as i32,
flags: if config.write_only {
SPI_DEVICE_NO_DUMMY
} else {
0_u32
} | config.duplex.as_flags()
| config.bit_order.as_flags(),
cs_ena_pretrans: config.cs_pre_delay_us.unwrap_or(0),
cs_ena_posttrans: config.cs_post_delay_us.unwrap_or(0),
post_cb: Some(spi_notify),
..Default::default()
};
let mut handle: spi_device_handle_t = ptr::null_mut();
esp!(unsafe { spi_bus_add_device(driver.borrow().host(), &conf, &mut handle as *mut _) })?;
let lock = BusLock::new(handle)?;
Ok(Self {
_lock: lock,
handle,
driver,
duplex: config.duplex,
polling: config.polling,
queue_size: config.queue_size,
_d: PhantomData,
})
}
pub fn read(&mut self, words: &mut [u8]) -> Result<(), EspError> {
// Full-Duplex Mode:
// The internal hardware 16*4 u8 FIFO buffer (shared for read/write) is not cleared
// between transactions (read/write/transfer)
// This can lead to rewriting the internal buffer to MOSI on a read call
let chunk_size = self.driver.borrow().max_transfer_size;
let transactions = spi_read_transactions(words, chunk_size, self.duplex);
spi_transmit(self.handle, transactions, self.polling, self.queue_size)?;
Ok(())
}
#[cfg(not(esp_idf_spi_master_isr_in_iram))]
pub async fn read_async(&mut self, words: &mut [u8]) -> Result<(), EspError> {
let chunk_size = self.driver.borrow().max_transfer_size;
let transactions = spi_read_transactions(words, chunk_size, self.duplex);
core::pin::pin!(spi_transmit_async(
self.handle,
transactions,
self.queue_size
))
.await?;
Ok(())
}
pub fn write(&mut self, words: &[u8]) -> Result<(), EspError> {
// Full-Duplex Mode:
// The internal hardware 16*4 u8 FIFO buffer (shared for read/write) is not cleared
// between transactions ( read/write/transfer)
// This can lead to re-reading the last internal buffer MOSI msg, in case the Slave fails to send a msg
let chunk_size = self.driver.borrow().max_transfer_size;
let transactions = spi_write_transactions(words, chunk_size);
spi_transmit(self.handle, transactions, self.polling, self.queue_size)?;
Ok(())
}
#[cfg(not(esp_idf_spi_master_isr_in_iram))]
pub async fn write_async(&mut self, words: &[u8]) -> Result<(), EspError> {
let chunk_size = self.driver.borrow().max_transfer_size;
let transactions = spi_write_transactions(words, chunk_size);
core::pin::pin!(spi_transmit_async(
self.handle,
transactions,
self.queue_size
))
.await?;
Ok(())
}
pub fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), EspError> {
// In non-DMA mode, it will internally split the transfers every 64 bytes (max_transf_len).
// - If the read and write buffers are not of the same length, it will first transfer the common buffer length
// and then (separately aligned) the remaining buffer.
// - Expect a delay time between every internally split (64-byte or remainder) package.
// Half-Duplex & Half-3-Duplex Mode:
// Data will be split into 64-byte write/read sections.
// Example: write: [u8;96] - read [u8; 160]
// Package 1: write 64, read 64 -> Package 2: write 32, read 32 -> Package 3: write 0, read 64.
// Note that the first "package" is a 128-byte clock out while the later are respectively 64 bytes.
let chunk_size = self.driver.borrow().max_transfer_size;
let transactions = spi_transfer_transactions(read, write, chunk_size, self.duplex);
spi_transmit(self.handle, transactions, self.polling, self.queue_size)?;
Ok(())
}
#[cfg(not(esp_idf_spi_master_isr_in_iram))]
pub async fn transfer_async(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), EspError> {
let chunk_size = self.driver.borrow().max_transfer_size;
let transactions = spi_transfer_transactions(read, write, chunk_size, self.duplex);
core::pin::pin!(spi_transmit_async(
self.handle,
transactions,
self.queue_size
))
.await?;
Ok(())
}
pub fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), EspError> {
let chunk_size = self.driver.borrow().max_transfer_size;
let transactions = spi_transfer_in_place_transactions(words, chunk_size);
spi_transmit(self.handle, transactions, self.polling, self.queue_size)?;
Ok(())
}
#[cfg(not(esp_idf_spi_master_isr_in_iram))]
pub async fn transfer_in_place_async(&mut self, words: &mut [u8]) -> Result<(), EspError> {
let chunk_size = self.driver.borrow().max_transfer_size;
let transactions = spi_transfer_in_place_transactions(words, chunk_size);
core::pin::pin!(spi_transmit_async(
self.handle,
transactions,
self.queue_size
))
.await?;
Ok(())
}
pub fn flush(&mut self) -> Result<(), EspError> {
Ok(())
}
}
impl<'d, T> Drop for SpiBusDriver<'d, T>
where
T: BorrowMut<SpiDriver<'d>>,
{
fn drop(&mut self) {
esp!(unsafe { spi_bus_remove_device(self.handle) }).unwrap();
}
}
impl<'d, T> embedded_hal::spi::ErrorType for SpiBusDriver<'d, T>
where
T: BorrowMut<SpiDriver<'d>>,
{
type Error = SpiError;
}
impl<'d, T> SpiBus for SpiBusDriver<'d, T>
where
T: BorrowMut<SpiDriver<'d>>,
{
fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
SpiBusDriver::read(self, words).map_err(to_spi_err)
}
fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
SpiBusDriver::write(self, words).map_err(to_spi_err)
}
fn flush(&mut self) -> Result<(), Self::Error> {
SpiBusDriver::flush(self).map_err(to_spi_err)
}
fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
SpiBusDriver::transfer(self, read, write).map_err(to_spi_err)
}
fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
SpiBusDriver::transfer_in_place(self, words).map_err(to_spi_err)
}
}
#[cfg(not(esp_idf_spi_master_isr_in_iram))]
impl<'d, T> embedded_hal_async::spi::SpiBus for SpiBusDriver<'d, T>
where
T: BorrowMut<SpiDriver<'d>>,
{
async fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
SpiBusDriver::read_async(self, buf)
.await
.map_err(to_spi_err)
}
async fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
SpiBusDriver::write_async(self, buf)
.await
.map_err(to_spi_err)
}
async fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
SpiBusDriver::transfer_async(self, read, write)
.await
.map_err(to_spi_err)
}
async fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
SpiBusDriver::transfer_in_place_async(self, words)
.await
.map_err(to_spi_err)
}
async fn flush(&mut self) -> Result<(), Self::Error> {
SpiBusDriver::flush(self).map_err(to_spi_err)
}
}
enum SpiOperation {
Transaction(spi_transaction_t),
Delay(u32),
}
impl SpiOperation {
pub fn transaction(self) -> Option<spi_transaction_t> {
if let Self::Transaction(transaction) = self {
Some(transaction)
} else {
None
}
}
}
pub type SpiSingleDeviceDriver<'d> = SpiDeviceDriver<'d, SpiDriver<'d>>;
pub struct SpiDeviceDriver<'d, T>
where
T: Borrow<SpiDriver<'d>> + 'd,
{
handle: spi_device_handle_t,
driver: T,
cs_pin_configured: bool,
duplex: Duplex,
polling: bool,
allow_pre_post_delays: bool,
queue_size: usize,
_d: PhantomData<&'d ()>,
}
impl<'d> SpiDeviceDriver<'d, SpiDriver<'d>> {
#[cfg(esp32)]
pub fn new_single_spi1(
spi: impl Peripheral<P = SPI1> + 'd,
sclk: impl Peripheral<P = crate::gpio::Gpio6> + 'd,
sdo: impl Peripheral<P = crate::gpio::Gpio7> + 'd,
sdi: Option<impl Peripheral<P = crate::gpio::Gpio8> + 'd>,
cs: Option<impl Peripheral<P = impl OutputPin> + 'd>,
bus_config: &config::DriverConfig,
config: &config::Config,
) -> Result<Self, EspError> {
Self::new(
SpiDriver::new_spi1(spi, sclk, sdo, sdi, bus_config)?,
cs,
config,
)
}
pub fn new_single<SPI: SpiAnyPins>(
spi: impl Peripheral<P = SPI> + 'd,
sclk: impl Peripheral<P = impl OutputPin> + 'd,
sdo: impl Peripheral<P = impl OutputPin> + 'd,
sdi: Option<impl Peripheral<P = impl InputPin> + 'd>,
cs: Option<impl Peripheral<P = impl OutputPin> + 'd>,
bus_config: &config::DriverConfig,
config: &config::Config,
) -> Result<Self, EspError> {
Self::new(SpiDriver::new(spi, sclk, sdo, sdi, bus_config)?, cs, config)
}
}
impl<'d, T> SpiDeviceDriver<'d, T>
where
T: Borrow<SpiDriver<'d>> + 'd,
{
pub fn new(
driver: T,
cs: Option<impl Peripheral<P = impl OutputPin> + 'd>,
config: &config::Config,
) -> Result<Self, EspError> {
let cs = cs.map(|cs| cs.into_ref().pin()).unwrap_or(-1);
let conf = spi_device_interface_config_t {
spics_io_num: cs,
clock_speed_hz: config.baudrate.0 as i32,
mode: data_mode_to_u8(config.data_mode),
queue_size: config.queue_size as i32,
input_delay_ns: config.input_delay_ns,
flags: if config.write_only {
SPI_DEVICE_NO_DUMMY
} else {
0_u32
} | if config.cs_active_high {
SPI_DEVICE_POSITIVE_CS
} else {
0_u32
} | config.duplex.as_flags()
| config.bit_order.as_flags(),
post_cb: Some(spi_notify),
cs_ena_pretrans: config.cs_pre_delay_us.unwrap_or(0),
cs_ena_posttrans: config.cs_post_delay_us.unwrap_or(0),
..Default::default()
};
let mut handle: spi_device_handle_t = ptr::null_mut();
esp!(unsafe { spi_bus_add_device(driver.borrow().host(), &conf, &mut handle as *mut _) })?;
Ok(Self {
handle,
driver,
cs_pin_configured: cs >= 0,
duplex: config.duplex,
polling: config.polling,
allow_pre_post_delays: config.allow_pre_post_delays,
queue_size: config.queue_size,
_d: PhantomData,
})
}
pub fn device(&self) -> spi_device_handle_t {
self.handle
}
pub fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), EspError> {
self.run(
self.hardware_cs_ctl(operations.iter_mut().map(copy_operation))?,
operations.iter_mut().map(copy_operation),
)
}
#[cfg(not(esp_idf_spi_master_isr_in_iram))]
pub async fn transaction_async(
&mut self,
operations: &mut [Operation<'_, u8>],
) -> Result<(), EspError> {
core::pin::pin!(self.run_async(
self.hardware_cs_ctl(operations.iter_mut().map(copy_operation))?,
operations.iter_mut().map(copy_operation),
))
.await
}
pub fn read(&mut self, read: &mut [u8]) -> Result<(), EspError> {
self.transaction(&mut [Operation::Read(read)])
}
#[cfg(not(esp_idf_spi_master_isr_in_iram))]
pub async fn read_async(&mut self, read: &mut [u8]) -> Result<(), EspError> {
core::pin::pin!(self.transaction_async(&mut [Operation::Read(read)])).await
}
pub fn write(&mut self, write: &[u8]) -> Result<(), EspError> {
self.transaction(&mut [Operation::Write(write)])
}
#[cfg(not(esp_idf_spi_master_isr_in_iram))]
pub async fn write_async(&mut self, write: &[u8]) -> Result<(), EspError> {
core::pin::pin!(self.transaction_async(&mut [Operation::Write(write)])).await
}
pub fn transfer_in_place(&mut self, buf: &mut [u8]) -> Result<(), EspError> {
self.transaction(&mut [Operation::TransferInPlace(buf)])
}
#[cfg(not(esp_idf_spi_master_isr_in_iram))]
pub async fn transfer_in_place_async(&mut self, buf: &mut [u8]) -> Result<(), EspError> {
core::pin::pin!(self.transaction_async(&mut [Operation::TransferInPlace(buf)])).await
}
pub fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), EspError> {
self.transaction(&mut [Operation::Transfer(read, write)])
}
#[cfg(not(esp_idf_spi_master_isr_in_iram))]
pub async fn transfer_async(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), EspError> {
core::pin::pin!(self.transaction_async(&mut [Operation::Transfer(read, write)])).await
}
fn run<'a, 'c, 'p, P, M>(
&mut self,
mut cs_pin: CsCtl<'c, 'p, P, M>,
operations: impl Iterator<Item = Operation<'a, u8>> + 'a,
) -> Result<(), EspError>
where
P: OutputPin,
M: OutputMode,
{
let _lock = if cs_pin.needs_bus_lock() {
Some(BusLock::new(self.device())?)
} else {
None
};
cs_pin.raise_cs()?;
let mut spi_operations = self
.spi_operations(operations)
.enumerate()
.map(|(index, mut operation)| {
cs_pin.configure(&mut operation, index);
operation
})
.peekable();
let delay_impl = crate::delay::Delay::new_default();
let mut result = Ok(());
while spi_operations.peek().is_some() {
if let Some(SpiOperation::Delay(delay)) = spi_operations.peek() {
delay_impl.delay_us(*delay / 1000);
spi_operations.next();
} else {
let transactions = core::iter::from_fn(|| {
spi_operations
.next_if(|operation| matches!(operation, SpiOperation::Transaction(_)))
})
.fuse()
.filter_map(|operation| operation.transaction());
result = spi_transmit(self.handle, transactions, self.polling, self.queue_size);
if result.is_err() {
break;
}
}
}
cs_pin.lower_cs()?;
result
}
#[allow(dead_code)]
async fn run_async<'a, 'c, 'p, P, M>(
&self,
mut cs_pin: CsCtl<'c, 'p, P, M>,
operations: impl Iterator<Item = Operation<'a, u8>> + 'a,
) -> Result<(), EspError>
where
P: OutputPin,
M: OutputMode,
{
let _async_bus_lock = if cs_pin.needs_bus_lock() {
Some(self.driver.borrow().bus_async_lock.lock().await)
} else {
None
};
let _lock = if cs_pin.needs_bus_lock() {
Some(BusLock::new(self.device())?)
} else {
None
};
cs_pin.raise_cs()?;
let delay_impl = crate::delay::Delay::new_default(); // TODO: Need to wait asnchronously if in async mode
let mut result = Ok(());
let mut spi_operations = self
.spi_operations(operations)
.enumerate()
.map(|(index, mut operation)| {
cs_pin.configure(&mut operation, index);
operation
})
.peekable();
while spi_operations.peek().is_some() {
if let Some(SpiOperation::Delay(delay)) = spi_operations.peek() {
delay_impl.delay_us(*delay);
spi_operations.next();