uferris-bsp 0.2.0

A Board Support Package for the uFerris Learner Board
Documentation
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
use core::marker::PhantomData;
use core::ops::Not;

use bitmask_enum::bitmask;
use embedded_hal::i2c::I2c;
#[cfg(feature = "async")]
use embedded_hal_async::i2c::I2c as AsyncI2c;

#[cfg(feature = "async")]
use crate::Async;
use crate::{Blocking, Mode};

// ------------------------------------------
// Constants & Registers
// ------------------------------------------
const TCA6424_ADDR: u8 = 0x22;

const IN_PORT0: u8 = 0x80;
const IN_PORT1: u8 = 0x81;
// const IN_PORT2: u8 = 0x82; // Placeholder only. Port 2 is not used as input
const OUT_PORT0: u8 = 0x84;
const OUT_PORT1: u8 = 0x85;
const OUT_PORT2: u8 = 0x86;
const CONFIG_PORT0: u8 = 0x8C;

// Direction Configuration for TCA6424
// 0 = Output, 1 = Input
const PORT0_DIR: u8 = 0xFF; // All inputs
const PORT1_DIR: u8 = 0xC0; // All outputs except P17 and P16
const PORT2_DIR: u8 = 0x00; // All outputs 

// ------------------------------------------
// Enums
// ------------------------------------------

#[bitmask(u8)]
enum IoExpPort0 {
    Sw7Pos1, // Port 0 Pin 0
    Sw7Pos2, // Port 0 Pin 1
    P02,     // Port 0 Pin 2 (Unused)
    P03,     // Port 0 Pin 3 (Unused)
    Sw4,     // Port 0 Pin 4
    Sw3,     // Port 0 Pin 5
    Sw2,     // Port 0 Pin 6
    Sw1,     // Port 0 Pin 7
}

#[bitmask(u8)]
enum IoExpPort1 {
    Digit1,  // Port 1 Pin 0
    Digit2,  // Port 1 Pin 1
    Digit3,  // Port 1 Pin 2
    Digit4,  // Port 1 Pin 3
    Led2,    // Port 1 Pin 4
    Led3,    // Port 1 Pin 5
    Sw6Pos2, // Port 1 Pin 6
    Sw6Pos1, // Port 1 Pin 7
}

#[bitmask(u8)]
enum IoExpPort2 {
    SegA, // Port 2 Pin 0
    SegB, // Port 2 Pin 1
    SegC, // Port 2 Pin 2
    SegD, // Port 2 Pin 3
    SegE, // Port 2 Pin 4
    SegF, // Port 2 Pin 5
    Dp,   // Port 2 Pin 6
    SegG, // Port 2 Pin 7
}

#[derive(PartialEq, Debug, Clone, Copy)]
pub enum SwPos {
    Down,
    Up,
    Undefined,
}

#[derive(PartialEq, Debug, Clone, Copy)]
pub enum SevenSegDigit {
    Digit1,
    Digit2,
    Digit3,
    Digit4,
}

// ------------------------------------------
// Driver Struct
// ------------------------------------------

/// The TCA6424 I/O expander the carrier board hangs its LEDs, switches and
/// seven segment display off.
///
/// `M` selects the board mode: see [`Mode`]. Both modes expose the same
/// methods, they just differ in whether the I2C traffic is awaited.
pub struct IoExpander<I2C, M = Blocking> {
    i2c: I2C,
    _mode: PhantomData<M>,
}

impl<I2C, M: Mode> IoExpander<I2C, M> {
    pub fn new(i2c: I2C) -> Self {
        Self {
            i2c,
            _mode: PhantomData,
        }
    }
}

impl<I2C: I2c> IoExpander<I2C, Blocking> {
    pub fn init(&mut self) -> Result<(), I2C::Error> {
        // Write configuration to each port individually
        // Configure I/O Expander pins before moving I2C to shared state
        // Write I/O Direction to TCA6424 Config Registers
        self.i2c
            .write(
                TCA6424_ADDR,
                &[CONFIG_PORT0, PORT0_DIR, PORT1_DIR, PORT2_DIR],
            )
            .unwrap();
        // Reset all output ports to low
        self.i2c.write(TCA6424_ADDR, &[OUT_PORT0, 0, 0, 0]).unwrap();
        Ok(())
    }

