Leds and Button Sample

Last updated on: November 16, 2020

Introduction

The "Leds and Button Sample" cycles through multiple LED colors, one color at a time, on each press of the button. The LEDs and button are initialized using information directly from the Icarus device tree.

Download sample from Icarus - LEDs and Button Sample

Project configuration

The sample enables the GPIO library in the prj.conf file as follows:

CONFIG_GPIO=y

Code explanation

The sample gets the GPIO handle from the Icarus device tree to use it in the configuration of the button and leds pins (gpio_dev = device_get_binding(DT_GPIO_P0_DEV_NAME);) then initializes the leds and button. The following calls initialize the led pins and set them as outputs:

gpio_pin_configure(gpio_dev, RED_LED, GPIO_OUTPUT_HIGH);
gpio_pin_configure(gpio_dev, BLUE_LED, GPIO_OUTPUT_HIGH);
gpio_pin_configure(gpio_dev, GREEN_LED, GPIO_OUTPUT_HIGH);

with the RED_LED_PIN, GREEN_LED_PIN, BLUE_LED_PIN defined as:

#define RED_LED_PIN DT_GPIO_PIN(DT_NODELABEL(red_led), gpios)
#define GREEN_LED_PIN DT_GPIO_PIN(DT_NODELABEL(green_led), gpios)
#define BLUE_LED_PIN DT_GPIO_PIN(DT_NODELABEL(blue_led), gpios)

The button configuration is performed by the following calls:

int ret = gpio_pin_configure(gpio_dev, BUTTON_GPIO_PIN, BUTTON_GPIO_FLAGS);
if (ret != 0) {
printk("Error %d: failed to configure %s pin %d\n",
ret, BUTTON_GPIO_LABEL, BUTTON_GPIO_PIN);
return false;
}
ret = gpio_pin_interrupt_configure(gpio_dev,
BUTTON_GPIO_PIN,
GPIO_INT_EDGE_TO_ACTIVE);
if (ret != 0) {
printk("Error %d: failed to configure interrupt on %s pin %d\n",
ret, BUTTON_GPIO_LABEL, BUTTON_GPIO_PIN);
return false;
}
gpio_init_callback(&gpio_cb, button_pressed_callback, BIT(BUTTON_GPIO_PIN));
gpio_add_callback(gpio_dev, &gpio_cb);

These set up the button pin according to the flags from the device tree (input, pull-up, active low) and enable the button press interrupt.

In order to turn a led on, the following code is executed:

gpio_pin_set(gpio_dev, RED_LED_PIN, LED_ON);

In order to turn a led off, the following code is executed:

gpio_pin_set(gpio_dev, RED_LED_PIN, LED_OFF);

The other colors follow the same model, the only difference being the pin that is used. To use composed colors you need to turn on multiple leds at the same time. For example to make the led yellow, make the the red and green led pins high at the same time: