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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! The display driver and Frame trait.

use crate::control::DisplayControl;
use crate::timer::DisplayTimer;
use crate::render::{Render, BRIGHTNESSES, MAX_BRIGHTNESS};


/// A set of matrix column indices.
///
/// Supports maximum index 15.
#[derive(Copy, Clone, Debug)]
struct ColumnSet (u16);

impl ColumnSet {

    /// Returns a new empty set.
    const fn empty() -> ColumnSet {
        ColumnSet(0)
    }

    /// Adds column index 'col' to the set.
    fn set(&mut self, col: usize) {
        self.0 |= 1<<col;
    }

    /// Returns the set as a bitmap in a u32 (LSB is index 0).
    fn as_u32(&self) -> u32 {
        self.0 as u32
    }

    /// Says whether the set is empty.
    fn is_empty(&self) -> bool {
        self.0 == 0
    }
}


/// A 'compiled' representation of the part of an image displayed on a single
/// matrix row.
///
/// RowPlans are created and contained by [`Frame`]s.
// This is effectively a map brightness -> set of columns
#[derive(Copy, Clone, Debug)]
pub struct RowPlan (
    [ColumnSet; BRIGHTNESSES],
);

impl RowPlan {

    /// Returns a new RowPlan with all LEDs brightness 0.
    pub const fn default() -> RowPlan {
        RowPlan([ColumnSet::empty(); BRIGHTNESSES])
    }

    /// Resets all LEDs to brightness 0.
    fn clear(&mut self) {
        self.0 = RowPlan::default().0;
    }

    /// Says which LEDs have the specified brightness.
    fn lit_cols(&self, brightness: u8) -> ColumnSet {
        self.0[brightness as usize]
    }

    /// Sets a single LED to the specified brightness.
    fn light_col(&mut self, brightness: u8, col: usize) {
        self.0[brightness as usize].set(col);
    }

}


/// Description of a device's LED layout.
///
/// This describes the correspondence between the visible layout of LEDs and
/// the pins controlling them.
///
/// # Example implementation
///
/// ```
/// # use tiny_led_matrix::Matrix;
/// struct SimpleMatrix ();
///
/// impl Matrix for SimpleMatrix {
///     const MATRIX_COLS: usize = 2;
///     const MATRIX_ROWS: usize = 3;
///     const IMAGE_COLS: usize = 3;
///     const IMAGE_ROWS: usize = 2;
///     fn image_coordinates(col: usize, row: usize) -> Option<(usize, usize)> {
///         Some((row, col))
///     }
/// }
/// ```
pub trait Matrix {
    /// The number of pins connected to LED columns.
    ///
    /// At present this can be at most 16.
    const MATRIX_COLS: usize;

    /// The number of pins connected to LED rows.
    ///
    /// This should normally be a small number (eg 3).
    const MATRIX_ROWS: usize;

    // Note that nothing uses IMAGE_COLS and IMAGE_ROWS directly; having these
    // constants allows us to document them.

    /// The number of visible LED columns.
    const IMAGE_COLS: usize;

    /// The number of visible LED rows.
    const IMAGE_ROWS: usize;

    /// Returns the image coordinates (x, y) to use for the LED at (col, row).
    ///
    /// Returns None if (col, row) doesn't control an LED.
    ///
    /// Otherwise the return value is in (0..IMAGE_COLS, 0..IMAGE_ROWS), with
    /// (0, 0) representing the top left.
    ///
    /// # Panics
    ///
    /// Panics if the provided col and row are out of range 0..MATRIX_COLS and
    /// 0..MATRIX_ROWS.

    fn image_coordinates(col: usize, row: usize) -> Option<(usize, usize)>;
}


