We can configure an on-board button as an input to detect presses and turn on an LED. This time, we define a node compatible with the gpio-keys
driver, which allows us to define child nodes representing buttons or keys.
In this example, we also added aliases to illustrate alternatives to the label names. This provides an extra layer of abstraction, making the software more hardware-agnostic
main.c
#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>
/* Get the devicetree alias for led0 and button 0*/
#define LED0 DT_ALIAS( myled )
#define BTN0 DT_ALIAS( mybtn )
/* Get GPIO specification for button0 from devicetree */
const struct gpio_dt_spec btn = GPIO_DT_SPEC_GET( BTN0, gpios );
/* Get GPIO specification for led0 from devicetree */
const struct gpio_dt_spec led = GPIO_DT_SPEC_GET( LED0, gpios );
int main( void )
{
/* Configure button0 as input*/
gpio_pin_configure_dt( &btn, GPIO_INPUT );
/* Configure led0 as output */
gpio_pin_configure_dt( &led, GPIO_OUTPUT );
while(1)
{
/* Get logical level of button0 */
uint8_t state = gpio_pin_get_dt( &btn );
/* Set logical level of led */
gpio_pin_set_dt( &led, state );
k_msleep( 500 );
}
return 0;
}
app.overlay
/ {
/* Create a node and called leds */
myLeds: myLeds {
/* We indicate we are going to use gpio-leds driver */
compatible = "gpio-leds";
/* Sub-node for one led in gpio2 pin 9, with the led been turn on
with a high logic level */
myLed_0: myLed-0 {
gpios= <&gpio2 9 GPIO_ACTIVE_HIGH>;
label = "User LD0";
};
};
/* Create a node called button */
myBtns: myBtns {
/* We indicate we are going to use gpio-keys driver */
compatible = "gpio-keys";
/* Sub-node for one button in gpio1 pin 13, connected to a internal pullup */
myBtn_0: myBtn-0 {
gpios = <&gpio1 13 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>;
label = "User BTN0";
};
};
aliases {
myLed = &myLed_0;
myBtn = &myBtn_0;
};
};
prj.conf
# Disable optimizations
CONFIG_NO_OPTIMIZATIONS=y
# Include GPIO driver in system config ( Kconfig )
CONFIG_GPIO=y