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
//! I2C Implementations

/// TWI Status Codes
pub mod twi_status {
    // The status codes defined in the C header are meant to be used with the
    // masked status value: (TWSR & TW_STATUS_MASK).  In our case, svd2rust
    // already added code to shift it to just the status value, so all status
    // codes need to be shifted to the right as well.

    /// Start condition transmitted
    pub const TW_START: u8 = 0x08 >> 3;

    /// Repeated start condition transmitted
    pub const TW_REP_START: u8 = 0x10 >> 3;

    // Master Transmitter -----------------------------------------------------
    /// SLA+W transmitted, ACK received
    pub const TW_MT_SLA_ACK: u8 = 0x18 >> 3;

    /// SLA+W transmitted, NACK received
    pub const TW_MT_SLA_NACK: u8 = 0x20 >> 3;

    /// Data transmitted, ACK received
    pub const TW_MT_DATA_ACK: u8 = 0x28 >> 3;

    /// Data transmitted, NACK received
    pub const TW_MT_DATA_NACK: u8 = 0x30 >> 3;

    /// Arbitration lost in SLA+W or data
    pub const TW_MT_ARB_LOST: u8 = 0x38 >> 3;

    // Master Receiver --------------------------------------------------------
    /// Arbitration lost in SLA+R or NACK
    pub const TW_MR_ARB_LOST: u8 = 0x38 >> 3;

    /// SLA+R transmitted, ACK received
    pub const TW_MR_SLA_ACK: u8 = 0x40 >> 3;

    /// SLA+R transmitted, NACK received
    pub const TW_MR_SLA_NACK: u8 = 0x48 >> 3;

    /// Data received, ACK returned
    pub const TW_MR_DATA_ACK: u8 = 0x50 >> 3;

    /// Data received, NACK returned
    pub const TW_MR_DATA_NACK: u8 = 0x58 >> 3;

    // Slave Transmitter ------------------------------------------------------
    /// SLA+R received, ACK returned
    pub const TW_ST_SLA_ACK: u8 = 0xA8 >> 3;

    /// Arbitration lost in SLA+RW, SLA+R received, ACK returned
    pub const TW_ST_ARB_LOST_SLA_ACK: u8 = 0xB0 >> 3;

    /// Data transmitted, ACK received
    pub const TW_ST_DATA_ACK: u8 = 0xB8 >> 3;

    /// Data transmitted, NACK received
    pub const TW_ST_DATA_NACK: u8 = 0xC0 >> 3;

    /// Last data byte transmitted, ACK received
    pub const TW_ST_LAST_DATA: u8 = 0xC8 >> 3;

    // Slave Receiver ---------------------------------------------------------
    /// SLA+W received, ACK returned
    pub const TW_SR_SLA_ACK: u8 = 0x60 >> 3;

    /// Arbitration lost in SLA+RW, SLA+W received, ACK returned
    pub const TW_SR_ARB_LOST_SLA_ACK: u8 = 0x68 >> 3;

    /// General call received, ACK returned
    pub const TW_SR_GCALL_ACK: u8 = 0x70 >> 3;

    /// Arbitration lost in SLA+RW, general call received, ACK returned
    pub const TW_SR_ARB_LOST_GCALL_ACK: u8 = 0x78 >> 3;

    /// Data received, ACK returned
    pub const TW_SR_DATA_ACK: u8 = 0x80 >> 3;

    /// Data received, NACK returned
    pub const TW_SR_DATA_NACK: u8 = 0x88 >> 3;

    /// General call data received, ACK returned
    pub const TW_SR_GCALL_DATA_ACK: u8 = 0x90 >> 3;

    /// General call data received, NACK returned
    pub const TW_SR_GCALL_DATA_NACK: u8 = 0x98 >> 3;

    /// Stop or repeated start condition received while selected
    pub const TW_SR_STOP: u8 = 0xA0 >> 3;

    // Misc -------------------------------------------------------------------
    /// No state information available
    pub const TW_NO_INFO: u8 = 0xF8 >> 3;

    /// Illegal start or stop condition
    pub const TW_BUS_ERROR: u8 = 0x00 >> 3;
}

