From 82c5d1542d907ec15bd39ac10d1b7cea0dd4f19d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20J=C3=A4ger?= Date: Sat, 31 Oct 2026 15:19:14 +0100 Subject: [PATCH] drivers: daq: add data acquisition driver Add a Zephyr driver for the data acquisition (DAQ), i.e. continuous sampling of all analog inputs with 1 kHz, low-pass filtering of the readings and checking them against upper and lower limits. It is based on the existing implementation in the application. The driver consists of a common part (filtering, alerts, scaling and calibration) and backends for the different ADC types: - STM32 ADCs with a fixed channel sequence (STM32F0, STM32L0 and newly supported STM32G0) - STM32 ADCs with a configurable channel sequence (STM32G4) - Emulated DAQ for tests on native_sim Compared to the application implementation, the position of the readings in the DMA buffer is determined by the driver, so that the inputs can be specified in any order in the devicetree. The factory calibration values for the internal reference voltage and temperature sensor are taken from the STM32 LL headers. Co-Authored-By: Claude Opus 5.5 --- drivers/CMakeLists.txt | 1 + drivers/Kconfig | 1 + drivers/daq/CMakeLists.txt | 9 + drivers/daq/Kconfig | 54 +++ drivers/daq/daq_common.c | 259 +++++++++++++ drivers/daq/daq_common.h | 140 +++++++ drivers/daq/daq_emul.c | 142 ++++++++ drivers/daq/daq_stm32.h | 23 ++ drivers/daq/daq_stm32_chsel.c | 240 ++++++++++++ drivers/daq/daq_stm32_rank.c | 342 ++++++++++++++++++ dts/bindings/daq/daq-common.yaml | 55 +++ dts/bindings/daq/libresolar,daq-emul.yaml | 11 + dts/bindings/daq/libresolar,stm32-daq.yaml | 13 + include/libresolar/drivers/daq.h | 230 ++++++++++++ include/libresolar/drivers/daq_emul.h | 93 +++++ tests/drivers/daq/CMakeLists.txt | 8 + tests/drivers/daq/boards/native_sim.overlay | 37 ++ .../daq/boards/native_sim_native_64.overlay | 37 ++ tests/drivers/daq/prj.conf | 1 + tests/drivers/daq/src/main.c | 311 ++++++++++++++++ tests/drivers/daq/testcase.yaml | 10 + 21 files changed, 2017 insertions(+) create mode 100644 drivers/daq/CMakeLists.txt create mode 100644 drivers/daq/Kconfig create mode 100644 drivers/daq/daq_common.c create mode 100644 drivers/daq/daq_common.h create mode 100644 drivers/daq/daq_emul.c create mode 100644 drivers/daq/daq_stm32.h create mode 100644 drivers/daq/daq_stm32_chsel.c create mode 100644 drivers/daq/daq_stm32_rank.c create mode 100644 dts/bindings/daq/daq-common.yaml create mode 100644 dts/bindings/daq/libresolar,daq-emul.yaml create mode 100644 dts/bindings/daq/libresolar,stm32-daq.yaml create mode 100644 include/libresolar/drivers/daq.h create mode 100644 include/libresolar/drivers/daq_emul.h create mode 100644 tests/drivers/daq/CMakeLists.txt create mode 100644 tests/drivers/daq/boards/native_sim.overlay create mode 100644 tests/drivers/daq/boards/native_sim_native_64.overlay create mode 100644 tests/drivers/daq/prj.conf create mode 100644 tests/drivers/daq/src/main.c create mode 100644 tests/drivers/daq/testcase.yaml diff --git a/drivers/CMakeLists.txt b/drivers/CMakeLists.txt index c7644ee..af26fdb 100644 --- a/drivers/CMakeLists.txt +++ b/drivers/CMakeLists.txt @@ -1,4 +1,5 @@ # Copyright (c) The Libre Solar Project Contributors # SPDX-License-Identifier: Apache-2.0 +add_subdirectory_ifdef(CONFIG_DAQ daq) add_subdirectory_ifdef(CONFIG_HALF_BRIDGE half_bridge) diff --git a/drivers/Kconfig b/drivers/Kconfig index cc3d638..91ce843 100644 --- a/drivers/Kconfig +++ b/drivers/Kconfig @@ -3,6 +3,7 @@ menu "Libre Solar drivers" +rsource "daq/Kconfig" rsource "half_bridge/Kconfig" endmenu diff --git a/drivers/daq/CMakeLists.txt b/drivers/daq/CMakeLists.txt new file mode 100644 index 0000000..9fd32e4 --- /dev/null +++ b/drivers/daq/CMakeLists.txt @@ -0,0 +1,9 @@ +# Copyright (c) The Libre Solar Project Contributors +# SPDX-License-Identifier: Apache-2.0 + +zephyr_library() + +zephyr_library_sources(daq_common.c) +zephyr_library_sources_ifdef(CONFIG_DAQ_STM32_CHSEL daq_stm32_chsel.c) +zephyr_library_sources_ifdef(CONFIG_DAQ_STM32_RANK daq_stm32_rank.c) +zephyr_library_sources_ifdef(CONFIG_DAQ_EMUL daq_emul.c) diff --git a/drivers/daq/Kconfig b/drivers/daq/Kconfig new file mode 100644 index 0000000..676aab0 --- /dev/null +++ b/drivers/daq/Kconfig @@ -0,0 +1,54 @@ +# Copyright (c) The Libre Solar Project Contributors +# SPDX-License-Identifier: Apache-2.0 + +menuconfig DAQ + bool "Data acquisition (DAQ) drivers" + default y if DT_HAS_LIBRESOLAR_STM32_DAQ_ENABLED + default y if DT_HAS_LIBRESOLAR_DAQ_EMUL_ENABLED + help + Enable drivers for data acquisition, i.e. continuous sampling, filtering and limit + checking of analog inputs. + +if DAQ + +config DAQ_INIT_PRIORITY + int "DAQ init priority" + default KERNEL_INIT_PRIORITY_DEVICE + help + DAQ driver device initialization priority. + +module = DAQ +module-str = daq +source "subsys/logging/Kconfig.template.log_config" + +config DAQ_STM32_CHSEL + bool "STM32 DAQ driver for ADCs with fixed channel sequence" + default y + depends on DT_HAS_LIBRESOLAR_STM32_DAQ_ENABLED + depends on SOC_SERIES_STM32F0X || SOC_SERIES_STM32L0X || SOC_SERIES_STM32G0X + select USE_STM32_LL_ADC + select USE_STM32_LL_DAC + select USE_STM32_LL_DMA + help + Enable DAQ driver for STM32 ADCs converting the selected channels in ascending order + (STM32F0, STM32L0 and STM32G0). + +config DAQ_STM32_RANK + bool "STM32 DAQ driver for ADCs with configurable channel sequence" + default y + depends on DT_HAS_LIBRESOLAR_STM32_DAQ_ENABLED + depends on SOC_SERIES_STM32G4X + select USE_STM32_LL_ADC + select USE_STM32_LL_DAC + select USE_STM32_LL_DMA + help + Enable DAQ driver for STM32 ADCs with ranks to define the channel sequence (STM32G4). + +config DAQ_EMUL + bool "Emulated DAQ driver" + default y + depends on DT_HAS_LIBRESOLAR_DAQ_EMUL_ENABLED + help + Enable emulated DAQ driver for tests on native_sim. + +endif # DAQ diff --git a/drivers/daq/daq_common.c b/drivers/daq/daq_common.c new file mode 100644 index 0000000..5511583 --- /dev/null +++ b/drivers/daq/daq_common.c @@ -0,0 +1,259 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "daq_common.h" + +#include + +LOG_MODULE_REGISTER(daq, CONFIG_DAQ_LOG_LEVEL); + +static inline bool channel_valid(const struct daq_common_config *config, int channel) +{ + return channel >= 0 && channel < config->num_channels; +} + +static inline uint32_t filtered_raw(const struct device *dev, int channel) +{ + const struct daq_common_config *config = dev->config; + const struct daq_common_data *data = dev->data; + + return data->channels[channel].filtered >> config->filter_const[channel]; +} + +static inline float raw_to_voltage(int32_t raw, int32_t vref_mv) +{ + return (raw * vref_mv) / ((float)DAQ_RAW_SCALE * 1000); +} + +int daq_common_init(const struct device *dev) +{ + const struct daq_common_config *config = dev->config; + struct daq_common_data *data = dev->data; + + for (int i = 0; i < config->num_channels; i++) { + data->channels[i].offset = config->offset[i]; + +#ifdef CONFIG_GPIO + const struct gpio_dt_spec *enable = &config->enable_gpios[i]; + + if (enable->port != NULL) { + if (!gpio_is_ready_dt(enable)) { + LOG_ERR("Enable GPIO of channel %d not ready", i); + return -ENODEV; + } + gpio_pin_configure_dt(enable, GPIO_OUTPUT_ACTIVE); + } +#endif + } + + return 0; +} + +static inline void check_alert(const struct device *dev, int channel, struct daq_alert *alert, + bool exceeded) +{ + daq_alert_callback_t callback = alert->callback; + + if (alert->debounce_ms < INT16_MAX) { + alert->debounce_ms++; + } + + if (callback != NULL && exceeded) { + if (alert->debounce_ms > 1) { + callback(dev, channel); + } + } + else if (alert->debounce_ms > 0) { + // reset debounce counter only if already close to triggering to allow setting negative + // values to specify a one-time inhibit delay + alert->debounce_ms = 0; + } +} + +void daq_common_process(const struct device *dev, int channel) +{ + const struct daq_common_config *config = dev->config; + struct daq_common_data *data = dev->data; + struct daq_channel_data *ch = &data->channels[channel]; + const uint16_t raw = data->buf[ch->buf_idx]; + daq_sample_filter_t filter = data->sample_filter; + + if (filter == NULL || (data->sample_filter_mask & BIT(channel)) == 0 || filter(dev, channel)) { + /* + * Low-pass filtering of raw readings + * (see also: http://techteach.no/simview/lowpass_filter/doc/filter_algorithm.pdf) + * + * y(n) = c * x(n) + (1 - c) * y(n-1) with filter constant c = 1/(2^filter_const) + * + * The filtered value is stored left-shifted by filter_const, so that the new raw reading + * can be added without shifting (equivalent to the multiplication with c). + */ + ch->filtered = raw + ch->filtered - (ch->filtered >> config->filter_const[channel]); + } + + check_alert(dev, channel, &ch->alerts[DAQ_ALERT_UPPER], + raw >= ch->alerts[DAQ_ALERT_UPPER].limit); + check_alert(dev, channel, &ch->alerts[DAQ_ALERT_LOWER], + raw <= ch->alerts[DAQ_ALERT_LOWER].limit); +} + +int daq_get_raw(const struct device *dev, int channel) +{ + if (!channel_valid(dev->config, channel)) { + return -EINVAL; + } + + return filtered_raw(dev, channel); +} + +int daq_get_vref_mv(const struct device *dev) +{ + const struct daq_common_config *config = dev->config; + const struct daq_common_data *data = dev->data; + + if (data->vref_mv != 0) { + return data->vref_mv; + } + + if (config->vref_channel < 0 || config->vrefint_cal == NULL) { + return -ENOTSUP; + } + + // factory calibration values are 12-bit right-aligned readings + uint32_t vrefint_raw = filtered_raw(dev, config->vref_channel) >> 4; + if (vrefint_raw == 0) { + return -EAGAIN; + } + + return config->vrefint_cal_mv * *config->vrefint_cal / vrefint_raw; +} + +float daq_get_pin_voltage(const struct device *dev, int channel) +{ + int vref_mv = daq_get_vref_mv(dev); + + if (!channel_valid(dev->config, channel) || vref_mv < 0) { + return 0.0F; + } + + return raw_to_voltage(filtered_raw(dev, channel), vref_mv); +} + +float daq_get_value(const struct device *dev, int channel) +{ + const struct daq_common_config *config = dev->config; + const struct daq_common_data *data = dev->data; + int vref_mv = daq_get_vref_mv(dev); + + if (!channel_valid(config, channel) || vref_mv < 0) { + return 0.0F; + } + + int32_t raw = (int32_t)filtered_raw(dev, channel) - data->channels[channel].offset; + + return raw_to_voltage(raw, vref_mv) * config->gain[channel]; +} + +int daq_get_internal_temp(const struct device *dev, float *temp) +{ + const struct daq_common_config *config = dev->config; + int vref_mv = daq_get_vref_mv(dev); + + if (config->temp_channel < 0 || config->ts_cal1 == NULL || config->ts_cal2 == NULL) { + return -ENOTSUP; + } + + if (vref_mv < 0) { + return vref_mv; + } + + // calibration values are 12-bit right-aligned readings taken at ts_cal_mv reference voltage + int32_t raw = (filtered_raw(dev, config->temp_channel) >> 4) * vref_mv / config->ts_cal_mv; + int32_t cal1 = *config->ts_cal1; + int32_t cal2 = *config->ts_cal2; + + *temp = (float)(config->ts_cal2_temp - config->ts_cal1_temp) / (cal2 - cal1) * (raw - cal1) + + config->ts_cal1_temp; + + return 0; +} + +int daq_calibrate_offset(const struct device *dev, int channel) +{ + struct daq_common_data *data = dev->data; + + if (!channel_valid(dev->config, channel)) { + return -EINVAL; + } + + data->channels[channel].offset = filtered_raw(dev, channel); + + return 0; +} + +int daq_set_alert(const struct device *dev, int channel, enum daq_alert_type type, float limit, + daq_alert_callback_t callback) +{ + const struct daq_common_config *config = dev->config; + struct daq_common_data *data = dev->data; + int vref_mv = daq_get_vref_mv(dev); + + if (!channel_valid(config, channel) || (type != DAQ_ALERT_UPPER && type != DAQ_ALERT_LOWER)) { + return -EINVAL; + } + + if (vref_mv < 0) { + return vref_mv; + } + + struct daq_channel_data *ch = &data->channels[channel]; + const float scale = ((float)DAQ_RAW_SCALE * 1000 / config->gain[channel]) / vref_mv; + float raw = limit * scale + ch->offset; + + // even if we have a higher limit, we must limit it to the range of possible readings + ch->alerts[type].limit = raw > UINT16_MAX ? UINT16_MAX : (raw < 0.0F ? 0 : (uint16_t)raw); + ch->alerts[type].callback = callback; + + return 0; +} + +int daq_inhibit_alert(const struct device *dev, int channel, enum daq_alert_type type, + int16_t timeout_ms) +{ + struct daq_common_data *data = dev->data; + + if (!channel_valid(dev->config, channel) + || (type != DAQ_ALERT_UPPER && type != DAQ_ALERT_LOWER)) + { + return -EINVAL; + } + + // set negative value so that we get a final debouncing of this timeout + the original delay + data->channels[channel].alerts[type].debounce_ms = -timeout_ms; + + return 0; +} + +int daq_set_sample_filter(const struct device *dev, daq_sample_filter_t filter, + uint32_t channel_mask) +{ + struct daq_common_data *data = dev->data; + + data->sample_filter = NULL; + data->sample_filter_mask = channel_mask; + data->sample_filter = filter; + + return 0; +} + +int daq_set_sample_callback(const struct device *dev, daq_sample_callback_t callback) +{ + struct daq_common_data *data = dev->data; + + data->sample_callback = callback; + + return 0; +} diff --git a/drivers/daq/daq_common.h b/drivers/daq/daq_common.h new file mode 100644 index 0000000..3136593 --- /dev/null +++ b/drivers/daq/daq_common.h @@ -0,0 +1,140 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef LIBRESOLAR_DRIVERS_DAQ_COMMON_H_ +#define LIBRESOLAR_DRIVERS_DAQ_COMMON_H_ + +/** + * @file + * @brief Common part of the DAQ drivers (filtering, alerts and scaling) + * + * Backends store new samples in a buffer and call daq_common_process() for each channel. The + * config and data structs of the backends must start with struct daq_common_config and + * struct daq_common_data. + */ + +#include + +#include +#include +#include +#include + +#include + +/** Sampling period of all DAQ backends (alert debouncing assumes 1 ms) */ +#define DAQ_SAMPLE_PERIOD_MS 1 + +struct daq_alert +{ + volatile daq_alert_callback_t callback; + volatile uint16_t limit; + volatile int16_t debounce_ms; +}; + +struct daq_channel_data +{ + /** Filtered raw reading left-shifted by filter_const */ + volatile uint32_t filtered; + struct daq_alert alerts[2]; + /** Offset to be subtracted from the raw reading */ + uint16_t offset; + /** Position of the channel in the sample buffer */ + uint8_t buf_idx; +}; + +struct daq_common_config +{ + const uint8_t *filter_const; + const float *gain; + const uint16_t *offset; + const uint8_t *adc_channel; + const struct gpio_dt_spec *enable_gpios; + /** Factory calibration values (NULL if not available) */ + const uint16_t *vrefint_cal; + const uint16_t *ts_cal1; + const uint16_t *ts_cal2; + uint16_t vrefint_cal_mv; + uint16_t ts_cal_mv; + int16_t ts_cal1_temp; + int16_t ts_cal2_temp; + /** Channel indices of internal reference and temperature sensor (-1 if not available) */ + int8_t vref_channel; + int8_t temp_channel; + uint8_t num_channels; +}; + +struct daq_common_data +{ + struct daq_channel_data *channels; + /** Buffer with the latest raw sample of each channel */ + volatile uint16_t *buf; + daq_sample_filter_t sample_filter; + uint32_t sample_filter_mask; + daq_sample_callback_t sample_callback; + /** Fixed reference voltage or 0 if calculated from the internal reference */ + uint16_t vref_mv; +}; + +/** + * Initialize the common part (offsets and enable GPIOs) + * + * The backend has to set the buffer and the buffer indices afterwards. + */ +int daq_common_init(const struct device *dev); + +/** Filter the latest sample of a channel and check its alerts */ +void daq_common_process(const struct device *dev, int channel); + +/** Call the sample callback after a new sample of all channels was processed */ +static inline void daq_common_sample_done(const struct device *dev) +{ + const struct daq_common_data *data = dev->data; + daq_sample_callback_t callback = data->sample_callback; + + if (callback != NULL) { + callback(dev); + } +} + +/* + * Helper macros to create the common config of a backend from the devicetree + */ + +#define DAQ_FILTER_CONST(child) DT_PROP(child, filter_const), +#define DAQ_GAIN(child) ((float)DT_PROP(child, multiplier) / DT_PROP(child, divider)), +#define DAQ_OFFSET(child) DT_PROP_OR(child, offset, 0), +#define DAQ_ADC_CHANNEL(child) DT_IO_CHANNELS_INPUT(child), +#define DAQ_ENABLE_GPIO(child) GPIO_DT_SPEC_GET_OR(child, enable_gpios, { 0 }), + +#define DAQ_CHILD_IDX_OR_NONE(node_id, name) \ + COND_CODE_1(DT_NODE_EXISTS(DT_CHILD(node_id, name)), \ + (DT_NODE_CHILD_IDX(DT_CHILD(node_id, name))), (-1)) + +/** Define the arrays used by DAQ_COMMON_CONFIG_INIT() */ +#define DAQ_COMMON_DEFINE(node_id) \ + BUILD_ASSERT(DT_CHILD_NUM(node_id) <= 32, "Too many DAQ channels"); \ + static const uint8_t daq_filter_const[] = { DT_FOREACH_CHILD(node_id, DAQ_FILTER_CONST) }; \ + static const float daq_gain[] = { DT_FOREACH_CHILD(node_id, DAQ_GAIN) }; \ + static const uint16_t daq_offset[] = { DT_FOREACH_CHILD(node_id, DAQ_OFFSET) }; \ + static const uint8_t daq_adc_channel[] = { DT_FOREACH_CHILD(node_id, DAQ_ADC_CHANNEL) }; \ + static const struct gpio_dt_spec daq_enable_gpios[] = { DT_FOREACH_CHILD(node_id, \ + DAQ_ENABLE_GPIO) }; \ + static struct daq_channel_data daq_channels[DT_CHILD_NUM(node_id)]; \ + static volatile uint16_t daq_buf[DT_CHILD_NUM(node_id)] + +/** Initializer for struct daq_common_config (without calibration values) */ +#define DAQ_COMMON_CONFIG_INIT(node_id) \ + .filter_const = daq_filter_const, .gain = daq_gain, .offset = daq_offset, \ + .adc_channel = daq_adc_channel, .enable_gpios = daq_enable_gpios, \ + .vref_channel = DAQ_CHILD_IDX_OR_NONE(node_id, vref_mcu), \ + .temp_channel = DAQ_CHILD_IDX_OR_NONE(node_id, temp_mcu), \ + .num_channels = DT_CHILD_NUM(node_id) + +/** Initializer for struct daq_common_data */ +#define DAQ_COMMON_DATA_INIT() .channels = daq_channels, .buf = daq_buf + +#endif /* LIBRESOLAR_DRIVERS_DAQ_COMMON_H_ */ diff --git a/drivers/daq/daq_emul.c b/drivers/daq/daq_emul.c new file mode 100644 index 0000000..5d27d5b --- /dev/null +++ b/drivers/daq/daq_emul.c @@ -0,0 +1,142 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file + * @brief Emulated DAQ driver for tests on native_sim + */ + +#define DT_DRV_COMPAT libresolar_daq_emul + +#include "daq_common.h" + +#include + +#include + +BUILD_ASSERT(DT_NUM_INST_STATUS_OKAY(DT_DRV_COMPAT) <= 1, "Only one DAQ instance supported"); + +#define DAQ_NODE DT_DRV_INST(0) + +/* + * Typical calibration values of an STM32 temperature sensor (0.76 V at 30 °C, 2.5 mV/°C) + * as 12-bit readings at 3.3 V + */ +static const uint16_t ts_cal1 = 4096 * 760 / 3300; +static const uint16_t ts_cal2 = 4096 * 1010 / 3300; + +DAQ_COMMON_DEFINE(DAQ_NODE); + +static const struct daq_common_config daq_emul_config = { + DAQ_COMMON_CONFIG_INIT(DAQ_NODE), + .ts_cal1 = &ts_cal1, + .ts_cal2 = &ts_cal2, + .ts_cal_mv = 3300, + .ts_cal1_temp = 30, + .ts_cal2_temp = 130, +}; + +static struct daq_common_data daq_emul_data = { + DAQ_COMMON_DATA_INIT(), + .vref_mv = DAQ_EMUL_VREF_MV, +}; + +static inline bool channel_valid(const struct device *dev, int channel) +{ + const struct daq_common_config *config = dev->config; + + return channel >= 0 && channel < config->num_channels; +} + +int daq_emul_set_raw(const struct device *dev, int channel, uint16_t raw) +{ + struct daq_common_data *data = dev->data; + + if (!channel_valid(dev, channel)) { + return -EINVAL; + } + + data->buf[data->channels[channel].buf_idx] = raw; + + return 0; +} + +int daq_emul_set_value(const struct device *dev, int channel, float value) +{ + const struct daq_common_config *config = dev->config; + struct daq_common_data *data = dev->data; + + if (!channel_valid(dev, channel)) { + return -EINVAL; + } + + // 12-bit resolution as provided by the ADC + float raw12 = (value / config->gain[channel]) / (DAQ_EMUL_VREF_MV / 1000.0F) * 4096; + raw12 = CLAMP(raw12, -4096.0F, 4096.0F); + + int32_t raw = (int32_t)raw12 * 16 + data->channels[channel].offset; + + return daq_emul_set_raw(dev, channel, CLAMP(raw, 0, UINT16_MAX)); +} + +int daq_emul_process(const struct device *dev, int channel) +{ + if (!channel_valid(dev, channel)) { + return -EINVAL; + } + + daq_common_process(dev, channel); + + return 0; +} + +void daq_emul_process_all(const struct device *dev) +{ + const struct daq_common_config *config = dev->config; + + for (int i = 0; i < config->num_channels; i++) { + daq_common_process(dev, i); + } + + daq_common_sample_done(dev); +} + +void daq_emul_preset_filtered(const struct device *dev) +{ + const struct daq_common_config *config = dev->config; + struct daq_common_data *data = dev->data; + + for (int i = 0; i < config->num_channels; i++) { + struct daq_channel_data *ch = &data->channels[i]; + + ch->filtered = (uint32_t)data->buf[ch->buf_idx] << config->filter_const[i]; + } +} + +void daq_emul_reset_filtered(const struct device *dev) +{ + const struct daq_common_config *config = dev->config; + struct daq_common_data *data = dev->data; + + for (int i = 0; i < config->num_channels; i++) { + data->channels[i].filtered = 0; + } +} + +static int daq_emul_init(const struct device *dev) +{ + const struct daq_common_config *config = dev->config; + struct daq_common_data *data = dev->data; + + for (int i = 0; i < config->num_channels; i++) { + data->channels[i].buf_idx = i; + } + + return daq_common_init(dev); +} + +DEVICE_DT_INST_DEFINE(0, daq_emul_init, NULL, &daq_emul_data, &daq_emul_config, POST_KERNEL, + CONFIG_DAQ_INIT_PRIORITY, NULL); diff --git a/drivers/daq/daq_stm32.h b/drivers/daq/daq_stm32.h new file mode 100644 index 0000000..c27b30a --- /dev/null +++ b/drivers/daq/daq_stm32.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef LIBRESOLAR_DRIVERS_DAQ_STM32_H_ +#define LIBRESOLAR_DRIVERS_DAQ_STM32_H_ + +#include + +/** + * Initializer for the factory calibration values in struct daq_common_config + * + * The addresses and calibration conditions are defined in the LL header of each STM32 series. + */ +#define DAQ_STM32_CAL_CONFIG_INIT() \ + .vrefint_cal = VREFINT_CAL_ADDR, .vrefint_cal_mv = VREFINT_CAL_VREF, \ + .ts_cal1 = TEMPSENSOR_CAL1_ADDR, .ts_cal2 = TEMPSENSOR_CAL2_ADDR, \ + .ts_cal_mv = TEMPSENSOR_CAL_VREFANALOG, .ts_cal1_temp = TEMPSENSOR_CAL1_TEMP, \ + .ts_cal2_temp = TEMPSENSOR_CAL2_TEMP + +#endif /* LIBRESOLAR_DRIVERS_DAQ_STM32_H_ */ diff --git a/drivers/daq/daq_stm32_chsel.c b/drivers/daq/daq_stm32_chsel.c new file mode 100644 index 0000000..86a74ec --- /dev/null +++ b/drivers/daq/daq_stm32_chsel.c @@ -0,0 +1,240 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file + * @brief DAQ driver for STM32 ADCs with a fixed channel sequence (STM32F0, STM32L0, STM32G0) + * + * The channels are selected with a bit mask and converted in ascending order of the channel + * numbers. All channels have to be connected to ADC1. + */ + +#define DT_DRV_COMPAT libresolar_stm32_daq + +#include "daq_common.h" +#include "daq_stm32.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +LOG_MODULE_DECLARE(daq, CONFIG_DAQ_LOG_LEVEL); + +BUILD_ASSERT(DT_NUM_INST_STATUS_OKAY(DT_DRV_COMPAT) <= 1, "Only one DAQ instance supported"); + +#define DAQ_NODE DT_DRV_INST(0) + +#define ADC_CHSEL_FN(child) BIT(DT_IO_CHANNELS_INPUT(child)) | +#define ADC_CHSEL (DT_FOREACH_CHILD(DAQ_NODE, ADC_CHSEL_FN) 0) + +/* priority 2: second-lowest value for STM32L0/F0 */ +#define DMA_IRQ_PRIORITY 2 + +struct daq_stm32_data +{ + struct daq_common_data common; + struct k_timer trigger_timer; +}; + +DAQ_COMMON_DEFINE(DAQ_NODE); + +static const struct daq_common_config daq_stm32_config = { + DAQ_COMMON_CONFIG_INIT(DAQ_NODE), + DAQ_STM32_CAL_CONFIG_INIT(), +}; + +static struct daq_stm32_data daq_stm32_data = { + .common = { DAQ_COMMON_DATA_INIT() }, +}; + +static void dac_setup(void) +{ + /* DAC1 at PA4 as reference voltage for current measurement amplifiers at 0.1 * VCC */ + LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_DAC1); + LL_DAC_SetOutputBuffer(DAC1, LL_DAC_CHANNEL_1, LL_DAC_OUTPUT_BUFFER_ENABLE); + LL_DAC_Enable(DAC1, LL_DAC_CHANNEL_1); + LL_DAC_ConvertData12RightAligned(DAC1, LL_DAC_CHANNEL_1, 4096 / 10); +} + +static int adc_setup(ADC_TypeDef *adc) +{ +#if defined(CONFIG_SOC_SERIES_STM32F0X) + LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_ADC1); + LL_ADC_SetClock(adc, LL_ADC_CLOCK_SYNC_PCLK_DIV4); +#elif defined(CONFIG_SOC_SERIES_STM32L0X) + LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_ADC1); + LL_ADC_EnableInternalRegulator(adc); + k_busy_wait(LL_ADC_DELAY_INTERNAL_REGUL_STAB_US); + LL_ADC_SetCommonClock(__LL_ADC_COMMON_INSTANCE(adc), LL_ADC_CLOCK_SYNC_PCLK_DIV4); +#elif defined(CONFIG_SOC_SERIES_STM32G0X) + LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_ADC); + LL_ADC_SetClock(adc, LL_ADC_CLOCK_SYNC_PCLK_DIV4); + LL_ADC_EnableInternalRegulator(adc); + k_busy_wait(LL_ADC_DELAY_INTERNAL_REGUL_STAB_US); +#endif + + if (LL_ADC_IsEnabled(adc)) { + LL_ADC_Disable(adc); + } + + LL_ADC_StartCalibration(adc); + while (LL_ADC_IsCalibrationOnGoing(adc)) { + } + +#if defined(CONFIG_SOC_SERIES_STM32G0X) + // a few ADC clock cycles are required between end of calibration and enabling the ADC + k_busy_wait(1); +#endif + + if (LL_ADC_IsActiveFlag_ADRDY(adc)) { + LL_ADC_ClearFlag_ADRDY(adc); + } + + // Enable internal reference voltage and temperature + LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(adc), + LL_ADC_PATH_INTERNAL_VREFINT | LL_ADC_PATH_INTERNAL_TEMPSENSOR); + +#if defined(CONFIG_SOC_SERIES_STM32F0X) + LL_ADC_REG_SetSequencerChannels(adc, ADC_CHSEL); + LL_ADC_SetSamplingTimeCommonChannels(adc, LL_ADC_SAMPLINGTIME_239CYCLES_5); +#elif defined(CONFIG_SOC_SERIES_STM32L0X) + LL_ADC_REG_SetSequencerChannels(adc, ADC_CHSEL); + LL_ADC_SetSamplingTimeCommonChannels(adc, LL_ADC_SAMPLINGTIME_160CYCLES_5); +#elif defined(CONFIG_SOC_SERIES_STM32G0X) + LL_ADC_REG_SetSequencerConfigurable(adc, LL_ADC_REG_SEQ_FIXED); + LL_ADC_ClearFlag_CCRDY(adc); + LL_ADC_REG_SetSequencerChannels(adc, ADC_CHSEL); + + // channel configuration must be applied before starting conversions + int timeout_us = 1000; + while (!LL_ADC_IsActiveFlag_CCRDY(adc) && timeout_us-- > 0) { + k_busy_wait(1); + } + if (timeout_us < 0) { + LOG_ERR("ADC channel configuration timed out"); + return -ETIMEDOUT; + } + LL_ADC_ClearFlag_CCRDY(adc); + + LL_ADC_SetSamplingTimeCommonChannels(adc, LL_ADC_SAMPLINGTIME_COMMON_1, + LL_ADC_SAMPLINGTIME_160CYCLES_5); +#endif + + LL_ADC_SetDataAlignment(adc, LL_ADC_DATA_ALIGN_LEFT); + LL_ADC_SetResolution(adc, LL_ADC_RESOLUTION_12B); + LL_ADC_REG_SetOverrun(adc, LL_ADC_REG_OVR_DATA_OVERWRITTEN); + // Enable DMA transfer on ADC and circular mode + LL_ADC_REG_SetDMATransfer(adc, LL_ADC_REG_DMA_TRANSFER_UNLIMITED); + + LL_ADC_Enable(adc); + + return 0; +} + +static void dma_isr(const void *arg) +{ + const struct device *dev = arg; + const struct daq_common_config *config = dev->config; + + if ((DMA1->ISR & DMA_ISR_TCIF1) != 0) { // transfer completed on DMA channel 1 + for (int i = 0; i < config->num_channels; i++) { + daq_common_process(dev, i); + } + daq_common_sample_done(dev); + } + DMA1->IFCR |= 0x0FFFFFFF; // clear all interrupt flags +} + +static void dma_setup(const struct device *dev) +{ + const struct daq_common_config *config = dev->config; + struct daq_common_data *data = dev->data; + + LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1); + +#if defined(CONFIG_SOC_SERIES_STM32G0X) + LL_DMA_SetPeriphRequest(DMA1, LL_DMA_CHANNEL_1, LL_DMAMUX_REQ_ADC1); +#endif + + LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_1, + LL_ADC_DMA_GetRegAddr(ADC1, LL_ADC_DMA_REG_REGULAR_DATA), + (uint32_t)data->buf, LL_DMA_DIRECTION_PERIPH_TO_MEMORY); + + // Configure the number of DMA transfers (data length in multiples of size per transfer) + LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, config->num_channels); + + LL_DMA_SetMemoryIncMode(DMA1, LL_DMA_CHANNEL_1, LL_DMA_MEMORY_INCREMENT); + LL_DMA_SetMemorySize(DMA1, LL_DMA_CHANNEL_1, LL_DMA_MDATAALIGN_HALFWORD); + LL_DMA_SetPeriphSize(DMA1, LL_DMA_CHANNEL_1, LL_DMA_PDATAALIGN_HALFWORD); + LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_1); // transfer error interrupt + LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_1); // transfer complete interrupt + LL_DMA_SetMode(DMA1, LL_DMA_CHANNEL_1, LL_DMA_MODE_CIRCULAR); + + LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1); + + IRQ_CONNECT(DMA1_Channel1_IRQn, DMA_IRQ_PRIORITY, dma_isr, DEVICE_DT_INST_GET(0), 0); + irq_enable(DMA1_Channel1_IRQn); +} + +static void trigger_conversion(struct k_timer *timer) +{ + ARG_UNUSED(timer); + + LL_ADC_REG_StartConversion(ADC1); +} + +static int daq_stm32_init(const struct device *dev) +{ + const struct daq_common_config *config = dev->config; + struct daq_stm32_data *data = dev->data; + int err; + + // channels are converted and stored by the DMA in ascending order of the channel numbers + for (int i = 0; i < config->num_channels; i++) { + uint8_t idx = 0; + + for (int j = 0; j < config->num_channels; j++) { + if (config->adc_channel[j] < config->adc_channel[i]) { + idx++; + } + else if (config->adc_channel[j] == config->adc_channel[i] && j != i) { + LOG_ERR("ADC channel %d used more than once", config->adc_channel[i]); + return -EINVAL; + } + } + data->common.channels[i].buf_idx = idx; + } + + err = daq_common_init(dev); + if (err != 0) { + return err; + } + + dac_setup(); + + err = adc_setup(ADC1); + if (err != 0) { + return err; + } + + dma_setup(dev); + LL_ADC_REG_StartConversion(ADC1); + + k_timer_init(&data->trigger_timer, trigger_conversion, NULL); + k_timer_start(&data->trigger_timer, K_MSEC(DAQ_SAMPLE_PERIOD_MS), K_MSEC(DAQ_SAMPLE_PERIOD_MS)); + + return 0; +} + +DEVICE_DT_INST_DEFINE(0, daq_stm32_init, NULL, &daq_stm32_data, &daq_stm32_config, POST_KERNEL, + CONFIG_DAQ_INIT_PRIORITY, NULL); diff --git a/drivers/daq/daq_stm32_rank.c b/drivers/daq/daq_stm32_rank.c new file mode 100644 index 0000000..39f58ef --- /dev/null +++ b/drivers/daq/daq_stm32_rank.c @@ -0,0 +1,342 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file + * @brief DAQ driver for STM32 ADCs with a configurable channel sequence (STM32G4) + * + * The channels can be connected to ADC1 and ADC2. They are converted in the order of the + * devicetree nodes. The reference voltage is generated by the internal reference buffer + * (VREFBUF) with 2.048 V. + */ + +#define DT_DRV_COMPAT libresolar_stm32_daq + +#include "daq_common.h" +#include "daq_stm32.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +LOG_MODULE_DECLARE(daq, CONFIG_DAQ_LOG_LEVEL); + +BUILD_ASSERT(DT_NUM_INST_STATUS_OKAY(DT_DRV_COMPAT) <= 1, "Only one DAQ instance supported"); + +#define DAQ_NODE DT_DRV_INST(0) + +/* priority 2: second-lowest value for STM32L0/F0 */ +#define DMA_IRQ_PRIORITY 2 + +/* reference voltage generated by VREFBUF */ +#define VREF_MV 2048 + +#define ADC_BASE_FN(child) DT_REG_ADDR(DT_IO_CHANNELS_CTLR(child)), +static const uint32_t adc_base[] = { DT_FOREACH_CHILD(DAQ_NODE, ADC_BASE_FN) }; + +// Depending on the channel, not just a single bit has to be set in the right location. So we need +// a map to get correct bit settings for each channel. +static const uint32_t table_channel[] = { + LL_ADC_CHANNEL_0, + LL_ADC_CHANNEL_1, + LL_ADC_CHANNEL_2, + LL_ADC_CHANNEL_3, + LL_ADC_CHANNEL_4, + LL_ADC_CHANNEL_5, + LL_ADC_CHANNEL_6, + LL_ADC_CHANNEL_7, + LL_ADC_CHANNEL_8, + LL_ADC_CHANNEL_9, + LL_ADC_CHANNEL_10, + LL_ADC_CHANNEL_11, + LL_ADC_CHANNEL_12, + LL_ADC_CHANNEL_13, + LL_ADC_CHANNEL_14, + LL_ADC_CHANNEL_15, + LL_ADC_CHANNEL_TEMPSENSOR_ADC1, + LL_ADC_CHANNEL_VBAT, + LL_ADC_CHANNEL_VREFINT, +}; + +// Rank and sequence definitions for STM32G4 from adc_stm32.c Zephyr driver + +#define RANK(n) LL_ADC_REG_RANK_##n +static const uint32_t table_rank[] = { + RANK(1), RANK(2), RANK(3), RANK(4), RANK(5), RANK(6), RANK(7), RANK(8), + RANK(9), RANK(10), RANK(11), RANK(12), RANK(13), RANK(14), RANK(15), RANK(16), +}; + +#define SEQ_LEN(n) LL_ADC_REG_SEQ_SCAN_ENABLE_##n##RANKS +static const uint32_t table_seq_len[] = { + LL_ADC_REG_SEQ_SCAN_DISABLE, + SEQ_LEN(2), + SEQ_LEN(3), + SEQ_LEN(4), + SEQ_LEN(5), + SEQ_LEN(6), + SEQ_LEN(7), + SEQ_LEN(8), + SEQ_LEN(9), + SEQ_LEN(10), + SEQ_LEN(11), + SEQ_LEN(12), + SEQ_LEN(13), + SEQ_LEN(14), + SEQ_LEN(15), + SEQ_LEN(16), +}; + +struct daq_stm32_data +{ + struct daq_common_data common; + struct k_timer trigger_timer; + uint8_t num_adc1_ch; + uint8_t num_adc2_ch; +}; + +DAQ_COMMON_DEFINE(DAQ_NODE); + +static const struct daq_common_config daq_stm32_config = { + DAQ_COMMON_CONFIG_INIT(DAQ_NODE), + DAQ_STM32_CAL_CONFIG_INIT(), +}; + +static struct daq_stm32_data daq_stm32_data = { + .common = { DAQ_COMMON_DATA_INIT(), .vref_mv = VREF_MV }, +}; + +static void vref_setup(void) +{ + // output 2.048V at VREF+ pin (also used internally for ADC and DAC) + LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_SYSCFG); + LL_VREFBUF_SetVoltageScaling(LL_VREFBUF_VOLTAGE_SCALE0); + LL_VREFBUF_DisableHIZ(); + LL_VREFBUF_Enable(); + while (LL_VREFBUF_IsVREFReady() == 0) { + } +} + +static void dac_setup(void) +{ + LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_DAC1); + /* DAC1 at PA4 for bi-directional DC/DC current measurement at 0.5 * VCC */ + LL_DAC_SetOutputBuffer(DAC1, LL_DAC_CHANNEL_1, LL_DAC_OUTPUT_BUFFER_ENABLE); + LL_DAC_Enable(DAC1, LL_DAC_CHANNEL_1); + LL_DAC_ConvertData12RightAligned(DAC1, LL_DAC_CHANNEL_1, 4096 / 2); + /* DAC1 at PA5 for uni-directional PWM and load current measurement at 0.1 * VCC */ + LL_DAC_SetOutputBuffer(DAC1, LL_DAC_CHANNEL_2, LL_DAC_OUTPUT_BUFFER_ENABLE); + LL_DAC_Enable(DAC1, LL_DAC_CHANNEL_2); + LL_DAC_ConvertData12RightAligned(DAC1, LL_DAC_CHANNEL_2, 4096 / 10); +} + +static void adc_setup(const struct device *dev, ADC_TypeDef *adc) +{ + const struct daq_common_config *config = dev->config; + int num_ch = 0; + + // ADC clock can be generated from SYSCLK or PLL (async mode) or derived from AHB clock + // (sync mode). For synchronization with a timer, sync mode is preferred. + LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_ADC12); + + if (LL_ADC_IsEnabled(adc)) { + LL_ADC_Disable(adc); + } + + // Use DIV1 only, as DIV2 and DIV4 lead to errors in ADC readings (not sure why...) + LL_ADC_SetCommonClock(__LL_ADC_COMMON_INSTANCE(adc), LL_ADC_CLOCK_SYNC_PCLK_DIV1); + + // Prepare for ADC calibration + LL_ADC_DisableDeepPowerDown(adc); + LL_ADC_EnableInternalRegulator(adc); + // Datasheet: wait 20us for regulator to stabilize (taking 100us to be safe) + // LL_ADC_DELAY_INTERNAL_REGUL_STAB_US is erroneously set to 10 in stm32g4xx_ll_adc.h + k_busy_wait(100); + + LL_ADC_StartCalibration(adc, LL_ADC_SINGLE_ENDED); + while (LL_ADC_IsCalibrationOnGoing(adc)) { + } + + if (LL_ADC_IsActiveFlag_ADRDY(adc)) { + LL_ADC_ClearFlag_ADRDY(adc); + } + + // Enable internal reference voltage and temperature + LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(adc), + LL_ADC_PATH_INTERNAL_VREFINT | LL_ADC_PATH_INTERNAL_TEMPSENSOR); + + // more complicated sequencer allows to define the sequence independent of the channel number + // (using ranks) + for (int i = 0; i < config->num_channels; i++) { + if (adc_base[i] == (uint32_t)adc) { + uint32_t channel = table_channel[config->adc_channel[i]]; + + LL_ADC_REG_SetSequencerRanks(adc, table_rank[num_ch], channel); + LL_ADC_SetChannelSamplingTime(adc, channel, LL_ADC_SAMPLINGTIME_247CYCLES_5); + num_ch++; + } + } + LL_ADC_REG_SetSequencerLength(adc, table_seq_len[num_ch - 1]); + + LL_ADC_SetDataAlignment(adc, LL_ADC_DATA_ALIGN_LEFT); + LL_ADC_SetResolution(adc, LL_ADC_RESOLUTION_12B); + LL_ADC_REG_SetOverrun(adc, LL_ADC_REG_OVR_DATA_OVERWRITTEN); + // Enable DMA transfer on ADC and circular mode + LL_ADC_REG_SetDMATransfer(adc, LL_ADC_REG_DMA_TRANSFER_UNLIMITED); + + LL_ADC_Enable(adc); +} + +static void process_adc_channels(const struct device *dev, ADC_TypeDef *adc) +{ + const struct daq_common_config *config = dev->config; + const struct daq_stm32_data *data = dev->data; + + for (int i = 0; i < config->num_channels; i++) { + if (adc_base[i] == (uint32_t)adc) { + daq_common_process(dev, i); + } + } + + // ADC2 is sampled after ADC1 (if used) + if (adc == ADC2 || data->num_adc2_ch == 0) { + daq_common_sample_done(dev); + } +} + +static void dma1_isr(const void *arg) +{ + if ((DMA1->ISR & DMA_ISR_TCIF1) != 0) { // transfer completed on DMA channel 1 + process_adc_channels(arg, ADC1); + } + DMA1->IFCR |= 0x0FFFFFFF; // clear all interrupt flags +} + +static void dma2_isr(const void *arg) +{ + if ((DMA2->ISR & DMA_ISR_TCIF1) != 0) { // transfer completed on DMA channel 1 + process_adc_channels(arg, ADC2); + } + DMA2->IFCR |= 0x0FFFFFFF; // clear all interrupt flags +} + +// DMA1 is mapped to ADC1 and DMA2 is mapped to ADC2 +static void dma_setup(DMA_TypeDef *dma, ADC_TypeDef *adc, volatile uint16_t *buf, uint32_t length) +{ + LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMAMUX1); + LL_DMA_SetPeriphRequest(dma, LL_DMA_CHANNEL_1, + (dma == DMA1) ? LL_DMAMUX_REQ_ADC1 : LL_DMAMUX_REQ_ADC2); + + LL_AHB1_GRP1_EnableClock((dma == DMA1) ? LL_AHB1_GRP1_PERIPH_DMA1 : LL_AHB1_GRP1_PERIPH_DMA2); + + LL_DMA_ConfigAddresses(dma, LL_DMA_CHANNEL_1, + LL_ADC_DMA_GetRegAddr(adc, LL_ADC_DMA_REG_REGULAR_DATA), (uint32_t)buf, + LL_DMA_DIRECTION_PERIPH_TO_MEMORY); + + // Configure the number of DMA transfers (data length in multiples of size per transfer) + LL_DMA_SetDataLength(dma, LL_DMA_CHANNEL_1, length); + + LL_DMA_SetMemoryIncMode(dma, LL_DMA_CHANNEL_1, LL_DMA_MEMORY_INCREMENT); + LL_DMA_SetMemorySize(dma, LL_DMA_CHANNEL_1, LL_DMA_MDATAALIGN_HALFWORD); + LL_DMA_SetPeriphSize(dma, LL_DMA_CHANNEL_1, LL_DMA_PDATAALIGN_HALFWORD); + LL_DMA_EnableIT_TE(dma, LL_DMA_CHANNEL_1); // transfer error interrupt + LL_DMA_EnableIT_TC(dma, LL_DMA_CHANNEL_1); // transfer complete interrupt + LL_DMA_SetMode(dma, LL_DMA_CHANNEL_1, LL_DMA_MODE_CIRCULAR); + + LL_DMA_EnableChannel(dma, LL_DMA_CHANNEL_1); + + if (dma == DMA1) { + IRQ_CONNECT(DMA1_Channel1_IRQn, DMA_IRQ_PRIORITY, dma1_isr, DEVICE_DT_INST_GET(0), 0); + irq_enable(DMA1_Channel1_IRQn); + } + else { + IRQ_CONNECT(DMA2_Channel1_IRQn, DMA_IRQ_PRIORITY, dma2_isr, DEVICE_DT_INST_GET(0), 0); + irq_enable(DMA2_Channel1_IRQn); + } +} + +static void trigger_conversion(struct k_timer *timer) +{ + const struct daq_stm32_data *data = k_timer_user_data_get(timer); + + if (data->num_adc1_ch > 0) { + LL_ADC_REG_StartConversion(ADC1); + } + if (data->num_adc2_ch > 0) { + LL_ADC_REG_StartConversion(ADC2); + } +} + +static int daq_stm32_init(const struct device *dev) +{ + const struct daq_common_config *config = dev->config; + struct daq_stm32_data *data = dev->data; + int err; + + // the DMA stores the channels of ADC1 first, followed by the channels of ADC2 + for (int i = 0; i < config->num_channels; i++) { + if (config->adc_channel[i] >= ARRAY_SIZE(table_channel)) { + LOG_ERR("Invalid ADC channel %d", config->adc_channel[i]); + return -EINVAL; + } + if (adc_base[i] == (uint32_t)ADC1) { + data->common.channels[i].buf_idx = data->num_adc1_ch++; + } + else if (adc_base[i] == (uint32_t)ADC2) { + data->common.channels[i].buf_idx = data->num_adc2_ch++; + } + else { + LOG_ERR("Only ADC1 and ADC2 are supported"); + return -EINVAL; + } + } + for (int i = 0; i < config->num_channels; i++) { + if (adc_base[i] == (uint32_t)ADC2) { + data->common.channels[i].buf_idx += data->num_adc1_ch; + } + } + + err = daq_common_init(dev); + if (err != 0) { + return err; + } + + vref_setup(); + dac_setup(); + + // configure both ADCs before starting conversions, as they share common settings + if (data->num_adc1_ch > 0) { + adc_setup(dev, ADC1); + } + if (data->num_adc2_ch > 0) { + adc_setup(dev, ADC2); + } + + if (data->num_adc1_ch > 0) { + dma_setup(DMA1, ADC1, &data->common.buf[0], data->num_adc1_ch); + LL_ADC_REG_StartConversion(ADC1); + } + if (data->num_adc2_ch > 0) { + dma_setup(DMA2, ADC2, &data->common.buf[data->num_adc1_ch], data->num_adc2_ch); + LL_ADC_REG_StartConversion(ADC2); + } + + k_timer_init(&data->trigger_timer, trigger_conversion, NULL); + k_timer_user_data_set(&data->trigger_timer, data); + k_timer_start(&data->trigger_timer, K_MSEC(DAQ_SAMPLE_PERIOD_MS), K_MSEC(DAQ_SAMPLE_PERIOD_MS)); + + return 0; +} + +DEVICE_DT_INST_DEFINE(0, daq_stm32_init, NULL, &daq_stm32_data, &daq_stm32_config, POST_KERNEL, + CONFIG_DAQ_INIT_PRIORITY, NULL); diff --git a/dts/bindings/daq/daq-common.yaml b/dts/bindings/daq/daq-common.yaml new file mode 100644 index 0000000..0e33cf8 --- /dev/null +++ b/dts/bindings/daq/daq-common.yaml @@ -0,0 +1,55 @@ +# Copyright (c) The Libre Solar Project Contributors +# SPDX-License-Identifier: Apache-2.0 + +description: | + Common properties for data acquisition (DAQ) devices + + The DAQ samples all inputs given as child nodes with 1 kHz, filters the readings with a + low-pass filter and checks them against configurable limits. + + The node is expected at the path /adc-inputs. The following child node names have a special + meaning: + + - vref-mcu: Internal reference voltage of the MCU, used to calculate the supply voltage of the + ADC if no fixed reference voltage is available. + - temp-mcu: Internal temperature sensor of the MCU. + +child-binding: + description: ADC input + properties: + io-channels: + type: phandle-array + required: true + description: | + ADC channel for this input. + + multiplier: + type: int + required: true + description: | + Gain numerator, e.g. the resistance of the full path through a voltage divider. + + divider: + type: int + required: true + description: | + Gain denominator, e.g. the resistance of the lower leg of a voltage divider. + + offset: + type: int + required: false + description: | + Offset to be subtracted from the 16-bit raw ADC reading before applying the gain + + filter-const: + type: int + default: 5 + description: Low-pass filter multiplier 1/(2^filter-const) + + enable-gpios: + type: phandle-array + required: false + description: | + Enable the voltage divider input or amplifier. + + If present the corresponding GPIO is set to its active level during initialization. diff --git a/dts/bindings/daq/libresolar,daq-emul.yaml b/dts/bindings/daq/libresolar,daq-emul.yaml new file mode 100644 index 0000000..7d05616 --- /dev/null +++ b/dts/bindings/daq/libresolar,daq-emul.yaml @@ -0,0 +1,11 @@ +# Copyright (c) The Libre Solar Project Contributors +# SPDX-License-Identifier: Apache-2.0 + +description: | + Emulated data acquisition (DAQ) for tests on native_sim + + Readings are set and processed using the API from . + +compatible: "libresolar,daq-emul" + +include: daq-common.yaml diff --git a/dts/bindings/daq/libresolar,stm32-daq.yaml b/dts/bindings/daq/libresolar,stm32-daq.yaml new file mode 100644 index 0000000..78402e0 --- /dev/null +++ b/dts/bindings/daq/libresolar,stm32-daq.yaml @@ -0,0 +1,13 @@ +# Copyright (c) The Libre Solar Project Contributors +# SPDX-License-Identifier: Apache-2.0 + +description: | + Data acquisition (DAQ) using the ADC of STM32 MCUs with DMA + + Conversions are triggered by a timer with 1 kHz and the results are transferred to RAM by the + DMA controller. The DAC is used to generate reference voltages for current measurement + amplifiers. + +compatible: "libresolar,stm32-daq" + +include: daq-common.yaml diff --git a/include/libresolar/drivers/daq.h b/include/libresolar/drivers/daq.h new file mode 100644 index 0000000..36d5922 --- /dev/null +++ b/include/libresolar/drivers/daq.h @@ -0,0 +1,230 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef LIBRESOLAR_DRIVERS_DAQ_H_ +#define LIBRESOLAR_DRIVERS_DAQ_H_ + +/** + * @file + * @brief Data acquisition (DAQ) driver API + * + * The DAQ samples all inputs defined as child nodes of the DAQ devicetree node with 1 kHz. Each + * reading is low-pass filtered and checked against an upper and a lower limit, which can trigger + * an alert callback. + * + * Raw readings are 16-bit values, even though the STM32 ADCs natively support 12-bit only. + * Left-aligned 12-bit readings can be treated as 16-bit readings, which allows to increase the + * resolution by filtering. + * + * Only a single DAQ instance is supported. + */ + +#include +#include + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup daq_interface DAQ + * @{ + */ + +/** Full-scale value of raw readings */ +#define DAQ_RAW_SCALE 65536 + +/** + * Get the channel index of a DAQ input + * + * @param node_id Node identifier of the DAQ device + * @param name Lower-case-and-underscores name of the child node, e.g. v_low + */ +#define DAQ_CHANNEL(node_id, name) DT_NODE_CHILD_IDX(DT_CHILD(node_id, name)) + +/** Alert types */ +enum daq_alert_type +{ + /** Alert if the reading is greater than or equal to the limit */ + DAQ_ALERT_UPPER, + /** Alert if the reading is less than or equal to the limit */ + DAQ_ALERT_LOWER, +}; + +/** + * Alert callback + * + * Called from interrupt context for every sample after the limit was exceeded for two + * consecutive samples, so it must be short. + * + * @param dev DAQ device + * @param channel Channel index + */ +typedef void (*daq_alert_callback_t)(const struct device *dev, int channel); + +/** + * Sample filter callback + * + * Called from interrupt context for each new sample of the channels selected with + * daq_set_sample_filter(). + * + * @param dev DAQ device + * @param channel Channel index + * + * @return false if the sample should not be used for the filtered value + */ +typedef bool (*daq_sample_filter_t)(const struct device *dev, int channel); + +/** + * Sample callback + * + * Called from interrupt context after a new sample of all channels was processed, so it must be + * very short. + * + * @param dev DAQ device + */ +typedef void (*daq_sample_callback_t)(const struct device *dev); + +/** + * Get the filtered raw reading of a channel + * + * @param dev DAQ device + * @param channel Channel index + * + * @return 16-bit raw reading or negative error code + */ +int daq_get_raw(const struct device *dev, int channel); + +/** + * Get the reference voltage of the ADC + * + * @param dev DAQ device + * + * @return Reference voltage in millivolts or negative error code + * @retval -EAGAIN if the reference voltage is calculated from readings and no reading is available + * yet + */ +int daq_get_vref_mv(const struct device *dev); + +/** + * Get the filtered voltage at the ADC pin of a channel + * + * @param dev DAQ device + * @param channel Channel index + * + * @return Voltage in volts (0 if the reference voltage is not yet known) + */ +float daq_get_pin_voltage(const struct device *dev, int channel); + +/** + * Get the filtered and scaled value of a channel + * + * The offset is subtracted from the raw reading before the gain is applied. + * + * @param dev DAQ device + * @param channel Channel index + * + * @return Scaled value, e.g. in volts or amps (0 if the reference voltage is not yet known) + */ +float daq_get_value(const struct device *dev, int channel); + +/** + * Get the internal temperature of the MCU + * + * Requires a child node named temp-mcu. + * + * @param dev DAQ device + * @param temp Pointer to store the temperature in °C + * + * @retval 0 on success + * @retval -ENOTSUP if the DAQ doesn't measure the internal temperature + * @retval -EAGAIN if no reading is available yet + */ +int daq_get_internal_temp(const struct device *dev, float *temp); + +/** + * Use the current filtered reading of a channel as its offset, i.e. as zero point + * + * All switches and consumers should be off, so that no current flows. + * + * @param dev DAQ device + * @param channel Channel index + * + * @retval 0 on success + * @retval -EINVAL if the channel is invalid + */ +int daq_calibrate_offset(const struct device *dev, int channel); + +/** + * Set an alert + * + * The limit is converted to a raw reading using the gain, offset and the current reference + * voltage. It is clamped to the range of valid readings. + * + * @param dev DAQ device + * @param channel Channel index + * @param type Alert type + * @param limit Limit as scaled value, e.g. in volts or amps + * @param callback Callback to be called if the limit is exceeded, or NULL to disable the alert + * + * @retval 0 on success + * @retval -EINVAL if the channel is invalid + * @retval -EAGAIN if the reference voltage is not yet known + */ +int daq_set_alert(const struct device *dev, int channel, enum daq_alert_type type, float limit, + daq_alert_callback_t callback); + +/** + * Inhibit an alert temporarily + * + * @param dev DAQ device + * @param channel Channel index + * @param type Alert type + * @param timeout_ms Time to inhibit the alert in milliseconds + * + * @retval 0 on success + * @retval -EINVAL if the channel is invalid + */ +int daq_inhibit_alert(const struct device *dev, int channel, enum daq_alert_type type, + int16_t timeout_ms); + +/** + * Set a filter to decide if a sample is used for the filtered value + * + * Alerts are checked for all samples. + * + * @param dev DAQ device + * @param filter Sample filter callback or NULL to use all samples + * @param channel_mask Bit mask of the channels the filter applies to + * + * @retval 0 on success + */ +int daq_set_sample_filter(const struct device *dev, daq_sample_filter_t filter, + uint32_t channel_mask); + +/** + * Set a callback to be called after each new sample of all channels + * + * @param dev DAQ device + * @param callback Sample callback or NULL to disable + * + * @retval 0 on success + */ +int daq_set_sample_callback(const struct device *dev, daq_sample_callback_t callback); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* LIBRESOLAR_DRIVERS_DAQ_H_ */ diff --git a/include/libresolar/drivers/daq_emul.h b/include/libresolar/drivers/daq_emul.h new file mode 100644 index 0000000..ea95b07 --- /dev/null +++ b/include/libresolar/drivers/daq_emul.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef LIBRESOLAR_DRIVERS_DAQ_EMUL_H_ +#define LIBRESOLAR_DRIVERS_DAQ_EMUL_H_ + +/** + * @file + * @brief Test API of the emulated DAQ driver + * + * The emulated DAQ doesn't sample by itself. Readings are set with daq_emul_set_raw() or + * daq_emul_set_value() and processed like a new sample of the ADC with daq_emul_process(). + * + * The reference voltage is fixed to DAQ_EMUL_VREF_MV. + */ + +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** Fixed reference voltage of the emulated DAQ in millivolts */ +#define DAQ_EMUL_VREF_MV 3300 + +/** + * Set the raw reading of a channel for the next sample + * + * @param dev DAQ device + * @param channel Channel index + * @param raw 16-bit raw reading + * + * @retval 0 on success + * @retval -EINVAL if the channel is invalid + */ +int daq_emul_set_raw(const struct device *dev, int channel, uint16_t raw); + +/** + * Set the reading of a channel for the next sample as scaled value + * + * The value is converted to a 12-bit reading, like a real ADC would provide. + * + * @param dev DAQ device + * @param channel Channel index + * @param value Scaled value, e.g. in volts or amps + * + * @retval 0 on success + * @retval -EINVAL if the channel is invalid + */ +int daq_emul_set_value(const struct device *dev, int channel, float value); + +/** + * Process the current reading of a channel like a new sample (filter and alerts) + * + * @param dev DAQ device + * @param channel Channel index + * + * @retval 0 on success + * @retval -EINVAL if the channel is invalid + */ +int daq_emul_process(const struct device *dev, int channel); + +/** + * Process the current readings of all channels and call the sample callback + * + * @param dev DAQ device + */ +void daq_emul_process_all(const struct device *dev); + +/** + * Set the filtered values of all channels to the current readings + * + * @param dev DAQ device + */ +void daq_emul_preset_filtered(const struct device *dev); + +/** + * Reset the filtered values of all channels to zero + * + * @param dev DAQ device + */ +void daq_emul_reset_filtered(const struct device *dev); + +#ifdef __cplusplus +} +#endif + +#endif /* LIBRESOLAR_DRIVERS_DAQ_EMUL_H_ */ diff --git a/tests/drivers/daq/CMakeLists.txt b/tests/drivers/daq/CMakeLists.txt new file mode 100644 index 0000000..fe52e04 --- /dev/null +++ b/tests/drivers/daq/CMakeLists.txt @@ -0,0 +1,8 @@ +# Copyright (c) The Libre Solar Project Contributors +# SPDX-License-Identifier: Apache-2.0 + +cmake_minimum_required(VERSION 3.20.0) +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) +project(daq) + +target_sources(app PRIVATE src/main.c) diff --git a/tests/drivers/daq/boards/native_sim.overlay b/tests/drivers/daq/boards/native_sim.overlay new file mode 100644 index 0000000..1361c55 --- /dev/null +++ b/tests/drivers/daq/boards/native_sim.overlay @@ -0,0 +1,37 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/ { + test_adc: test-adc { + compatible = "zephyr,dummy-adc"; + #io-channel-cells = <1>; + }; + + daq: daq { + compatible = "libresolar,daq-emul"; + + v-in { + io-channels = <&test_adc 3>; + multiplier = <105600>; + divider = <5600>; + }; + + /* bi-directional current measurement with zero point at half of the ADC range */ + i-bidir { + io-channels = <&test_adc 1>; + multiplier = <1000>; + divider = <50>; + offset = <32768>; + filter-const = <3>; + }; + + temp-mcu { + io-channels = <&test_adc 12>; + multiplier = <1>; + divider = <1>; + }; + }; +}; diff --git a/tests/drivers/daq/boards/native_sim_native_64.overlay b/tests/drivers/daq/boards/native_sim_native_64.overlay new file mode 100644 index 0000000..1361c55 --- /dev/null +++ b/tests/drivers/daq/boards/native_sim_native_64.overlay @@ -0,0 +1,37 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/ { + test_adc: test-adc { + compatible = "zephyr,dummy-adc"; + #io-channel-cells = <1>; + }; + + daq: daq { + compatible = "libresolar,daq-emul"; + + v-in { + io-channels = <&test_adc 3>; + multiplier = <105600>; + divider = <5600>; + }; + + /* bi-directional current measurement with zero point at half of the ADC range */ + i-bidir { + io-channels = <&test_adc 1>; + multiplier = <1000>; + divider = <50>; + offset = <32768>; + filter-const = <3>; + }; + + temp-mcu { + io-channels = <&test_adc 12>; + multiplier = <1>; + divider = <1>; + }; + }; +}; diff --git a/tests/drivers/daq/prj.conf b/tests/drivers/daq/prj.conf new file mode 100644 index 0000000..9467c29 --- /dev/null +++ b/tests/drivers/daq/prj.conf @@ -0,0 +1 @@ +CONFIG_ZTEST=y diff --git a/tests/drivers/daq/src/main.c b/tests/drivers/daq/src/main.c new file mode 100644 index 0000000..2e0f4ff --- /dev/null +++ b/tests/drivers/daq/src/main.c @@ -0,0 +1,311 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include + +#include +#include + +#define DAQ_NODE DT_NODELABEL(daq) + +#define CH_V_IN DAQ_CHANNEL(DAQ_NODE, v_in) +#define CH_I_BIDIR DAQ_CHANNEL(DAQ_NODE, i_bidir) +#define CH_TEMP DAQ_CHANNEL(DAQ_NODE, temp_mcu) + +#define I_BIDIR_OFFSET DT_PROP(DT_CHILD(DAQ_NODE, i_bidir), offset) + +/* resolution of 12-bit readings for the v-in channel (gain 105.6 / 5.6) */ +#define V_IN_LSB (3.3F / 4096 * 105.6F / 5.6F) + +static const struct device *const dev = DEVICE_DT_GET(DAQ_NODE); + +static int alert_count; +static int alert_channel; +static int sample_count; +static bool sample_filter_result; + +static void alert_callback(const struct device *d, int channel) +{ + alert_count++; + alert_channel = channel; +} + +static bool sample_filter(const struct device *d, int channel) +{ + return sample_filter_result; +} + +static void sample_callback(const struct device *d) +{ + sample_count++; +} + +static void process_samples(int channel, int count) +{ + for (int i = 0; i < count; i++) { + zassert_ok(daq_emul_process(dev, channel)); + } +} + +static void *daq_setup(void) +{ + zassert_true(device_is_ready(dev), "DAQ device not ready"); + + return NULL; +} + +static void daq_before(void *fixture) +{ + ARG_UNUSED(fixture); + + /* restore offsets from devicetree, as they may have been changed by calibration */ + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, 0)); + zassert_ok(daq_emul_set_raw(dev, CH_I_BIDIR, I_BIDIR_OFFSET)); + zassert_ok(daq_emul_set_raw(dev, CH_TEMP, 0)); + daq_emul_preset_filtered(dev); + zassert_ok(daq_calibrate_offset(dev, CH_V_IN)); + zassert_ok(daq_calibrate_offset(dev, CH_I_BIDIR)); + + for (int ch = CH_V_IN; ch <= CH_TEMP; ch++) { + zassert_ok(daq_set_alert(dev, ch, DAQ_ALERT_UPPER, 0, NULL)); + zassert_ok(daq_set_alert(dev, ch, DAQ_ALERT_LOWER, 0, NULL)); + zassert_ok(daq_inhibit_alert(dev, ch, DAQ_ALERT_UPPER, 0)); + zassert_ok(daq_inhibit_alert(dev, ch, DAQ_ALERT_LOWER, 0)); + } + + zassert_ok(daq_set_sample_filter(dev, NULL, 0)); + zassert_ok(daq_set_sample_callback(dev, NULL)); + + alert_count = 0; + alert_channel = -1; + sample_count = 0; +} + +ZTEST(daq, test_channel_index) +{ + zassert_equal(CH_V_IN, 0); + zassert_equal(CH_I_BIDIR, 1); + zassert_equal(CH_TEMP, 2); +} + +ZTEST(daq, test_invalid_channel) +{ + zassert_equal(daq_get_raw(dev, -1), -EINVAL); + zassert_equal(daq_get_raw(dev, 3), -EINVAL); + zassert_equal(daq_calibrate_offset(dev, 3), -EINVAL); + zassert_equal(daq_set_alert(dev, 3, DAQ_ALERT_UPPER, 1.0F, alert_callback), -EINVAL); + zassert_equal(daq_inhibit_alert(dev, 3, DAQ_ALERT_UPPER, 10), -EINVAL); + zassert_equal(daq_emul_process(dev, 3), -EINVAL); +} + +ZTEST(daq, test_vref) +{ + zassert_equal(daq_get_vref_mv(dev), DAQ_EMUL_VREF_MV); +} + +ZTEST(daq, test_raw_to_pin_voltage) +{ + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, 0)); + daq_emul_preset_filtered(dev); + zassert_equal(daq_get_raw(dev, CH_V_IN), 0); + zassert_within(daq_get_pin_voltage(dev, CH_V_IN), 0.0F, 0.001F); + + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, 32767)); + daq_emul_preset_filtered(dev); + zassert_equal(daq_get_raw(dev, CH_V_IN), 32767); + zassert_within(daq_get_pin_voltage(dev, CH_V_IN), 1.65F, 0.01F); + + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, 65535)); + daq_emul_preset_filtered(dev); + zassert_equal(daq_get_raw(dev, CH_V_IN), 65535); + zassert_within(daq_get_pin_voltage(dev, CH_V_IN), 3.3F, 0.01F); +} + +ZTEST(daq, test_value_with_gain) +{ + zassert_ok(daq_emul_set_value(dev, CH_V_IN, 12.0F)); + daq_emul_preset_filtered(dev); + zassert_within(daq_get_value(dev, CH_V_IN), 12.0F, V_IN_LSB); +} + +ZTEST(daq, test_value_with_offset) +{ + zassert_ok(daq_emul_set_value(dev, CH_I_BIDIR, 5.0F)); + daq_emul_preset_filtered(dev); + zassert_within(daq_get_value(dev, CH_I_BIDIR), 5.0F, 0.05F); + + zassert_ok(daq_emul_set_value(dev, CH_I_BIDIR, -5.0F)); + daq_emul_preset_filtered(dev); + zassert_within(daq_get_value(dev, CH_I_BIDIR), -5.0F, 0.05F); +} + +ZTEST(daq, test_calibrate_offset) +{ + zassert_ok(daq_emul_set_raw(dev, CH_I_BIDIR, I_BIDIR_OFFSET + 500)); + daq_emul_preset_filtered(dev); + zassert_true(daq_get_value(dev, CH_I_BIDIR) > 0.5F); + + zassert_ok(daq_calibrate_offset(dev, CH_I_BIDIR)); + zassert_within(daq_get_value(dev, CH_I_BIDIR), 0.0F, 0.001F); +} + +ZTEST(daq, test_filter_convergence) +{ + daq_emul_reset_filtered(dev); + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, 20000)); + zassert_ok(daq_emul_set_raw(dev, CH_I_BIDIR, 40000)); + + /* first sample is attenuated by the filter */ + daq_emul_process_all(dev); + zassert_true(daq_get_raw(dev, CH_V_IN) < 20000); + + /* collect samples until the filtered values have converged */ + for (int i = 0; i < 1000; i++) { + daq_emul_process_all(dev); + } + zassert_equal(daq_get_raw(dev, CH_V_IN), 20000); + zassert_equal(daq_get_raw(dev, CH_I_BIDIR), 40000); +} + +ZTEST(daq, test_alert_upper_debounce) +{ + zassert_ok(daq_set_alert(dev, CH_V_IN, DAQ_ALERT_UPPER, 15.0F, alert_callback)); + + zassert_ok(daq_emul_set_value(dev, CH_V_IN, 14.0F)); + process_samples(CH_V_IN, 5); + zassert_equal(alert_count, 0); + + /* triggered at the second sample above the limit and then for each sample */ + zassert_ok(daq_emul_set_value(dev, CH_V_IN, 16.0F)); + process_samples(CH_V_IN, 1); + zassert_equal(alert_count, 0); + process_samples(CH_V_IN, 1); + zassert_equal(alert_count, 1); + zassert_equal(alert_channel, CH_V_IN); + process_samples(CH_V_IN, 1); + zassert_equal(alert_count, 2); + + /* a single sample below the limit resets the debouncing */ + zassert_ok(daq_emul_set_value(dev, CH_V_IN, 14.0F)); + process_samples(CH_V_IN, 1); + zassert_ok(daq_emul_set_value(dev, CH_V_IN, 16.0F)); + process_samples(CH_V_IN, 1); + zassert_equal(alert_count, 2); +} + +ZTEST(daq, test_alert_lower) +{ + zassert_ok(daq_set_alert(dev, CH_V_IN, DAQ_ALERT_LOWER, 10.0F, alert_callback)); + + zassert_ok(daq_emul_set_value(dev, CH_V_IN, 11.0F)); + process_samples(CH_V_IN, 5); + zassert_equal(alert_count, 0); + + zassert_ok(daq_emul_set_value(dev, CH_V_IN, 9.0F)); + process_samples(CH_V_IN, 2); + zassert_equal(alert_count, 1); +} + +ZTEST(daq, test_alert_disabled) +{ + zassert_ok(daq_set_alert(dev, CH_V_IN, DAQ_ALERT_UPPER, 15.0F, alert_callback)); + zassert_ok(daq_set_alert(dev, CH_V_IN, DAQ_ALERT_UPPER, 15.0F, NULL)); + + zassert_ok(daq_emul_set_value(dev, CH_V_IN, 16.0F)); + process_samples(CH_V_IN, 5); + zassert_equal(alert_count, 0); +} + +ZTEST(daq, test_alert_inhibit) +{ + zassert_ok(daq_set_alert(dev, CH_V_IN, DAQ_ALERT_UPPER, 15.0F, alert_callback)); + zassert_ok(daq_inhibit_alert(dev, CH_V_IN, DAQ_ALERT_UPPER, 10)); + + /* inhibit time plus regular debouncing of 2 samples */ + zassert_ok(daq_emul_set_value(dev, CH_V_IN, 16.0F)); + process_samples(CH_V_IN, 11); + zassert_equal(alert_count, 0); + process_samples(CH_V_IN, 1); + zassert_equal(alert_count, 1); +} + +ZTEST(daq, test_alert_limit_clamped) +{ + /* limits beyond the range of the ADC are clamped instead of overflowing */ + zassert_ok(daq_set_alert(dev, CH_V_IN, DAQ_ALERT_UPPER, 10000.0F, alert_callback)); + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, UINT16_MAX - 1)); + process_samples(CH_V_IN, 3); + zassert_equal(alert_count, 0); + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, UINT16_MAX)); + process_samples(CH_V_IN, 2); + zassert_equal(alert_count, 1); + + zassert_ok(daq_set_alert(dev, CH_V_IN, DAQ_ALERT_UPPER, 0, NULL)); + zassert_ok(daq_set_alert(dev, CH_V_IN, DAQ_ALERT_LOWER, -10000.0F, alert_callback)); + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, 1)); + process_samples(CH_V_IN, 3); + zassert_equal(alert_count, 1); + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, 0)); + process_samples(CH_V_IN, 2); + zassert_equal(alert_count, 2); +} + +ZTEST(daq, test_sample_filter) +{ + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, 1000)); + zassert_ok(daq_emul_set_raw(dev, CH_I_BIDIR, 1000)); + daq_emul_preset_filtered(dev); + + zassert_ok(daq_set_sample_filter(dev, sample_filter, BIT(CH_V_IN))); + zassert_ok(daq_set_alert(dev, CH_V_IN, DAQ_ALERT_UPPER, 0.0F, alert_callback)); + + /* rejected samples are not filtered, but alerts are still checked */ + sample_filter_result = false; + zassert_ok(daq_emul_set_raw(dev, CH_V_IN, 2000)); + zassert_ok(daq_emul_set_raw(dev, CH_I_BIDIR, 2000)); + for (int i = 0; i < 100; i++) { + daq_emul_process_all(dev); + } + zassert_equal(daq_get_raw(dev, CH_V_IN), 1000); + zassert_equal(daq_get_raw(dev, CH_I_BIDIR), 2000); + zassert_true(alert_count > 0); + + sample_filter_result = true; + for (int i = 0; i < 1000; i++) { + daq_emul_process_all(dev); + } + zassert_equal(daq_get_raw(dev, CH_V_IN), 2000); +} + +ZTEST(daq, test_sample_callback) +{ + daq_emul_process_all(dev); + zassert_equal(sample_count, 0); + + zassert_ok(daq_set_sample_callback(dev, sample_callback)); + daq_emul_process_all(dev); + daq_emul_process_all(dev); + zassert_equal(sample_count, 2); +} + +ZTEST(daq, test_internal_temp) +{ + float temp; + + /* calibration values of the emulator: 0.76 V at 30 °C and 1.01 V at 130 °C */ + zassert_ok(daq_emul_set_raw(dev, CH_TEMP, (4096 * 760 / 3300) << 4)); + daq_emul_preset_filtered(dev); + zassert_ok(daq_get_internal_temp(dev, &temp)); + zassert_within(temp, 30.0F, 0.5F); + + zassert_ok(daq_emul_set_raw(dev, CH_TEMP, (4096 * 1010 / 3300) << 4)); + daq_emul_preset_filtered(dev); + zassert_ok(daq_get_internal_temp(dev, &temp)); + zassert_within(temp, 130.0F, 0.5F); +} + +ZTEST_SUITE(daq, NULL, daq_setup, daq_before, NULL, NULL); diff --git a/tests/drivers/daq/testcase.yaml b/tests/drivers/daq/testcase.yaml new file mode 100644 index 0000000..20d7d4d --- /dev/null +++ b/tests/drivers/daq/testcase.yaml @@ -0,0 +1,10 @@ +tests: + drivers.daq.emul: + tags: + - drivers + - daq + platform_allow: + - native_sim + - native_sim/native/64 + integration_platforms: + - native_sim