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
//! GPIOs
//!
//! This GPIO driver supports the `embedded_hal`'s `v2` digital traits.
//!
//! # Fast and Normal GPIOs
//!
//! High speed, or "fast," GPIOs are GPIOs that run on the AHB clock. Normal GPIOs
//! run on the IPG clock.
//!
//! # Example
//!
//! ```no_run
//! use imxrt_hal::{self, gpio::GPIO};
//!
//! let mut peripherals = imxrt_hal::Peripherals::take().unwrap();
//! let input = GPIO::new(peripherals.iomuxc.ad_b0.p11);
//!
//! assert!(!input.is_set());
//! let mut output = input.output();
//!
//! output.set();
//! assert!(output.is_set());
//!
//! output.toggle();
//! assert!(!output.is_set());
//!
//! assert!(output.set_fast(true));
//! output.toggle();
//! assert!(output.is_set());
//! ```

use crate::iomuxc::{consts::Unsigned, gpio::Pin};
use crate::ral::{
    self,
    gpio::{self, RegisterBlock},
};
use core::marker::PhantomData;

/// Denotes that a pin is configured as an input
pub enum Input {}
/// Denotes that a pin is configured as an output
pub enum Output {}

pub struct GPIO<P, D> {
    pin: P,
    dir: PhantomData<D>,
}

impl<P, D> GPIO<P, D>
where
    P: Pin,
{
    fn register_block(&self) -> *const RegisterBlock {
        const REGISTER_BLOCKS: [*const RegisterBlock; 9] = [
            gpio::GPIO1,
            gpio::GPIO2,
            gpio::GPIO3,
            gpio::GPIO4,
            gpio::GPIO5,
            gpio::GPIO6,
            gpio::GPIO7,
            gpio::GPIO8,
            gpio::GPIO9,
        ];
        REGISTER_BLOCKS[self.module().wrapping_sub(1)]
    }

    #[inline(always)]
    fn offset(&self) -> u32 {
        1u32 << <P as Pin>::Offset::USIZE
    }

    /// The return is a non-zero number, since the GPIO identifiers
    /// start with '1.'
    #[inline(always)]
    fn module(&self) -> usize {
        let fast_offset = if self.is_fast() { 5 } else { 0 };
        <P as Pin>::Module::USIZE + fast_offset
    }

    fn gpr(&self) -> Option<*mut u32> {
        // GPR register for GPIO1
        const GPR26: *mut u32 = 0x400A_C068 as *mut u32;
        if <P as Pin>::Module::USIZE < 5 {
            // Safety: GPR registers in range for GPIO1, 2, 3, and 4
            Some(unsafe { GPR26.add(<P as Pin>::Module::USIZE.wrapping_sub(1)) })
        } else {
            None
        }
    }

    /// Returns `true` if the GPIO is configured for fast mode
    ///
    /// If the GPIO cannot support fast mode, `is_fast()` always returns `false`
    pub fn is_fast(&self) -> bool {
        // Safety: MMIO valid per gpr() function.
        // Read is atomic
        self.gpr()
            .map(|gpr| unsafe { core::ptr::read_volatile(gpr) & self.offset() != 0 })
            .unwrap_or(false)
    }

    /// Configures the GPIO to fast mode. `true` indicates "fast," and `false` indicates "normal."
    ///
    /// Returns `false` if this pin does not support fast mode. Otherwise, returns `true`, indicating
    /// that the setting was respected.
    ///
    /// If you transition an output pin into fast mode, the GPIO output state may *not* be maintained.
    /// That is, if your GPIO pin was high, a transition into fast mode may set the pin low. Consider
    /// setting fast mode before driving the GPIO output to avoid inconsistencies.
    pub fn set_fast(&mut self, fast: bool) -> bool {
        self.gpr()
            .map(|gpr| {
                cortex_m::interrupt::free(|cs| unsafe {
                    let v = core::ptr::read_volatile(gpr);

                    let was_output = self.is_output();

                    if fast {
                        core::ptr::write_volatile(gpr, v | self.offset());
                    } else {
                        core::ptr::write_volatile(gpr, v & !self.offset());
                    }

                    // At this point, calls to set_output / set_input will refer to the 'fast'
                    // or 'slow' GPIO register block.
                    if was_output {
                        self.set_output(cs);
                    } else {
                        self.set_input(cs);
                    }

                    true
                })
            })
            .unwrap_or(false)
    }

    /// Returns `true` if the pin is configured as an output pin
    fn is_output(&self) -> bool {
        // Safety: atomic read
        unsafe { ral::read_reg!(ral::gpio, self.register_block(), GDIR) & self.offset() != 0 }
    }

    /// Configure the GPIO as an output
    fn set_output(&self, _: &cortex_m::interrupt::CriticalSection) {
        // Safety: critical section, enforced by API, ensures consistency
        unsafe {
            ral::modify_reg!(ral::gpio, self.register_block(), GDIR, |gdir| gdir
                | self.offset());
        }
    }

    /// Configure the GPIO as an input
    fn set_input(&self, _: &cortex_m::interrupt::CriticalSection) {
        // Safety: critical section, enforced by API, ensures consistency
        unsafe {
            ral::modify_reg!(ral::gpio, self.register_block(), GDIR, |gdir| gdir
                & !self.offset());
        }
    }
}