/// I2C Error
#[derive(ufmt::derive::uDebug, Debug, Clone, Copy, Eq, PartialEq)]
pub enum Error {
    /// Lost arbitration while trying to acquire bus
    ArbitrationLost,
    /// No slave answered for this address or a slave replied NACK
    AddressNack,
    /// Slave replied NACK to sent data
    DataNack,
    /// A bus-error occured
    BusError,
    /// An unknown error occured.  The bus might be in an unknown state.
    Unknown,
}

/// I2C Transfer Direction
#[derive(ufmt::derive::uDebug, Debug, Clone, Copy, Eq, PartialEq)]
pub enum Direction {
    /// Write to a slave (LSB is 0)
    Write,
    /// Read from a slave (LSB is 1)
    Read,
}

#[doc(hidden)]
pub fn i2cdetect<W: ufmt::uWrite, F>(s: &mut W, mut f: F) -> Result<(), W::Error>
where
    // Detection function
    F: FnMut(u8) -> Result<bool, Error>,
{
    s.write_str("\
-    0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f\r\n\
00:      ")?;

    fn u4_to_hex(b: u8) -> char {
        match b {
            x if x < 0xa => (0x30 + x).into(),
            x if x < 0x10 => (0x57 + x).into(),
            _ => '?',
        }
    }

    for addr in 0x02..=0x77 {
        let (ah, al) = (u4_to_hex(addr >> 4), u4_to_hex(addr & 0xf));

        if addr % 0x10 == 0 {
            s.write_str("\r\n")?;
            s.write_char(ah)?;
            s.write_str("0:")?;
        }

        match f(addr) {
            Ok(true) => {
                s.write_char(' ')?;
                s.write_char(ah)?;
                s.write_char(al)?;
            },
            Ok(false) => {
                s.write_str(" --")?;
            },
            Err(e) => {
                s.write_str(" E")?;
                s.write_char(u4_to_hex(e as u8))?;
            },
        }
    }

    s.write_str("\r\n")?;

    Ok(())
}

#[doc(hidden)]
pub type I2cFloating = crate::port::mode::Input<crate::port::mode::Floating>;
#[doc(hidden)]
pub type I2cPullUp = crate::port::mode::Input<crate::port::mode::PullUp>;

