gpio.h 2.08 KB
Newer Older
1
2
3
4
5
6
7
#pragma once

#include <avr/io.h>
#include <stdint.h>

enum modes
{
8
9
10
11
12
13
14
15
16
    INVERTED            = PORT_INVEN_bm,
    TOTEM_POLE          = PORT_OPC_TOTEM_gc,
    BUS_KEEPER          = PORT_OPC_BUSKEEPER_gc,
    TOTEM_PULL_UP       = PORT_OPC_PULLDOWN_gc,
    TOTEM_PULL_DOWN     = PORT_OPC_PULLUP_gc,
    WIRED_OR            = PORT_OPC_WIREDOR_gc,
    WIRED_AND           = PORT_OPC_WIREDAND_gc,
    WIRED_OR_PULL_DOWN  = PORT_OPC_WIREDORPULL_gc,
    WIRED_AND_PULL_UP   = PORT_OPC_WIREDANDPULL_gc
17
18
};

19
enum directions
20
21
22
23
24
25
26
{
    INPUT,
    OUTPUT
};

class gpio
{
27
28
29
30
    private:
        volatile PORT_t &port;
        uint8_t pin_bm;

31
    public:
32
33
        gpio(PORT_t &port, uint8_t pin_bm): port(port),
                                           pin_bm(pin_bm)
34
        {
35

36
37
        }

38
        void set_direction(directions direction)
39
        {
40
41
42
43
44
45
46
47
48
49
            if (direction == INPUT)       port.DIRCLR = pin_bm;
            else if (direction == OUTPUT) port.DIRSET = pin_bm;
            else return;
        }

        void set_mode(modes mode)
        {
            *(&port.PIN0CTRL+pin_bm) &= (0x38);
            *(&port.PIN0CTRL+pin_bm) |= mode;
        }
50

51
52
53
54
        void set_invert(bool state)
        {
            if (state) *(&port.PIN0CTRL+pin_bm) |=  PORT_INVEN_bm;
            else       *(&port.PIN0CTRL+pin_bm) &= ~PORT_INVEN_bm;
55
56
57
58
        }

        void on()
        {
59
            port.OUTSET = pin_bm;
60
61
62
63
        }

        void off()
        {
64
            port.OUTCLR = pin_bm;
65
66
67
68
        }

        void toggle()
        {
69
70
71
72
73
74
            port.OUTTGL = pin_bm;
        }

        bool read()
        {
            return port.IN & pin_bm;
75
76
77
        }
};

78
class output
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
    private:
        volatile PORT_t &port;
        uint8_t pin_bm;

    public:
        output(PORT_t &port, uint8_t pin_bm): port(port),
                                             pin_bm(pin_bm)
        {
            port.DIRSET = pin_bm;
        }

        void on()
        {
            port.OUTSET = pin_bm;
        }

        void off()
        {
            port.OUTCLR = pin_bm;
        }

        void toggle()
        {
            port.OUTTGL = pin_bm;
        }
105
};