|
| 1 | +/* |
| 2 | + * Copyright (c) 2021 Nordic Semiconductor ASA |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +#define DT_DRV_COMPAT zephyr_example_sensor |
| 7 | + |
| 8 | +#include <zephyr/device.h> |
| 9 | +#include <zephyr/drivers/gpio.h> |
| 10 | +#include <zephyr/drivers/sensor.h> |
| 11 | + |
| 12 | +#include <zephyr/logging/log.h> |
| 13 | +LOG_MODULE_REGISTER(example_sensor, CONFIG_SENSOR_LOG_LEVEL); |
| 14 | + |
| 15 | +struct example_sensor_data { |
| 16 | + int state; |
| 17 | +}; |
| 18 | + |
| 19 | +struct example_sensor_config { |
| 20 | + struct gpio_dt_spec input; |
| 21 | +}; |
| 22 | + |
| 23 | +static int example_sensor_sample_fetch(const struct device *dev, |
| 24 | + enum sensor_channel chan) |
| 25 | +{ |
| 26 | + const struct example_sensor_config *config = dev->config; |
| 27 | + struct example_sensor_data *data = dev->data; |
| 28 | + |
| 29 | + data->state = gpio_pin_get_dt(&config->input); |
| 30 | + |
| 31 | + return 0; |
| 32 | +} |
| 33 | + |
| 34 | +static int example_sensor_channel_get(const struct device *dev, |
| 35 | + enum sensor_channel chan, |
| 36 | + struct sensor_value *val) |
| 37 | +{ |
| 38 | + struct example_sensor_data *data = dev->data; |
| 39 | + |
| 40 | + if (chan != SENSOR_CHAN_PROX) { |
| 41 | + return -ENOTSUP; |
| 42 | + } |
| 43 | + |
| 44 | + val->val1 = data->state; |
| 45 | + |
| 46 | + return 0; |
| 47 | +} |
| 48 | + |
| 49 | +static const struct sensor_driver_api example_sensor_api = { |
| 50 | + .sample_fetch = &example_sensor_sample_fetch, |
| 51 | + .channel_get = &example_sensor_channel_get, |
| 52 | +}; |
| 53 | + |
| 54 | +static int example_sensor_init(const struct device *dev) |
| 55 | +{ |
| 56 | + const struct example_sensor_config *config = dev->config; |
| 57 | + |
| 58 | + int ret; |
| 59 | + |
| 60 | + if (!device_is_ready(config->input.port)) { |
| 61 | + LOG_ERR("Input GPIO not ready"); |
| 62 | + return -ENODEV; |
| 63 | + } |
| 64 | + |
| 65 | + ret = gpio_pin_configure_dt(&config->input, GPIO_INPUT); |
| 66 | + if (ret < 0) { |
| 67 | + LOG_ERR("Could not configure input GPIO (%d)", ret); |
| 68 | + return ret; |
| 69 | + } |
| 70 | + |
| 71 | + return 0; |
| 72 | +} |
| 73 | + |
| 74 | +#define EXAMPLE_SENSOR_INIT(i) \ |
| 75 | + static struct example_sensor_data example_sensor_data_##i; \ |
| 76 | + \ |
| 77 | + static const struct example_sensor_config example_sensor_config_##i = {\ |
| 78 | + .input = GPIO_DT_SPEC_INST_GET(i, input_gpios), \ |
| 79 | + }; \ |
| 80 | + \ |
| 81 | + DEVICE_DT_INST_DEFINE(i, example_sensor_init, NULL, \ |
| 82 | + &example_sensor_data_##i, \ |
| 83 | + &example_sensor_config_##i, POST_KERNEL, \ |
| 84 | + CONFIG_SENSOR_INIT_PRIORITY, &example_sensor_api); |
| 85 | + |
| 86 | +DT_INST_FOREACH_STATUS_OKAY(EXAMPLE_SENSOR_INIT) |
0 commit comments