/// A 'Compiled' representation of an image to be displayed.
///
/// `Frame`s are populated from images implementing [`Render`], then passed on
/// to [`Display::set_frame()`].
///
/// # Implementing `Frame`
///
/// Implementations of `Frame` do two things:
///
/// - specify the [`Matrix`] used to convert between image and matrix
///   coordinates
/// - act like an array of [`RowPlan`]s, one for each matrix row.
///
/// Note that implementations of `Frame` must also implement `Copy` and
/// `Default`.
///
/// # Example implementation
///
/// ```
/// # use tiny_led_matrix::{Matrix,Frame,RowPlan};
/// # struct SimpleMatrix ();
/// # impl Matrix for SimpleMatrix {
/// #     const MATRIX_COLS: usize = 2;
/// #     const MATRIX_ROWS: usize = 3;
/// #     const IMAGE_COLS: usize = 3;
/// #     const IMAGE_ROWS: usize = 2;
/// #     fn image_coordinates(col: usize, row: usize) ->
/// #                         Option<(usize, usize)> {
/// #         Some((row, col))
/// #     }
/// # }
/// #
/// #[derive(Copy, Clone)]
/// struct SimpleFrame (
///     [RowPlan; 3]
/// );
///
/// impl Default for SimpleFrame {
///     fn default() -> SimpleFrame {
///         SimpleFrame([RowPlan::default(); SimpleFrame::ROWS])
///     }
/// }
///
/// impl Frame for SimpleFrame {
///     type Mtx = SimpleMatrix;
///
///     fn row_plan(&self, row: usize) -> &RowPlan {
///         &self.0[row]
///     }
///
///     fn row_plan_mut(&mut self, row: usize) -> &mut RowPlan {
///         &mut self.0[row]
///     }
/// }
/// ```
pub trait Frame: Copy + Default {

    /// The Matrix used to convert between image and matrix coordinates.
    type Mtx: Matrix;

    /// The number of pins connected to LED columns.
    const COLS: usize = Self::Mtx::MATRIX_COLS;

    /// The number of pins connected to LED rows.
    const ROWS: usize = Self::Mtx::MATRIX_ROWS;

    /// Returns a reference to the RowPlan for a row of LEDs.
    ///
    /// # Panics
    ///
    /// Panics if `row` is not in the range 0..ROWS
    fn row_plan(&self, row: usize) -> &RowPlan;

    /// Returns a mutable reference to the RowPlan for a row of LEDs.
    ///
    /// # Panics
    ///
    /// Panics if `row` is not in the range 0..ROWS
    fn row_plan_mut(&mut self, row: usize) -> &mut RowPlan;


    /// Stores a new image into the frame.
    ///
    /// Example:
    ///
    /// ```ignore
    /// frame.set(GreyscaleImage::blank());
    /// ```
    fn set<T>(&mut self, image: &T) where T: Render + ?Sized {
        for row in 0..Self::ROWS {
            let plan = self.row_plan_mut(row);
            plan.clear();
            for col in 0..Self::COLS {
                if let Some((x, y)) = Self::Mtx::image_coordinates(col, row) {
                    let brightness = image.brightness_at(x, y);
                    plan.light_col(brightness, col);
                }
            }
        }
    }
}


// With a 16µs period, 375 ticks is 6ms
const CYCLE_TICKS: u16 = 375;

const GREYSCALE_TIMINGS: [u16; BRIGHTNESSES-2] = [
//   Delay,   Bright, Ticks, Duration, Relative power
//   375,  //   0,      0,      0µs,    ---
     373,  //   1,      2,     32µs,    inf
     371,  //   2,      4,     64µs,   200%
     367,  //   3,      8,    128µs,   200%
     360,  //   4,     15,    240µs,   187%
     347,  //   5,     28,    448µs,   187%
     322,  //   6,     53,    848µs,   189%
     273,  //   7,    102,   1632µs,   192%
     176,  //   8,    199,   3184µs,   195%
//     0,  //   9,    375,   6000µs,   188%
];


/// The reason for a display-timer interrupt.
///
/// This is the return value from [`handle_event()`].
///
/// [`handle_event()`]: Display::handle_event
#[derive(PartialEq, Eq, Debug)]
pub enum Event {
    /// The display has switched to lighting a new row.
    SwitchedRow,
    /// The display has changed the LEDs in the current row.
    UpdatedRow,
    /// Neither a new primary cycle nor a secondary alarm has occurred.
    Unknown,
}

