|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 Renesas Electronics Corporation |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#include <zephyr/kernel.h> |
| 8 | +#include <zephyr/device.h> |
| 9 | +#include <zephyr/drivers/comparator.h> |
| 10 | +#include <zephyr/drivers/gpio.h> |
| 11 | +#include <zephyr/kernel.h> |
| 12 | +#include <zephyr/sys/util.h> |
| 13 | +#include <zephyr/sys/printk.h> |
| 14 | + |
| 15 | +#if DT_HAS_COMPAT_STATUS_OKAY(renesas_rx_lvd) |
| 16 | +#define LVD_DEV DT_INST(0, renesas_rx_lvd) |
| 17 | +#else |
| 18 | +#error "Please set the correct device" |
| 19 | +#endif |
| 20 | + |
| 21 | +static struct gpio_dt_spec led = GPIO_DT_SPEC_GET_OR(DT_ALIAS(led0), gpios, {0}); |
| 22 | +static const struct device *lvd_dev = DEVICE_DT_GET(LVD_DEV); |
| 23 | + |
| 24 | +#define VREF_MV (DT_PROP(LVD_DEV, voltage_level)) |
| 25 | + |
| 26 | +static void lvd_callback(const struct device *dev, void *user_data) |
| 27 | +{ |
| 28 | + int ret; |
| 29 | + |
| 30 | + printk("[WARNING] Voltage instability detected! Check power supply.\n"); |
| 31 | + gpio_pin_set_dt(&led, 1); |
| 32 | + |
| 33 | + ret = comparator_get_output(lvd_dev); |
| 34 | + if (ret < 0) { |
| 35 | + printk("Error: failed to get comparator output\n"); |
| 36 | + return; |
| 37 | + } |
| 38 | + printk("Comparator output is %s Vref (%.2fV)\n", ret ? "ABOVE" : "BELOW", |
| 39 | + ((double)VREF_MV / 100)); |
| 40 | +} |
| 41 | + |
| 42 | +int main(void) |
| 43 | +{ |
| 44 | + int ret; |
| 45 | + |
| 46 | + if (!device_is_ready(lvd_dev)) { |
| 47 | + printk("Comparator device not ready\n"); |
| 48 | + return 0; |
| 49 | + } |
| 50 | + |
| 51 | + ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE); |
| 52 | + if (ret != 0) { |
| 53 | + printk("Error: failed to configure LED\n"); |
| 54 | + return -EINVAL; |
| 55 | + } |
| 56 | + |
| 57 | + gpio_pin_set_dt(&led, 0); |
| 58 | + |
| 59 | + ret = comparator_get_output(lvd_dev); |
| 60 | + if (ret < 0) { |
| 61 | + printk("Error: failed to get comparator output\n"); |
| 62 | + return -EINVAL; |
| 63 | + } |
| 64 | + |
| 65 | + printk("Comparator output is %s Vref (%.2fV)\n", ret ? "ABOVE" : "BELOW", |
| 66 | + ((double)VREF_MV / 100)); |
| 67 | + |
| 68 | + ret = comparator_set_trigger(lvd_dev, COMPARATOR_TRIGGER_RISING_EDGE); |
| 69 | + if (ret < 0) { |
| 70 | + printk("Error: failed to set comparator trigger\n"); |
| 71 | + return -EINVAL; |
| 72 | + } |
| 73 | + |
| 74 | + ret = comparator_set_trigger_callback(lvd_dev, lvd_callback, NULL); |
| 75 | + if (ret < 0) { |
| 76 | + printk("Error: failed to set comparator callback\n"); |
| 77 | + return -EINVAL; |
| 78 | + } |
| 79 | + |
| 80 | + while (1) { |
| 81 | + k_sleep(K_MSEC(100)); |
| 82 | + } |
| 83 | +} |
0 commit comments