app: use DAQ driver

Replace the register-level ADC, DAC and DMA handling in daq_driver.c by
the new DAQ driver. The application only maps the measurements to the
power ports and DC buses and handles the alerts. The factory calibration
values are removed from mcu.h, as they are provided by the driver now.

All boards are migrated to the new libresolar,stm32-daq compatible. The
unit tests use the emulated DAQ.

The high-side overvoltage limit is now set after the DAQ setup. Before,
the limit was calculated before any reading of the internal reference
voltage was available, so that the alert never triggered on boards
without fixed reference voltage (STM32F0 and STM32L0).

Note for out-of-tree boards: The adc-inputs node must use the compatible
libresolar,stm32-daq instead of adc-inputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Martin Jäger
2026-11-01 12:16:45 +01:00
co-authored by Claude Opus 5.5
parent 82c5d1542d
commit 55f1c86523
27 changed files with 158 additions and 859 deletions
-7
View File
@@ -352,13 +352,6 @@ config CAN_LOG_LEVEL
help
Log level for the CAN module (if included). 0=off, 1=ERR, 2=WRN, 3=INF, 4=DBG
config DAQ_LOG_LEVEL
int "Log level for the DAQ module"
default 2
depends on LOG
help
Log level for the DAQ module. 0=off, 1=ERR, 2=WRN, 3=INF, 4=DBG
config DATA_OBJECTS_LOG_LEVEL
int "Log level for the data objects module"
default 2
+1 -1
View File
@@ -52,7 +52,7 @@
};
adc-inputs {
compatible = "adc-inputs";
compatible = "libresolar,stm32-daq";
v-low {
io-channels = <&adc1 12>;
-1
View File
@@ -5,7 +5,6 @@ zephyr_include_directories(.)
target_sources(app PRIVATE
bat_charger.cpp
daq.cpp
daq_driver.c
device_status.cpp
dcdc.cpp
hardware.cpp
+72 -206
View File
@@ -9,12 +9,10 @@
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(daq, CONFIG_DAQ_LOG_LEVEL);
LOG_MODULE_REGISTER(daq_app, CONFIG_DAQ_LOG_LEVEL);
#include <assert.h>
#include <math.h> // log for thermistor calculation
#include "mcu.h"
#include "setup.h"
// typical value for Semitec 103AT-5 thermistor: 3435
@@ -27,66 +25,22 @@ LOG_MODULE_REGISTER(daq, CONFIG_DAQ_LOG_LEVEL);
#define LV_TERMINAL_CURRENT_FILTER_CONST 0.0099F
#define PWM_CURRENT_FILTER_CONST 0.0625F // 1.5 seconds
#if BOARD_HAS_DCDC
static uint16_t dcdc_current_offset_raw;
#endif
#if BOARD_HAS_PWM_PORT
static uint16_t pwm_current_offset_raw;
#endif
#if BOARD_HAS_LOAD_OUTPUT
static uint16_t load_current_offset_raw;
#endif
#define ADC_GAIN(name) \
((float)DT_PROP(DT_CHILD(DAQ_NODE, name), multiplier) \
/ DT_PROP(DT_CHILD(DAQ_NODE, name), divider))
// 16-bit ADC raw readings (actually left-aligned 12-bit, i.e. left-shifted by 4 bits)
volatile uint16_t adc_readings[NUM_ADC_CH] = {};
static const struct device *const daq = DAQ_DEV;
// filtered raw readings left-shifted by additional adc_filter_const[channel] bits
volatile uint32_t adc_filtered[NUM_ADC_CH] = {};
static volatile AdcAlert adc_alerts_upper[NUM_ADC_CH] = {};
static volatile AdcAlert adc_alerts_lower[NUM_ADC_CH] = {};
/*
* Channel-specific ADC filter constant from devicetree
*
* multiplier = 1/(2^adc_filter_const[channel])
*/
#define ADC_FILTER_CONST(node_id) DT_PROP(node_id, filter_const),
static const uint8_t adc_filter_const[NUM_ADC_CH] = { DT_FOREACH_CHILD(DT_PATH(adc_inputs),
ADC_FILTER_CONST) };
/**
* Average value for ADC channel
*
* @param channel valid ADC channel position using ADC_POS() macro
*/
static inline uint32_t adc_raw_filtered(uint32_t channel)
{
return adc_filtered[channel] >> adc_filter_const[channel];
}
/**
* Measured current/voltage for ADC channel after average and scaling
*
* @param channel valid ADC channel position using ADC_POS() macro
* @param vref reference voltage in millivolts
* @param offset offset added to raw ADC value before applying gain
*
* @return scaled final value in volts/amps
*/
static inline float adc_scaled(uint32_t channel, int32_t vref, const float gain, int32_t offset = 0)
{
return adc_raw_to_voltage(adc_raw_filtered(channel) - offset, vref) * gain;
}
static inline float ntc_temp(uint32_t channel, int32_t vref, float ntc_series_resistor)
static inline float ntc_temp(int channel, float ntc_series_resistor)
{
/** \todo Improved (faster) temperature calculation:
https://www.embeddedrelated.com/showarticle/91.php
*/
int vref = daq_get_vref_mv(daq);
// voltage read by ADC (mV)
float v_temp = adc_raw_to_voltage(adc_raw_filtered(channel), vref) * 1000;
float v_temp = daq_get_pin_voltage(daq, channel) * 1000;
// resistance of NTC (Ohm)
float rts = ntc_series_resistor * v_temp / (vref - v_temp);
@@ -98,77 +52,56 @@ static inline float ntc_temp(uint32_t channel, int32_t vref, float ntc_series_re
void calibrate_current_sensors()
{
#if BOARD_HAS_DCDC
dcdc_current_offset_raw = adc_raw_filtered(ADC_POS(i_dcdc));
daq_calibrate_offset(daq, DAQ_CH(i_dcdc));
#endif
#if BOARD_HAS_PWM_PORT
pwm_current_offset_raw = adc_raw_filtered(ADC_POS(i_pwm));
daq_calibrate_offset(daq, DAQ_CH(i_pwm));
#endif
#if BOARD_HAS_LOAD_OUTPUT
load_current_offset_raw = adc_raw_filtered(ADC_POS(i_load));
daq_calibrate_offset(daq, DAQ_CH(i_load));
#endif
}
void adc_update_value(unsigned int pos)
{
#if BOARD_HAS_PWM_PORT
static bool pwm_sample_filter(const struct device *dev, int channel)
{
// only read input voltage and current when switch is on or permanently off
if ((pos != ADC_POS(v_pwm) && pos != ADC_POS(i_pwm)) || pwm_switch.signal_high()
|| pwm_switch.active() == false)
return pwm_switch.signal_high() || pwm_switch.active() == false;
}
#endif
{
/*
* Low-pass filtering of ADC 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^adc_filter_const[pos])
*
* Remarks regarding below implementation optimized for efficiency:
*
* 1. adc_readings has different fixed-point math format, so that it would have to be
* aligned with << adc_filter_const[pos] before calculation. Not aligning it is
* equivalent to multiplication with c:
* adc_readings[pos] == c * (adc_readings[pos] << adc_filter_const[pos])
*
* 2. c * adc_filtered[pos] == adc_filtered[pos] >> adc_filter_const[pos]
*/
adc_filtered[pos] = (uint32_t)adc_readings[pos] + adc_filtered[pos]
- (adc_filtered[pos] >> adc_filter_const[pos]);
#ifdef CONFIG_CUSTOM_DCDC_CONTROLLER
static void dcdc_sample_callback(const struct device *dev)
{
dcdc_low_level_controller();
}
#endif
void daq_setup()
{
if (!device_is_ready(daq)) {
LOG_ERR("DAQ device not ready");
return;
}
// check upper alerts
adc_alerts_upper[pos].debounce_ms++;
if (adc_alerts_upper[pos].callback != NULL && adc_readings[pos] >= adc_alerts_upper[pos].limit)
{
if (adc_alerts_upper[pos].debounce_ms > 1) {
// create function pointer and call function
adc_alerts_upper[pos].callback();
}
}
else if (adc_alerts_upper[pos].debounce_ms > 0) {
// reset debounce ms counter only if already close to triggering to allow setting negative
// values to specify a one-time inhibit delay
adc_alerts_upper[pos].debounce_ms = 0;
}
#if BOARD_HAS_PWM_PORT
daq_set_sample_filter(daq, pwm_sample_filter, BIT(DAQ_CH(v_pwm)) | BIT(DAQ_CH(i_pwm)));
#endif
// same for lower alerts
adc_alerts_lower[pos].debounce_ms++;
if (adc_alerts_lower[pos].callback != NULL && adc_readings[pos] <= adc_alerts_lower[pos].limit)
{
if (adc_alerts_lower[pos].debounce_ms > 1) {
adc_alerts_lower[pos].callback();
}
}
else if (adc_alerts_lower[pos].debounce_ms > 0) {
adc_alerts_lower[pos].debounce_ms = 0;
}
#ifdef CONFIG_CUSTOM_DCDC_CONTROLLER
daq_set_sample_callback(daq, dcdc_sample_callback);
#endif
k_sleep(K_MSEC(500)); // wait for ADC to collect some measurement values
daq_update();
calibrate_current_sensors();
daq_update();
}
void daq_update()
{
int vref = VREF;
// calculate lower voltage first, as it is needed for PWM terminal voltage calculation
lv_bus.voltage = adc_scaled(ADC_POS(v_low), vref, ADC_GAIN(v_low));
lv_bus.voltage = daq_get_value(daq, DAQ_CH(v_low));
if (lv_bus.voltage_filtered != 0.0F) {
lv_bus.voltage_filtered = LV_BUS_VOLTAGE_FILTER_CONST * lv_bus.voltage
@@ -180,7 +113,7 @@ void daq_update()
}
#if BOARD_HAS_DCDC
hv_bus.voltage = adc_scaled(ADC_POS(v_high), vref, ADC_GAIN(v_high));
hv_bus.voltage = daq_get_value(daq, DAQ_CH(v_high));
if (hv_bus.voltage_filtered != 0.0F) {
hv_bus.voltage_filtered = HV_BUS_VOLTAGE_FILTER_CONST * hv_bus.voltage
@@ -193,12 +126,11 @@ void daq_update()
#endif
#if BOARD_HAS_PWM_PORT
pwm_switch.ext_voltage =
lv_bus.voltage - adc_scaled(ADC_POS(v_pwm), vref, ADC_GAIN(v_pwm), ADC_OFFSET(v_pwm));
pwm_switch.ext_voltage = lv_bus.voltage - daq_get_value(daq, DAQ_CH(v_pwm));
#endif
#if BOARD_HAS_LOAD_OUTPUT
load.current = adc_scaled(ADC_POS(i_load), vref, ADC_GAIN(i_load), load_current_offset_raw);
load.current = daq_get_value(daq, DAQ_CH(i_load));
float load_current = load.current;
#else
float load_current = 0; // value used below, so we still need to define the variable
@@ -209,9 +141,7 @@ void daq_update()
#if BOARD_HAS_PWM_PORT
// current multiplied with PWM duty cycle for PWM charger to get avg current for correct power
// calculation
pwm_switch.current =
-pwm_switch.get_duty_cycle()
* adc_scaled(ADC_POS(i_pwm), vref, ADC_GAIN(i_pwm), pwm_current_offset_raw);
pwm_switch.current = -pwm_switch.get_duty_cycle() * daq_get_value(daq, DAQ_CH(i_pwm));
pwm_switch.current_filtered = PWM_CURRENT_FILTER_CONST * pwm_switch.current
+ (1.0F - PWM_CURRENT_FILTER_CONST) * pwm_switch.current_filtered;
@@ -221,8 +151,7 @@ void daq_update()
#endif
#if BOARD_HAS_DCDC
dcdc.inductor_current =
adc_scaled(ADC_POS(i_dcdc), vref, ADC_GAIN(i_dcdc), dcdc_current_offset_raw);
dcdc.inductor_current = daq_get_value(daq, DAQ_CH(i_dcdc));
lv_terminal_current += dcdc.inductor_current;
@@ -245,7 +174,7 @@ void daq_update()
#if BOARD_HAS_TEMP_BAT
// battery temperature calculation
float bat_temp = ntc_temp(ADC_POS(temp_bat), vref, ADC_GAIN(temp_bat));
float bat_temp = ntc_temp(DAQ_CH(temp_bat), ADC_GAIN(temp_bat));
if (bat_temp > -50) {
// external sensor connected: take measured value
@@ -260,14 +189,13 @@ void daq_update()
#endif
#if BOARD_HAS_TEMP_FETS
dcdc.temp_mosfets = ntc_temp(ADC_POS(temp_fets), vref, ADC_GAIN(temp_fets));
dcdc.temp_mosfets = ntc_temp(DAQ_CH(temp_fets), ADC_GAIN(temp_fets));
#endif
// internal MCU temperature (calibrated using 12-bit right-aligned readings)
uint16_t adcval = (adc_raw_filtered(ADC_POS(temp_mcu)) >> 4) * vref / VREFINT_VALUE;
dev_stat.internal_temp = (TSENSE_CAL2_VALUE - TSENSE_CAL1_VALUE) / (TSENSE_CAL2 - TSENSE_CAL1)
* (adcval - TSENSE_CAL1)
+ TSENSE_CAL1_VALUE;
float internal_temp;
if (daq_get_internal_temp(daq, &internal_temp) == 0) {
dev_stat.internal_temp = internal_temp;
}
if (dev_stat.internal_temp > 80) {
dev_stat.set_error(ERR_INT_OVERTEMP);
@@ -279,7 +207,7 @@ void daq_update()
// else: keep previous setting
}
void lv_overvoltage_alert()
static void lv_overvoltage_alert(const struct device *dev, int channel)
{
// disable any sort of input
#if BOARD_HAS_DCDC
@@ -293,23 +221,30 @@ void lv_overvoltage_alert()
dev_stat.set_error(ERR_BAT_OVERVOLTAGE);
LOG_ERR("Low-side overvoltage alert, ADC reading: %d limit: %d\n", adc_readings[ADC_POS(v_low)],
adc_alerts_upper[ADC_POS(v_low)].limit);
LOG_ERR("Low-side overvoltage alert");
}
void lv_undervoltage_alert()
static void lv_undervoltage_alert(const struct device *dev, int channel)
{
#if BOARD_HAS_LOAD_OUTPUT
// the battery undervoltage must have been caused by a load current peak
load.stop(ERR_LOAD_VOLTAGE_DIP);
#endif
LOG_ERR("Low-side undervoltage alert, ADC reading: %d limit: %d\n",
adc_readings[ADC_POS(v_low)], adc_alerts_lower[ADC_POS(v_low)].limit);
LOG_ERR("Low-side undervoltage alert");
}
void daq_set_lv_limits(float lv_overvoltage, float lv_undervoltage)
{
// LV side (battery) overvoltage alert
daq_set_alert(daq, DAQ_CH(v_low), DAQ_ALERT_UPPER, lv_overvoltage, lv_overvoltage_alert);
// LV side (battery) undervoltage alert
daq_set_alert(daq, DAQ_CH(v_low), DAQ_ALERT_LOWER, lv_undervoltage, lv_undervoltage_alert);
}
#if BOARD_HAS_DCDC
void hv_overvoltage_alert()
static void hv_overvoltage_alert(const struct device *dev, int channel)
{
dcdc.stop();
@@ -318,85 +253,16 @@ void hv_overvoltage_alert()
dev_stat.set_error(ERR_DCDC_HS_OVERVOLTAGE);
LOG_ERR("High-side overvoltage alert, ADC reading: %d limit: %d\n",
adc_readings[ADC_POS(v_high)], adc_alerts_upper[ADC_POS(v_high)].limit);
}
#endif
void adc_upper_alert_inhibit(int adc_pos, int timeout_ms)
{
// set negative value so that we get a final debouncing of this timeout + the original
// delay in the alert function (currently only waiting for 2 samples = 2 ms)
adc_alerts_upper[adc_pos].debounce_ms = -timeout_ms;
LOG_ERR("High-side overvoltage alert");
}
uint16_t adc_raw_clamp(float scale, float limit)
{
// even if we have a higher voltage limit, we must limit it
// to the max value the ADC will be able to deliver
const float limit_scaled = limit * scale;
return limit_scaled > (float)UINT16_MAX ? UINT16_MAX : (uint16_t)(limit_scaled);
}
void daq_set_lv_limits(float lv_overvoltage, float lv_undervoltage)
{
float scale = (((4096 << 4) * 1000) / ADC_GAIN(v_low)) / (float)VREF;
// LV side (battery) overvoltage alert
adc_alerts_upper[ADC_POS(v_low)].limit = adc_raw_clamp(scale, lv_overvoltage);
adc_alerts_upper[ADC_POS(v_low)].callback = lv_overvoltage_alert;
// LV side (battery) undervoltage alert
adc_alerts_lower[ADC_POS(v_low)].limit = adc_raw_clamp(scale, lv_undervoltage);
adc_alerts_lower[ADC_POS(v_low)].callback = lv_undervoltage_alert;
}
#if BOARD_HAS_DCDC
void daq_set_hv_limit(float hv_overvoltage)
{
float scale = (((4096 << 4) * 1000) / ADC_GAIN(v_high)) / (float)VREF;
// HV side (solar/grid) overvoltage alert
adc_alerts_upper[ADC_POS(v_high)].limit = adc_raw_clamp(scale, hv_overvoltage);
adc_alerts_upper[ADC_POS(v_high)].callback = hv_overvoltage_alert;
int err =
daq_set_alert(daq, DAQ_CH(v_high), DAQ_ALERT_UPPER, hv_overvoltage, hv_overvoltage_alert);
if (err != 0) {
LOG_ERR("Failed to set high-side overvoltage alert: %d", err);
}
}
#endif
#if !defined(CONFIG_SOC_FAMILY_STM32)
#include "daq_stub.h"
void prepare_adc_readings(AdcValues values)
{
adc_readings[ADC_POS(vref_mcu)] = (uint16_t)(1.224 / 3.3 * 4096) << 4;
adc_readings[ADC_POS(v_high)] =
(uint16_t)((values.solar_voltage / ADC_GAIN(v_high)) / 3.3f * 4096) << 4;
adc_readings[ADC_POS(v_low)] =
(uint16_t)((values.battery_voltage / ADC_GAIN(v_low)) / 3.3f * 4096) << 4;
adc_readings[ADC_POS(i_dcdc)] =
(uint16_t)((values.dcdc_current / ADC_GAIN(i_dcdc)) / 3.3f * 4096) << 4;
adc_readings[ADC_POS(i_load)] =
(uint16_t)((values.load_current / ADC_GAIN(i_load)) / 3.3f * 4096) << 4;
}
void prepare_adc_filtered()
{
// initialize also filtered values
for (int i = 0; i < NUM_ADC_CH; i++) {
adc_filtered[i] = adc_readings[i] << adc_filter_const[i];
}
}
void clear_adc_filtered()
{
// initialize also filtered values
for (int i = 0; i < NUM_ADC_CH; i++) {
adc_filtered[i] = 0;
}
}
uint32_t get_adc_filtered(uint32_t channel)
{
return adc_raw_filtered(channel);
}
#endif /* UNIT_TEST */
+17 -96
View File
@@ -8,101 +8,35 @@
* @file
* @brief Data Acquisition (DAQ)
*
* Measurements are taken using ADC with DMA. The DAC is used to generate reference voltages
* for bi-directional current measurement. Data is stored in structs, which are afterwards
* used by the control algorithms
*
* All calculations assume a 16-bit ADC, even though the STM32 ADCs natively support 12-bit.
* Using 16-bit for calculation allows to increase resolution by oversampling. Left-aligned
* 12-bit ADC readings can be treated as 16-bit ADC readings.
* Measurements are taken by the DAQ driver. This module converts them to the measurement values
* stored in the structs of the power ports and DC buses, which are afterwards used by the control
* algorithms.
*/
#ifndef DAQ_H_
#define DAQ_H_
#include <libresolar/drivers/daq.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#ifdef __cplusplus
extern "C" {
#endif
#include <zephyr/kernel.h>
/** DAQ devicetree node */
#define DAQ_NODE DT_PATH(adc_inputs)
#include <stdint.h>
#define ADC_SCALE_FLOAT 65536.0F // 16-bit full scale
#ifdef CONFIG_SOC_SERIES_STM32G4X
// Using internal reference buffer at VREF+ pin, set to 2048 mV
#define VREF (2048)
#elif defined(UNIT_TEST)
#define VREF (3300)
#else
// internal STM reference voltage (calibrated using 12-bit right-aligned readings)
#define VREF (VREFINT_VALUE * VREFINT_CAL / (adc_raw_filtered(ADC_POS(vref_mcu)) >> 4))
#endif
#define ADC_GAIN(name) \
((float)DT_PROP(DT_CHILD(DT_PATH(adc_inputs), name), multiplier) \
/ DT_PROP(DT_CHILD(DT_PATH(adc_inputs), name), divider))
#define ADC_OFFSET(name) (DT_PROP(DT_CHILD(DT_PATH(adc_inputs), name), offset))
/*
* Find out the position in the ADC reading array for a channel identified by its Devicetree node
*/
#define ADC_POS(node) DT_N_S_adc_inputs_S_##node##_ADC_POS
/*
* Creates a unique name for below enum
*/
#define ADC_ENUM(node) node##_ADC_POS,
/*
* Enum for numbering of ADC channels as they are written by the DMA controller
*
* The channels must be specified in ascending order in the board.dts file.
*/
// cppcheck-suppress syntaxError
enum
{
DT_FOREACH_CHILD(DT_PATH(adc_inputs), ADC_ENUM)
NUM_ADC_CH // trick to get the number of elements
};
/** DAQ device */
#define DAQ_DEV DEVICE_DT_GET(DAQ_NODE)
/**
* Struct to define upper and lower limit alerts for any ADC channel
* Get the channel index of a DAQ input
*
* @param name Lower-case-and-underscores name of the child node of the DAQ node, e.g. v_low
*/
typedef struct
{
void (*callback)(); ///< Function to be called when limits are exceeded
uint16_t limit; ///< ADC reading for lower limit
int16_t debounce_ms; ///< Milliseconds delay for triggering alert
} AdcAlert;
/**
* Convert 16-bit raw ADC reading to voltage
*
* @param raw 16-bit ADC reading
* @param vref_mV Reference voltage in millivolts
*
* @return Voltage in volts
*/
static inline float adc_raw_to_voltage(int32_t raw, int32_t vref_mV)
{
return (raw * vref_mV) / (ADC_SCALE_FLOAT * 1000);
}
/**
* Convert voltage to 16-bit raw ADC reading
*
* @param voltage Voltage in volts
* @param vref_mV Reference voltage in millivolts
*
* @return 16-bit ADC reading
*/
static inline int32_t adc_voltage_to_raw(float voltage, int32_t vref_mV)
{
return voltage / vref_mV * ADC_SCALE_FLOAT * 1000;
}
#define DAQ_CH(name) DAQ_CHANNEL(DAQ_NODE, name)
/**
* Set offset vs. actual measured value, i.e. sets zero current point.
@@ -117,15 +51,10 @@ void calibrate_current_sensors(void);
void daq_update(void);
/**
* Initializes ADC, DAC and DMA
* Waits for initial measurements and calibrates the current sensors
*/
void daq_setup(void);
/**
* Read, filter and check raw ADC readings stored by DMA controller
*/
void adc_update_value(unsigned int pos);
/**
* Set lv side (battery) voltage limits where an alert should be triggered
*
@@ -141,14 +70,6 @@ void daq_set_lv_limits(float lv_overvoltage, float lv_undervoltage);
*/
void daq_set_hv_limit(float hv_overvoltage);
/**
* Add an inhibit delay to the alerts to disable it temporarily
*
* @param adc_pos The position of the ADC measurement channel
* @param timeout_ms Timeout in milliseconds
*/
void adc_upper_alert_inhibit(int adc_pos, int timeout_ms);
#ifdef __cplusplus
}
#endif
-368
View File
@@ -1,368 +0,0 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "daq.h"
#ifndef UNIT_TEST
#include <inttypes.h>
#include <stdint.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/kernel.h>
#include <stm32_ll_adc.h>
#include <stm32_ll_bus.h>
#include <stm32_ll_dac.h>
#include <stm32_ll_dma.h>
#include <stm32_ll_system.h>
#include "dcdc.h" // for low-level control function called by DMA
#if defined(CONFIG_SOC_SERIES_STM32F0X) || defined(CONFIG_SOC_SERIES_STM32L0X)
// automatic channel selection based on devicetree settings
#define ADC_CHSEL_FN(node_id) (1UL << DT_PHA(node_id, io_channels, input)) |
#define ADC_CHSEL (DT_FOREACH_CHILD(DT_PATH(adc_inputs), ADC_CHSEL_FN) 0)
int num_adc1_ch = NUM_ADC_CH;
#elif defined(CONFIG_SOC_SERIES_STM32G4X)
// create array with selected channel for each ADC input
#define ADC_CH_NUM_(node_id) DT_PHA(node_id, io_channels, input),
static const uint32_t adc_ch_numbers[] = { DT_FOREACH_CHILD(DT_PATH(adc_inputs), ADC_CH_NUM_) };
// create array with ADC instance register address for each ADC input
#define ADC_REG_(node_id) DT_REG_ADDR_BY_IDX(DT_PHANDLE(node_id, io_channels), 0),
static const uint32_t adc_registers[] = { DT_FOREACH_CHILD(DT_PATH(adc_inputs), ADC_REG_) };
// number of channels per ADC peripheral will be calculated in adc_init function
int num_adc1_ch = 0;
int num_adc2_ch = 0;
// 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),
};
#endif /* STM32G4X */
// for ADC and DMA
extern uint16_t adc_readings[];
void adc_update_value(unsigned int pos);
static void vref_setup()
{
#ifdef CONFIG_SOC_SERIES_STM32G4X
// 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) {
}
#endif
}
static void dac_setup()
{
#if defined(CONFIG_SOC_SERIES_STM32F0X) || defined(CONFIG_SOC_SERIES_STM32L0X)
/* DAC1 at PA4 for load and DC/DC / PWM switch current measurement * 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);
#elif defined(CONFIG_SOC_SERIES_STM32G4X)
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);
#endif
}
static void adc_init(ADC_TypeDef *adc)
{
LL_ADC_Disable(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_STM32G4X)
// 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);
// LL_RCC_SetADCClockSource(LL_RCC_ADC12_CLKSOURCE_SYSCLK);
// 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);
// LL_ADC_SetCommonClock(__LL_ADC_COMMON_INSTANCE(adc), LL_ADC_CLOCK_ASYNC_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);
#endif
#if defined(CONFIG_SOC_SERIES_STM32G4X)
LL_ADC_StartCalibration(adc, LL_ADC_SINGLE_ENDED);
#elif defined(CONFIG_SOC_SERIES_STM32F0X) || defined(CONFIG_SOC_SERIES_STM32L0X)
LL_ADC_StartCalibration(adc);
#endif
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);
#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_STM32G4X)
// more complicated sequencer allows to define the sequence independent
// of the channel number (using ranks)
int *num_ch = (adc == ADC1) ? &num_adc1_ch : &num_adc2_ch;
for (int i = 0; i < NUM_ADC_CH; i++) {
if (adc_registers[i] == (uint32_t)adc) {
uint32_t ch_number = adc_ch_numbers[i];
if (ch_number < sizeof(table_channel)) {
LL_ADC_REG_SetSequencerRanks(adc, table_rank[*num_ch], table_channel[ch_number]);
LL_ADC_SetChannelSamplingTime(adc, table_channel[ch_number],
LL_ADC_SAMPLINGTIME_247CYCLES_5);
(*num_ch)++;
}
}
}
LL_ADC_REG_SetSequencerLength(adc, table_seq_len[*num_ch - 1]);
#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);
}
#define V_HIGH_ENABLE_NODE DT_CHILD(DT_PATH(adc_inputs), v_high)
static void adc_setup()
{
#if DT_NODE_EXISTS(DT_PROP(V_HIGH_ENABLE_NODE, enable_gpios))
const struct gpio_dt_spec v_high_enable = GPIO_DT_SPEC_GET(V_HIGH_ENABLE_NODE, enable_gpios);
if (device_is_ready(v_high_enable.port)) {
gpio_pin_configure_dt(&v_high_enable, GPIO_OUTPUT_ACTIVE);
}
#endif
adc_init(ADC1);
#if defined(CONFIG_SOC_SERIES_STM32G4X)
adc_init(ADC2);
#endif
}
static inline void adc_trigger_conversion(struct k_timer *timer_id)
{
LL_ADC_REG_StartConversion(ADC1);
#if defined(CONFIG_SOC_SERIES_STM32G4X)
LL_ADC_REG_StartConversion(ADC2);
#endif
}
static void DMA1_Channel1_IRQHandler(void *args)
{
ARG_UNUSED(args);
if ((DMA1->ISR & DMA_ISR_TCIF1) != 0) // Test if transfer completed on DMA channel 1
{
for (unsigned int i = 0; i < num_adc1_ch; i++) {
adc_update_value(i);
}
}
DMA1->IFCR |= 0x0FFFFFFF; // clear all interrupt registers
}
#if defined(CONFIG_SOC_SERIES_STM32G4X)
static void DMA2_Channel1_IRQHandler(void *args)
{
if ((DMA2->ISR & DMA_ISR_TCIF1) != 0) { // Test if transfer completed on DMA channel 2
for (unsigned int i = num_adc1_ch; i < num_adc1_ch + num_adc2_ch; i++) {
adc_update_value(i);
}
}
DMA2->IFCR |= 0x0FFFFFFF; // clear all interrupt registers
#ifdef CONFIG_CUSTOM_DCDC_CONTROLLER
// Implement this function e.g. for cycle-by-cylce current limitation.
// As it runs in an ISR with high frequency, it must be VERY fast!
dcdc_low_level_controller();
#endif
}
#endif // CONFIG_SOC_SERIES_STM32G4X
// Assuming DMA1 is mapped to ADC1 and DMA2 mapped to ADC2.
static void dma_init(DMA_TypeDef *dma)
{
#if defined(CONFIG_SOC_SERIES_STM32G4X)
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMAMUX1);
if (dma == DMA1) {
LL_DMA_SetPeriphRequest(dma, LL_DMA_CHANNEL_1, LL_DMAMUX_REQ_ADC1);
}
else if (dma == DMA2) {
LL_DMA_SetPeriphRequest(dma, LL_DMA_CHANNEL_1, LL_DMAMUX_REQ_ADC2);
}
#endif // CONFIG_SOC_SERIES_STM32G4X
if (dma == DMA1) {
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1);
LL_DMA_ConfigAddresses(
dma, LL_DMA_CHANNEL_1,
LL_ADC_DMA_GetRegAddr(ADC1, LL_ADC_DMA_REG_REGULAR_DATA), // source address
(uint32_t)(&(adc_readings[0])), // destination address
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, num_adc1_ch);
}
#if defined(CONFIG_SOC_SERIES_STM32G4X)
else if (dma == DMA2) {
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA2);
// If DMA 2 is mapped to ADC 2
LL_DMA_ConfigAddresses(
dma, LL_DMA_CHANNEL_1,
LL_ADC_DMA_GetRegAddr(ADC2, LL_ADC_DMA_REG_REGULAR_DATA), // source address
// destination address = position behind ADC_1 values
(uint32_t)(&(adc_readings[num_adc1_ch])), 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, num_adc2_ch);
}
#endif // CONFIG_SOC_SERIES_STM32G4X
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);
// Configure NVIC for DMA (priority 2: second-lowest value for STM32L0/F0)
if (dma == DMA1) {
IRQ_CONNECT(DMA1_Channel1_IRQn, 2, DMA1_Channel1_IRQHandler, 0, 0);
irq_enable(DMA1_Channel1_IRQn);
}
#if defined(CONFIG_SOC_SERIES_STM32G4X)
else if (dma == DMA2) {
IRQ_CONNECT(DMA2_Channel1_IRQn, 2, DMA2_Channel1_IRQHandler, 0, 0);
irq_enable(DMA2_Channel1_IRQn);
}
#endif // CONFIG_SOC_SERIES_STM32G4X
}
static void dma_setup()
{
dma_init(DMA1);
LL_ADC_REG_StartConversion(ADC1);
#if defined(CONFIG_SOC_SERIES_STM32G4X)
dma_init(DMA2);
LL_ADC_REG_StartConversion(ADC2);
#endif // CONFIG_SOC_SERIES_STM32G4X
}
void daq_setup()
{
static struct k_timer adc_trigger_timer;
vref_setup();
dac_setup();
adc_setup();
dma_setup();
k_timer_init(&adc_trigger_timer, adc_trigger_conversion, NULL);
k_timer_start(&adc_trigger_timer, K_MSEC(1), K_MSEC(1)); // 1 kHz
k_sleep(K_MSEC(500)); // wait for ADC to collect some measurement values
daq_update();
calibrate_current_sensors();
daq_update();
}
#endif // UNIT_TEST
+5 -4
View File
@@ -42,10 +42,6 @@ int main(void)
battery_conf_init(&bat_conf, CONFIG_BAT_TYPE, CONFIG_BAT_NUM_CELLS, CONFIG_BAT_CAPACITY_AH);
battery_conf_overwrite(&bat_conf, &bat_conf_user); // initialize conf_user with same values
#if BOARD_HAS_DCDC
daq_set_hv_limit(DT_PROP(DT_PATH(pcb), hs_voltage_max));
#endif
#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR
solar_terminal.init_solar();
#endif
@@ -60,6 +56,11 @@ int main(void)
// Data Acquisition (DAQ) setup
daq_setup();
#if BOARD_HAS_DCDC
// requires the reference voltage, which may be calculated from initial measurements
daq_set_hv_limit(DT_PROP(DT_PATH(pcb), hs_voltage_max));
#endif
charger.detect_num_batteries(&bat_conf); // check if we have 24V instead of 12V system
charger.init_terminal(&bat_conf);
-40
View File
@@ -21,44 +21,4 @@
#include "stm32g474xx.h"
#endif
// factory calibration values for internal voltage reference and temperature sensor
// (see MCU datasheet, not Reference Manual)
#if defined(CONFIG_SOC_SERIES_STM32F0X)
#define VREFINT_CAL (*((uint16_t *)0x1FFFF7BA)) // VREFINT @3.3V/30°C
#define VREFINT_VALUE 3300 // mV
#define TSENSE_CAL1 (*((uint16_t *)0x1FFFF7B8))
#define TSENSE_CAL2 (*((uint16_t *)0x1FFFF7C2))
#define TSENSE_CAL1_VALUE 30.0 // temperature of first calibration point
#define TSENSE_CAL2_VALUE 110.0 // temperature of second calibration point
#elif defined(CONFIG_SOC_SERIES_STM32L0X)
#define VREFINT_CAL (*((uint16_t *)0x1FF80078)) // VREFINT @3.0V/25°C
#define VREFINT_VALUE 3000 // mV
#define TSENSE_CAL1 (*((uint16_t *)0x1FF8007A))
#define TSENSE_CAL2 (*((uint16_t *)0x1FF8007E))
#define TSENSE_CAL1_VALUE 30.0 // temperature of first calibration point
#define TSENSE_CAL2_VALUE 130.0 // temperature of second calibration point
#elif defined(CONFIG_SOC_SERIES_STM32G4X)
#define VREFINT_CAL (*((uint16_t *)0x1FFF75AA)) // VREFINT @3.0V/30°C
#define VREFINT_VALUE 3000 // mV
#define TSENSE_CAL1 (*((uint16_t *)0x1FFF75A8))
#define TSENSE_CAL2 (*((uint16_t *)0x1FFF75CA))
#define TSENSE_CAL1_VALUE 30.0 // temperature of first calibration point
#define TSENSE_CAL2_VALUE 110.0 // temperature of second calibration point
#elif !defined(CONFIG_SOC_FAMILY_STM32)
#define VREFINT_CAL (4096 * 1.224 / 3.0) // VREFINT @3.0V/25°C
#define VREFINT_VALUE 3000 // mV
#define TSENSE_CAL1 (4096.0 * (670 - 161) / 3300) // datasheet: slope 1.61 mV/°C
#define TSENSE_CAL2 (4096.0 * 670 / 3300) // datasheet: 670 mV
#define TSENSE_CAL1_VALUE 30.0 // temperature of first calibration point
#define TSENSE_CAL2_VALUE 130.0 // temperature of second calibration point
#endif
#endif // MCU_H_
+2 -2
View File
@@ -48,7 +48,7 @@ void PwmSwitch::test()
}
else if (!pwm_active() && enable == true) {
// turning the PWM switch on creates a short voltage rise, so inhibit alerts by 50 ms
adc_upper_alert_inhibit(ADC_POS(v_low), 50);
daq_inhibit_alert(DAQ_DEV, DAQ_CH(v_low), DAQ_ALERT_UPPER, 50);
pwm_signal_start(0.9F);
LOG_INF("PWM test mode start.");
}
@@ -127,7 +127,7 @@ void PwmSwitch::control()
&& uptime() > (off_timestamp + restart_interval) && enable == true)
{
// turning the PWM switch on creates a short voltage rise, so inhibit alerts by 50 ms
adc_upper_alert_inhibit(ADC_POS(v_low), 50);
daq_inhibit_alert(DAQ_DEV, DAQ_CH(v_low), DAQ_ALERT_UPPER, 50);
if (dev_stat.has_error(ERR_PWM_SWITCH_OVERVOLTAGE)) {
// start with minimum duty cycle in order to prevent another overvoltage event
+1 -1
View File
@@ -73,7 +73,7 @@ static void TIM3_IRQHandler(void *args)
if ((int)LL_TIM_OC_GetCompare(tim) < _pwm_resolution) {
// turning the PWM switch on creates a short voltage rise, so inhibit alerts by 10 ms
// at each rising edge if switch is not continuously on
adc_upper_alert_inhibit(ADC_POS(v_low), 10);
daq_inhibit_alert(DAQ_DEV, DAQ_CH(v_low), DAQ_ALERT_UPPER, 10);
}
}
@@ -77,7 +77,7 @@
};
adc-inputs {
compatible = "adc-inputs";
compatible = "libresolar,stm32-daq";
v-low {
io-channels = <&adc1 0>;
@@ -55,7 +55,7 @@
};
adc-inputs {
compatible = "adc-inputs";
compatible = "libresolar,stm32-daq";
i-load {
io-channels = <&adc1 6>;
@@ -68,7 +68,7 @@
};
adc-inputs {
compatible = "adc-inputs";
compatible = "libresolar,stm32-daq";
v-low {
io-channels = <&adc1 12>;
@@ -67,7 +67,7 @@
};
adc-inputs {
compatible = "adc-inputs";
compatible = "libresolar,stm32-daq";
v-low {
io-channels = <&adc1 12>;
@@ -75,7 +75,7 @@
};
adc-inputs {
compatible = "adc-inputs";
compatible = "libresolar,stm32-daq";
temp-bat {
io-channels = <&adc1 0>;
@@ -56,7 +56,7 @@
};
adc-inputs {
compatible = "adc-inputs";
compatible = "libresolar,stm32-daq";
v-low {
io-channels = <&adc1 12>;
@@ -88,7 +88,7 @@
};
adc-inputs {
compatible = "adc-inputs";
compatible = "libresolar,stm32-daq";
v-low {
io-channels = <&adc1 0>;
@@ -11,7 +11,7 @@
};
adc-inputs {
compatible = "adc-inputs";
compatible = "libresolar,stm32-daq";
i-load {
io-channels = <&adc1 5>;
@@ -63,9 +63,7 @@
};
adc-inputs {
compatible = "adc-inputs";
/* nodes must be sorted by channel number, as the ADC converts in ascending order */
compatible = "libresolar,stm32-daq";
i-dump-load {
io-channels = <&adc1 0>;
+1 -1
View File
@@ -2,7 +2,7 @@
#
# Only contains most important options, as HTML rendering is done by Sphinx
INPUT = ../app/src
INPUT = ../app/src ../include
OUTPUT_DIRECTORY = build/doxygen
RECURSIVE = YES
GENERATE_HTML = NO
+10 -1
View File
@@ -1,5 +1,14 @@
Data Acquisition
================
.. doxygenfile:: daq.h
Driver
------
.. doxygenfile:: drivers/daq.h
:project: app
Application
-----------
.. doxygenfile:: src/daq.h
:project: app
-47
View File
@@ -1,47 +0,0 @@
# Copyright (c) The Libre Solar Project Contributors
# SPDX-License-Identifier: Apache-2.0
description: Description for an ADC input including gain (multiplier/divider) and offset
compatible: "adc-inputs"
child-binding:
description: ADC inputs child node
properties:
io-channels:
type: phandle-array
required: true
description: |
ADC channel for this input.
multiplier:
type: int
required: true
description: |
Resistance of the lower leg of the voltage divider.
divider:
type: int
required: true
description: |
Resistance of the full path through the voltage divider.
offset:
type: int
required: false
description: |
Offset to be substracted from ADC raw 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 must be set to an active level
to enable the divider input.
+1
View File
@@ -21,6 +21,7 @@ zephyr_include_directories(../../app/src)
zephyr_include_directories(../../../modules/thingset/src)
target_sources(app PRIVATE
src/daq_stub.cpp
src/tests_bat_charger.cpp
src/tests_daq.cpp
src/tests_dcdc.cpp
+1 -1
View File
@@ -69,7 +69,7 @@
};
adc-inputs {
compatible = "adc-inputs";
compatible = "libresolar,daq-emul";
v-low {
io-channels = <&adc1 12>;
+24
View File
@@ -0,0 +1,24 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "daq_stub.h"
#include <libresolar/drivers/daq_emul.h>
#include "daq.h"
void prepare_adc_readings(AdcValues values)
{
daq_emul_set_value(DAQ_DEV, DAQ_CH(v_high), values.solar_voltage);
daq_emul_set_value(DAQ_DEV, DAQ_CH(v_low), values.battery_voltage);
daq_emul_set_value(DAQ_DEV, DAQ_CH(i_dcdc), values.dcdc_current);
daq_emul_set_value(DAQ_DEV, DAQ_CH(i_load), values.load_current);
}
void prepare_adc_filtered()
{
daq_emul_preset_filtered(DAQ_DEV);
}
+3 -4
View File
@@ -7,7 +7,7 @@
#ifndef DAQ_STUB_H_
#define DAQ_STUB_H_
/** Data to fill adc_filtered array during unit-tests
/** Data to fill readings of the emulated DAQ during unit-tests
*/
typedef struct
{
@@ -19,11 +19,10 @@ typedef struct
float internal_temperature;
} AdcValues;
/** Set the readings of the emulated DAQ for the next samples */
void prepare_adc_readings(AdcValues values);
/** Set the filtered values of the emulated DAQ to the current readings */
void prepare_adc_filtered();
void clear_adc_filtered();
uint32_t get_adc_filtered(uint32_t channel);
uint16_t adc_raw_clamp(float scale, float limit);
#endif
+11 -68
View File
@@ -4,6 +4,8 @@
* SPDX-License-Identifier: Apache-2.0
*/
#include <libresolar/drivers/daq_emul.h>
#include "daq.h"
#include "daq_stub.h"
#include "helper.h"
@@ -14,58 +16,6 @@
static AdcValues adcval;
ZTEST(daq, test_adc_voltage_to_raw)
{
int32_t raw;
raw = adc_voltage_to_raw(0.0, 3300);
zassert_equal(raw, 0);
raw = adc_voltage_to_raw(3.3, 3300);
zassert_equal(raw, 65535);
raw = adc_voltage_to_raw(1.65, 3300);
zassert_equal(raw, 32767);
}
ZTEST(daq, test_adc_raw_to_voltage)
{
float voltage;
voltage = adc_raw_to_voltage(0, 3300);
assert_float_equal(voltage, 0.0);
voltage = adc_raw_to_voltage(65535, 3300);
zassert_within(voltage, 3.3F, 0.01F);
voltage = adc_raw_to_voltage(32767, 3300);
zassert_within(voltage, 1.65F, 0.01F);
}
// testing only for 2 values
ZTEST(daq, test_check_filtering)
{
// reset values
clear_adc_filtered();
// collect 1000 samples to update filtered values
for (int s = 0; s < 1000; s++) {
for (int i = 0; i < NUM_ADC_CH; i++) {
adc_update_value(i);
}
}
uint32_t adc_filtered_bak[NUM_ADC_CH];
adc_filtered_bak[ADC_POS(vref_mcu)] = get_adc_filtered(ADC_POS(vref_mcu));
adc_filtered_bak[ADC_POS(v_high)] = get_adc_filtered(ADC_POS(v_high));
// overwrite filtered values
prepare_adc_filtered();
zassert_equal(adc_filtered_bak[ADC_POS(vref_mcu)], get_adc_filtered(ADC_POS(vref_mcu)));
zassert_equal(adc_filtered_bak[ADC_POS(v_high)], get_adc_filtered(ADC_POS(v_high)));
}
ZTEST(daq, test_check_solar_terminal_readings)
{
assert_float_equal(round(hv_terminal.bus->voltage * 10) / 10, adcval.solar_voltage);
@@ -97,14 +47,14 @@ ZTEST(daq, test_adc_alert_lv_undervoltage_triggering)
battery_conf_init(&bat_conf, BAT_TYPE_LFP, 4, 100);
daq_set_lv_limits(bat_conf.absolute_max_voltage, bat_conf.absolute_min_voltage);
prepare_adc_filtered();
adc_update_value(ADC_POS(v_low));
daq_emul_process(DAQ_DEV, DAQ_CH(v_low));
// undervoltage test
adcval.battery_voltage = bat_conf.absolute_min_voltage - 0.1f;
prepare_adc_readings(adcval);
adc_update_value(ADC_POS(v_low));
daq_emul_process(DAQ_DEV, DAQ_CH(v_low));
zassert_equal(dev_stat.has_error(ERR_LOAD_VOLTAGE_DIP), false);
adc_update_value(ADC_POS(v_low));
daq_emul_process(DAQ_DEV, DAQ_CH(v_low));
load.control();
zassert_equal(flags_check(&load.error_flags, ERR_LOAD_VOLTAGE_DIP), true);
zassert_equal(load.state, LOAD_STATE_OFF);
@@ -125,16 +75,16 @@ ZTEST(daq, test_adc_alert_lv_overvoltage_triggering)
battery_conf_init(&bat_conf, BAT_TYPE_LFP, 4, 100);
daq_set_lv_limits(bat_conf.absolute_max_voltage, bat_conf.absolute_min_voltage);
prepare_adc_filtered();
adc_update_value(ADC_POS(v_low));
daq_emul_process(DAQ_DEV, DAQ_CH(v_low));
dcdc.state = DCDC_CONTROL_MPPT;
// overvoltage test
adcval.battery_voltage = bat_conf.absolute_max_voltage + 0.1f;
prepare_adc_readings(adcval);
adc_update_value(ADC_POS(v_low));
daq_emul_process(DAQ_DEV, DAQ_CH(v_low));
zassert_equal(dev_stat.has_error(ERR_BAT_OVERVOLTAGE), false);
adc_update_value(ADC_POS(v_low));
daq_emul_process(DAQ_DEV, DAQ_CH(v_low));
zassert_equal(dev_stat.has_error(ERR_BAT_OVERVOLTAGE), true);
// zassert_equal(pwm_switch.active(), false);
zassert_equal(dcdc.state, DCDC_CONTROL_OFF);
@@ -155,25 +105,18 @@ ZTEST(daq, test_adc_alert_hv_overvoltage_triggering)
dev_stat.clear_error(ERR_ANY_ERROR);
daq_set_hv_limit(DT_PROP(DT_PATH(pcb), hs_voltage_max));
prepare_adc_filtered();
adc_update_value(ADC_POS(v_high));
daq_emul_process(DAQ_DEV, DAQ_CH(v_high));
// overvoltage test
adcval.solar_voltage = 85.0F;
prepare_adc_readings(adcval);
adc_update_value(ADC_POS(v_high));
daq_emul_process(DAQ_DEV, DAQ_CH(v_high));
zassert_equal(dev_stat.has_error(ERR_DCDC_HS_OVERVOLTAGE), false);
adc_update_value(ADC_POS(v_high));
daq_emul_process(DAQ_DEV, DAQ_CH(v_high));
zassert_equal(dev_stat.has_error(ERR_DCDC_HS_OVERVOLTAGE), true);
zassert_equal(dcdc.state, DCDC_CONTROL_OFF);
}
ZTEST(daq, test_adc_alert_overflow_prevention)
{
// try to set an alert that overflows the 12-bit ADC resolution
uint16_t limit = adc_raw_clamp(1, UINT16_MAX + 1);
zassert_equal(limit, UINT16_MAX);
}
/** Data acquisition tests
*
* Purpose: Check if raw data from 2 voltage and 2 current measurements are converted