avr-oxide 0.2.0

An extremely simple Rusty operating system for AVR microcontrollers
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
/* ports.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! Generic I/O ports provided by the AVR microcontroller.

// Imports ===================================================================



use core::any::Any;
use ufmt::derive::uDebug;
use oxide_macros::Persist;
use crate::hal::generic::callback::IsrCallback;

// Declarations ==============================================================
/**
 * Input/output mode for a pin
 */
#[derive(Clone,Copy,PartialEq,Eq,uDebug,Persist)]
pub enum PinMode {
  /// Pin is configured as output
  Output,
  /// Pin is configured as an input with internal pullup enabled
  InputPullup,
  /// Pin is configured as an input with internal pullup disabled
  InputFloating
}

/**
 * Interrupt generation mode for a pin
 */
#[derive(Clone,Copy,PartialEq,Eq,uDebug,Persist)]
pub enum InterruptMode {
  /// Do not generate interrupts
  Disabled,
  /// Interrupt on both rising and falling edges
  BothEdges,
  /// Interrupt on rising edge
  RisingEdge,
  /// Interrupt on falling edge
  FallingEdge,
  /// Interrupt while input is low
  LowLevel
}

/**
 * Identifies a particular pin as the source of an event at runtime.
 */
#[derive(Clone,Copy,PartialEq,Eq,uDebug,Persist)]
pub enum PinIdentity {
  /// Port A, pin number (u8)
  PortA(u8),
  /// Port A, pin number (u8)
  PortB(u8),
  /// Port A, pin number (u8)
  PortC(u8),
  /// Port A, pin number (u8)
  PortD(u8),
  /// Port A, pin number (u8)
  PortE(u8),
  /// Port A, pin number (u8)
  PortF(u8)
}

/**
 * Callback called by a pin when it generates an interrupt.  The callback
 * is given the new state read from the pin (true = high).
 * The callback should return a boolean:
 * * true:  Continue generating interrupts for this pin
 * * false: Disable generating interrupts for this pin
 *
 * Note: The callback runs *within the interrupt context* - be careful about
 * using mutual exclusion where necessary, and *DO NOT DO HEAVY PROCESSING
 * IN THE CALLBACK*.
 */