impl<P> GPIO<P, Input>
where
    P: Pin,
{
    /// Create a GPIO from a pad that supports a GPIO configuration
    ///
    /// All pads may be used as a GPIO, so this should always work.
    pub fn new(mut pin: P) -> Self {
        crate::iomuxc::gpio::prepare(&mut pin);
        Self {
            pin,
            dir: PhantomData,
        }
    }

    /// Set the GPIO as an output
    pub fn output(self) -> GPIO<P, Output> {
        cortex_m::interrupt::free(|cs| self.set_output(cs));
        GPIO {
            pin: self.pin,
            dir: PhantomData,
        }
    }

    /// Returns `true` if this input pin is high
    pub fn is_set(&self) -> bool {
        // Safety: read is atomic
        unsafe { ral::read_reg!(ral::gpio, self.register_block(), PSR) & self.offset() != 0 }
    }
}

impl<P> GPIO<P, Output>
where
    P: Pin,
{
    /// Transition the pin back to an input
    pub fn input(self) -> GPIO<P, Input> {
        cortex_m::interrupt::free(|cs| self.set_input(cs));
        GPIO {
            pin: self.pin,
            dir: PhantomData,
        }
    }

    /// Set the GPIO high
    pub fn set(&mut self) {
        // Safety: atomic write
        unsafe { ral::write_reg!(ral::gpio, self.register_block(), DR_SET, self.offset()) };
    }

    /// Set the GPIO low
    pub fn clear(&mut self) {
        // Safety: atomic write
        unsafe { ral::write_reg!(ral::gpio, self.register_block(), DR_CLEAR, self.offset()) };
    }

    /// Returns `true` if the pin is high
    pub fn is_set(&self) -> bool {
        // Safety: atomic read
        unsafe { ral::read_reg!(ral::gpio, self.register_block(), DR) & self.offset() != 0u32 }
    }

    /// Alternate the state of the pin
    pub fn toggle(&mut self) {
        // Safety: atomic write
        unsafe { ral::write_reg!(ral::gpio, self.register_block(), DR_TOGGLE, self.offset()) }
    }
}

use embedded_hal::digital::v2::{InputPin, OutputPin, StatefulOutputPin, ToggleableOutputPin};

impl<P> OutputPin for GPIO<P, Output>
where
    P: Pin,
{
    type Error = core::convert::Infallible;

    fn set_high(&mut self) -> Result<(), Self::Error> {
        self.set();
        Ok(())
    }

    fn set_low(&mut self) -> Result<(), Self::Error> {
        self.clear();
        Ok(())
    }
}

impl<P> StatefulOutputPin for GPIO<P, Output>
where
    P: Pin,
{
    fn is_set_high(&self) -> Result<bool, Self::Error> {
        Ok(self.is_set())
    }
    fn is_set_low(&self) -> Result<bool, Self::Error> {
        self.is_set_high().map(|res| !res)
    }
}

impl<P> ToggleableOutputPin for GPIO<P, Output>
where
    P: Pin,
{
    type Error = core::convert::Infallible;
    fn toggle(&mut self) -> Result<(), Self::Error> {
        GPIO::<P, Output>::toggle(self);
        Ok(())
    }
}

impl<P> InputPin for GPIO<P, Input>
where
    P: Pin,
{
    type Error = core::convert::Infallible;
    fn is_high(&self) -> Result<bool, Self::Error> {
        Ok(self.is_set())
    }
    fn is_low(&self) -> Result<bool, Self::Error> {
        self.is_high().map(|res| !res)
    }
}