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
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Interface for LEDs that abstract away polarity and pin.
//!
//!  Author: Philip Levis <pal@cs.stanford.edu>
//!  Date: July 31, 2015
//!

use crate::hil::gpio;

/// Simple on/off interface for LED pins.
///
/// Since GPIO pins are synchronous in Tock the LED interface is synchronous as
/// well.
pub trait Led {
    /// Initialize the LED. Must be called before the LED is used.
    fn init(&self);

    /// Turn the LED on.
    fn on(&self);

    /// Turn the LED off.
    fn off(&self);

    /// Toggle the LED.
    fn toggle(&self);

    /// Return the on/off state of the LED. `true` if the LED is on, `false` if
    /// it is off.
    fn read(&self) -> bool;
}

/// For LEDs in which on is when GPIO is high.
pub struct LedHigh<'a, P: gpio::Pin> {
    pub pin: &'a P,
}

/// For LEDs in which on is when GPIO is low.
pub struct LedLow<'a, P: gpio::Pin> {
    pub pin: &'a P,
}

impl<'a, P: gpio::Pin> LedHigh<'a, P> {
    pub fn new(p: &'a P) -> Self {
        Self { pin: p }
    }
}

impl<'a, P: gpio::Pin> LedLow<'a, P> {
    pub fn new(p: &'a P) -> Self {
        Self { pin: p }
    }
}

impl<P: gpio::Pin> Led for LedHigh<'_, P> {
    fn init(&self) {
        self.pin.make_output();
    }

    fn on(&self) {
        self.pin.set();
    }

    fn off(&self) {
        self.pin.clear();
    }

    fn toggle(&self) {
        self.pin.toggle();
    }

    fn read(&self) -> bool {
        self.pin.read()
    }
}

impl<P: gpio::Pin> Led for LedLow<'_, P> {
    fn init(&self) {
        self.pin.make_output();
    }

    fn on(&self) {
        self.pin.clear();
    }

    fn off(&self) {
        self.pin.set();
    }

    fn toggle(&self) {
        self.pin.toggle();
    }

    fn read(&self) -> bool {
        !self.pin.read()
    }
}