pub type PinIsrFunction<P> = fn(&'static P,PinIdentity,bool,Option<*const dyn Any>) -> ();

pub type PinIsrCallback<P> = IsrCallback<PinIsrFunction<P>,()>;

pub trait Pin {
  /// Set the input/output mode for this pin
  fn set_mode(&self, mode: PinMode);

  /// Toggle this pin's output level
  fn toggle(&self);

  /// Set the pin's output to high
  fn set_high(&self);

  /// Set the pin's output to low
  fn set_low(&self);

  /// Set the pin's output according to the boolean (true == high, false == low)
  fn set(&self, high: bool);

  /// Get the pin's input; true == high, false == low.
  fn get(&self) -> bool;

  /// Set when this pin will generate interrupts
  fn set_interrupt_mode(&self, mode: InterruptMode);

  /// Listen for interrupts on this pin and call the given handler callback
  /// when one occurs.
  fn listen(&'static self, handler: PinIsrCallback<Self>);
}

pub trait Port<P>
where
  P: Pin
{
  fn pin_instance(&self, pin: u8) -> &P;
}

// Code ======================================================================
#[cfg(target_arch="avr")]
pub mod base {
  use crate::hal::generic::port::InterruptMode;

  pub trait AtmelPortControl {
    /// Set this pin as an output.
    fn enable_output(&mut self, p: u8);
    /// Disable output on this pin
    fn disable_output(&mut self, p: u8);
    /// Enable internal pullup on this pin
    fn enable_pullup(&mut self, p: u8);
    /// Disable internal pullup on this pin
    fn disable_pullup(&mut self, p: u8);
    /// Set a pin's output state high
    fn set_high(&mut self, p: u8);
    /// Set a pin's output state low
    fn set_low(&mut self, p: u8);
    /// Toggle a pin's input state
    fn toggle(&mut self, p: u8);
    /// Get a pin's state
    fn get(&self, p: u8) -> bool;
    /// Set the mode for interrupt generation for a pin
    fn set_interrupt_mode(&mut self, p: u8, mode: InterruptMode);
    /// True iff the given pin has generated an interrupt
    fn interrupted(&self, p: u8) -> bool;
    /// Clear the interrupt flag for all pins on this port
    fn clear_interrupts(&mut self);
  }

  impl InterruptMode {
    #[inline(always)]
    fn to_pinctrl_isc(&self) -> u8 {
      match self {
        InterruptMode::Disabled => 0x00,
        InterruptMode::BothEdges => 0x01,
        InterruptMode::RisingEdge => 0x02,
        InterruptMode::FallingEdge => 0x03,
        InterruptMode::LowLevel => 0x05
      }
    }

    #[inline(always)]
    fn pinctrl_mask() -> u8 {
      0b00000111
    }
  }

  /**
   * The AVR port control register block.  The structure provided by the
   * auto-generated avr-device crate is just horrible, so we use our own
   * rendition.  This allows accessing pin control by index, and also avoids
   * having different types for every port.
   */
  #[repr(C)]
  pub struct AvrPortRegisterBlock {
    pub(crate) dir: u8,
    pub(crate) dir_set: u8,
    pub(crate) dir_clr: u8,
    pub(crate) dir_tgl: u8,
    pub(crate) out: u8,
    pub(crate) out_set: u8,
    pub(crate) out_clr: u8,
    pub(crate) out_tgl: u8,
    pub(crate) inp: u8,
    pub(crate) intflags: u8,
    pub(crate) portctrl: u8,
    pub(crate) reserved: [u8; 5],
    pub(crate) pinctrl: [u8; 8]
  }



  impl AtmelPortControl for AvrPortRegisterBlock {
    #[inline(always)]
    fn enable_output(&mut self, p: u8) {
      unsafe {
        core::ptr::write_volatile(&mut self.dir_set as *mut u8, 0x01 << p);
      }
    }
    #[inline(always)]
    fn disable_output(&mut self, p: u8) {
      unsafe {
        core::ptr::write_volatile(&mut self.dir_clr as *mut u8, 0x01 << p);
      }
    }

    fn enable_pullup(&mut self, p: u8) {
      unsafe {
        let pinctrl_reg = &mut self.pinctrl[p as usize] as *mut u8;

        let pinctrl = core::ptr::read_volatile(pinctrl_reg);

        core::ptr::write_volatile(pinctrl_reg, pinctrl | 0b00001000);
      }
    }

    fn disable_pullup(&mut self, p: u8) {
      unsafe {
        let pinctrl_reg = &mut self.pinctrl[p as usize] as *mut u8;

        let pinctrl = core::ptr::read_volatile(pinctrl_reg);

        core::ptr::write_volatile(pinctrl_reg, pinctrl & 0b11110111);
      }
    }

    #[inline(always)]
    fn set_high(&mut self, p: u8) {
      unsafe {
        core::ptr::write_volatile(&mut self.out_set as *mut u8, 0x01 << p);
      }
    }
    #[inline(always)]
    fn set_low(&mut self, p: u8) {
      unsafe {
        core::ptr::write_volatile(&mut self.out_clr as *mut u8, 0x01 << p);
      }
    }
    #[inline(always)]
    fn toggle(&mut self, p: u8) {
      unsafe {
        core::ptr::write_volatile(&mut self.out_tgl as *mut u8, 0x01 << p);
      }
    }

    #[inline(always)]
    fn get(&self, p: u8) -> bool {
      unsafe {
        core::ptr::read_volatile(&self.inp as *const u8) & (0x01 << p) != 0
      }
    }

    fn set_interrupt_mode(&mut self, p: u8, mode: InterruptMode) {
      unsafe {
        let pinctrl_reg = &mut self.pinctrl[p as usize] as *mut u8;

        let pinctrl = core::ptr::read_volatile(pinctrl_reg);

        core::ptr::write_volatile(pinctrl_reg,
                                  (pinctrl & !InterruptMode::pinctrl_mask()) | mode.to_pinctrl_isc());
      }
    }

    #[inline(always)]
    fn interrupted(&self, p: u8) -> bool {
      unsafe {
        core::ptr::read_volatile(&self.intflags as *const u8) & (0x01 << p) != 0
      }
    }

    #[inline(always)]
    fn clear_interrupts(&mut self) {
      unsafe {
        core::ptr::write_volatile(&mut self.intflags as *mut u8, 0xff);
      }
    }
  }

  #[doc(hidden)]
  #[macro_export]
  macro_rules! atmel_port_tpl {
    ($ref:expr, $portsrc:expr, $isr:ident) => {
      use core::any::Any;

      use crate::hal::generic::port::{PinMode,Pin,PinIdentity,InterruptMode,PinIsrCallback};
      use crate::hal::generic::port::base::{AtmelPortControl,AvrPortRegisterBlock};
      use crate::isr_cb_invoke;

      pub type PortImpl = AvrPortRegisterBlock;
      pub type PinImpl = AtmelPin;

      /**
       * A single pin instance.  This is just a wrapper for a reference to
       * the pin number and a place to stash the callback function that will
       * be called when we have an interrupt.
       */
      pub struct AtmelPin {
        n: u8,
        handler: PinIsrCallback<Self>
      }

      /**
       * Implementation of the Pin API for our Atmel PINs.
       */
      impl Pin for AtmelPin {
        #[inline(always)]
        fn set_mode(&self, mode: PinMode) {
          match mode {
            PinMode::Output => {
              instance().enable_output(self.n);
            },
            PinMode::InputPullup => {
              instance().enable_pullup(self.n);
              instance().disable_output(self.n);
            },
            PinMode::InputFloating => {
              instance().disable_pullup(self.n);
              instance().disable_output(self.n);
            }
          }
        }
        #[inline(always)]
        fn toggle(&self) {
          instance().toggle(self.n);
        }
        #[inline(always)]
        fn set_high(&self) {
          instance().set_high(self.n);
        }
        #[inline(always)]
        fn set_low(&self) {
          instance().set_low(self.n);
        }
        #[inline(always)]
        fn set(&self, high: bool) {
          match high {
            true  => instance().set_high(self.n),
            false => instance().set_low(self.n)
          }
        }
        #[inline(always)]
        fn get(&self) -> bool {
          instance().get(self.n)
        }
        fn set_interrupt_mode(&self, mode: InterruptMode) {
          instance().set_interrupt_mode(self.n, mode)
        }
        fn listen(&self, handler: PinIsrCallback<Self>){
          crate::hal::concurrency::interrupt::isolated(||{
            unsafe {
              PINS[self.n as usize].handler = handler;
            }
          });
        }
      }

      static mut INITIALISED: bool = false;

      /**
       * Get an instance of this port's register block.  Also does any
       * static initialisation required of the device the first time it is
       * called.
       */
      #[inline(always)]
      pub fn instance() -> &'static mut AvrPortRegisterBlock  {
        unsafe {
          // Not sure if this is a compiler bug or what, but our static
          // muts don't seem to be correctly initialised, so we need to
          // do this here instead
          //
          // ( @todo investigate - Probably I need to amend my boot code to call
          //         something to do the initialisation for me )
          if(!INITIALISED){
            for pin in 0..=7 {
              PINS[pin].n = pin as u8;
              PINS[pin].handler = PinIsrCallback::Nop(());
            }
            INITIALISED = true;
          }

          core::mem::transmute($ref)
        }
      }

      static mut PINS : [AtmelPin; 8] = [
        AtmelPin { n: 0, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 1, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 2, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 3, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 4, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 5, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 6, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 7, handler: PinIsrCallback::Nop(()) },
      ];


      /**
       * Return a single pin instance wrapper.
       */
      pub fn pin_instance(pin: u8) -> &'static mut AtmelPin {
        unsafe {
          &mut PINS[pin as usize]
        }
      }

      /**
       * Interrupt service routine.  Checks which pins caused the interrupt
       * and then calls the relevant callback routine.
       */
      #[no_mangle]
      pub unsafe extern "avr-interrupt" fn $isr() {
        crate::hal::concurrency::interrupt::isr(||{
          let intflags:u8 = core::ptr::read_volatile(&instance().intflags as *const u8);
          let state:u8    = core::ptr::read_volatile(&instance().inp as *const u8);
          let mut mask    = 0x01;

          for pin in 0..=7 {
            if (intflags & mask) > 0 {
              isr_cb_invoke!(PINS[pin].handler, &mut PINS[pin], $portsrc(pin as u8), (state & mask) > 0);
            }
            mask <<= 1;
          }
          instance().clear_interrupts();
        })
      }
    }
  }
}

#[cfg(not(target_arch="avr"))]
pub mod base {
  use crate::hal::generic::port::InterruptMode;

  pub trait AtmelPortControl {
    /// Set this pin as an output.
    fn enable_output(&mut self, p: u8);
    /// Disable output on this pin
    fn disable_output(&mut self, p: u8);
    /// Enable internal pullup on this pin
    fn enable_pullup(&mut self, p: u8);
    /// Disable internal pullup on this pin
    fn disable_pullup(&mut self, p: u8);
    /// Set a pin's output state high
    fn set_high(&mut self, p: u8);
    /// Set a pin's output state low
    fn set_low(&mut self, p: u8);
    /// Toggle a pin's input state
    fn toggle(&mut self, p: u8);
    /// Get a pin's state
    fn get(&self, p: u8) -> bool;
    /// Set the mode for interrupt generation for a pin
    fn set_interrupt_mode(&mut self, p: u8, mode: InterruptMode);
    /// True iff the given pin has generated an interrupt
    fn interrupted(&self, p: u8) -> bool;
    /// Clear the interrupt flag for all pins on this port
    fn clear_interrupts(&mut self);
  }

  /**
   * The AVR port control register block.  The structure provided by the
   * auto-generated avr-device crate is just horrible, so we use our own
   * rendition.  This allows accessing pin control by index, and also avoids
   * having different types for every port.
   */
  #[repr(C)]
  pub struct DummyPortRegisterBlock {
    pub(crate) pin: [bool; 8],
    pub(crate) o_en: [bool; 8],
    pub(crate) pu_en: [bool; 8]
  }



  impl AtmelPortControl for DummyPortRegisterBlock {
    fn enable_output(&mut self, p: u8) {
      println!("*** PORT: Enable output pin {}", p);
      self.o_en[p as usize] = true;
    }

    fn disable_output(&mut self, p: u8) {
      println!("*** PORT: Disable output pin {}", p);
      self.o_en[p as usize] = false;
    }

    fn enable_pullup(&mut self, p: u8) {
      println!("*** PORT: Enable pullup pin {}", p);
      self.pu_en[p as usize] = true;
    }

    fn disable_pullup(&mut self, p: u8) {
      println!("*** PORT: Disable pullup pin {}", p);
      self.pu_en[p as usize] = false;
    }

    fn set_high(&mut self, p: u8) {
      println!("*** PORT: Set HIGH pin {}", p);
      self.pin[p as usize] = true;
    }

    fn set_low(&mut self, p: u8) {
      println!("*** PORT: Set LOW pin {}", p);
      self.pin[p as usize] = false;
    }

    fn toggle(&mut self, p: u8) {
      let old = self.pin[p as usize];

      println!("*** PORT: TOGGLE pin {} ({} => {})", p, old, !old);

      self.pin[p as usize] = !old;
    }

    fn get(&self, p: u8) -> bool {
      let val = self.pin[p as usize];
      println!("*** PORT: GET pin {} ({})", p, val);
      val
    }

    fn set_interrupt_mode(&mut self, p: u8, _mode: InterruptMode) {
      println!("*** PORT: Set interrupt mode pin {}", p);
    }

