1、工程创建
在zephyr目录下面的app目录下面添加工程nrf54l15_led_button文件夹。
添加prj.conf、CMakeLists.txt以及src目录下面的main.c
2、文件内容:
prj.conf
CONFIG_SHELL=y CONFIG_LOG=y CONFIG_GPIO=y
CMakeLists.txt
cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(nrf54l15_led_button)
target_sources(app PRIVATE src/main.c)main.c
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/sys/printk.h>
#define LED0_NODE DT_ALIAS(led0)
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET_OR(LED0_NODE, gpios, {0});
#define BUTTON0_NODE DT_ALIAS(sw0)
static const struct gpio_dt_spec button = GPIO_DT_SPEC_GET_OR(BUTTON0_NODE, gpios, {0});
static struct gpio_callback button_cb_data;
static bool led_state;
static void button_callback(const struct device *dev, struct gpio_callback *cb, uint32_t pins)
{
if (pins & BIT(button.pin)) {
/* Toggle LED state */
led_state = !led_state;
gpio_pin_set_dt(&led, led_state ? 0 : 1);
if (led_state) {
printk("[BTN] LED ON\n");
} else {
printk("[BTN] LED OFF\n");
}
}
}
int main(void)
{
int ret;
printk("=================================\n");
printk("nRF54L15-DK LED/Button Test\n");
printk("=================================\n");
if (!device_is_ready(led.port)) {
printk("LED device not ready\n");
return -ENODEV;
}
led_state = false;
ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT_INACTIVE);
if (ret != 0) {
printk("LED config failed: %d\n", ret);
return ret;
}
if (!device_is_ready(button.port)) {
printk("Button device not ready\n");
return -ENODEV;
}
ret = gpio_pin_configure_dt(&button, GPIO_INPUT | GPIO_PULL_UP);
if (ret != 0) {
printk("Button config failed: %d\n", ret);
return ret;
}
ret = gpio_pin_interrupt_configure_dt(&button, GPIO_INT_EDGE_FALLING);
if (ret != 0) {
printk("Interrupt config failed: %d\n", ret);
return ret;
}
gpio_init_callback(&button_cb_data, button_callback, BIT(button.pin));
gpio_add_callback(button.port, &button_cb_data);
printk("Ready! Press button SW1 on the board.\n");
while (1) {
k_sleep(K_SECONDS(1));
}
return 0;
}在prj.conf中开启shell、log实现日志打印,开启GPIO实现按键与LED灯
在main.c中注册按键的回调函数,同时添加led_state,实现LED灯翻转。
【编译与下载】
west build -b nrf54l15dk/nrf54l15/cpuapp
(.venv) PS D:\zephyr_w71\app\nrf54l15_led_button> west flash -r jlink -- west flash: rebuilding ninja: no work to do. -- west flash: using runner jlink -- runners.jlink: reset after flashing requested -- runners.jlink: JLink version: 9.24a -- runners.jlink: Flashing file: D:\zephyr_w71\app\nrf54l15_led_button\build\zephyr\zephyr.hex
由于开发板上有jlink-ob因此指定下载工具为jlink。
【实验效果】
下载好开发板后,打开串口助手,按下SW1打印日志如下,同时LED0也实现翻转效果

我要赚赏金
