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
//! A platform agnostic driver to interface with the MAX7219 (LED matrix display driver)
//!
//! This driver was built using [`embedded-hal`] traits.
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal/~0.2

#![deny(unsafe_code)]
#![deny(warnings)]
#![no_std]

extern crate embedded_hal;

use embedded_hal::blocking::spi::Write;
use embedded_hal::digital::v2::OutputPin;

mod connectors;
use connectors::*;

/// Maximum number of displays connected in series supported by this lib.
const MAX_DISPLAYS: usize = 8;

/// Digits per display
const MAX_DIGITS: usize = 8;

/// Possible command register values on the display chip.
#[derive(Clone, Copy)]
pub enum Command {
    Noop = 0x00,
    Digit0 = 0x01,
    Digit1 = 0x02,
    Digit2 = 0x03,
    Digit3 = 0x04,
    Digit4 = 0x05,
    Digit5 = 0x06,
    Digit6 = 0x07,
    Digit7 = 0x08,
    DecodeMode = 0x09,
    Intensity = 0x0A,
    ScanLimit = 0x0B,
    Power = 0x0C,
    DisplayTest = 0x0F,
}

/// Decode modes for BCD encoded input.
#[derive(Copy, Clone)]
pub enum DecodeMode {
    NoDecode = 0x00,
    CodeBDigit0 = 0x01,
    CodeBDigits3_0 = 0x0F,
    CodeBDigits7_0 = 0xFF,
}

///
/// Error raised in case there was a PIN interaction
/// error during communication with the MAX7219 chip.
///
#[derive(Debug)]
pub struct PinError;

impl From<core::convert::Infallible> for PinError {
    fn from(_: core::convert::Infallible) -> Self {
        PinError {}
    }
}

impl From<()> for PinError {
    fn from(_: ()) -> Self {
        PinError {}
    }
}

///
/// Handles communication with the MAX7219
/// chip for segmented displays. Each display can be
/// connected in series with another and controlled via
/// a single connection. The actual connection interface
/// is selected via constructor functions.
///
pub struct MAX7219<CONNECTOR> {
    c: CONNECTOR,
    decode_mode: DecodeMode,
}

