|
1 |
| -#define P0 ((struct gpio *) 0x50000000) |
2 |
| -#define P1 ((struct gpio *) 0x50000300) |
| 1 | +#pragma once |
3 | 2 |
|
4 |
| -enum { GPIO_MODE_INPUT, GPIO_MODE_OUTPUT }; |
5 |
| -enum { LOW, HIGH }; |
| 3 | +#include <stdbool.h> |
| 4 | +#include <stdint.h> |
6 | 5 |
|
7 |
| -struct gpio { |
8 |
| - volatile uint32_t RESERVED[321], OUT, OUTSET, OUTCLR, IN, DIR, DIRSET, DIRCLR, |
9 |
| - LATCH, DETECTMODE, RESERVED_SECOND[118], PIN_CNF[32]; |
10 |
| -}; |
| 6 | +#include "nrf52.h" |
11 | 7 |
|
12 |
| -void set_gpio_mode(struct gpio *port, int pin, int mode, int pull) { |
13 |
| - if (pull == 0) { |
14 |
| - port->PIN_CNF[pin] = mode << 0; |
15 |
| - } else { |
16 |
| - port->PIN_CNF[pin] = mode << 0 | pull << 2; |
17 |
| - } |
| 8 | +#define BIT(x) (1UL << (x)) |
| 9 | +#define CLRSET(R, CLEARMASK, SETMASK) (R) = ((R) & ~(CLEARMASK)) | (SETMASK) |
| 10 | +#define PIN(bank, num) ((((bank) - 'A') << 8) | (num)) |
| 11 | +#define PINNO(pin) (pin & 255) |
| 12 | +#define PINBANK(pin) (pin >> 8) |
| 13 | + |
| 14 | +static inline void spin(volatile uint32_t count) { |
| 15 | + while (count--) (void) 0; |
18 | 16 | }
|
19 | 17 |
|
20 |
| -int gpio_read(struct gpio *port, int pin) { |
21 |
| - uint32_t button = ~(port->IN); |
22 |
| - if (button & (1 << pin)) { |
23 |
| - return 1; |
24 |
| - } else { |
25 |
| - return 0; |
26 |
| - } |
| 18 | +#define GPIO(N) ((NRF_GPIO_Type *) ((NRF_P0_BASE) + 0x300 * (N))) |
| 19 | + |
| 20 | +static inline NRF_GPIO_Type *gpio_bank(uint16_t pin) { |
| 21 | + return GPIO(PINBANK(pin)); |
27 | 22 | }
|
28 |
| -void gpio_write(struct gpio *port, int pin, int value) { |
29 |
| - if (value == 0) { |
30 |
| - port->OUTSET = 1 << pin; |
31 |
| - } else { |
32 |
| - port->OUTCLR = 1 << pin; |
33 |
| - } |
| 23 | + |
| 24 | +enum { GPIO_MODE_INPUT = 0, GPIO_MODE_OUTPUT = 1 }; |
| 25 | +enum { GPIO_PULL_NONE = 0, GPIO_PULL_DOWN = 1, GPIO_PULL_UP = 3U }; |
| 26 | + |
| 27 | +void gpio_init(uint16_t pin, uint8_t mode, uint8_t pull) { |
| 28 | + NRF_GPIO_Type *gpio = gpio_bank(pin); |
| 29 | + gpio->PIN_CNF[pin] = (mode & 1U) << 0 | (pull & 3U) << 2U; |
34 | 30 | }
|
35 | 31 |
|
36 |
| -static inline void spin(volatile uint32_t count) { |
37 |
| - while (count--) (void) 0; |
| 32 | +static inline bool gpio_read(uint16_t pin) { |
| 33 | + NRF_GPIO_Type *gpio = gpio_bank(pin); |
| 34 | + return ~(gpio->IN) & BIT(PINNO(pin)); |
| 35 | +} |
| 36 | + |
| 37 | +static inline void gpio_write(uint16_t pin, bool value) { |
| 38 | + NRF_GPIO_Type *gpio = gpio_bank(pin); |
| 39 | + if (value) { |
| 40 | + gpio->OUTSET = BIT(PINNO(pin)); |
| 41 | + } else { |
| 42 | + gpio->OUTCLR = BIT(PINNO(pin)); |
| 43 | + } |
38 | 44 | }
|
0 commit comments