【前言】
掌握按键输入,是一个最基本的外设使用,本篇将在上一篇的基础上添加按键中断输入,来控制LED灯的翻转。
上篇的链接:【nRF7002DK】点灯-电子产品世界论坛
【按键的设备树】
在设备树文件<C:\ncs\v2.9.0\zephyr\boards\nordic\nrf7002dk\nrf5340_cpuapp_common.dtsi>中我看到了开发板有两个按键
分别为button_0、button_1:

同时又被取别名 sw0、sw1:

【程序编写】
1、先查找 led与button:
#define LED0_NODE DT_ALIAS(led0) static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios); #define BUTTON0_NODE DT_ALIAS(sw0) static const struct gpio_dt_spec button = GPIO_DT_SPEC_GET(BUTTON0_NODE, gpios);
2、初始化一个按键回调:
static struct gpio_callback button_cb_data;
3、编写按键回调函数,在回调函数中,我们对led进行翻转:
void button_pressed(const struct device *dev, struct gpio_callback *cb, uint32_t pins)
{
gpio_pin_toggle_dt(&led);
}4、初始化按键与LED:
int ret;
if (!device_is_ready(led.port)) {
return -1;
}
if(!device_is_ready(button.port)){
return -1;
}
ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE);
if (ret < 0) {
return -1;
}
ret = gpio_pin_configure_dt(&button, GPIO_INPUT);
if (ret < 0) {
return -1;
}
ret = gpio_pin_interrupt_configure_dt(&button, GPIO_INT_EDGE_TO_ACTIVE);
if (ret < 0) {
printf("Error %d: failed to configure interrupt on pin %s\n",
ret, button.port->name);
return -1;
}5、初始化按键回调,并把回调函数添加到button回调事件中:
gpio_init_callback(&button_cb_data, button_pressed, BIT(button.pin)); gpio_add_callback(button.port, &button_cb_data);
6、在while中添加休眠:
while (1) {
k_msleep(SLEEP_TIME_MS); // Put the main thread to sleep for 100ms for power
}【程序源码】
/*
* Copyright (c) 2016 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/gpio.h>
void button_pressed(const struct device *dev, struct gpio_callback *cb, uint32_t pins);
#define SLEEP_TIME_MS 10*60*1000
#define LED0_NODE DT_ALIAS(led0)
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios);
#define BUTTON0_NODE DT_ALIAS(sw0)
static const struct gpio_dt_spec button = GPIO_DT_SPEC_GET(BUTTON0_NODE, gpios);
static struct gpio_callback button_cb_data;
int main(void)
{
int ret;
if (!device_is_ready(led.port)) {
return -1;
}
if(!device_is_ready(button.port)){
return -1;
}
ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE);
if (ret < 0) {
return -1;
}
ret = gpio_pin_configure_dt(&button, GPIO_INPUT);
if (ret < 0) {
return -1;
}
ret = gpio_pin_interrupt_configure_dt(&button, GPIO_INT_EDGE_TO_ACTIVE);
if (ret < 0) {
printf("Error %d: failed to configure interrupt on pin %s\n",
ret, button.port->name);
return -1;
}
gpio_init_callback(&button_cb_data, button_pressed, BIT(button.pin));
gpio_add_callback(button.port, &button_cb_data);
while (1) {
k_msleep(SLEEP_TIME_MS); // Put the main thread to sleep for 100ms for power
}
}
void button_pressed(const struct device *dev, struct gpio_callback *cb, uint32_t pins)
{
gpio_pin_toggle_dt(&led);
}重新编译后下载到开发板,按下按键sw0就可以成功的翻LED灯了。
我要赚赏金
