You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.2 KiB

#include <stm32f4xx.h>
#include "gpio.h"
static GPIO_TypeDef * __get_port(uint32_t _pin, uint32_t *_rcc)
{
int x, n, port = (_pin >> PORT_SHIFT) & 0xff;
static struct mapper {
char ascii;
GPIO_TypeDef *port;
uint32_t rcc;
} __maps[] = {
{'A', GPIOA, RCC_AHB1Periph_GPIOA},
{'B', GPIOB, RCC_AHB1Periph_GPIOB},
{'C', GPIOC, RCC_AHB1Periph_GPIOC},
{'D', GPIOD, RCC_AHB1Periph_GPIOD},
{'E', GPIOE, RCC_AHB1Periph_GPIOE},
{'F', GPIOF, RCC_AHB1Periph_GPIOF},
{'G', GPIOG, RCC_AHB1Periph_GPIOG},
{'H', GPIOH, RCC_AHB1Periph_GPIOH},
{'I', GPIOI, RCC_AHB1Periph_GPIOI},
{'J', GPIOJ, RCC_AHB1Periph_GPIOJ},
{'K', GPIOK, RCC_AHB1Periph_GPIOK},
};
n = sizeof __maps / sizeof __maps[0];
for (x = 0; x < n; ++x) {
if (__maps[x].ascii == port) {
if (_rcc) {
*_rcc = __maps[x].rcc;
}
return __maps[x].port;
}
}
return 0;
}
int gpio_init(uint32_t _pin, uint32_t dir)
{
GPIO_InitTypeDef gpio_conf;
GPIO_TypeDef *gpio_port;
uint32_t rcc = 0;
if ((gpio_port = __get_port(_pin, &rcc)) == 0) {
return -1;
}
RCC_AHB1PeriphClockCmd(rcc, ENABLE);
GPIO_StructInit(&gpio_conf);
gpio_conf.GPIO_Pin = _pin & PIN_MASK;
gpio_conf.GPIO_Mode = dir & 0xf;
gpio_conf.GPIO_OType = (dir >> 4) & 0xf;
gpio_conf.GPIO_PuPd = (dir >> 8) & 0xf;
gpio_conf.GPIO_Speed = (dir >> 12) & 0xf;
GPIO_Init(gpio_port, &gpio_conf);
return 0;
}
int gpio_read(uint32_t _pin)
{
int pin = _pin & PIN_MASK;
GPIO_TypeDef *gpio_port = __get_port(_pin, 0);
if (gpio_port) {
return GPIO_ReadInputDataBit(gpio_port, pin);
}
return -1;
}
int gpio_write(uint32_t _pin, int value)
{
int pin = _pin & PIN_MASK;
GPIO_TypeDef *gpio_port = __get_port(_pin, 0);
if (gpio_port) {
GPIO_WriteBit(gpio_port, pin, value ? Bit_SET : Bit_RESET);
return 0;
}
return -1;
}
int gpio_toggle(uint32_t _pin)
{
int pin = _pin & PIN_MASK;
GPIO_TypeDef *gpio_port = __get_port(_pin, 0);
if (gpio_port) {
GPIO_ToggleBits(gpio_port, pin);
return 0;
}
return -1;
}