Leds and Button Sample
Last updated on: December 31, 2019
The leds and button sample configures the GPIO pins for the leds and button reading them from the Icarus device tree then sets up a callback for the button that when pressed allows the main loop to execute the code that changes the color of the led. Pressing the button multiple times cycles through multiple led colors.
The leds and buttons sample enables the following setting in the
which enables the use of the GPIO library.
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_DIR_OUT);gpio_pin_configure(gpio_dev, BLUE_LED, GPIO_DIR_OUT);gpio_pin_configure(gpio_dev, GREEN_LED, GPIO_DIR_OUT);
RED_LED, BLUE_LED, GREEN_LED defined as:
#define RED_LED LED0_GPIO_PIN#define GREEN_LED LED1_GPIO_PIN#define BLUE_LED LED2_GPIO_PIN
LED2_GPIO_PIN being the definitions of the led pins read from the Icarus device tree and
gpio_dev being the GPIO handle (see previous paragraph).
The button configuration is performed by the following calls:
gpio_pin_configure(gpio_dev, BUTTON, GPIO_DIR_IN | GPIO_PUD_PULL_UP | GPIO_INT | GPIO_INT_DEBOUNCE | GPIO_INT_EDGE);gpio_init_callback(&gpio_cb, button_pressed_callback, BIT(BUTTON));gpio_add_callback(gpio_dev, &gpio_cb);gpio_pin_enable_callback(gpio_dev, BUTTON);
These set up the button pin as input, pullup, make the button press interrupt based (adding a button pressed callback) and debounce it.
BUTTON is defined as:
#define BUTTON SW0_GPIO_PIN
SW0_GPIO_PIN being the button pin read from the Icarus device tree,
gpio_cb being of type
struct gpio_callback gpio_cb; and
gpio_dev being the GPIO handle (see first paragraph).
When the button is pressed, the led color changes.
In order to turn the red led on the following code is executed:
gpio_pin_write(gpio_dev, RED_LED, 1);
In order to turn the red led off the following code is executed:
gpio_pin_write(gpio_dev, RED_LED, 0);
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:
gpio_pin_write(gpio_dev, GREEN_LED, 1);gpio_pin_write(gpio_dev, RED_LED, 1);