impl<CONNECTOR> MAX7219<CONNECTOR>
where
    CONNECTOR: Connector,
{
    ///
    /// Powers on all connected displays
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn power_on(&mut self) -> Result<(), PinError> {
        for i in 0..self.c.devices() {
            self.c.write_data(i, Command::Power, 0x01)?;
        }

        Ok(())
    }

    ///
    /// Powers off all connected displays
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn power_off(&mut self) -> Result<(), PinError> {
        for i in 0..self.c.devices() {
            self.c.write_data(i, Command::Power, 0x00)?;
        }

        Ok(())
    }

    ///
    /// Clears display by settings all digits to empty
    ///
    /// # Arguments
    ///
    /// * `addr` - display to address as connected in series (0 -> last)
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn clear_display(&mut self, addr: usize) -> Result<(), PinError> {
        for i in 1..9 {
            self.c.write_raw(addr, i, 0x00)?;
        }

        Ok(())
    }

    ///
    /// Sets intensity level on the display
    ///
    /// # Arguments
    ///
    /// * `addr` - display to address as connected in series (0 -> last)
    /// * `intensity` - intensity value to set to `0x00` to 0x0F`
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn set_intensity(&mut self, addr: usize, intensity: u8) -> Result<(), PinError> {
        self.c.write_data(addr, Command::Intensity, intensity)
    }

    ///
    /// Sets decode mode to be used on input sent to the display chip.
    ///
    /// # Arguments
    ///
    /// * `addr` - display to address as connected in series (0 -> last)
    /// * `mode` - the decode mode to set
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn set_decode_mode(&mut self, addr: usize, mode: DecodeMode) -> Result<(), PinError> {
        self.decode_mode = mode; // store what we set
        self.c.write_data(addr, Command::DecodeMode, mode as u8)
    }

    ///
    /// Writes byte string to the display
    ///
    /// # Arguments
    ///
    /// * `addr` - display to address as connected in series (0 -> last)
    /// * `string` - the byte string to send 8 bytes long. Unknown characters result in question mark.
    /// * `dots` - u8 bit array specifying where to put dots in the string (1 = dot, 0 = not)
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn write_str(
        &mut self,
        addr: usize,
        string: &[u8; MAX_DIGITS],
        dots: u8,
    ) -> Result<(), PinError> {
        let prev_dm = self.decode_mode;
        self.set_decode_mode(0, DecodeMode::NoDecode)?;

        let mut digit: u8 = MAX_DIGITS as u8;
        let mut dot_product: u8 = 0b10000000;
        for b in string {
            let dot = (dots & dot_product) > 0;
            dot_product = dot_product >> 1;
            self.c.write_raw(addr, digit, ssb_byte(*b, dot))?;

            digit = digit - 1;
        }

        self.set_decode_mode(0, prev_dm)?;

        Ok(())
    }

    ///
    /// Writes BCD encoded string to the display
    ///
    /// # Arguments
    ///
    /// * `addr` - display to address as connected in series (0 -> last)
    /// * `bcd` - the bcd encoded string slice consisting of [0-9,-,E,L,H,P]
    /// where upper case input for alphabetic characters results in dot being set.
    /// Length of string is always 8 bytes, use spaces for blanking.
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn write_bcd(&mut self, addr: usize, bcd: &[u8; MAX_DIGITS]) -> Result<(), PinError> {
        let prev_dm = self.decode_mode;
        self.set_decode_mode(0, DecodeMode::CodeBDigits7_0)?;

        let mut digit: u8 = MAX_DIGITS as u8;
        for b in bcd {
            self.c.write_raw(addr, digit, bcd_byte(*b))?;

            digit = digit - 1;
        }

        self.set_decode_mode(0, prev_dm)?;

        Ok(())
    }

    ///
    /// Set test mode on/off
    ///
    /// # Arguments
    ///
    /// * `addr` - display to address as connected in series (0 -> last)
    /// * `is_on` - whether to turn test mode on or off
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn test(&mut self, addr: usize, is_on: bool) -> Result<(), PinError> {
        if is_on {
            self.c.write_data(addr, Command::DisplayTest, 0x01)
        } else {
            self.c.write_data(addr, Command::DisplayTest, 0x00)
        }
    }

    // internal constructor, users should call ::from_pins or ::from_spi
    fn new(connector: CONNECTOR) -> Result<Self, PinError> {
        let mut max7219 = MAX7219 {
            c: connector,
            decode_mode: DecodeMode::NoDecode,
        };

        max7219.init()?;
        Ok(max7219)
    }

    fn init(&mut self) -> Result<(), PinError> {
        for i in 0..self.c.devices() {
            self.test(i, false)?; // turn testmode off
            self.c.write_data(i, Command::ScanLimit, 0x07)?; // set scanlimit
            self.set_decode_mode(i, DecodeMode::NoDecode)?; // direct decode
            self.clear_display(i)?; // clear all digits
        }
        self.power_off()?; // power off

        Ok(())
    }
}

impl<DATA, CS, SCK> MAX7219<PinConnector<DATA, CS, SCK>>
where
    DATA: OutputPin,
    CS: OutputPin,
    SCK: OutputPin,
    PinError: core::convert::From<DATA::Error>,
    PinError: core::convert::From<CS::Error>,
    PinError: core::convert::From<SCK::Error>,
{
    ///
    /// Construct a new MAX7219 driver instance from DATA, CS and SCK pins.
    ///
    /// # Arguments
    ///
    /// * `displays` - number of displays connected in series
    /// * `data` - the MOSI/DATA PIN used to send data through to the display set to output mode
    /// * `cs` - the CS PIN used to LOAD register on the display set to output mode
    /// * `sck` - the SCK clock PIN used to drive the clock set to output mode
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn from_pins(displays: usize, data: DATA, cs: CS, sck: SCK) -> Result<Self, PinError> {
        MAX7219::new(PinConnector::new(displays, data, cs, sck))
    }
}

