1 /*
2 * Copyright (c) 2016 Open-RnD Sp. z o.o.
3 * Copyright (c) 2020 Nordic Semiconductor ASA
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * NOTE: If you are looking into an implementation of button events with
8 * debouncing, check out `input` subsystem and `samples/subsys/input/input_dump`
9 * example instead.
10 */
11
12 #include <zephyr/kernel.h>
13 #include <zephyr/device.h>
14 #include <zephyr/drivers/gpio.h>
15 #include <zephyr/sys/util.h>
16 #include <zephyr/sys/printk.h>
17 #include <inttypes.h>
18
19 #define SLEEP_TIME_MS 1
20
21 /*
22 * Get button configuration from the devicetree sw0 alias. This is mandatory.
23 */
24 #define SW0_NODE DT_ALIAS(sw0)
25 #if !DT_NODE_HAS_STATUS_OKAY(SW0_NODE)
26 #error "Unsupported board: sw0 devicetree alias is not defined"
27 #endif
28 static const struct gpio_dt_spec button = GPIO_DT_SPEC_GET_OR(SW0_NODE, gpios,
29 {0});
30 static struct gpio_callback button_cb_data;
31
32 /*
33 * The led0 devicetree alias is optional. If present, we'll use it
34 * to turn on the LED whenever the button is pressed.
35 */
36 static struct gpio_dt_spec led = GPIO_DT_SPEC_GET_OR(DT_ALIAS(led0), gpios,
37 {0});
38
button_pressed(const struct device * dev,struct gpio_callback * cb,uint32_t pins)39 void button_pressed(const struct device *dev, struct gpio_callback *cb,
40 uint32_t pins)
41 {
42 printk("Button pressed at %" PRIu32 "\n", k_cycle_get_32());
43 }
44
main(void)45 int main(void)
46 {
47 int ret;
48
49 if (!gpio_is_ready_dt(&button)) {
50 printk("Error: button device %s is not ready\n",
51 button.port->name);
52 return 0;
53 }
54
55 ret = gpio_pin_configure_dt(&button, GPIO_INPUT);
56 if (ret != 0) {
57 printk("Error %d: failed to configure %s pin %d\n",
58 ret, button.port->name, button.pin);
59 return 0;
60 }
61
62 ret = gpio_pin_interrupt_configure_dt(&button,
63 GPIO_INT_EDGE_TO_ACTIVE);
64 if (ret != 0) {
65 printk("Error %d: failed to configure interrupt on %s pin %d\n",
66 ret, button.port->name, button.pin);
67 return 0;
68 }
69
70 gpio_init_callback(&button_cb_data, button_pressed, BIT(button.pin));
71 gpio_add_callback(button.port, &button_cb_data);
72 printk("Set up button at %s pin %d\n", button.port->name, button.pin);
73
74 if (led.port && !gpio_is_ready_dt(&led)) {
75 printk("Error %d: LED device %s is not ready; ignoring it\n",
76 ret, led.port->name);
77 led.port = NULL;
78 }
79 if (led.port) {
80 ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT);
81 if (ret != 0) {
82 printk("Error %d: failed to configure LED device %s pin %d\n",
83 ret, led.port->name, led.pin);
84 led.port = NULL;
85 } else {
86 printk("Set up LED at %s pin %d\n", led.port->name, led.pin);
87 }
88 }
89
90 printk("Press the button\n");
91 if (led.port) {
92 while (1) {
93 /* If we have an LED, match its state to the button's. */
94 int val = gpio_pin_get_dt(&button);
95
96 if (val >= 0) {
97 gpio_pin_set_dt(&led, val);
98 }
99 k_msleep(SLEEP_TIME_MS);
100 }
101 }
102 return 0;
103 }
104