impl Event {
    /// Checks whether this event is `SwitchedRow`.
    ///
    /// This is provided for convenience in the common case where you want to
    /// perform some action based on the display timer's primary cycle.
    pub fn is_new_row(self) -> bool {
        self == Event::SwitchedRow
    }
}


/// Starts the timer you plan to use with a [`Display`].
///
/// Call this once before using a [`Display`].
///
/// This calls the timer's
/// [`initialise_cycle()`][DisplayTimer::initialise_cycle] implementation.
pub fn initialise_timer(timer: &mut impl DisplayTimer) {
    timer.initialise_cycle(CYCLE_TICKS);
}


/// Initialises the display hardware you plan to use with a [`Display`].
///
/// Call this once before using a [`Display`].
///
/// This calls the [`DisplayControl`]'s
/// [`initialise_for_display()`][DisplayControl::initialise_for_display]
/// implementation.
pub fn initialise_control(control: &mut impl DisplayControl) {
    control.initialise_for_display();
}


/// Manages a small LED display.
///
/// There should normally be a single `Display` instance for a single piece of
/// display hardware.
///
/// Display is generic over a [`Frame`] type, which holds image data suitable
/// for display on a particular piece of hardware.
///
/// Call [`initialise_control()`] and [`initialise_timer()`] before using a
/// `Display`.
///
/// # Example
///
/// Using `cortex-m-rtfm` v0.5:
/// ```ignore
/// #[app(device = nrf51, peripherals = true)]
/// const APP: () = {
///
///     struct Resources {
///         gpio: nrf51::GPIO,
///         timer1: nrf51::TIMER1,
///         display: Display<MyFrame>,
///     }
///
///     #[init]
///     fn init(cx: init::Context) -> init::LateResources {
///         let mut p: nrf51::Peripherals = cx.device;
///         display::initialise_control(&mut MyDisplayControl(&mut p.GPIO));
///         display::initialise_timer(&mut MyDisplayTimer(&mut p.TIMER1));
///         init::LateResources {
///             gpio : p.GPIO,
///             timer1 : p.TIMER1,
///             display : Display::new(),
///         }
///     }
/// }
/// ```

pub struct Display<F: Frame> {
    // index (0..F::ROWS) of the row being displayed
    row_strobe      : usize,
    // brightness level (0..=MAX_BRIGHTNESS) to process next
    next_brightness : u8,
    frame           : F,
    current_plan    : RowPlan
}

impl<F: Frame> Display<F> {

    /// Creates a Display instance, initially holding a blank image.
    pub fn new() -> Display<F> {
        Display {
            row_strobe: 0,
            next_brightness: 0,
            frame: F::default(),
            current_plan: RowPlan::default(),
        }
    }

    /// Accepts a new image to be displayed.
    ///
    /// The code that calls this method must not be interrupting, or
    /// interruptable by, [`handle_event()`][Display::handle_event].
    ///
    /// After calling this, it's safe to modify the frame again (its data is
    /// copied into the `Display`).
    ///
    /// # Example
    ///
    /// In the style of `cortex-m-rtfm` v0.5:
    ///
    /// ```ignore
    /// #[task(binds = RTC0, priority = 1, resources = [rtc0, display])]
    /// fn rtc0(mut cx: rtc0::Context) {
    ///     static mut FRAME: MyFrame = MyFrame::const_default();
    ///     &cx.resources.rtc0.clear_tick_event();
    ///     FRAME.set(GreyscaleImage::blank());
    ///     cx.resources.display.lock(|display| {
    ///         display.set_frame(FRAME);
    ///     });
    /// }
    /// ```
    pub fn set_frame(&mut self, frame: &F) {
        self.frame = *frame;
    }

