GPIO hal prototype (#9)

* gpio hal prototype
* Example gpio hal usage
* Use uint8_t for GPIO enums
pull/14/head
Alex Voinea 2021-05-14 16:42:41 +03:00 committed by GitHub
parent 1887576429
commit 47400f16c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 85 additions and 3 deletions

76
src/hal/gpio.h Normal file
View File

@ -0,0 +1,76 @@
#include <inttypes.h>
#include <avr/io.h>
namespace hal {
namespace gpio {
struct GPIO_TypeDef {
volatile uint8_t PINx;
volatile uint8_t DDRx;
volatile uint8_t PORTx;
};
enum class Mode : uint8_t {
input = 0,
output,
};
enum class Pull : uint8_t {
none = 0,
up,
down, //not available on the AVR
};
enum class Level : uint8_t {
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)

View File

@ -5,9 +5,7 @@
namespace hal { namespace hal {
namespace pins { namespace pins {
/// pin access routines /// pin definitions
void WritePin(uint8_t pin, uint8_t value);
uint8_t ReadPin(uint8_t pin);
} // namespace pins } // namespace pins
} // namespace hal } // namespace hal

View File

@ -1,8 +1,11 @@
#include "logic/mm_control.h" #include "logic/mm_control.h"
#include "hal/gpio.h"
/// One-time setup of HW and SW components /// One-time setup of HW and SW components
/// Called before entering the loop() function /// Called before entering the loop() function
void setup(){ void setup(){
using namespace hal::gpio;
hal::gpio::Init(GPIOB, 1, GPIO_InitTypeDef(Mode::output, Level::low));
} }
@ -27,6 +30,11 @@ void loop(){
int main() { int main() {
setup(); setup();
for(;;){ for(;;){
using namespace hal::gpio;
WritePin(GPIOB, 5, Level::low);
TogglePin(GPIOB, 6);
if (hal::gpio::ReadPin(GPIOB, 7) == hal::gpio::Level::low)
break;
loop(); loop();
} }
return 0; return 0;