    fn interrupted(&self, p: u8) -> bool {
      println!("*** PORT: Get interrupt flag pin {}", p);
      false
    }

    fn clear_interrupts(&mut self) {
      println!("*** PORT: Clear all interrupts");
    }


  }

  #[doc(hidden)]
  #[macro_export]
  macro_rules! atmel_port_tpl {
    ($ref:expr, $portsrc:expr, $isr:ident) => {
      use core::any::Any;

      use crate::hal::generic::port::{PinMode,Pin,PinIdentity,InterruptMode,PinIsrCallback};
      use crate::hal::generic::port::base::{AtmelPortControl,DummyPortRegisterBlock};

      pub type PortImpl = DummyPortRegisterBlock;
      pub type PinImpl = AtmelPin;

      /**
       * A single pin instance.  This is just a wrapper for a reference to
       * the pin number and a place to stash the callback function that will
       * be called when we have an interrupt.
       */
      pub struct AtmelPin {
        n: u8,
        handler: PinIsrCallback<Self>
      }

      /**
       * Implementation of the Pin API for our Atmel PINs.
       */
      impl Pin for AtmelPin {
        #[inline(always)]
        fn set_mode(&self, mode: PinMode) {
          match mode {
            PinMode::Output => {
              instance().enable_output(self.n);
            },
            PinMode::InputPullup => {
              instance().enable_pullup(self.n);
              instance().disable_output(self.n);
            },
            PinMode::InputFloating => {
              instance().disable_pullup(self.n);
              instance().disable_output(self.n);
            }
          }
        }
        #[inline(always)]
        fn toggle(&self) {
          instance().toggle(self.n);
        }
        #[inline(always)]
        fn set_high(&self) {
          instance().set_high(self.n);
        }
        #[inline(always)]
        fn set_low(&self) {
          instance().set_low(self.n);
        }
        #[inline(always)]
        fn set(&self, high: bool) {
          match high {
            true  => instance().set_high(self.n),
            false => instance().set_low(self.n)
          }
        }
        #[inline(always)]
        fn get(&self) -> bool {
          instance().get(self.n)
        }
        fn set_interrupt_mode(&self, mode: InterruptMode) {
          instance().set_interrupt_mode(self.n, mode)
        }
        fn listen(&self, handler: PinIsrCallback<Self>){
          crate::hal::concurrency::interrupt::isolated(||{
            unsafe {
              PINS[self.n as usize].handler = handler;
            }
          });
        }
      }

      static mut INITIALISED: bool = false;

      static mut INSTANCE : DummyPortRegisterBlock = DummyPortRegisterBlock {
        pin: [false; 8],
        o_en: [false; 8],
        pu_en: [false; 8]
      };

      /**
       * Get an instance of this port's register block.  Also does any
       * static initialisation required of the device the first time it is
       * called.
       */
      #[inline(always)]
      pub fn instance() -> &'static mut DummyPortRegisterBlock  {
        unsafe {
          // Not sure if this is a compiler bug or what, but our static
          // muts don't seem to be correctly initialised, so we need to
          // do this here instead
          //
          // ( @todo investigate - Probably I need to amend my boot code to call
          //         something to do the initialisation for me )
          if(!INITIALISED){
            for pin in 0..=7 {
              PINS[pin].n = pin as u8;
              PINS[pin].handler = PinIsrCallback::Nop(());
            }
            INITIALISED = true;
          }

          &mut INSTANCE
        }
      }

      static mut PINS : [AtmelPin; 8] = [
        AtmelPin { n: 0, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 1, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 2, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 3, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 4, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 5, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 6, handler: PinIsrCallback::Nop(()) },
        AtmelPin { n: 7, handler: PinIsrCallback::Nop(()) },
      ];


      /**
       * Return a single pin instance wrapper.
       */
      pub fn pin_instance(pin: u8) -> &'static mut AtmelPin {
        unsafe {
          &mut PINS[pin as usize]
        }
      }
    }
  }
}