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