/// Implement I2C traits for a TWI peripheral
#[macro_export]
macro_rules! impl_twi_i2c {
    (
        $(#[$i2c_attr:meta])*
        pub struct $I2c:ident {
            peripheral: $I2C:ty,
            pins: {
                sda: $sdamod:ident::$SDA:ident,
                scl: $sclmod:ident::$SCL:ident,
            },
        }
    ) => {$crate::paste::paste! {
        $(#[$i2c_attr])*
        pub struct [<$I2c Master>]<CLOCK: $crate::clock::Clock, M> {
            p: $I2C,
            _clock: ::core::marker::PhantomData<CLOCK>,
            sda: $sdamod::$SDA<M>,
            scl: $sclmod::$SCL<M>,
        }

        impl<CLOCK> [<$I2c Master>]<CLOCK, $crate::i2c::I2cPullUp>
        where
            CLOCK: $crate::clock::Clock,
        {
            /// Initialize the I2C bus
            ///
            /// `new()` will enable the internal pull-ups to comply with the I2C
            /// specification.  If you have external pull-ups connected, please
            /// use `new_with_external_pullup()` instead.
            pub fn new(
                p: $I2C,
                sda: $sdamod::$SDA<$crate::port::mode::Input<$crate::port::mode::PullUp>>,
                scl: $sclmod::$SCL<$crate::port::mode::Input<$crate::port::mode::PullUp>>,
                speed: u32,
            ) -> [<$I2c Master>]<CLOCK, $crate::i2c::I2cPullUp> {
                let mut i2c = [<$I2c Master>] {
                    p,
                    sda,
                    scl,
                    _clock: ::core::marker::PhantomData,
                };

                i2c.set_speed(speed);
                i2c
            }
        }

        impl<CLOCK> [<$I2c Master>]<CLOCK, $crate::i2c::I2cFloating>
        where
            CLOCK: $crate::clock::Clock,
        {
            /// Initialize the I2C bus, without enabling internal pull-ups
            ///
            /// This function should be used if your hardware design includes
            /// pull-up resistors outside the MCU.  If you do not have these,
            /// please use `new()` instead.
            pub fn new_with_external_pullup(
                p: $I2C,
                sda: $sdamod::$SDA<$crate::port::mode::Input<$crate::port::mode::Floating>>,
                scl: $sclmod::$SCL<$crate::port::mode::Input<$crate::port::mode::Floating>>,
                speed: u32,
            ) -> [<$I2c Master>]<CLOCK, $crate::i2c::I2cFloating> {
                let mut i2c = [<$I2c Master>] {
                    p,
                    sda,
                    scl,
                    _clock: ::core::marker::PhantomData,
                };

                i2c.set_speed(speed);
                i2c
            }
        }

        impl<CLOCK, M> [<$I2c Master>]<CLOCK, M>
        where
            CLOCK: $crate::clock::Clock,
        {
            fn set_speed(&mut self, speed: u32){
                // Calculate TWBR register value
                let twbr = ((CLOCK::FREQ / speed) - 16) / 2;
                self.p.twbr.write(|w| unsafe { w.bits(twbr as u8) });

                // Disable prescaler
                self.p.twsr.write(|w| w.twps().prescaler_1());
            }

            /// Check whether a slave answers ACK for a given address
            ///
            /// Note that some devices might not respond to both read and write
            /// operations.
            pub fn ping_slave(
                &mut self,
                addr: u8,
                dir: $crate::i2c::Direction,
            ) -> Result<bool, $crate::i2c::Error> {
                match self.start(addr, dir) {
                    Err($crate::i2c::Error::AddressNack) => Ok(false),
                    Err(e) => Err(e),
                    Ok(()) => {
                        self.stop();
                        Ok(true)
                    },
                }
            }

            fn start(
                &mut self,
                addr: u8,
                dir: $crate::i2c::Direction,
            ) -> Result<(), $crate::i2c::Error> {
                // Write start condition
                self.p.twcr.write(|w| w
                    .twen().set_bit()
                    .twint().set_bit()
                    .twsta().set_bit()
                );
                self.wait();

                // Validate status
                match self.p.twsr.read().tws().bits() {
                      $crate::i2c::twi_status::TW_START
                    | $crate::i2c::twi_status::TW_REP_START => (),
                      $crate::i2c::twi_status::TW_MT_ARB_LOST
                    | $crate::i2c::twi_status::TW_MR_ARB_LOST => {
                        return Err($crate::i2c::Error::ArbitrationLost);
                    },
                    $crate::i2c::twi_status::TW_BUS_ERROR => {
                        return Err($crate::i2c::Error::BusError);
                    },
                    _ => {
                        return Err($crate::i2c::Error::Unknown);
                    },
                }

                // Send slave address
                let dirbit = if dir == $crate::i2c::Direction::Read { 1 } else { 0 };
                let rawaddr = (addr << 1) | dirbit;
                self.p.twdr.write(|w| unsafe { w.bits(rawaddr) });
                self.transact();

                // Check if the slave responded
                match self.p.twsr.read().tws().bits() {
                      $crate::i2c::twi_status::TW_MT_SLA_ACK
                    | $crate::i2c::twi_status::TW_MR_SLA_ACK => (),
                      $crate::i2c::twi_status::TW_MT_SLA_NACK
                    | $crate::i2c::twi_status::TW_MR_SLA_NACK => {
                        // Stop the transaction if it did not respond
                        self.stop();
                        return Err($crate::i2c::Error::AddressNack);
                    },
                      $crate::i2c::twi_status::TW_MT_ARB_LOST
                    | $crate::i2c::twi_status::TW_MR_ARB_LOST => {
                        return Err($crate::i2c::Error::ArbitrationLost);
                    },
                    $crate::i2c::twi_status::TW_BUS_ERROR => {
                        return Err($crate::i2c::Error::BusError);
                    },
                    _ => {
                        return Err($crate::i2c::Error::Unknown);
                    },
                }

                Ok(())
            }

            fn wait(&mut self) {
                while self.p.twcr.read().twint().bit_is_clear() { }
            }

            fn transact(&mut self) {
                self.p.twcr.write(|w| w.twen().set_bit().twint().set_bit());
                while self.p.twcr.read().twint().bit_is_clear() { }
            }

            fn write_data(&mut self, bytes: &[u8]) -> Result<(), $crate::i2c::Error> {
                for byte in bytes {
                    self.p.twdr.write(|w| unsafe { w.bits(*byte) });
                    self.transact();

                    match self.p.twsr.read().tws().bits() {
                        $crate::i2c::twi_status::TW_MT_DATA_ACK => (),
                        $crate::i2c::twi_status::TW_MT_DATA_NACK => {
                            self.stop();
                            return Err($crate::i2c::Error::DataNack);
                        },
                        $crate::i2c::twi_status::TW_MT_ARB_LOST => {
                            return Err($crate::i2c::Error::ArbitrationLost);
                        },
                        $crate::i2c::twi_status::TW_BUS_ERROR => {
                            return Err($crate::i2c::Error::BusError);
                        },
                        _ => {
                            return Err($crate::i2c::Error::Unknown);
                        },
                    }
                }
                Ok(())
            }

            fn read_data(&mut self, buffer: &mut [u8]) -> Result<(), $crate::i2c::Error> {
                let last = buffer.len() - 1;
                for (i, byte) in buffer.iter_mut().enumerate() {
                    if i != last {
                        self.p.twcr.write(|w| w.twint().set_bit().twen().set_bit().twea().set_bit());
                        self.wait();
                    } else {
                        self.p.twcr.write(|w| w.twint().set_bit().twen().set_bit());
                        self.wait();
                    }

                    match self.p.twsr.read().tws().bits() {
                          $crate::i2c::twi_status::TW_MR_DATA_ACK
                        | $crate::i2c::twi_status::TW_MR_DATA_NACK => (),
                        $crate::i2c::twi_status::TW_MR_ARB_LOST => {
                            return Err($crate::i2c::Error::ArbitrationLost);
                        },
                        $crate::i2c::twi_status::TW_BUS_ERROR => {
                            return Err($crate::i2c::Error::BusError);
                        },
                        _ => {
                            return Err($crate::i2c::Error::Unknown);
                        },
                    }

                    *byte = self.p.twdr.read().bits();
                }
                Ok(())
            }

            fn stop(&mut self) {
                self.p.twcr.write(|w| w
                    .twen().set_bit()
                    .twint().set_bit()
                    .twsto().set_bit()
                );
            }
        }

        impl<CLOCK, M> [<$I2c Master>]<CLOCK, M>
        where
            CLOCK: $crate::clock::Clock,
            $crate::delay::Delay<CLOCK>: $crate::hal::blocking::delay::DelayMs<u16>,
        {
            /// Output an `i2cdetect`-like summary of connected slaves to a serial device
            ///
            /// Note that output for `Read` and `Write` might differ.
            pub fn i2cdetect<W: $crate::ufmt::uWrite>(
                &mut self,
                w: &mut W,
                dir: $crate::i2c::Direction,
            ) -> Result<(), W::Error> {
                let mut delay = $crate::delay::Delay::<CLOCK>::new();
                $crate::i2c::i2cdetect(w, |a| {
                    use $crate::prelude::*;

                    delay.delay_ms(10u16);
                    self.ping_slave(a, dir)
                })
            }
        }


        impl<CLOCK, M> $crate::hal::blocking::i2c::Write for [<$I2c Master>]<CLOCK, M>
        where
            CLOCK: $crate::clock::Clock,
        {
            type Error = $crate::i2c::Error;

            fn write(&mut self, address: u8, bytes: &[u8]) -> Result<(), Self::Error> {
                self.start(address, $crate::i2c::Direction::Write)?;
                self.write_data(bytes)?;
                self.stop();
                Ok(())
            }
        }

        impl<CLOCK, M> $crate::hal::blocking::i2c::Read for [<$I2c Master>]<CLOCK, M>
        where
            CLOCK: $crate::clock::Clock,
        {
            type Error = $crate::i2c::Error;

            fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
                self.start(address, $crate::i2c::Direction::Read)?;
                self.read_data(buffer)?;
                self.stop();
                Ok(())
            }
        }

        impl<CLOCK, M> $crate::hal::blocking::i2c::WriteRead for [<$I2c Master>]<CLOCK, M>
        where
            CLOCK: $crate::clock::Clock,
        {
            type Error = $crate::i2c::Error;

            fn write_read(
                &mut self,
                address: u8,
                bytes: &[u8],
                buffer: &mut [u8],
            ) -> Result<(), Self::Error> {
                self.start(address, $crate::i2c::Direction::Write)?;
                self.write_data(bytes)?;
                self.start(address, $crate::i2c::Direction::Read)?;
                self.read_data(buffer)?;
                self.stop();
                Ok(())
            }
        }
    }};
}