impl<SPI> MAX7219<SpiConnector<SPI>>
where
    SPI: Write<u8>,
    PinError: core::convert::From<()>,
    PinError: core::convert::From<SPI::Error>,
{
    ///
    /// Construct a new MAX7219 driver instance from pre-existing SPI in full hardware mode.
    /// The SPI will control CS (LOAD) line according to it's internal mode set.
    /// If you need the CS line to be controlled manually use MAX7219::from_spi_cs
    /// 
    /// * `NOTE` - make sure the SPI is initialized in MODE_0 with max 10 Mhz frequency.
    ///
    /// # Arguments
    ///
    /// * `displays` - number of displays connected in series
    /// * `spi` - the SPI interface initialized with MOSI, MISO(unused) and CLK
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn from_spi(displays: usize, spi: SPI) -> Result<Self, PinError> {
        MAX7219::new(SpiConnector::new(displays, spi))
    }
}

impl<SPI, CS> MAX7219<SpiConnectorSW<SPI, CS>>
where
    SPI: Write<u8>,
    CS: OutputPin,
    PinError: core::convert::From<()>,
    PinError: core::convert::From<SPI::Error>,
    PinError: core::convert::From<CS::Error>,
{
    ///
    /// Construct a new MAX7219 driver instance from pre-existing SPI and CS pin
    /// set to output. This version of the connection uses the CS pin manually
    /// to avoid issues with how the CS mode is handled in hardware SPI implementations.
    /// 
    /// * `NOTE` - make sure the SPI is initialized in MODE_0 with max 10 Mhz frequency.
    ///
    /// # Arguments
    ///
    /// * `displays` - number of displays connected in series
    /// * `spi` - the SPI interface initialized with MOSI, MISO(unused) and CLK
    /// * `cs` - the CS PIN used to LOAD register on the display set to output mode
    ///
    /// # Errors
    ///
    /// * `PinError` - returned in case there was an error setting a PIN on the device
    ///
    pub fn from_spi_cs(displays: usize, spi: SPI, cs: CS) -> Result<Self, PinError> {
        MAX7219::new(SpiConnectorSW::new(displays, spi, cs))
    }
}

///
/// Translate alphanumeric ASCII bytes into BCD
/// encoded bytes expected by the display chip.
///
fn bcd_byte(b: u8) -> u8 {
    match b as char {
        ' ' => 0b00001111, // "blank"
        '-' => 0b00001010, // - without .
        'e' => 0b00001011, // E without .
        'E' => 0b10001011, // E with .
        'h' => 0b00001100, // H without .
        'H' => 0b10001100, // H with .
        'l' => 0b00001101, // L without .
        'L' => 0b10001101, // L with .
        'p' => 0b00001110, // L without .
        'P' => 0b10001110, // L with .
        _ => b,
    }
}

///
/// Translate alphanumeric ASCII bytes into segment set bytes
///
fn ssb_byte(b: u8, dot: bool) -> u8 {
    let mut result = match b as char {
        ' ' => 0b00000000, // "blank"
        '.' => 0b10000000,
        '-' => 0b00000001, // -
        '_' => 0b00001000, // _
        '0' => 0b01111110,
        '1' => 0b00110000,
        '2' => 0b01101101,
        '3' => 0b01111001,
        '4' => 0b00110011,
        '5' => 0b01011011,
        '6' => 0b01011111,
        '7' => 0b01110000,
        '8' => 0b01111111,
        '9' => 0b01111011,
        'a' | 'A' => 0b01110111,
        'b' => 0b00011111,
        'c' | 'C' => 0b01001110,
        'd' => 0b00111101,
        'e' | 'E' => 0b01001111,
        'f' | 'F' => 0b01000111,
        'g' | 'G' => 0b01011110,
        'h' | 'H' => 0b00110111,
        'i' | 'I' => 0b00110000,
        'j' | 'J' => 0b00111100,
        // K undoable
        'l' | 'L' => 0b00001110,
        // M undoable
        // N undoable
        'o' | 'O' => 0b01111110,
        'p' | 'P' => 0b01100111,
        'q' => 0b01110011,
        // R undoable
        's' | 'S' => 0b01011011,
        // T undoable
        'u' | 'U' => 0b00111110,
        // V undoable
        // W undoable
        // X undoable
        // Y undoable
        // Z undoable
        _ => 0b11100101, // ?
    };

    if dot {
        result = result | 0b10000000; // turn "." on
    }

    result
}