    // Active Low example
    pub fn led2_on(&mut self) -> Result<(), I2C::Error> {
        let port2 = self.read_register(OUT_PORT1)?;
        let new_port2 = port2 | IoExpPort1::Led2.bits();
        self.write_register(OUT_PORT1, new_port2)
    }

    pub fn led2_off(&mut self) -> Result<(), I2C::Error> {
        let port1 = self.read_register(OUT_PORT1)?;
        let new_port1 = port1 & IoExpPort1::Led2.bits().not();
        self.write_register(OUT_PORT1, new_port1)
    }

    pub fn led3_on(&mut self) -> Result<(), I2C::Error> {
        let port1 = self.read_register(OUT_PORT1)?;
        let new_port1 = port1 | IoExpPort1::Led3.bits();
        self.write_register(OUT_PORT1, new_port1)
    }

    pub fn led3_off(&mut self) -> Result<(), I2C::Error> {
        let port1 = self.read_register(OUT_PORT1)?;
        let new_port1 = port1 & IoExpPort1::Led3.bits().not();
        self.write_register(OUT_PORT1, new_port1)
    }

    // ------------------------------------------
    // Switch Inputs
    // ------------------------------------------

    pub fn read_sw1(&mut self) -> Result<bool, I2C::Error> {
        let port0 = self.read_register(IN_PORT0)?;
        if port0 & IoExpPort0::Sw1.bits() == 0 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    pub fn read_sw2(&mut self) -> Result<bool, I2C::Error> {
        let port0 = self.read_register(IN_PORT0)?;
        if port0 & IoExpPort0::Sw2.bits() == 0 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    pub fn read_sw3(&mut self) -> Result<bool, I2C::Error> {
        let port0 = self.read_register(IN_PORT0)?;
        if port0 & IoExpPort0::Sw3.bits() == 0 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    pub fn read_sw4(&mut self) -> Result<bool, I2C::Error> {
        let port0 = self.read_register(IN_PORT0)?;
        if port0 & IoExpPort0::Sw4.bits() == 0 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    pub fn read_slide_sw6_position(&mut self) -> Result<SwPos, I2C::Error> {
        let port2 = self.read_register(IN_PORT1)?;

        if port2 & IoExpPort1::Sw6Pos1.bits() == 0 {
            Ok(SwPos::Down)
        } else if port2 & IoExpPort1::Sw6Pos2.bits() == 0 {
            Ok(SwPos::Up)
        } else {
            Ok(SwPos::Undefined)
        }
    }

    pub fn read_slide_sw7_position(&mut self) -> Result<SwPos, I2C::Error> {
        let port0 = self.read_register(IN_PORT0)?;

        if port0 & IoExpPort0::Sw7Pos1.bits() == 0 {
            Ok(SwPos::Down)
        } else if port0 & IoExpPort0::Sw7Pos2.bits() == 0 {
            Ok(SwPos::Up)
        } else {
            Ok(SwPos::Undefined)
        }
    }

    // ------------------------------------------
    // Seven Segment Display
    // ------------------------------------------

    pub fn write_seven_segment_digit(
        &mut self,
        digit: SevenSegDigit,
        value: Option<u8>,
    ) -> Result<(), I2C::Error> {
        // 1. Activate the Specified Digit (Port 1)
        let digit_bits = match digit {
            SevenSegDigit::Digit1 => IoExpPort1::Digit1.bits(),
            SevenSegDigit::Digit2 => IoExpPort1::Digit2.bits(),
            SevenSegDigit::Digit3 => IoExpPort1::Digit3.bits(),
            SevenSegDigit::Digit4 => IoExpPort1::Digit4.bits(),
        };

        let port1 = self.read_register(OUT_PORT1)?;
        // Clear existing digit bits (0-3) then set the new one
        let new_port1 = (port1 & 0xF0) | digit_bits;
        self.write_register(OUT_PORT1, new_port1)?; // Fixed: Was OUT_PORT2

        // 2. Write the Segments (Port 2)
        let segment_map = match value {
            Some(v) => match v {
                0 => 0b00111111,
                1 => 0b00000110,
                2 => 0b10011011,
                3 => 0b10001111,
                4 => 0b10100110,
                5 => 0b10101101,
                6 => 0b10111101,
                7 => 0b00000111,
                8 => 0b10111111,
                9 => 0b10101111,
                _ => 0b00000000,
            },
            None => 0x00,
        };

        self.write_register(OUT_PORT2, segment_map) // Fixed: Was OUT_PORT1
    }

    pub fn seven_segment_display_colon_en(&mut self, enable: bool) -> Result<(), I2C::Error> {
        // 1. Activate Digits 2 & 4 (Port 1)
        let digits = IoExpPort1::Digit2.or(IoExpPort1::Digit4).bits();
        let mut port1 = self.read_register(OUT_PORT1)?;
        if enable {
            port1 |= digits;
        } else {
            port1 &= !digits;
        }
        self.write_register(OUT_PORT1, port1)?; // Fixed: Was OUT_PORT2

        // 2. Activate Colon (DP pin on Port 2)
        let mut port2 = self.read_register(OUT_PORT2)?;
        if enable {
            port2 |= IoExpPort2::Dp.bits();
        } else {
            port2 &= !IoExpPort2::Dp.bits();
        }

        self.write_register(OUT_PORT2, port2) // Fixed: Was OUT_PORT1
    }

    // ------------------------------------------
    // Helper Methods
    // ------------------------------------------

    /// Reads a single byte from a register
    fn read_register(&mut self, reg: u8) -> Result<u8, I2C::Error> {
        let mut buf = [0u8];
        self.i2c.write_read(TCA6424_ADDR, &[reg], &mut buf)?;
        Ok(buf[0])
    }

    fn write_register(&mut self, reg: u8, value: u8) -> Result<(), I2C::Error> {
        self.i2c.write(TCA6424_ADDR, &[reg, value])
    }
}

// ------------------------------------------
// Driver Struct - `async` Mode
// ------------------------------------------

#[cfg(feature = "async")]
impl<I2C: AsyncI2c> IoExpander<I2C, Async> {
    pub async fn init(&mut self) -> Result<(), I2C::Error> {
        // Write configuration to each port individually
        // Configure I/O Expander pins before moving I2C to shared state
        // Write I/O Direction to TCA6424 Config Registers
        self.i2c
            .write(
                TCA6424_ADDR,
                &[CONFIG_PORT0, PORT0_DIR, PORT1_DIR, PORT2_DIR],
            )
            .await
            .unwrap();
        // Reset all output ports to low
        self.i2c
            .write(TCA6424_ADDR, &[OUT_PORT0, 0, 0, 0])
            .await
            .unwrap();
        Ok(())
    }

    // Active Low example
    pub async fn led2_on(&mut self) -> Result<(), I2C::Error> {
        let port2 = self.read_register(OUT_PORT1).await?;
        let new_port2 = port2 | IoExpPort1::Led2.bits();
        self.write_register(OUT_PORT1, new_port2).await
    }

    pub async fn led2_off(&mut self) -> Result<(), I2C::Error> {
        let port1 = self.read_register(OUT_PORT1).await?;
        let new_port1 = port1 & IoExpPort1::Led2.bits().not();
        self.write_register(OUT_PORT1, new_port1).await
    }

    pub async fn led3_on(&mut self) -> Result<(), I2C::Error> {
        let port1 = self.read_register(OUT_PORT1).await?;
        let new_port1 = port1 | IoExpPort1::Led3.bits();
        self.write_register(OUT_PORT1, new_port1).await
    }

    pub async fn led3_off(&mut self) -> Result<(), I2C::Error> {
        let port1 = self.read_register(OUT_PORT1).await?;
        let new_port1 = port1 & IoExpPort1::Led3.bits().not();
        self.write_register(OUT_PORT1, new_port1).await
    }

    // ------------------------------------------
    // Switch Inputs
    // ------------------------------------------

    pub async fn read_sw1(&mut self) -> Result<bool, I2C::Error> {
        let port0 = self.read_register(IN_PORT0).await?;
        if port0 & IoExpPort0::Sw1.bits() == 0 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    pub async fn read_sw2(&mut self) -> Result<bool, I2C::Error> {
        let port0 = self.read_register(IN_PORT0).await?;
        if port0 & IoExpPort0::Sw2.bits() == 0 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    pub async fn read_sw3(&mut self) -> Result<bool, I2C::Error> {
        let port0 = self.read_register(IN_PORT0).await?;
        if port0 & IoExpPort0::Sw3.bits() == 0 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    pub async fn read_sw4(&mut self) -> Result<bool, I2C::Error> {
        let port0 = self.read_register(IN_PORT0).await?;
        if port0 & IoExpPort0::Sw4.bits() == 0 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    pub async fn read_slide_sw6_position(&mut self) -> Result<SwPos, I2C::Error> {
        let port2 = self.read_register(IN_PORT1).await?;

        if port2 & IoExpPort1::Sw6Pos1.bits() == 0 {
            Ok(SwPos::Down)
        } else if port2 & IoExpPort1::Sw6Pos2.bits() == 0 {
            Ok(SwPos::Up)
        } else {
            Ok(SwPos::Undefined)
        }
    }

    pub async fn read_slide_sw7_position(&mut self) -> Result<SwPos, I2C::Error> {
        let port0 = self.read_register(IN_PORT0).await?;

        if port0 & IoExpPort0::Sw7Pos1.bits() == 0 {
            Ok(SwPos::Down)
        } else if port0 & IoExpPort0::Sw7Pos2.bits() == 0 {
            Ok(SwPos::Up)
        } else {
            Ok(SwPos::Undefined)
        }
    }

    // ------------------------------------------
    // Seven Segment Display
    // ------------------------------------------

    pub async fn write_seven_segment_digit(
        &mut self,
        digit: SevenSegDigit,
        value: Option<u8>,
    ) -> Result<(), I2C::Error> {
        // 1. Activate the Specified Digit (Port 1)
        let digit_bits = match digit {
            SevenSegDigit::Digit1 => IoExpPort1::Digit1.bits(),
            SevenSegDigit::Digit2 => IoExpPort1::Digit2.bits(),
            SevenSegDigit::Digit3 => IoExpPort1::Digit3.bits(),
            SevenSegDigit::Digit4 => IoExpPort1::Digit4.bits(),
        };

        let port1 = self.read_register(OUT_PORT1).await?;
        // Clear existing digit bits (0-3) then set the new one
        let new_port1 = (port1 & 0xF0) | digit_bits;
        self.write_register(OUT_PORT1, new_port1).await?;

        // 2. Write the Segments (Port 2)
        let segment_map = match value {
            Some(v) => match v {
                0 => 0b00111111,
                1 => 0b00000110,
                2 => 0b10011011,
                3 => 0b10001111,
                4 => 0b10100110,
                5 => 0b10101101,
                6 => 0b10111101,
                7 => 0b00000111,
                8 => 0b10111111,
                9 => 0b10101111,
                _ => 0b00000000,
            },
            None => 0x00,
        };

        self.write_register(OUT_PORT2, segment_map).await
    }

    pub async fn seven_segment_display_colon_en(&mut self, enable: bool) -> Result<(), I2C::Error> {
        // 1. Activate Digits 2 & 4 (Port 1)
        let digits = IoExpPort1::Digit2.or(IoExpPort1::Digit4).bits();
        let mut port1 = self.read_register(OUT_PORT1).await?;
        if enable {
            port1 |= digits;
        } else {
            port1 &= !digits;
        }
        self.write_register(OUT_PORT1, port1).await?;

        // 2. Activate Colon (DP pin on Port 2)
        let mut port2 = self.read_register(OUT_PORT2).await?;
        if enable {
            port2 |= IoExpPort2::Dp.bits();
        } else {
            port2 &= !IoExpPort2::Dp.bits();
        }

        self.write_register(OUT_PORT2, port2).await
    }

    // ------------------------------------------
    // Helper Methods
    // ------------------------------------------

    /// Reads a single byte from a register
    async fn read_register(&mut self, reg: u8) -> Result<u8, I2C::Error> {
        let mut buf = [0u8];
        self.i2c.write_read(TCA6424_ADDR, &[reg], &mut buf).await?;
        Ok(buf[0])
    }

    async fn write_register(&mut self, reg: u8, value: u8) -> Result<(), I2C::Error> {
        self.i2c.write(TCA6424_ADDR, &[reg, value]).await
    }
}