-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathmod.rs
1453 lines (1317 loc) · 45 KB
/
mod.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
//! General Purpose Input and Output (GPIO)
//!
//! ## Basic usage
//! ```no_run
//! use embedded_hal::digital::v2::{InputPin, OutputPin};
//! use rp2040_hal::{clocks::init_clocks_and_plls, gpio::Pins, watchdog::Watchdog, pac, Sio};
//! let mut peripherals = pac::Peripherals::take().unwrap();
//! let mut watchdog = Watchdog::new(peripherals.WATCHDOG);
//! const XOSC_CRYSTAL_FREQ: u32 = 12_000_000; // Typically found in BSP crates
//! let mut clocks = init_clocks_and_plls(XOSC_CRYSTAL_FREQ, peripherals.XOSC, peripherals.CLOCKS, peripherals.PLL_SYS, peripherals.PLL_USB, &mut peripherals.RESETS, &mut watchdog).ok().unwrap();
//!
//! let mut pac = pac::Peripherals::take().unwrap();
//! let sio = Sio::new(pac.SIO);
//! let pins = rp2040_hal::gpio::Pins::new(pac.IO_BANK0, pac.PADS_BANK0, sio.gpio_bank0, &mut pac.RESETS);
//! // Set a pin to drive output
//! let mut output_pin = pins.gpio25.into_push_pull_output();
//! // Drive output to 3.3V
//! output_pin.set_high().unwrap();
//! // Drive output to 0V
//! output_pin.set_low().unwrap();
//! // Set a pin to input
//! let input_pin = pins.gpio24.into_floating_input();
//! // pinstate will be true if the pin is above 2V
//! let pinstate = input_pin.is_high().unwrap();
//! // pinstate_low will be true if the pin is below 1.15V
//! let pinstate_low = input_pin.is_low().unwrap();
//! // you'll want to pull-up or pull-down a switch if it's not done externally
//! let button_pin = pins.gpio23.into_pull_down_input();
//! let button2_pin = pins.gpio22.into_pull_up_input();
//! ```
//! See [examples/gpio_in_out.rs](https://github.com/rp-rs/rp-hal/tree/main/rp2040-hal/examples/gpio_in_out.rs) for a more practical example
// Design Notes:
//
// - The user must not be able to instantiate by themselves nor obtain an instance of the Type-level
// structure.
// - non-typestated features (overides, irq configuration, pads' output disable, pad's input
// enable, drive strength, schmitt, slew rate, sio's in sync bypass) are considered somewhat
// advanced usage of the pin (relative to reading/writing a gpio) and it is the responsibility of
// the user to make sure these are in a correct state when converting and passing the pin around.
pub use embedded_hal::digital::v2::PinState;
use crate::{
atomic_register_access::{write_bitmask_clear, write_bitmask_set},
pac,
sio::Sio,
typelevel::{self, Sealed},
};
mod func;
pub(crate) mod pin;
mod pin_group;
mod pull;
pub use func::*;
pub use pin::{DynBankId, DynPinId, PinId};
pub use pin_group::PinGroup;
pub use pull::*;
/// The amount of current that a pin can drive when used as an output.
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum OutputDriveStrength {
/// 2 mA
TwoMilliAmps,
/// 4 mA
FourMilliAmps,
/// 8 mA
EightMilliAmps,
/// 12 mA
TwelveMilliAmps,
}
/// The slew rate of a pin when used as an output.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum OutputSlewRate {
/// Slew slow
Slow,
/// Slew fast
Fast,
}
/// Interrupt kind.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum Interrupt {
/// While low
LevelLow,
/// While high
LevelHigh,
/// On falling edge
EdgeLow,
/// On rising edge
EdgeHigh,
}
impl Interrupt {
fn mask(&self) -> u32 {
match self {
Interrupt::LevelLow => 0b0001,
Interrupt::LevelHigh => 0b0010,
Interrupt::EdgeLow => 0b0100,
Interrupt::EdgeHigh => 0b1000,
}
}
}
/// Interrupt override state.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum InterruptOverride {
/// Don't invert the interrupt.
Normal = 0,
/// Invert the interrupt.
Invert = 1,
/// Drive interrupt low.
AlwaysLow = 2,
/// Drive interrupt high.
AlwaysHigh = 3,
}
/// Input override state.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum InputOverride {
/// Don't invert the peripheral input.
Normal = 0,
/// Invert the peripheral input.
Invert = 1,
/// Drive peripheral input low.
AlwaysLow = 2,
/// Drive peripheral input high.
AlwaysHigh = 3,
}
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
/// Output enable override state.
pub enum OutputEnableOverride {
/// Use the original output enable signal from selected peripheral.
Normal = 0,
/// Invert the output enable signal from selected peripheral.
Invert = 1,
/// Disable output.
Disable = 2,
/// Enable output.
Enable = 3,
}
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
/// Output override state.
pub enum OutputOverride {
/// Use the original output signal from selected peripheral.
DontInvert = 0,
/// Invert the output signal from selected peripheral.
Invert = 1,
/// Drive output low.
AlwaysLow = 2,
/// Drive output high.
AlwaysHigh = 3,
}
/// Represents a pin, with a given ID (e.g. Gpio3), a given function (e.g. FunctionUart) and a given pull type
/// (e.g. pull-down).
pub struct Pin<I: PinId, F: func::Function, P: PullType> {
id: I,
function: F,
pull_type: P,
}
/// Create a new pin instance.
///
/// # Safety
/// The uniqueness of the pin is not verified. User must make sure no other instance of that specific
/// pin exists at the same time.
pub unsafe fn new_pin(id: DynPinId) -> Pin<DynPinId, DynFunction, DynPullType> {
use pac::io_bank0::gpio::gpio_ctrl::FUNCSEL_A;
use pin::pin_sealed::PinIdOps;
let funcsel = id
.io_ctrl()
.read()
.funcsel()
.variant()
.expect("Invalid funcsel read from register.");
let function = match funcsel {
FUNCSEL_A::JTAG => DynFunction::Xip,
FUNCSEL_A::SPI => DynFunction::Spi,
FUNCSEL_A::UART => DynFunction::Uart,
FUNCSEL_A::I2C => DynFunction::I2c,
FUNCSEL_A::PWM => DynFunction::Pwm,
FUNCSEL_A::SIO => {
let mask = id.mask();
let cfg = if id.sio_oe().read().bits() & mask == mask {
DynSioConfig::Output
} else {
DynSioConfig::Input
};
DynFunction::Sio(cfg)
}
FUNCSEL_A::PIO0 => DynFunction::Pio0,
FUNCSEL_A::PIO1 => DynFunction::Pio1,
FUNCSEL_A::CLOCK => DynFunction::Clock,
FUNCSEL_A::USB => DynFunction::Usb,
FUNCSEL_A::NULL => DynFunction::Null,
};
let pad = id.pad_ctrl().read();
let pull_type = match (pad.pue().bit_is_set(), pad.pde().bit_is_set()) {
(true, true) => DynPullType::BusKeep,
(true, false) => DynPullType::Up,
(false, true) => DynPullType::Down,
(false, false) => DynPullType::None,
};
Pin {
id,
function,
pull_type,
}
}
impl<I: PinId, F: func::Function, P: PullType> Pin<I, F, P> {
/// Pin ID.
pub fn id(&self) -> DynPinId {
self.id.as_dyn()
}
/// # Safety
/// This method does not check if the pin is actually configured as the target function or pull
/// mode. This may lead to inconcistencies between the type-state and the actual state of the
/// pin's configuration.
pub unsafe fn into_unchecked<F2: func::Function, P2: PullType>(self) -> Pin<I, F2, P2> {
Pin {
id: self.id,
function: F2::from(self.function.as_dyn()),
pull_type: P2::from(self.pull_type.as_dyn()),
}
}
/// Convert the pin from one state to the other.
pub fn reconfigure<F2, P2>(self) -> Pin<I, F2, P2>
where
F2: func::Function,
P2: PullType,
I: func::ValidFunction<F2>,
{
self.into_function().into_pull_type()
}
/// Convert the pin function.
#[deprecated(
note = "Misleading name `mode` when it changes the `function`. Please use `into_function` instead.",
since = "0.9.0"
)]
pub fn into_mode<F2>(self) -> Pin<I, F2, P>
where
F2: func::Function,
I: func::ValidFunction<F2>,
{
self.into_function()
}
/// Convert the pin function.
pub fn into_function<F2>(self) -> Pin<I, F2, P>
where
F2: func::Function,
I: func::ValidFunction<F2>,
{
// Thanks to type-level validation, we know F2 is valid for I
let prev_function = self.function.as_dyn();
let function = F2::from(prev_function);
let new_function = function.as_dyn();
if prev_function != new_function {
pin::set_function(&self.id, new_function);
}
Pin {
function,
id: self.id,
pull_type: self.pull_type,
}
}
/// Convert the pin pull type.
pub fn into_pull_type<M2: PullType>(self) -> Pin<I, F, M2> {
let prev_pull_type = self.pull_type.as_dyn();
let pull_type = M2::from(prev_pull_type);
let new_pull_type = pull_type.as_dyn();
if prev_pull_type != new_pull_type {
pin::set_pull_type(&self.id, new_pull_type);
}
Pin {
pull_type,
id: self.id,
function: self.function,
}
}
/// Erase the Pin ID type check.
pub fn into_dyn_pin(self) -> Pin<DynPinId, F, P> {
Pin {
id: self.id.as_dyn(),
function: self.function,
pull_type: self.pull_type,
}
}
/// Get the pin's pull type.
pub fn pull_type(&self) -> DynPullType {
self.pull_type.as_dyn()
}
//==============================================================================
// Typical pin conversions.
//==============================================================================
/// Disable the pin and set it to float
#[inline]
pub fn into_floating_disabled(self) -> Pin<I, FunctionNull, PullNone>
where
I: ValidFunction<FunctionNull>,
{
self.reconfigure()
}
/// Disable the pin and set it to pull down
#[inline]
pub fn into_pull_down_disabled(self) -> Pin<I, FunctionNull, PullDown>
where
I: ValidFunction<FunctionNull>,
{
self.reconfigure()
}
/// Disable the pin and set it to pull up
#[inline]
pub fn into_pull_up_disabled(self) -> Pin<I, FunctionNull, PullUp>
where
I: ValidFunction<FunctionNull>,
{
self.reconfigure()
}
/// Configure the pin to operate as a floating input
#[inline]
pub fn into_floating_input(self) -> Pin<I, FunctionSio<SioInput>, PullNone>
where
I: ValidFunction<FunctionSio<SioInput>>,
{
self.into_function().into_pull_type()
}
/// Configure the pin to operate as a pulled down input
#[inline]
pub fn into_pull_down_input(self) -> Pin<I, FunctionSio<SioInput>, PullDown>
where
I: ValidFunction<FunctionSio<SioInput>>,
{
self.into_function().into_pull_type()
}
/// Configure the pin to operate as a pulled up input
#[inline]
pub fn into_pull_up_input(self) -> Pin<I, FunctionSio<SioInput>, PullUp>
where
I: ValidFunction<FunctionSio<SioInput>>,
{
self.into_function().into_pull_type()
}
/// Configure the pin to operate as a bus keep input
#[inline]
pub fn into_bus_keep_input(self) -> Pin<I, FunctionSio<SioInput>, PullBusKeep>
where
I: ValidFunction<FunctionSio<SioInput>>,
{
self.into_function().into_pull_type()
}
/// Configure the pin to operate as a push-pull output.
///
/// If you want to specify the initial pin state, use [`Pin::into_push_pull_output_in_state`].
#[inline]
pub fn into_push_pull_output(self) -> Pin<I, FunctionSio<SioOutput>, P>
where
I: ValidFunction<FunctionSio<SioOutput>>,
{
self.into_function()
}
/// Configure the pin to operate as a push-pull output, specifying an initial
/// state which is applied immediately.
#[inline]
pub fn into_push_pull_output_in_state(
mut self,
state: PinState,
) -> Pin<I, FunctionSio<SioOutput>, P>
where
I: ValidFunction<FunctionSio<SioOutput>>,
{
match state {
PinState::High => self._set_high(),
PinState::Low => self._set_low(),
}
self.into_push_pull_output()
}
/// Configure the pin to operate as a readable push pull output.
///
/// If you want to specify the initial pin state, use [`Pin::into_readable_output_in_state`].
#[inline]
#[deprecated(
note = "All gpio are readable, use `.into_push_pull_output()` instead.",
since = "0.9.0"
)]
pub fn into_readable_output(self) -> Pin<I, FunctionSio<SioOutput>, P>
where
I: ValidFunction<FunctionSio<SioOutput>>,
{
self.into_function()
}
/// Configure the pin to operate as a readable push pull output, specifying an initial
/// state which is applied immediately.
#[inline]
#[deprecated(
note = "All gpio are readable, use `.into_push_pull_output_in_state()` instead.",
since = "0.9.0"
)]
pub fn into_readable_output_in_state(self, state: PinState) -> Pin<I, FunctionSio<SioOutput>, P>
where
I: ValidFunction<FunctionSio<SioOutput>>,
{
self.into_push_pull_output_in_state(state)
}
//==============================================================================
// methods available for all pins.
//==============================================================================
// =======================
// Pad related methods
/// Get the current drive strength of the pin.
#[inline]
pub fn get_drive_strength(&self) -> OutputDriveStrength {
use pac::pads_bank0::gpio::DRIVE_A;
match self.id.pad_ctrl().read().drive().variant() {
DRIVE_A::_2M_A => OutputDriveStrength::TwoMilliAmps,
DRIVE_A::_4M_A => OutputDriveStrength::FourMilliAmps,
DRIVE_A::_8M_A => OutputDriveStrength::EightMilliAmps,
DRIVE_A::_12M_A => OutputDriveStrength::TwelveMilliAmps,
}
}
/// Set the drive strength for the pin.
#[inline]
pub fn set_drive_strength(&mut self, strength: OutputDriveStrength) {
use pac::pads_bank0::gpio::DRIVE_A;
let variant = match strength {
OutputDriveStrength::TwoMilliAmps => DRIVE_A::_2M_A,
OutputDriveStrength::FourMilliAmps => DRIVE_A::_4M_A,
OutputDriveStrength::EightMilliAmps => DRIVE_A::_8M_A,
OutputDriveStrength::TwelveMilliAmps => DRIVE_A::_12M_A,
};
self.id.pad_ctrl().modify(|_, w| w.drive().variant(variant))
}
/// Get the slew rate for the pin.
#[inline]
pub fn get_slew_rate(&self) -> OutputSlewRate {
if self.id.pad_ctrl().read().slewfast().bit_is_set() {
OutputSlewRate::Fast
} else {
OutputSlewRate::Slow
}
}
/// Set the slew rate for the pin.
#[inline]
pub fn set_slew_rate(&mut self, rate: OutputSlewRate) {
self.id
.pad_ctrl()
.modify(|_, w| w.slewfast().bit(OutputSlewRate::Fast == rate));
}
/// Get wether the schmitt trigger (hysteresis) is enabled.
#[inline]
pub fn get_schmitt_enabled(&self) -> bool {
self.id.pad_ctrl().read().schmitt().bit_is_set()
}
/// Enable/Disable the schmitt trigger.
#[inline]
pub fn set_schmitt_enabled(&self, enable: bool) {
self.id.pad_ctrl().modify(|_, w| w.schmitt().bit(enable));
}
/// Get the state of the digital output circuitery of the pad.
#[inline]
pub fn get_output_disable(&mut self) -> bool {
self.id.pad_ctrl().read().od().bit_is_set()
}
/// Set the digital output circuitery of the pad.
#[inline]
pub fn set_output_disable(&mut self, disable: bool) {
self.id.pad_ctrl().modify(|_, w| w.od().bit(disable));
}
/// Get the state of the digital input circuitery of the pad.
#[inline]
pub fn get_input_enable(&mut self) -> bool {
self.id.pad_ctrl().read().ie().bit_is_set()
}
/// Set the digital input circuitery of the pad.
#[inline]
pub fn set_input_enable(&mut self, enable: bool) {
self.id.pad_ctrl().modify(|_, w| w.ie().bit(enable));
}
// =======================
// IO related methods
/// Set the input override.
#[inline]
pub fn set_input_override(&mut self, override_value: InputOverride) {
use pac::io_bank0::gpio::gpio_ctrl::INOVER_A;
let variant = match override_value {
InputOverride::Normal => INOVER_A::NORMAL,
InputOverride::Invert => INOVER_A::INVERT,
InputOverride::AlwaysLow => INOVER_A::LOW,
InputOverride::AlwaysHigh => INOVER_A::HIGH,
};
self.id.io_ctrl().modify(|_, w| w.inover().variant(variant));
}
/// Set the output enable override.
#[inline]
pub fn set_output_enable_override(&mut self, override_value: OutputEnableOverride) {
use pac::io_bank0::gpio::gpio_ctrl::OEOVER_A;
let variant = match override_value {
OutputEnableOverride::Normal => OEOVER_A::NORMAL,
OutputEnableOverride::Invert => OEOVER_A::INVERT,
OutputEnableOverride::Disable => OEOVER_A::DISABLE,
OutputEnableOverride::Enable => OEOVER_A::ENABLE,
};
self.id.io_ctrl().modify(|_, w| w.oeover().variant(variant));
}
/// Set the output override.
#[inline]
pub fn set_output_override(&mut self, override_value: OutputOverride) {
use pac::io_bank0::gpio::gpio_ctrl::OUTOVER_A;
let variant = match override_value {
OutputOverride::DontInvert => OUTOVER_A::NORMAL,
OutputOverride::Invert => OUTOVER_A::INVERT,
OutputOverride::AlwaysLow => OUTOVER_A::LOW,
OutputOverride::AlwaysHigh => OUTOVER_A::HIGH,
};
self.id
.io_ctrl()
.modify(|_, w| w.outover().variant(variant));
}
/// Set the interrupt override.
#[inline]
pub fn set_interrupt_override(&mut self, override_value: InterruptOverride) {
use pac::io_bank0::gpio::gpio_ctrl::IRQOVER_A;
let variant = match override_value {
InterruptOverride::Normal => IRQOVER_A::NORMAL,
InterruptOverride::Invert => IRQOVER_A::INVERT,
InterruptOverride::AlwaysLow => IRQOVER_A::LOW,
InterruptOverride::AlwaysHigh => IRQOVER_A::HIGH,
};
self.id
.io_ctrl()
.modify(|_, w| w.irqover().variant(variant));
}
// =======================
// SIO related methods
#[inline]
#[allow(clippy::bool_comparison)] // more explicit this way
pub(crate) fn _is_low(&self) -> bool {
let mask = self.id.mask();
self.id.sio_in().read().bits() & mask == 0
}
#[inline]
#[allow(clippy::bool_comparison)] // more explicit this way
pub(crate) fn _is_high(&self) -> bool {
!self._is_low()
}
#[inline]
pub(crate) fn _set_low(&mut self) {
let mask = self.id.mask();
self.id
.sio_out_clr()
.write(|w| unsafe { w.gpio_out_clr().bits(mask) });
}
#[inline]
pub(crate) fn _set_high(&mut self) {
let mask = self.id.mask();
self.id
.sio_out_set()
.write(|w| unsafe { w.gpio_out_set().bits(mask) });
}
#[inline]
pub(crate) fn _toggle(&mut self) {
let mask = self.id.mask();
self.id
.sio_out_xor()
.write(|w| unsafe { w.gpio_out_xor().bits(mask) });
}
#[inline]
pub(crate) fn _is_set_low(&self) -> bool {
let mask = self.id.mask();
self.id.sio_out().read().bits() & mask == 0
}
#[inline]
pub(crate) fn _is_set_high(&self) -> bool {
!self._is_set_low()
}
// =======================
// Interrupt related methods
/// Clear interrupt.
#[inline]
pub fn clear_interrupt(&mut self, interrupt: Interrupt) {
let (reg, offset) = self.id.intr();
let mask = interrupt.mask();
reg.write(|w| unsafe { w.bits(mask << offset) });
}
/// Interrupt status.
#[inline]
pub fn interrupt_status(&self, interrupt: Interrupt) -> bool {
let (reg, offset) = self.id.proc_ints(Sio::core());
let mask = interrupt.mask();
(reg.read().bits() >> offset) & mask == mask
}
/// Is interrupt enabled.
#[inline]
pub fn is_interrupt_enabled(&self, interrupt: Interrupt) -> bool {
let (reg, offset) = self.id.proc_inte(Sio::core());
let mask = interrupt.mask();
(reg.read().bits() >> offset) & mask == mask
}
/// Enable or disable interrupt.
#[inline]
pub fn set_interrupt_enabled(&self, interrupt: Interrupt, enabled: bool) {
let (reg, offset) = self.id.proc_inte(Sio::core());
let mask = interrupt.mask();
unsafe {
if enabled {
write_bitmask_set(reg.as_ptr(), mask << offset);
} else {
write_bitmask_clear(reg.as_ptr(), mask << offset);
}
}
}
/// Is interrupt forced.
#[inline]
pub fn is_interrupt_forced(&self, interrupt: Interrupt) -> bool {
let (reg, offset) = self.id.proc_intf(Sio::core());
let mask = interrupt.mask();
(reg.read().bits() >> offset) & mask == mask
}
/// Force or release interrupt.
#[inline]
pub fn set_interrupt_forced(&self, interrupt: Interrupt, forced: bool) {
let (reg, offset) = self.id.proc_intf(Sio::core());
let mask = interrupt.mask();
unsafe {
if forced {
write_bitmask_set(reg.as_ptr(), mask << offset);
} else {
write_bitmask_clear(reg.as_ptr(), mask << offset);
}
}
}
/// Dormant wake status.
#[inline]
pub fn dormant_wake_status(&self, interrupt: Interrupt) -> bool {
let (reg, offset) = self.id.dormant_wake_ints();
let mask = interrupt.mask();
(reg.read().bits() >> offset) & mask == mask
}
/// Is dormant wake enabled.
#[inline]
pub fn is_dormant_wake_enabled(&self, interrupt: Interrupt) -> bool {
let (reg, offset) = self.id.dormant_wake_inte();
let mask = interrupt.mask();
(reg.read().bits() >> offset) & mask == mask
}
/// Enable or disable dormant wake.
#[inline]
pub fn set_dormant_wake_enabled(&self, interrupt: Interrupt, enabled: bool) {
let (reg, offset) = self.id.dormant_wake_inte();
let mask = interrupt.mask();
unsafe {
if enabled {
write_bitmask_set(reg.as_ptr(), mask << offset);
} else {
write_bitmask_clear(reg.as_ptr(), mask << offset);
}
}
}
/// Is dormant wake forced.
#[inline]
pub fn is_dormant_wake_forced(&self, interrupt: Interrupt) -> bool {
let (reg, offset) = self.id.dormant_wake_intf();
let mask = interrupt.mask();
(reg.read().bits() >> offset) & mask == mask
}
/// Force dormant wake.
#[inline]
pub fn set_dormant_wake_forced(&mut self, interrupt: Interrupt, forced: bool) {
let (reg, offset) = self.id.dormant_wake_intf();
let mask = interrupt.mask();
unsafe {
if forced {
write_bitmask_set(reg.as_ptr(), mask << offset);
} else {
write_bitmask_clear(reg.as_ptr(), mask << offset);
}
}
}
}
impl<I: PinId, C: SioConfig, P: PullType> Pin<I, FunctionSio<C>, P> {
/// Is bypass enabled
#[inline]
pub fn is_sync_bypass(&self) -> bool {
let mask = self.id.mask();
self.id.proc_in_by_pass().read().bits() & mask == mask
}
/// Bypass the input sync stages.
///
/// This saves two clock cycles in the input signal's path at the risks of intruducing metastability.
#[inline]
pub fn set_sync_bypass(&mut self, bypass: bool) {
let mask = self.id.mask();
let reg = self.id.proc_in_by_pass();
unsafe {
if bypass {
write_bitmask_set(reg.as_ptr(), mask);
} else {
write_bitmask_clear(reg.as_ptr(), mask);
}
}
}
}
impl<F: func::Function, P: PullType> Pin<DynPinId, F, P> {
/// Try to return to a type-checked pin id.
///
/// This method may fail if the target pin id differs from the current dynamic one.
pub fn try_into_pin<P2: pin::pin_sealed::TypeLevelPinId>(self) -> Result<Pin<P2, F, P>, Self> {
if P2::ID == self.id {
Ok(Pin {
id: P2::new(),
function: self.function,
pull_type: self.pull_type,
})
} else {
Err(self)
}
}
/// Try to change the pin's function.
pub fn try_into_function<F2>(self) -> Result<Pin<DynPinId, F2, P>, Pin<DynPinId, F, P>>
where
F2: func::Function,
{
// Thanks to type-level validation, we know F2 is valid for I
let prev_function = self.function.as_dyn();
let function = F2::from(prev_function);
let function_as_dyn = function.as_dyn();
use func_sealed::Function;
if function_as_dyn.is_valid(&self.id) {
if function_as_dyn != prev_function.as_dyn() {
pin::set_function(&self.id, function_as_dyn);
}
Ok(Pin {
function,
id: self.id,
pull_type: self.pull_type,
})
} else {
Err(self)
}
}
}
impl<I: PinId, P: PullType> Pin<I, DynFunction, P> {
/// Try to set the pin's function.
///
/// This method may fail if the requested function is not supported by the pin, eg `FunctionXiP`
/// on a gpio from `Bank0`.
pub fn try_set_function(&mut self, function: DynFunction) -> Result<(), func::InvalidFunction> {
use func_sealed::Function;
if !function.is_valid(&self.id) {
return Err(func::InvalidFunction);
} else if function != self.function.as_dyn() {
pin::set_function(&self.id, function);
self.function = function;
}
Ok(())
}
/// Gets the pin's function.
pub fn function(&self) -> DynFunction {
use func_sealed::Function;
self.function.as_dyn()
}
}
impl<I: PinId, F: func::Function> Pin<I, F, DynPullType> {
/// Set the pin's pull type.
pub fn set_pull_type(&mut self, pull_type: DynPullType) {
if pull_type != self.pull_type {
pin::set_pull_type(&self.id, pull_type);
self.pull_type = pull_type;
}
}
}
//==============================================================================
// Embedded-HAL
//==============================================================================
/// GPIO error type.
pub type Error = core::convert::Infallible;
impl<I, P> embedded_hal::digital::v2::OutputPin for Pin<I, FunctionSio<SioOutput>, P>
where
I: PinId,
P: PullType,
{
type Error = Error;
fn set_low(&mut self) -> Result<(), Self::Error> {
self._set_low();
Ok(())
}
fn set_high(&mut self) -> Result<(), Self::Error> {
self._set_high();
Ok(())
}
}
impl<I, P> embedded_hal::digital::v2::InputPin for Pin<I, FunctionSio<SioOutput>, P>
where
I: PinId,
P: PullType,
{
type Error = Error;
fn is_high(&self) -> Result<bool, Self::Error> {
Ok(self._is_high())
}
fn is_low(&self) -> Result<bool, Self::Error> {
Ok(self._is_low())
}
}
impl<I, P> embedded_hal::digital::v2::StatefulOutputPin for Pin<I, FunctionSio<SioOutput>, P>
where
I: PinId,
P: PullType,
{
fn is_set_high(&self) -> Result<bool, Self::Error> {
Ok(self._is_set_high())
}
fn is_set_low(&self) -> Result<bool, Self::Error> {
Ok(self._is_set_low())
}
}
impl<I, P> embedded_hal::digital::v2::ToggleableOutputPin for Pin<I, FunctionSio<SioOutput>, P>
where
I: PinId,
P: PullType,
{
type Error = Error;
fn toggle(&mut self) -> Result<(), Self::Error> {
self._toggle();
Ok(())
}
}
impl<I, P> embedded_hal::digital::v2::InputPin for Pin<I, FunctionSio<SioInput>, P>
where
I: PinId,
P: PullType,
{
type Error = Error;
fn is_high(&self) -> Result<bool, Self::Error> {
Ok(self._is_high())
}
fn is_low(&self) -> Result<bool, Self::Error> {
Ok(self._is_low())
}
}
//==============================================================================
// Pins
//==============================================================================
/// Default type state of a pin after reset of the pads, io and sio.
pub trait DefaultTypeState: crate::typelevel::Sealed {
/// Default function.
type Function: Function;
/// Default pull type.
type PullType: PullType;
}
macro_rules! gpio {
( $bank:ident:$prefix:ident, [ $(($id:expr, $pull_type:ident, $func:ident)),* ] ) => {
paste::paste!{
#[doc = "Pin bank " [<$bank>] ]
pub mod [<$bank:snake>] {
use $crate::pac::{[<IO_ $bank:upper>],[<PADS_ $bank:upper>]};
use crate::sio::[<SioGpio $bank>];
use super::{Pin, pin, pull, func};
$(pub use super::pin::[<$bank:lower>]::[<$prefix $id>];)*
$(
impl super::DefaultTypeState for [<$prefix $id>] {
type Function = super::[<Function $func>];
type PullType = super::[<Pull $pull_type>];
}
)*
gpio!(struct: $bank $prefix $([<$prefix $id>], $id, $func, $pull_type),*);
impl Pins {
/// Take ownership of the PAC peripherals and SIO slice and split it into discrete [`Pin`]s
pub fn new(io : [<IO_ $bank:upper>], pads: [<PADS_ $bank:upper>], sio: [<SioGpio $bank>], reset : &mut $crate::pac::RESETS) -> Self {
use crate::resets::SubsystemReset;
pads.reset_bring_down(reset);
io.reset_bring_down(reset);
{
use $crate::gpio::pin::DynBankId;
// SAFETY: this function owns the whole bank that will be affected.
let sio = unsafe { &*$crate::pac::SIO::PTR };
if DynBankId::$bank == DynBankId::Bank0 {
sio.gpio_oe.reset();
sio.gpio_out.reset();
} else {
sio.gpio_hi_oe.reset();
sio.gpio_hi_out.reset();
}
}
io.reset_bring_up(reset);
pads.reset_bring_up(reset);
gpio!(members: io, pads, sio, $(([<$prefix $id>], $func, $pull_type)),+)
}
}
}
}
};
(struct: $bank:ident $prefix:ident $($PXi:ident, $id:expr, $func:ident, $pull_type:ident),*) => {
paste::paste!{
/// Collection of all the individual [`Pin`]s
pub struct Pins {
_io: [<IO_ $bank:upper>],
_pads: [<PADS_ $bank:upper>],
_sio: [<SioGpio $bank>],
$(
#[doc = "Pin " [<$PXi>] ]
pub [<$PXi:snake>]: Pin<pin::[<$bank:lower>]::[<$prefix $id>] , func::[<Function $func>], pull::[<Pull $pull_type>]>,
)*
}
}
};
(members: $io:ident, $pads:ident, $sio:ident, $(($PXi:ident, $func:ident, $pull_type:ident)),+) => {