1 /*
2 * Copyright (c) 2019 Manivannan Sadhasivam
3 * Copyright (c) 2020 Andreas Sandberg
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8 #include <drivers/gpio.h>
9 #include <zephyr.h>
10
11 #include "sx126x_common.h"
12
13 #include <logging/log.h>
14 LOG_MODULE_DECLARE(sx126x, CONFIG_LORA_LOG_LEVEL);
15
16 static const struct gpio_dt_spec sx126x_gpio_reset = GPIO_DT_SPEC_INST_GET(
17 0, reset_gpios);
18 static const struct gpio_dt_spec sx126x_gpio_busy = GPIO_DT_SPEC_INST_GET(
19 0, busy_gpios);
20 static const struct gpio_dt_spec sx126x_gpio_dio1 = GPIO_DT_SPEC_INST_GET(
21 0, dio1_gpios);
22
sx126x_reset(struct sx126x_data * dev_data)23 void sx126x_reset(struct sx126x_data *dev_data)
24 {
25 gpio_pin_set_dt(&sx126x_gpio_reset, 1);
26 k_sleep(K_MSEC(20));
27 gpio_pin_set_dt(&sx126x_gpio_reset, 0);
28 k_sleep(K_MSEC(10));
29 }
30
sx126x_is_busy(struct sx126x_data * dev_data)31 bool sx126x_is_busy(struct sx126x_data *dev_data)
32 {
33 return gpio_pin_get_dt(&sx126x_gpio_busy);
34 }
35
sx126x_get_dio1_pin_state(struct sx126x_data * dev_data)36 uint32_t sx126x_get_dio1_pin_state(struct sx126x_data *dev_data)
37 {
38 return gpio_pin_get_dt(&sx126x_gpio_dio1) > 0 ? 1U : 0U;
39 }
40
sx126x_dio1_irq_enable(struct sx126x_data * dev_data)41 void sx126x_dio1_irq_enable(struct sx126x_data *dev_data)
42 {
43 gpio_pin_interrupt_configure_dt(&sx126x_gpio_dio1,
44 GPIO_INT_EDGE_TO_ACTIVE);
45 }
46
sx126x_dio1_irq_disable(struct sx126x_data * dev_data)47 void sx126x_dio1_irq_disable(struct sx126x_data *dev_data)
48 {
49 gpio_pin_interrupt_configure_dt(&sx126x_gpio_dio1,
50 GPIO_INT_DISABLE);
51 }
52
sx126x_dio1_irq_callback(const struct device * dev,struct gpio_callback * cb,uint32_t pins)53 static void sx126x_dio1_irq_callback(const struct device *dev,
54 struct gpio_callback *cb, uint32_t pins)
55 {
56 struct sx126x_data *dev_data = CONTAINER_OF(cb, struct sx126x_data,
57 dio1_irq_callback);
58
59 if (pins & BIT(sx126x_gpio_dio1.pin)) {
60 k_work_submit(&dev_data->dio1_irq_work);
61 }
62 }
63
sx126x_variant_init(const struct device * dev)64 int sx126x_variant_init(const struct device *dev)
65 {
66 struct sx126x_data *dev_data = dev->data;
67
68 if (gpio_pin_configure_dt(&sx126x_gpio_reset, GPIO_OUTPUT_ACTIVE) ||
69 gpio_pin_configure_dt(&sx126x_gpio_busy, GPIO_INPUT) ||
70 gpio_pin_configure_dt(&sx126x_gpio_dio1,
71 GPIO_INPUT | GPIO_INT_DEBOUNCE)) {
72 LOG_ERR("GPIO configuration failed.");
73 return -EIO;
74 }
75
76 gpio_init_callback(&dev_data->dio1_irq_callback,
77 sx126x_dio1_irq_callback, BIT(sx126x_gpio_dio1.pin));
78 if (gpio_add_callback(sx126x_gpio_dio1.port,
79 &dev_data->dio1_irq_callback) < 0) {
80 LOG_ERR("Could not set GPIO callback for DIO1 interrupt.");
81 return -EIO;
82 }
83
84 return 0;
85 }
86