1 /*
2 * Copyright (c) 2021 Nordic Semiconductor ASA
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/init.h>
8 #include <zephyr/drivers/gpio.h>
9 #include <zephyr/drivers/pinctrl.h>
10
11 /* make sure devices and remap hook are initialized in the correct order */
12 BUILD_ASSERT((CONFIG_GPIO_INIT_PRIORITY < CONFIG_REMAP_INIT_PRIORITY) &&
13 (CONFIG_REMAP_INIT_PRIORITY < CONFIG_SERIAL_INIT_PRIORITY),
14 "Device driver priorities are not set correctly");
15
16 PINCTRL_DT_DEV_CONFIG_DECLARE(DT_NODELABEL(uart0));
17
18 /* UART0 alternative configurations (default and sleep states) */
19 PINCTRL_DT_STATE_PINS_DEFINE(DT_PATH(zephyr_user), uart0_alt_default);
20 #ifdef CONFIG_PM_DEVICE
21 PINCTRL_DT_STATE_PINS_DEFINE(DT_PATH(zephyr_user), uart0_alt_sleep);
22 #endif
23
24 static const struct pinctrl_state uart0_alt[] = {
25 PINCTRL_DT_STATE_INIT(uart0_alt_default, PINCTRL_STATE_DEFAULT),
26 #ifdef CONFIG_PM_DEVICE
27 PINCTRL_DT_STATE_INIT(uart0_alt_sleep, PINCTRL_STATE_SLEEP),
28 #endif
29 };
30
remap_pins(void)31 static int remap_pins(void)
32 {
33 int ret;
34 const struct gpio_dt_spec button = GPIO_DT_SPEC_GET_OR(DT_ALIAS(sw0),
35 gpios, {0});
36
37
38 if (!gpio_is_ready_dt(&button)) {
39 return -ENODEV;
40 }
41
42 ret = gpio_pin_configure_dt(&button, GPIO_INPUT);
43 if (ret < 0) {
44 return ret;
45 }
46
47 /* remap UART0 pins if button is pressed */
48 if (gpio_pin_get_dt(&button)) {
49 struct pinctrl_dev_config *uart0_config =
50 PINCTRL_DT_DEV_CONFIG_GET(DT_NODELABEL(uart0));
51
52 return pinctrl_update_states(uart0_config, uart0_alt,
53 ARRAY_SIZE(uart0_alt));
54
55 }
56
57 return 0;
58 }
59
60 SYS_INIT(remap_pins, PRE_KERNEL_1, CONFIG_REMAP_INIT_PRIORITY);
61