Add gpio.{h, c}

This commit is contained in:
Alexander Heldt
2024-07-28 11:42:38 +02:00
parent 9b1e1b6f21
commit a8a5e21b77
14 changed files with 8228 additions and 721 deletions

16
src/gpio.c Normal file
View File

@@ -0,0 +1,16 @@
#include <inttypes.h>
#include <stdbool.h>
#include "gpio.h"
void gpio_set_mode(uint16_t pin, GPIO_MODE mode) {
struct gpio *gpio = GPIO(PINPORT(pin)); // GPIO port address
int pn = PINNUM(pin); // Pin number
gpio->MODER &= ~(0x0011 << (pn * 2)); // Clear existing setting. Each pin uses 2 bits
gpio->MODER |= (mode & 0b011) << (pn * 2); // Set new mode. Each pin uses 2 bits
}
void gpio_write(uint16_t pin, bool val) {
struct gpio *gpio = GPIO(PINPORT(pin));
gpio->BSRR = (0b0011 << PINNUM(pin)) << (val ? 0 : 16);
}

42
src/gpio.h Normal file
View File

@@ -0,0 +1,42 @@
#ifndef GPIO_H_
#define GPIO_H_
#include <stdbool.h>
#include <inttypes.h>
struct gpio {
volatile uint32_t MODER; // Port mode register
volatile uint32_t OTYPER; // Port output type register
volatile uint32_t OSPEEDR; // Port output speed register
volatile uint32_t PUPDR; // Port pull-up/pull-down register
volatile uint32_t IDR; // Port input data register
volatile uint32_t ODR; // Port output data register
volatile uint32_t BSRR; // Port bit set/reset register
volatile uint32_t LCKR; // Port configuration lock register
volatile uint32_t AFRL[2]; // Alternative function low register
volatile uint32_t AFRH[2]; // Alternative function high register
};
#define GPIO_BASE_ADDR (0x40020000U)
#define GPIO_PORT_OFFSET (0x400U)
#define GPIO(port) ((struct gpio*)(uintptr_t)(GPIO_BASE_ADDR + (GPIO_PORT_OFFSET * port)))
#define BIT(x) (1 << x)
// Create a 16bit number from a port and pin
#define PIN(port, num) ((((port) - 'A') << 8) | num)
// get the lower byte from a PIN
#define PINNUM(pin) (pin & 0b1111)
// get the upper byte from a PIN
#define PINPORT(pin) (pin >> 8)
typedef enum {
GPIO_MODE_INPUT,
GPIO_MODE_OUTPUT,
GPIO_MODE_AF,
GPIO_MODE_ANALOG
} GPIO_MODE;
void gpio_set_mode(uint16_t pin, GPIO_MODE mode);
void gpio_write(uint16_t pin, bool val);
#endif