Zephyr GPIO驱动及使用方法

1. 参考说明
参考的单板: stm32f429i_disc1

2. 驱动加载方法 
// 文件: gpio_stm32.c (drivers\gpio)
static const struct gpio_driver_api gpio_stm32_driver = {
/* 以下为GPIO驱动操作函数,它们会最终调用soc_gpio.c(arch\arm\soc\st_stm32\stm32f4)中的GPIO配置底层函数,直接操作寄存器*/
.config = gpio_stm32_config,
.write = gpio_stm32_write,
.read = gpio_stm32_read,
.manage_callback = gpio_stm32_manage_callback,
.enable_callback = gpio_stm32_enable_callback,
.disable_callback = gpio_stm32_disable_callback,
};

#define GPIO_DEVICE_INIT(__name, __suffix, __base_addr, __port, __cenr, __bus) \   // 驱动注册
static const struct gpio_stm32_config gpio_stm32_cfg_## __suffix = { \
.base = (u32_t *)__base_addr, \
.port = __port, \
.pclken = { .bus = __bus, .enr = __cenr } \
}; \
static struct gpio_stm32_data gpio_stm32_data_## __suffix; \
DEVICE_AND_API_INIT(gpio_stm32_## __suffix, \
__name, \
gpio_stm32_init, /* 使能对应的GPIO时钟*/ \
&gpio_stm32_data_## __suffix, \
&gpio_stm32_cfg_## __suffix, \
POST_KERNEL, \
CONFIG_KERNEL_INIT_PRIORITY_DEVICE, \
&gpio_stm32_driver);   /*真正的GPIO操作函数 */

#define GPIO_DEVICE_INIT_STM32(__suffix, __SUFFIX) \
GPIO_DEVICE_INIT("GPIO" #__SUFFIX, __suffix, \
GPIO##__SUFFIX##_BASE, STM32_PORT##__SUFFIX, \
STM32_PERIPH_GPIO##__SUFFIX, \
STM32_CLOCK_BUS_GPIO)
 
#ifdef CONFIG_GPIO_STM32_PORTA    // 如果定义CONFIG_GPIO_STM32_PORTA,则加载GPIOA的驱动
GPIO_DEVICE_INIT_STM32(a, A);
#endif /* CONFIG_GPIO_STM32_PORTA */

2. 使用方法
1) 配置
# enable GPIO ports G
CONFIG_GPIO=y
CONFIG_GPIO_STM32_PORTG=y
2) 使用
#define PORT   "GPIOG"
#define PIN    13
struct device *dev;
dev = device_get_binding(PORT);
/* a. 用作输出,参考samples/basic/blinky */
gpio_pin_configure(dev, GPIO_PIN, GPIO_DIR_OUT);
gpio_pin_write(dev, GPIO_PIN, 1);
/* b. 用作输入,参考samples/basic/button */
#define EDGE   (GPIO_INT_EDGE | GPIO_INT_ACTIVE_LOW)
#define PULL_UP 0
void button_pressed(struct device *gpiob, struct gpio_callback *cb, u32_t pins) {
printk("Button pressed at %d\n", k_cycle_get_32());
}
static struct gpio_callback gpio_cb;
struct device *gpiob;
gpiob = device_get_binding(PORT);
gpio_pin_configure(gpiob, PIN, GPIO_DIR_IN | GPIO_INT |  PULL_UP | EDGE);
gpio_init_callback(&gpio_cb, button_pressed, BIT(PIN));
gpio_add_callback(gpiob, &gpio_cb);
gpio_pin_enable_callback(gpiob, PIN);
u32_t val = 0;
gpio_pin_read(gpiob, PIN, &val);

3. API说明
1) 常用API
gpio_pin_configure
gpio_pin_write
gpio_init_callback
gpio_add_callback
gpio_pin_enable_callback
gpio_pin_read
2) 说明
GPIO相关API是面向用户最上层操作函数,它们均来自gpio.h (include)文件,函数较为简单,且都具有相似的格式。
此处以gpio_pin_write为例做简要说明:
static inline int _impl_gpio_write(struct device *port, int access_op, u32_t pin, u32_t value)
{
// 获取驱动api,对应gpio_stm32.c (drivers\gpio)中的 static const struct gpio_driver_api gpio_stm32_driver 结构体
const struct gpio_driver_api *api = port->driver_api;
// 若是gpio_pin_read函数,则替换为api->read即可
return api->write(port, access_op, pin, value);
}

猜你喜欢

转载自blog.csdn.net/u012408797/article/details/80264670