From ea3ab2e2638945e47872f081fb45a1bbc29937fe Mon Sep 17 00:00:00 2001 From: Alex Voinea Date: Wed, 12 May 2021 16:49:02 +0300 Subject: [PATCH] gpio hal prototype --- src/hal/gpio.h | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/hal/pins.h | 4 +-- 2 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 src/hal/gpio.h diff --git a/src/hal/gpio.h b/src/hal/gpio.h new file mode 100644 index 0000000..236e40f --- /dev/null +++ b/src/hal/gpio.h @@ -0,0 +1,82 @@ +#include +#include + +namespace hal { +namespace gpio { + +typedef struct +{ + volatile uint8_t PINx; + volatile uint8_t DDRx; + volatile uint8_t PORTx; +} GPIO_TypeDef; + + enum class Mode + { + input = 0, + output, + }; + + enum class Pull + { + none = 0, + up, + down, //not available on the AVR + }; + + enum class Level + { + low = 0, + high, + }; + +struct GPIO_InitTypeDef +{ + Mode mode; + Pull pull; + Level level; + inline GPIO_InitTypeDef() : mode(Mode::input), pull(Pull::none){}; + inline GPIO_InitTypeDef(Mode mode, Pull pull) : mode(mode), pull(pull) {}; + inline GPIO_InitTypeDef(Mode mode, Level level) : mode(mode), level(level) {}; +}; + +inline void WritePin(GPIO_TypeDef * const port, const uint8_t pin, Level level) +{ + if (level == Level::high) + port->PORTx |= (1 << pin); + else + port->PORTx &= ~(1 << pin); +} + +inline Level ReadPin(GPIO_TypeDef * const port, const uint8_t pin) +{ + return (Level)(port->PINx & (1 << pin)); +} + +inline void TogglePin(GPIO_TypeDef * const port, const uint8_t pin) +{ + port->PINx |= (1 << pin); +} + +inline void Init(GPIO_TypeDef * const port, const uint8_t pin, GPIO_InitTypeDef GPIO_Init) +{ + if (GPIO_Init.mode == Mode::output) + { + WritePin(port, pin, GPIO_Init.level); + port->DDRx |= (1 << pin); + } + else + { + port->DDRx &= ~(1 << pin); + WritePin(port, pin, (Level)GPIO_Init.pull); + } +} + +} +} + +#define GPIOB ((hal::gpio::GPIO_TypeDef *)&PINB) +#define GPIOC ((hal::gpio::GPIO_TypeDef *)&PINC) +#define GPIOD ((hal::gpio::GPIO_TypeDef *)&PIND) +#define GPIOE ((hal::gpio::GPIO_TypeDef *)&PINE) +#define GPIOF ((hal::gpio::GPIO_TypeDef *)&PINF) \ No newline at end of file diff --git a/src/hal/pins.h b/src/hal/pins.h index 34a30f7..8745ad5 100644 --- a/src/hal/pins.h +++ b/src/hal/pins.h @@ -5,9 +5,7 @@ namespace hal { namespace pins { - /// pin access routines - void WritePin(uint8_t pin, uint8_t value); - uint8_t ReadPin(uint8_t pin); + /// pin definitions } // namespace pins } // namespace hal