    /// Updates the display for the start of a new primary cycle.
    ///
    /// Leaves the timer's secondary alarm enabled iff there are any
    /// intermediate brightnesses in the current image.
    fn render_row(&mut self,
                  control: &mut impl DisplayControl,
                  timer: &mut impl DisplayTimer) {
        assert! (self.row_strobe < F::ROWS);
        self.row_strobe += 1;
        if self.row_strobe == F::ROWS {self.row_strobe = 0};

        let plan = self.frame.row_plan(self.row_strobe);

        let lit_cols = plan.lit_cols(MAX_BRIGHTNESS);
        control.display_row_leds(self.row_strobe, lit_cols.as_u32());

        // We copy this so that we'll continue using it for the rest of this
        // 'tick' even if set_frame() is called part way through
        self.current_plan = *plan;
        self.next_brightness = MAX_BRIGHTNESS;
        self.program_next_brightness(timer);
        if self.next_brightness != 0 {
            timer.enable_secondary();
        }
    }

    /// Updates the display to represent an intermediate brightness.
    ///
    /// This is called after an interrupt from the secondary alarm.
    fn render_subrow(&mut self,
                     control: &mut impl DisplayControl,
                     timer: &mut impl DisplayTimer) {
        // When this method is called, next_brightness is an intermediate
        // brightness in the range 1..8 (the one that it's time to display).

        let additional_cols = self.current_plan.lit_cols(self.next_brightness);
        control.light_current_row_leds(additional_cols.as_u32());

        self.program_next_brightness(timer);
    }

    /// Updates next_brightness to the next (dimmer) brightness that needs
    /// displaying, and program the timer's secondary alarm correspondingly.
    ///
    /// If no further brightness needs displaying for this row, this means
    /// disabling the secondary alarm.
    fn program_next_brightness(&mut self, timer: &mut impl DisplayTimer) {
        loop {
            self.next_brightness -= 1;
            if self.next_brightness == 0 {
                timer.disable_secondary();
                break;
            }
            if !self.current_plan.lit_cols(self.next_brightness).is_empty() {
                timer.program_secondary(
                    GREYSCALE_TIMINGS[(self.next_brightness-1) as usize]
                );
                break;
            }
        }
    }

    /// Updates the LEDs and timer state during a timer interrupt.
    ///
    /// You should call this each time the timer's interrupt is signalled.
    ///
    /// The `timer` parameter must represent the same device each time you
    /// call this method, and the same as originally passed to
    /// [`initialise_timer()`].
    ///
    /// The `control` parameter must represent the same device each time you
    /// call this method, and the same as originally passed to
    /// [`initialise_control()`].
    ///
    /// This method always calls the timer's
    /// [`check_primary()`][DisplayTimer::check_primary] and
    /// [`check_secondary()`][DisplayTimer::check_secondary] methods.
    ///
    /// As well as updating the LED state by calling [`DisplayControl`]
    /// methods, it may update the timer state by calling the timer's
    /// [`program_secondary()`][DisplayTimer::program_secondary],
    /// [`enable_secondary()`][DisplayTimer::enable_secondary], and/or
    /// [`disable_secondary()`][DisplayTimer::disable_secondary] methods.
    ///
    /// Returns a value indicating the reason for the interrupt. You can check
    /// this if you wish to perform some other action once per primary cycle.
    ///
    /// # Example
    ///
    /// In the style of `cortex-m-rtfm` v0.5:
    ///
    /// ```ignore
    /// #[task(binds = TIMER1, priority = 2,
    ///        resources = [timer1, gpio, display])]
    /// fn timer1(cx: timer1::Context) {
    ///     let display_event = cx.resources.display.handle_event(
    ///         &mut MyDisplayControl(&mut cx.resources.timer1),
    ///         &mut MyDisplayControl(&mut cx.resources.gpio),
    ///     );
    ///     if display_event.is_new_row() {
    ///         ...
    ///     }
    /// }
    /// ```
    pub fn handle_event(&mut self,
                        timer: &mut impl DisplayTimer,
                        control: &mut impl DisplayControl) -> Event {
        let row_timer_fired = timer.check_primary();
        let brightness_timer_fired = timer.check_secondary();
        if row_timer_fired {
            self.render_row(control, timer);
            Event::SwitchedRow
        } else if brightness_timer_fired {
            self.render_subrow(control, timer);
            Event::UpdatedRow
        } else {
            Event::Unknown
        }
    }

}