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
//! HAL interface to the TWIM peripheral
//!
//! See product specification:
//!
//! - nrf52832: Section 33
//! - nrf52840: Section 6.31


use core::ops::Deref;

use crate::target::{
    twim0,
    P0,
    TWIM0,
    TWIM1,
};

use crate::gpio::{
    p0::P0_Pin,
    Floating,
    Input,
};


pub use crate::target::twim0::frequency::FREQUENCYW as Frequency;


pub trait TwimExt: Deref<Target=twim0::RegisterBlock> + Sized {
    fn constrain(self, pins: Pins, frequency: Frequency)
        -> Twim<Self>;
}

macro_rules! impl_twim_ext {
    ($($twim:ty,)*) => {
        $(
            impl TwimExt for $twim {
                fn constrain(self, pins: Pins, frequency: Frequency)
                    -> Twim<Self>
                {
                    Twim::new(self, pins, frequency)
                }
            }
        )*
    }
}

impl_twim_ext!(
    TWIM0,
    TWIM1,
);


/// Interface to a TWIM instance
///
/// This is a very basic interface that comes with the following limitation:
/// The TWIM instances share the same address space with instances of SPIM,
/// SPIS, SPI, TWIS, and TWI. For example, TWIM0 conflicts with SPIM0, SPIS0,
/// etc.; TWIM1 conflicts with SPIM1, SPIS1, etc. You need to make sure that
/// conflicting instances are disabled before using `Twim`. Please refer to the
/// product specification for more information (section 15.2 for nRF52832,
/// section 6.1.2 for nRF52840).
pub struct Twim<T>(T);

impl<T> Twim<T> where T: TwimExt {
    pub fn new(twim: T, pins: Pins, frequency: Frequency) -> Self {
        // The TWIM peripheral requires the pins to be in a mode that is not
        // exposed through the GPIO API, and might it might not make sense to
        // expose it there.
        //
        // Until we've figured out what to do about this, let's just configure
        // the pins through the raw peripheral API. All of the following is
        // safe, as we own the pins now and have exclusive access to their
        // registers.
        for &pin in &[pins.scl.pin, pins.sda.pin] {
            unsafe { &*P0::ptr() }.pin_cnf[pin as usize].write(|w|
                w
                    .dir().input()
                    .input().connect()
                    .pull().pullup()
                    .drive().s0d1()
                    .sense().disabled()
            );
        }

        // Select pins
        twim.psel.scl.write(|w| {
            let w = unsafe { w.pin().bits(pins.scl.pin) };
            w.connect().connected()
        });
        twim.psel.sda.write(|w| {
            let w = unsafe { w.pin().bits(pins.sda.pin) };
            w.connect().connected()
        });

        // Enable TWIM instance
        twim.enable.write(|w|
            w.enable().enabled()
        );

        // Configure frequency
        twim.frequency.write(|w| w.frequency().variant(frequency));


        Twim(twim)
    }

    /// Write to an I2C slave
    ///
    /// The buffer must have a length of at most 255 bytes.
    pub fn write(&mut self,
        address: u8,
        buffer:  &[u8],
    )
        -> Result<(), Error>
    {
        // This is overly restrictive. See:
        // https://github.com/nrf-rs/nrf52-hal/issues/17
        if buffer.len() > u8::max_value() as usize {
            return Err(Error::BufferTooLong);
        }

        self.0.address.write(|w| unsafe { w.address().bits(address) });

        // Set up the DMA write
        self.0.txd.ptr.write(|w|
            // We're giving the register a pointer to the stack. Since we're
            // waiting for the I2C transaction to end before this stack pointer
            // becomes invalid, there's nothing wrong here.
            //
            // The PTR field is a full 32 bits wide and accepts the full range
            // of values.
            unsafe { w.ptr().bits(buffer.as_ptr() as u32) }
        );
        self.0.txd.maxcnt.write(|w|
            // We're giving it the length of the buffer, so no danger of
            // accessing invalid memory. We have verified that the length of the
            // buffer fits in an `u8`, so the cast to `u8` is also fine.
            //
            // The MAXCNT field is 8 bits wide and accepts the full range of
            // values.
            unsafe { w.maxcnt().bits(buffer.len() as _) }
        );

        // Start write operation
        self.0.tasks_starttx.write(|w|
            // `1` is a valid value to write to task registers.
            unsafe { w.bits(1) }
        );

        // Wait until write operation is about to end
        while self.0.events_lasttx.read().bits() == 0 {}
        self.0.events_lasttx.write(|w| w); // reset event

        // Stop read operation
        self.0.tasks_stop.write(|w|
            // `1` is a valid value to write to task registers.
            unsafe { w.bits(1) }
        );

        // Wait until write operation has ended
        while self.0.events_stopped.read().bits() == 0 {}
        self.0.events_stopped.write(|w| w); // reset event

        if self.0.txd.amount.read().bits() != buffer.len() as u32 {
            return Err(Error::Transmit);
        }

        Ok(())
    }

    /// Read from an I2C slave
    pub fn read(&mut self,
        address: u8,
        buffer:  &mut [u8],
    )
        -> Result<(), Error>
    {
        // This is overly restrictive. See:
        // https://github.com/nrf-rs/nrf52-hal/issues/17
        if buffer.len() > u8::max_value() as usize {
            return Err(Error::BufferTooLong);
        }

        self.0.address.write(|w| unsafe { w.address().bits(address) });

        // Set up the DMA read
        self.0.rxd.ptr.write(|w|
            // We're giving the register a pointer to the stack. Since we're
            // waiting for the I2C transaction to end before this stack pointer
            // becomes invalid, there's nothing wrong here.
            //
            // The PTR field is a full 32 bits wide and accepts the full range
            // of values.
            unsafe { w.ptr().bits(buffer.as_mut_ptr() as u32) }
        );
        self.0.rxd.maxcnt.write(|w|
            // We're giving it the length of the buffer, so no danger of
            // accessing invalid memory. We have verified that the length of the
            // buffer fits in an `u8`, so the cast to the type of maxcnt
            // is also fine.
            //
            // Note that that nrf52840 maxcnt is a wider
            // type than a u8, so we use a `_` cast rather than a `u8` cast.
            // The MAXCNT field is thus at least 8 bits wide and accepts the
            // full range of values that fit in a `u8`.
            unsafe { w.maxcnt().bits(buffer.len() as _) }
        );

        // Start read operation
        self.0.tasks_startrx.write(|w|
            // `1` is a valid value to write to task registers.
            unsafe { w.bits(1) }
        );

        // Wait until read operation is about to end
        while self.0.events_lastrx.read().bits() == 0 {}
        self.0.events_lastrx.write(|w| w); // reset event

        // Stop read operation
        self.0.tasks_stop.write(|w|
            // `1` is a valid value to write to task registers.
            unsafe { w.bits(1) }
        );

        // Wait until read operation has ended
        while self.0.events_stopped.read().bits() == 0 {}
        self.0.events_stopped.write(|w| w); // reset event

        if self.0.rxd.amount.read().bits() != buffer.len() as u32 {
            return Err(Error::Receive);
        }

        Ok(())
    }

    /// Return the raw interface to the underlying TWIM peripheral
    pub fn free(self) -> T {
        self.0
    }
}


/// The pins used by the TWIN peripheral
///
/// Currently, only P0 pins are supported.
pub struct Pins {
    // Serial Clock Line
    pub scl: P0_Pin<Input<Floating>>,

    // Serial Data Line
    pub sda: P0_Pin<Input<Floating>>,
}


#[derive(Debug)]
pub enum Error {
    BufferTooLong,
    Transmit,
    Receive,
}