Move to standard Zephyr T2 workspace structure (star topology)

https://docs.zephyrproject.org/latest/guides/west/workspaces.html

Previously, west manifest and CMake entry point were in zephyr subfolder
as required for PlatformIO. As PlatformIO support was dropped, we can
follow the default Zephyr folder structure more closely.

The application is built and flashed from app subfolder, where as unit
tests are run from tests subfolder.
This commit is contained in:
Martin Jäger
2021-12-12 14:09:05 +01:00
parent 15ee7d8553
commit 8ab8ea244a
57 changed files with 67 additions and 48 deletions
+35
View File
@@ -0,0 +1,35 @@
# SPDX-License-Identifier: Apache-2.0
zephyr_include_directories(.)
target_sources(app PRIVATE
bat_charger.cpp
data_objects.cpp
data_storage.cpp
daq.cpp
daq_driver.c
device_status.cpp
dcdc.cpp
half_bridge.cpp
hardware.cpp
leds.cpp
load.cpp
load_driver.c
main.cpp
power_port.cpp
pwm_switch_driver.c
pwm_switch.cpp
setup.cpp
)
add_subdirectory(ext)
if(${CONFIG_CUSTOM_DATA_OBJECTS_FILE})
target_sources(app PRIVATE data_objects_custom.cpp)
endif()
# Using this option enables user-specific customization of the firmware. The
# custom subfolder should have its own CMakeLists.txt file.
if(${CONFIG_CUSTOMIZATION})
add_subdirectory(custom build/custom)
endif()
+643
View File
@@ -0,0 +1,643 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "bat_charger.h"
#include <zephyr.h>
#include <logging/log.h>
LOG_MODULE_REGISTER(bat_charger, CONFIG_BAT_LOG_LEVEL);
#include <math.h> // for fabs function
#include <stdio.h>
#include "board.h"
#include "helper.h"
#include "device_status.h"
extern DeviceStatus dev_stat;
extern LoadOutput load;
// DISCHARGE_CURRENT_MAX used to estimate current-compensation of load disconnect voltage
#if BOARD_HAS_LOAD_OUTPUT
#define DISCHARGE_CURRENT_MAX DT_PROP(DT_CHILD(DT_PATH(outputs), load), current_max)
#else
#define DISCHARGE_CURRENT_MAX DT_PROP(DT_PATH(pcb), dcdc_current_max)
#endif
void battery_conf_init(BatConf *bat, int type, int num_cells, float nominal_capacity)
{
bat->nominal_capacity = nominal_capacity;
// 1C should be safe for all batteries
bat->charge_current_max = bat->nominal_capacity;
bat->discharge_current_max = bat->nominal_capacity;
bat->time_limit_recharge = 60; // sec
bat->topping_duration = 120*60; // sec
bat->charge_temp_max = 50;
bat->charge_temp_min = -10;
bat->discharge_temp_max = 50;
bat->discharge_temp_min = -10;
switch (type)
{
case BAT_TYPE_FLOODED:
case BAT_TYPE_AGM:
case BAT_TYPE_GEL:
bat->absolute_max_voltage = static_cast<float>(num_cells) * 2.45F;
bat->topping_voltage = static_cast<float>(num_cells) * 2.4F;
bat->recharge_voltage = static_cast<float>(num_cells) * 2.2F;
// Cell-level thresholds based on EN 62509:2011 (both thresholds current-compensated)
bat->load_disconnect_voltage = static_cast<float>(num_cells) * 1.95F;
bat->load_reconnect_voltage = static_cast<float>(num_cells) * 2.10F;
// assumption: Battery selection matching charge controller
bat->internal_resistance = static_cast<float>(num_cells) * (1.95F - 1.80F) /
DISCHARGE_CURRENT_MAX;
bat->absolute_min_voltage = static_cast<float>(num_cells) * 1.6F;
// Voltages during idle (no charging/discharging current)
bat->ocv_full = static_cast<float>(num_cells) *
((type == BAT_TYPE_FLOODED) ? 2.10F : 2.15F);
bat->ocv_empty = static_cast<float>(num_cells) * 1.90F;
// https://batteryuniversity.com/learn/article/charging_the_lead_acid_battery
bat->topping_cutoff_current = bat->nominal_capacity * 0.04F; // 3-5 % of C/1
bat->float_enabled = true;
bat->float_recharge_time = 30*60;
// Values as suggested in EN 62509:2011
bat->float_voltage = static_cast<float>(num_cells) *
((type == BAT_TYPE_FLOODED) ? 2.35F : 2.3F);
// Enable for flooded batteries only, according to
// https://discoverbattery.com/battery-101/equalizing-flooded-batteries-only
bat->equalization_enabled = false;
// Values as suggested in EN 62509:2011
bat->equalization_voltage = static_cast<float>(num_cells) *
((type == BAT_TYPE_FLOODED) ? 2.50F : 2.45F);
bat->equalization_duration = 60*60;
bat->equalization_current_limit = (1.0F / 7.0F) * bat->nominal_capacity;
bat->equalization_trigger_days = 60;
bat->equalization_trigger_deep_cycles = 10;
bat->temperature_compensation = -0.003F; // -3 mV/°C/cell
break;
case BAT_TYPE_LFP:
bat->absolute_max_voltage = static_cast<float>(num_cells) * 3.60F;
bat->topping_voltage = static_cast<float>(num_cells) * 3.55F; // CV voltage
bat->recharge_voltage = static_cast<float>(num_cells) * 3.35F;
bat->load_disconnect_voltage = static_cast<float>(num_cells) * 3.00F;
bat->load_reconnect_voltage = static_cast<float>(num_cells) * 3.15F;
// 5% voltage drop at max current
bat->internal_resistance = bat->load_disconnect_voltage * 0.05F /
DISCHARGE_CURRENT_MAX;
bat->absolute_min_voltage = static_cast<float>(num_cells) * 2.0F;
// will give really nonlinear SOC calculation because of flat OCV of LFP cells...
bat->ocv_full = static_cast<float>(num_cells) * 3.4F;
bat->ocv_empty = static_cast<float>(num_cells) * 3.0F;
// C/10 cut-off at end of CV phase by default
bat->topping_cutoff_current = bat->nominal_capacity / 10;
bat->float_enabled = false;
bat->equalization_enabled = false;
bat->temperature_compensation = 0;
bat->charge_temp_min = 0;
break;
case BAT_TYPE_NMC:
case BAT_TYPE_NMC_HV:
bat->topping_voltage = static_cast<float>(num_cells) *
((type == BAT_TYPE_NMC_HV) ? 4.35F : 4.20F);
bat->absolute_max_voltage = bat->topping_voltage +
static_cast<float>(num_cells) * 0.05F;
bat->recharge_voltage = static_cast<float>(num_cells) * 3.9F;
bat->load_disconnect_voltage = static_cast<float>(num_cells) * 3.3F;
bat->load_reconnect_voltage = static_cast<float>(num_cells) * 3.6F;
// 5% voltage drop at max current
bat->internal_resistance = bat->load_disconnect_voltage * 0.05F /
DISCHARGE_CURRENT_MAX;
bat->absolute_min_voltage = static_cast<float>(num_cells) * 2.5F;
bat->ocv_full = static_cast<float>(num_cells) * 4.0F;
bat->ocv_empty = static_cast<float>(num_cells) * 3.0F;
// C/10 cut-off at end of CV phase by default
bat->topping_cutoff_current = bat->nominal_capacity / 10;
bat->float_enabled = false;
bat->equalization_enabled = false;
bat->temperature_compensation = 0;
bat->charge_temp_min = 0;
break;
case BAT_TYPE_CUSTOM:
#ifdef CONFIG_BAT_TYPE_CUSTOM
bat->absolute_max_voltage = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_ABS_MAX_VOLTAGE_MV);
bat->topping_voltage = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_TOPPING_VOLTAGE_MV);
bat->recharge_voltage = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_RECHARGE_VOLTAGE_MV);
bat->load_disconnect_voltage = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_DISCONNECT_VOLTAGE_MV);
bat->load_reconnect_voltage = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_RECONNECT_VOLTAGE_MV);
bat->internal_resistance = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_INTERNAL_RESISTANCE_MOHM);
bat->absolute_min_voltage = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_ABS_MIN_VOLTAGE_MV);
// Voltages during idle (no charging/discharging current)
bat->ocv_full = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_OCV_FULL_MV);
bat->ocv_empty = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_OCV_EMPTY_MV);
// https://batteryuniversity.com/learn/article/charging_the_lead_acid_battery
bat->topping_cutoff_current = bat->nominal_capacity * 0.04F; // 3-5 % of C/1
bat->float_enabled = IS_ENABLED(CONFIG_CELL_FLOAT);
bat->float_recharge_time = CONFIG_CELL_FLOAT_RECHARGE_TIME;
bat->float_voltage = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_FLOAT_VOLTAGE_MV);
bat->equalization_enabled = IS_ENABLED(CONFIG_CELL_EQUALIZATION);
bat->equalization_voltage = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_EQUALIZATION_VOLTAGE_MV);
bat->equalization_duration = CONFIG_CELL_EQUALIZATION_DURATION;
bat->equalization_current_limit = (1.0F / 7.0F) * bat->nominal_capacity;
bat->equalization_trigger_days = CONFIG_CELL_EQUALIZATION_TRIGGER_DAYS;
bat->equalization_trigger_deep_cycles = CONFIG_CELL_EQUALIZATION_TRIGGER_DEEP_CYCLES;
bat->temperature_compensation = 0.001F *
static_cast<float>(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_TEMP_COMPENSATION_MV_K);
bat->charge_temp_max = CONFIG_BAT_CHARGE_TEMP_MAX;
bat->charge_temp_min = CONFIG_BAT_CHARGE_TEMP_MIN;
bat->discharge_temp_max = CONFIG_BAT_DISCHARGE_TEMP_MAX;
bat->discharge_temp_min = CONFIG_BAT_DISCHARGE_TEMP_MIN;
#else
LOG_ERR("Custom battery type cannot be initialized at runtime.");
#endif
break;
}
}
// checks settings in bat_conf for plausibility
bool battery_conf_check(BatConf *bat_conf)
{
// things to check:
// - load_disconnect/reconnect hysteresis makes sense?
// - cutoff current not extremely low/high
// - capacity plausible
LOG_DBG("battery_conf_check: %d %d %d %d %d %d %d",
bat_conf->load_reconnect_voltage > (bat_conf->load_disconnect_voltage + 0.6),
bat_conf->recharge_voltage < (bat_conf->topping_voltage - 0.4),
bat_conf->recharge_voltage > (bat_conf->load_disconnect_voltage + 1),
bat_conf->load_disconnect_voltage > (bat_conf->absolute_min_voltage + 0.4),
bat_conf->topping_cutoff_current < (bat_conf->nominal_capacity / 10.0),
bat_conf->topping_cutoff_current > 0.01,
(bat_conf->float_enabled == false ||
(bat_conf->float_voltage < bat_conf->topping_voltage &&
bat_conf->float_voltage > bat_conf->load_disconnect_voltage))
);
return (
bat_conf->load_reconnect_voltage > (bat_conf->load_disconnect_voltage + 0.4) &&
bat_conf->recharge_voltage < (bat_conf->topping_voltage - 0.4) &&
bat_conf->recharge_voltage > (bat_conf->load_disconnect_voltage + 1) &&
bat_conf->load_disconnect_voltage > (bat_conf->absolute_min_voltage + 0.4) &&
// max. 10% drop
bat_conf->internal_resistance < bat_conf->load_disconnect_voltage * 0.1 /
DISCHARGE_CURRENT_MAX &&
// max. 3% loss
bat_conf->wire_resistance < bat_conf->topping_voltage * 0.03 / DISCHARGE_CURRENT_MAX &&
// C/10 or lower current cutoff allowed
bat_conf->topping_cutoff_current < (bat_conf->nominal_capacity / 10.0) &&
bat_conf->topping_cutoff_current > 0.01 &&
(bat_conf->float_enabled == false ||
(bat_conf->float_voltage < bat_conf->topping_voltage &&
bat_conf->float_voltage > bat_conf->load_disconnect_voltage))
);
}
void battery_conf_overwrite(BatConf *source, BatConf *destination, Charger *charger)
{
// TODO: stop DC/DC
destination->topping_voltage = source->topping_voltage;
destination->recharge_voltage = source->recharge_voltage;
destination->load_reconnect_voltage = source->load_reconnect_voltage;
destination->load_disconnect_voltage = source->load_disconnect_voltage;
destination->absolute_max_voltage = source->absolute_max_voltage;
destination->absolute_min_voltage = source->absolute_min_voltage;
destination->charge_current_max = source->charge_current_max;
destination->topping_cutoff_current = source->topping_cutoff_current;
destination->topping_duration = source->topping_duration;
destination->float_enabled = source->float_enabled;
destination->float_voltage = source->float_voltage;
destination->float_recharge_time = source->float_recharge_time;
destination->charge_temp_max = source->charge_temp_max;
destination->charge_temp_min = source->charge_temp_min;
destination->discharge_temp_max = source->discharge_temp_max;
destination->discharge_temp_min = source->discharge_temp_min;
destination->temperature_compensation = source->temperature_compensation;
destination->internal_resistance = source->internal_resistance;
destination->wire_resistance = source->wire_resistance;
// reset Ah counter and SOH if battery nominal capacity was changed
if (destination->nominal_capacity != source->nominal_capacity) {
destination->nominal_capacity = source->nominal_capacity;
if (charger != NULL) {
charger->discharged_Ah = 0;
charger->usable_capacity = 0;
charger->soh = 0;
}
}
// TODO:
// - update also DC/DC etc. (now this function only works at system startup)
// - restart DC/DC
}
bool battery_conf_changed(BatConf *a, BatConf *b)
{
return (
a->topping_voltage != b->topping_voltage ||
a->recharge_voltage != b->recharge_voltage ||
a->load_reconnect_voltage != b->load_reconnect_voltage ||
a->load_disconnect_voltage != b->load_disconnect_voltage ||
a->absolute_max_voltage != b->absolute_max_voltage ||
a->absolute_min_voltage != b->absolute_min_voltage ||
a->charge_current_max != b->charge_current_max ||
a->topping_cutoff_current != b->topping_cutoff_current ||
a->topping_duration != b->topping_duration ||
a->float_enabled != b->float_enabled ||
a->float_voltage != b->float_voltage ||
a->float_recharge_time != b->float_recharge_time ||
a->charge_temp_max != b->charge_temp_max ||
a->charge_temp_min != b->charge_temp_min ||
a->discharge_temp_max != b->discharge_temp_max ||
a->discharge_temp_min != b->discharge_temp_min ||
a->temperature_compensation != b->temperature_compensation ||
a->internal_resistance != b->internal_resistance ||
a->wire_resistance != b->wire_resistance
);
}
void Charger::detect_num_batteries(BatConf *bat) const
{
if (port->bus->voltage > bat->absolute_min_voltage * 2 &&
port->bus->voltage < bat->absolute_max_voltage * 2)
{
port->bus->series_multiplier = 2;
printf("Detected two batteries (total %.2f V max)\n", bat->topping_voltage * 2);
}
else {
printf("Detected single battery (%.2f V max)\n", bat->topping_voltage);
}
}
void Charger::update_soc(BatConf *bat_conf)
{
static int soc_filtered = 0; // SOC / 100 for better filtering
if (fabs(port->current) < 0.2) {
int soc_new = (int)((port->bus->voltage - bat_conf->ocv_empty) /
(bat_conf->ocv_full - bat_conf->ocv_empty) * 10000.0);
if (soc_new > 500 && soc_filtered == 0) {
// bypass filter during initialization
soc_filtered = soc_new;
}
else {
// filtering to adjust SOC very slowly
soc_filtered += (soc_new - soc_filtered) / 100;
}
if (soc_filtered > 10000) {
soc_filtered = 10000;
}
else if (soc_filtered < 0) {
soc_filtered = 0;
}
soc = soc_filtered / 100;
}
discharged_Ah += -port->current / 3600.0F; // charged current is positive: change sign
}
void Charger::enter_state(int next_state)
{
LOG_DBG("Enter State: %d", next_state);
time_state_changed = uptime();
state = next_state;
}
void Charger::discharge_control(BatConf *bat_conf)
{
#if BOARD_HAS_LOAD_OUTPUT || \
BOARD_HAS_USB_OUTPUT
if (!empty) {
// as we don't have a proper SOC estimation, we determine an empty battery by the main
// load output being switched off
if (flags_check(&load.error_flags, ERR_LOAD_SHEDDING)) {
empty = true;
num_deep_discharges++;
if (usable_capacity == 0.0F) {
// reset to measured value if discharged the first time
usable_capacity = discharged_Ah;
}
else {
// slowly adapt new measurements with low-pass filter
usable_capacity =
0.8F * usable_capacity +
0.2F * discharged_Ah;
}
// simple SOH estimation
soh = usable_capacity / bat_conf->nominal_capacity;
}
}
else {
if (!flags_check(&load.error_flags, ERR_LOAD_SHEDDING)) {
empty = false;
}
}
// negative current limit = allowed battery discharge current
if (port->neg_current_limit < 0) {
// This limit should normally never be reached, as the load output settings should be
// higher. The flag can be used to trigger actions of last resort, e.g. deep-sleep
// of the charge controller itself.
if (port->bus->voltage < port->bus->src_control_voltage(bat_conf->absolute_min_voltage)) {
port->neg_current_limit = 0;
dev_stat.set_error(ERR_BAT_UNDERVOLTAGE);
}
if (bat_temperature > bat_conf->discharge_temp_max) {
port->neg_current_limit = 0;
dev_stat.set_error(ERR_BAT_DIS_OVERTEMP);
}
else if (bat_temperature < bat_conf->discharge_temp_min) {
port->neg_current_limit = 0;
dev_stat.set_error(ERR_BAT_DIS_UNDERTEMP);
}
}
else {
// discharging currently not allowed. should we allow it?
if (port->bus->voltage >=
port->bus->src_control_voltage(bat_conf->absolute_min_voltage + 0.1F))
{
dev_stat.clear_error(ERR_BAT_UNDERVOLTAGE);
}
if (bat_temperature < bat_conf->discharge_temp_max - 1 &&
bat_temperature > bat_conf->discharge_temp_min + 1)
{
dev_stat.clear_error(ERR_BAT_DIS_OVERTEMP | ERR_BAT_DIS_UNDERTEMP);
}
if (!dev_stat.has_error(
ERR_BAT_UNDERVOLTAGE | ERR_BAT_DIS_OVERTEMP | ERR_BAT_DIS_UNDERTEMP))
{
// discharge current is stored as absolute value in bat_conf, but defined
// as negative current for power port
port->neg_current_limit = -bat_conf->discharge_current_max;
}
}
#endif
}
void Charger::charge_control(BatConf *bat_conf)
{
// check battery temperature for charging direction
if (bat_temperature > bat_conf->charge_temp_max) {
port->pos_current_limit = 0;
dev_stat.set_error(ERR_BAT_CHG_OVERTEMP);
enter_state(CHG_STATE_IDLE);
}
else if (bat_temperature < bat_conf->charge_temp_min) {
port->pos_current_limit = 0;
dev_stat.set_error(ERR_BAT_CHG_UNDERTEMP);
enter_state(CHG_STATE_IDLE);
}
if (dev_stat.has_error(ERR_BAT_OVERVOLTAGE) &&
port->bus->voltage < (bat_conf->absolute_max_voltage - 0.5F) *
port->bus->series_multiplier)
{
dev_stat.clear_error(ERR_BAT_OVERVOLTAGE);
}
if (state != CHG_STATE_FOLLOWER && (uptime() - time_last_ctrl_msg) <= 1) {
enter_state(CHG_STATE_FOLLOWER);
}
// state machine
switch (state) {
case CHG_STATE_IDLE: {
if ((time_state_changed == CHARGER_TIME_NEVER ||
((uptime() - time_state_changed) > bat_conf->time_limit_recharge &&
port->bus->voltage < port->bus->sink_control_voltage(
bat_conf->recharge_voltage))
)
&& port->bus->voltage > port->bus->sink_control_voltage(
bat_conf->absolute_min_voltage) // ToDo set error flag otherwise
&& bat_temperature < bat_conf->charge_temp_max - 1
&& bat_temperature > bat_conf->charge_temp_min + 1)
{
port->bus->sink_voltage_intercept = bat_conf->topping_voltage +
bat_conf->temperature_compensation * (bat_temperature - 25);
port->pos_current_limit = bat_conf->charge_current_max;
target_current_control = port->pos_current_limit;
full = false;
dev_stat.clear_error(ERR_BAT_CHG_OVERTEMP);
dev_stat.clear_error(ERR_BAT_CHG_UNDERTEMP);
dev_stat.clear_error(ERR_BAT_OVERVOLTAGE);
enter_state(CHG_STATE_BULK);
}
break;
}
case CHG_STATE_BULK: {
// continuously adjust voltage setting for temperature compensation
port->bus->sink_voltage_intercept = bat_conf->topping_voltage +
bat_conf->temperature_compensation * (bat_temperature - 25);
if (port->bus->voltage > port->bus->sink_control_voltage()) {
target_voltage_timer = 0;
enter_state(CHG_STATE_TOPPING);
}
break;
}
case CHG_STATE_TOPPING: {
// continuously adjust voltage setting for temperature compensation
port->bus->sink_voltage_intercept = bat_conf->topping_voltage +
bat_conf->temperature_compensation * (bat_temperature - 25);
// power sharing: multiple devices in parallel supply the same current
target_current_control = port->current_filtered;
if (port->bus->voltage_filtered >= port->bus->sink_control_voltage() - 0.05F) {
// battery is full if topping target voltage is still reached (i.e. sufficient
// solar power available) and time limit or cut-off current reached
if (port->current_filtered < bat_conf->topping_cutoff_current ||
target_voltage_timer > bat_conf->topping_duration)
{
full = true;
}
target_voltage_timer++;
}
else if (uptime() - time_state_changed > 8 * 60 * 60) {
// in topping phase already for 8 hours (i.e. not enough solar power available)
// --> go back to bulk charging for the next day
enter_state(CHG_STATE_BULK);
}
if (full) {
num_full_charges++;
discharged_Ah = 0; // reset coulomb counter
if (bat_conf->equalization_enabled && (
(uptime() - time_last_equalization) / (24*60*60)
>= bat_conf->equalization_trigger_days ||
num_deep_discharges - deep_dis_last_equalization
>= bat_conf->equalization_trigger_deep_cycles))
{
port->bus->sink_voltage_intercept = bat_conf->equalization_voltage;
port->pos_current_limit = bat_conf->equalization_current_limit;
enter_state(CHG_STATE_EQUALIZATION);
}
else if (bat_conf->float_enabled) {
port->bus->sink_voltage_intercept = bat_conf->float_voltage +
bat_conf->temperature_compensation * (bat_temperature - 25);
enter_state(CHG_STATE_FLOAT);
}
else {
port->pos_current_limit = 0;
enter_state(CHG_STATE_IDLE);
}
}
break;
}
case CHG_STATE_FLOAT: {
// continuously adjust voltage setting for temperature compensation
port->bus->sink_voltage_intercept = bat_conf->float_voltage +
bat_conf->temperature_compensation * (bat_temperature - 25);
target_current_control = port->current_filtered;
if (port->bus->voltage >= port->bus->sink_control_voltage()) {
time_target_voltage_reached = uptime();
}
if ((uptime() - time_target_voltage_reached > bat_conf->float_recharge_time) &&
port->bus->voltage_filtered < port->bus->sink_control_voltage(
bat_conf->recharge_voltage))
{
// the battery was discharged: float voltage could not be reached anymore
port->pos_current_limit = bat_conf->charge_current_max;
full = false;
// assumption: float does not harm the battery --> never go back to idle
// (for Li-ion battery: disable float!)
enter_state(CHG_STATE_BULK);
}
break;
}
case CHG_STATE_EQUALIZATION: {
// continuously adjust voltage setting for temperature compensation
port->bus->sink_voltage_intercept = bat_conf->equalization_voltage +
bat_conf->temperature_compensation * (bat_temperature - 25);
target_current_control = port->current_filtered;
// current or time limit for equalization reached
if (uptime() - time_state_changed > bat_conf->equalization_duration)
{
// reset triggers
time_last_equalization = uptime();
deep_dis_last_equalization = num_deep_discharges;
discharged_Ah = 0; // reset coulomb counter again
if (bat_conf->float_enabled) {
port->bus->sink_voltage_intercept = bat_conf->float_voltage +
bat_conf->temperature_compensation * (bat_temperature - 25);
enter_state(CHG_STATE_FLOAT);
}
else {
port->pos_current_limit = 0;
enter_state(CHG_STATE_IDLE);
}
}
break;
}
case CHG_STATE_FOLLOWER: {
if ((uptime() - time_last_ctrl_msg) > 1) {
// go back to normal state machine
port->pos_current_limit = bat_conf->charge_current_max;
enter_state(CHG_STATE_BULK);
}
else {
// set current target as received from external device
port->pos_current_limit = target_current_control;
// set safety limit for voltage
port->bus->sink_voltage_intercept = bat_conf->absolute_max_voltage;
}
break;
}
}
}
void Charger::init_terminal(BatConf *bat) const
{
port->bus->sink_voltage_intercept = bat->topping_voltage;
port->bus->src_voltage_intercept = bat->load_disconnect_voltage;
port->neg_current_limit = -bat->discharge_current_max;
port->pos_current_limit = bat->charge_current_max;
/*
* Negative sign for compensation of actual resistance
*
* droop_res is multiplied with number of series connected batteries to calculate control
* voltage, so we need to divide by number of batteries here for correction
*/
port->bus->sink_droop_res = -bat->wire_resistance /
static_cast<float>(port->bus->series_multiplier);
/*
* In discharging direction also include battery internal resistance for current-compensation
* of voltage setpoints
*/
port->bus->src_droop_res = -bat->wire_resistance /
static_cast<float>(port->bus->series_multiplier)
- bat->internal_resistance;
}
+507
View File
@@ -0,0 +1,507 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef BAT_CHARGER_H
#define BAT_CHARGER_H
/** @file
*
* @brief Battery and charger configuration and functions
*/
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <time.h>
#include "power_port.h"
#define CHARGER_TIME_NEVER INT32_MIN
/**
* Battery cell types
*/
enum BatType {
/*
* IMPORTANT: make sure to adjust also boards/Kconfig if enum is changed here!
*/
BAT_TYPE_CUSTOM = 0, ///< Custom battery type
BAT_TYPE_FLOODED, ///< Old flooded (wet) lead-acid batteries
BAT_TYPE_GEL, ///< VRLA gel batteries (maintainance-free)
BAT_TYPE_AGM, ///< AGM batteries (maintainance-free)
BAT_TYPE_LFP, ///< LiFePO4 Li-ion batteries (3.3V nominal)
BAT_TYPE_NMC, ///< NMC/Graphite Li-ion batteries (3.7V nominal)
BAT_TYPE_NMC_HV ///< NMC/Graphite High Voltage Li-ion batteries (3.7V nominal, 4.35 max)
};
/**
* Battery configuration data
*
* Data will be initialized in battery_init depending on configured cell type in config.h.
*/
typedef struct
{
/**
* Nominal battery capacity or sum of parallel cells capacity (Ah)
*
* The nominal capacity is used for SOC calculation and definition of current limits.
*/
float nominal_capacity;
/**
* Recharge voltage (V)
*
* Start charging again if voltage of fully charged battery drops below this threshold.
*
* Remark: Setting the value too close to the max voltage will cause more charging stress on
* lithium based batteries.
*/
float recharge_voltage;
/**
* Recharge time limit (sec)
*
* Start charging of previously fully charged battery earliest after this period of time.
*/
uint32_t time_limit_recharge;
/**
* Absolute maximum voltage (V)
*
* Above this voltage the battery or loads might get damaged.
*/
float absolute_max_voltage;
/**
* Absolute minimum voltage (V)
*
* Below this voltage the battery is considered damaged.
*/
float absolute_min_voltage;
/**
* Maximum charge current in *CC/bulk* phase (A)
*
* Limits the current if the PCB allows more than the battery. (positive value)
*/
float charge_current_max;
/**
* Maximum discharge current via load port (A)
*
* Limits the current if the PCB allows more than the battery. (positive value)
*/
float discharge_current_max;
/**
* Maximum voltage in CV/absorption phase (V)
*
* Charger target voltage, switching from CC to CV at this voltage threshold.
*/
float topping_voltage;
/**
* CV phase cut-off current limit (A)
*
* Constant voltage charging phase stopped if current is below this value.
*/
float topping_cutoff_current;
/**
* CV phase cut-off time limit (s)
*
* After this time, CV charging is stopped independent of current.
*/
uint32_t topping_duration;
/**
* Enable float/trickle charging
*
* Caution: Do not enable float charging for lithium-ion batteries
*/
bool float_enabled;
/**
* Float voltage (V)
*
* Charger target voltage for float charging of lead-acid batteries
*/
float float_voltage;
/**
* Float recharge time (s)
*
* If the float voltage is not reached anymore (e.g. because of lack of solar
* input power) for this period of time, the charger state machine goes back
* into CC/bulk charging mode.
*/
uint32_t float_recharge_time;
/**
* Enable equalization charging
*
* Caution: Do not enable float charging for lithium-ion batteries
*/
bool equalization_enabled;
/**
* Equalization voltage (V)
*
* Charger target voltage for equalization charging of lead-acid batteries
*/
float equalization_voltage;
/**
* Equalization cut-off time limit (s)
*
* After this time, equalization charging is stopped.
*/
uint32_t equalization_duration;
/**
* Equalization phase maximum current (A)
*
* The current of the charger is controlled to stay below this limit during equalization.
*/
float equalization_current_limit;
/**
* Equalization trigger time interval (days)
*
* After passing specified amount of days, an equalization charge is triggered.
*/
uint32_t equalization_trigger_days;
/**
* Equalization trigger deep-discharge cycles
*
* After specified number of deep discharges, an equalization charge is triggered.
*/
uint32_t equalization_trigger_deep_cycles;
/**
* Load disconnect open circuit voltage (V)
*
* Load output is disabled if battery voltage is below this threshold.
*
* The voltage is current-compensated using the battery internal resistance:
* threshold = load_disconnect_voltage + battery_current * internal_resistance
*
* (Remark: battery_current negative during discharge, internal_resistance positive)
*/
float load_disconnect_voltage;
/**
* Load reconnect open circuit voltage (V)
*
* Re-enable the load only after charged beyond this value.
*
* The voltage is current-compensated using the battery internal resistance:
* threshold = load_reconnect_voltage + battery_current * internal_resistance
*
* (Remark: battery_current positive during charge, internal_resistance positive)
*/
float load_reconnect_voltage;
/**
* Battery internal resistance (Ohm)
*
* Resistance value for current-compensation of load switch voltage thresholds.
*
* The value must have a positive sign. Only resistance values leading to less than 10% voltage
* drop at max. current are allowed.
*/
float internal_resistance;
/**
* Resistance of wire between charge controller and battery (Ohm)
*
* Resistance value for current-compensation of charging voltages.
*
* The value must have a positive sign. Only resistance values leading to less than 3% voltage
* loss at max. current are allowed.
*/
float wire_resistance;
/**
* Open circuit voltage of full battery (V)
*
* Used for simple state of charge (SOC) algorithm.
*/
float ocv_full;
/**
* Open circuit voltage of empty battery (V)
*
* Used for simple state of charge (SOC) algorithm.
*/
float ocv_empty;
/**
* Maximum allowed charging temperature of the battery (°C)
*/
float charge_temp_max;
/**
* Minimum allowed charging temperature of the battery (°C)
*/
float charge_temp_min;
/**
* Maximum allowed discharging temperature of the battery (°C)
*/
float discharge_temp_max;
/**
* Minimum allowed discharging temperature of the battery (°C)
*/
float discharge_temp_min;
/**
* Voltage compensation based on battery temperature (mV/K/cell)
*
* Suggested value: -3 mV/K/cell
*/
float temperature_compensation;
} BatConf;
/**
* Possible charger states
*
* Further information:
* - https://en.wikipedia.org/wiki/IUoU_battery_charging
* - https://batteryuniversity.com/learn/article/charging_the_lead_acid_battery
*/
enum ChargerState {
/**
* Idle
*
* Initial state of the charge controller. If the solar voltage is high enough
* and the battery is not full, bulk charging mode is started.
*/
CHG_STATE_IDLE,
/**
* Bulk / CC / MPPT charging
*
* The battery is charged with maximum possible current (MPPT algorithm is
* active) until the CV voltage limit is reached.
*/
CHG_STATE_BULK,
/**
* Topping / CV / absorption charging
*
* Lead-acid batteries are charged for some time using a slightly higher charge
* voltage. After a current cutoff limit or a time limit is reached, the charger
* goes into float or equalization mode for lead-acid batteries or back into
* Standby for Li-ion batteries.
*/
CHG_STATE_TOPPING,
/**
* Float / trickle charging
*
* This mode is kept forever for a lead-acid battery and keeps the battery at
* full state of charge. If too much power is drawn from the battery, the
* charger switches back into CC / bulk charging mode.
*/
CHG_STATE_FLOAT,
/**
* Equalization charging
*
* This mode is only used for lead-acid batteries after several deep-discharge
* cycles or a very long period of time with no equalization. Voltage is
* increased to 15V or above, so care must be taken for the other system
* components attached to the battery. (currently, no equalization charging is
* enabled in the software)
*/
CHG_STATE_EQUALIZATION,
/**
* Parallel operation of multiple converters
*
* This mode is enabled if the device receives commands from an external controller with
* higher priority on the CAN bus. The device goes in current control modes and tries to
* match the current of the other controller.
*/
CHG_STATE_FOLLOWER
};
/**
* Charger configuration and battery state
*/
class Charger
{
public:
Charger(PowerPort *pwr_port):
port(pwr_port) {};
PowerPort *port;
/**
* Current charger state (see enum ChargerState)
*/
uint32_t state = CHG_STATE_IDLE;
/**
* Battery temperature (°C) from ext. temperature sensor (if existing)
*/
float bat_temperature = 25;
/**
* Flag to indicate if external temperature sensor was detected
*/
bool ext_temp_sensor;
/**
* Estimated usable capacity (Ah) based on coulomb counting
*/
float usable_capacity;
/**
* Coulomb counter for SOH calculation
*/
float discharged_Ah;
/**
* Number of full charge cycles
*/
uint16_t num_full_charges;
/**
* Number of deep-discharge cycles
*/
uint16_t num_deep_discharges;
/**
* State of Charge (%)
*/
uint16_t soc = 100;
/**
* State of Health (%)
*/
uint16_t soh = 100;
/**
* Timestamp of last state change
*/
time_t time_state_changed = CHARGER_TIME_NEVER;
/**
* Last time the CV limit was reached
*/
time_t time_target_voltage_reached = CHARGER_TIME_NEVER;
/**
* Counts the number of seconds during which the target voltage of current charging phase was
* reached.
*/
uint32_t target_voltage_timer;
/**
* Timestamp after finish of last equalization charge
*/
time_t time_last_equalization = CHARGER_TIME_NEVER;
/**
* Deep discharge counter value after last equalization
*/
uint32_t deep_dis_last_equalization;
/**
* Flag to indicate if battery was fully charged
*/
bool full;
/**
* Flag to indicate if battery was completely discharged
*/
bool empty;
/**
* Last time a control message from external device was received
*/
time_t time_last_ctrl_msg = CHARGER_TIME_NEVER;
/**
* Target current of the converter if operating in follower mode (received from external
* converter with higher priority via CAN)
*/
float target_current_control;
/**
* Detect if two batteries are connected in series (12V/24V auto-detection)
*/
void detect_num_batteries(BatConf *bat) const;
/**
* Discharging control update (for load output), should be called once per second
*/
void discharge_control(BatConf *bat_conf);
/**
* Charger state machine update, should be called once per second
*/
void charge_control(BatConf *bat_conf);
/**
* SOC estimation
*
* Must be called exactly once per second, otherwise SOC calculation gets wrong.
*/
void update_soc(BatConf *bat_conf);
/**
* Initialize terminal and dc bus for battery connection
*
* @param bat Configuration to be used for terminal setpoints
*/
void init_terminal(BatConf *bat) const;
private:
void enter_state(int next_state);
};
/**
* Basic initialization of battery configuration
*
* Configures battery based on settings defined in config.h and initializes
* bat_user with same values
*
* @param bat Battery configuration that should be initialized
* @param type Battery type, one of enum BatType (declared as int instead of enum BatType because
* configuration via Kconfig symbol cannot handle enums)
* @param num_cells Number of cells (e.g. 6 for 12V lead-acid battery)
* @param nominal_capacity Nominal capacity (Ah)
*/
void battery_conf_init(BatConf *bat, int type, int num_cells, float nominal_capacity);
/**
* Checks battery user settings for plausibility
*/
bool battery_conf_check(BatConf *bat);
/**
* Overwrites battery settings (config should be checked first)
*
* Settings specified in bat_user will be copied to actual battery_t,
* if suggested updates are valid (includes plausibility check!)
*/
void battery_conf_overwrite(BatConf *source, BatConf *destination, Charger *charger = NULL);
/**
* Checks if incoming configuration is different to current configuration
*
* Returns true if changed
*/
bool battery_conf_changed(BatConf *a, BatConf *b);
#endif /* BAT_CHARGER_H */
+25
View File
@@ -0,0 +1,25 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef BOARD_H_
#define BOARD_H_
/**
* @file
*
* @brief Defines for conditional compiling based on existing board features
*/
#include <zephyr.h>
#define BOARD_HAS_DCDC DT_HAS_COMPAT_STATUS_OKAY(half_bridge)
#define BOARD_HAS_PWM_PORT DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), pwm_switch))
#define BOARD_HAS_LOAD_OUTPUT DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), load))
#define BOARD_HAS_USB_OUTPUT DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), usb_pwr))
#define BOARD_HAS_TEMP_FETS DT_NODE_EXISTS(DT_CHILD(DT_PATH(adc_inputs), temp_fets))
#define BOARD_HAS_TEMP_BAT DT_NODE_EXISTS(DT_CHILD(DT_PATH(adc_inputs), temp_bat))
#endif /* BOARD_H_ */
+402
View File
@@ -0,0 +1,402 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "daq.h"
#include <zephyr.h>
#include <logging/log.h>
LOG_MODULE_REGISTER(daq, CONFIG_DAQ_LOG_LEVEL);
#include <math.h> // log for thermistor calculation
#include <assert.h>
#include "mcu.h"
#include "setup.h"
// typical value for Semitec 103AT-5 thermistor: 3435
#define NTC_BETA_VALUE 3435
// filter parameter c for additional battery voltage and current low-pass filter
// c = dt / (tau + dt) = 0.1s / (10s + 0.1s)
#define HV_BUS_VOLTAGE_FILTER_CONST 0.0099F
#define LV_BUS_VOLTAGE_FILTER_CONST 0.0099F
#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
// 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] = {};
// 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)
{
/** \todo Improved (faster) temperature calculation:
https://www.embeddedrelated.com/showarticle/91.php
*/
// voltage read by ADC (mV)
float v_temp = adc_raw_to_voltage(adc_raw_filtered(channel), vref) * 1000;
// resistance of NTC (Ohm)
float rts = ntc_series_resistor * v_temp / (vref - v_temp);
return 1.0/(1.0/(273.15+25) + 1.0/NTC_BETA_VALUE*log(rts/10000.0)) - 273.15; // °C
}
void calibrate_current_sensors()
{
#if BOARD_HAS_DCDC
dcdc_current_offset_raw = adc_raw_filtered(ADC_POS(i_dcdc));
#endif
#if BOARD_HAS_PWM_PORT
pwm_current_offset_raw = adc_raw_filtered(ADC_POS(i_pwm));
#endif
#if BOARD_HAS_LOAD_OUTPUT
load_current_offset_raw = adc_raw_filtered(ADC_POS(i_load));
#endif
}
void adc_update_value(unsigned int pos)
{
#if BOARD_HAS_PWM_PORT
// 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)
#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]);
}
// 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;
}
// 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;
}
}
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));
if (lv_bus.voltage_filtered != 0.0F) {
lv_bus.voltage_filtered = LV_BUS_VOLTAGE_FILTER_CONST * lv_bus.voltage +
(1.0F - LV_BUS_VOLTAGE_FILTER_CONST) * lv_bus.voltage_filtered;
}
else {
// initialize properly at startup
lv_bus.voltage_filtered = lv_bus.voltage;
}
#if BOARD_HAS_DCDC
hv_bus.voltage = adc_scaled(ADC_POS(v_high), vref, ADC_GAIN(v_high));
if (hv_bus.voltage_filtered != 0.0F) {
hv_bus.voltage_filtered = HV_BUS_VOLTAGE_FILTER_CONST * hv_bus.voltage +
(1.0F - HV_BUS_VOLTAGE_FILTER_CONST) * hv_bus.voltage_filtered;
}
else {
// initialize properly at startup
hv_bus.voltage_filtered = hv_bus.voltage;
}
#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));
#endif
#if BOARD_HAS_LOAD_OUTPUT
load.current = adc_scaled(ADC_POS(i_load), vref, ADC_GAIN(i_load), load_current_offset_raw);
float load_current = load.current;
#else
float load_current = 0; // value used below, so we still need to define the variable
#endif
float lv_terminal_current = -load_current;
#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_filtered = PWM_CURRENT_FILTER_CONST * pwm_switch.current +
(1.0F - PWM_CURRENT_FILTER_CONST) * pwm_switch.current_filtered;
lv_terminal_current -= pwm_switch.current;
pwm_switch.power = pwm_switch.bus->voltage * pwm_switch.current;
#endif
#if BOARD_HAS_DCDC
dcdc.inductor_current =
adc_scaled(ADC_POS(i_dcdc), vref, ADC_GAIN(i_dcdc), dcdc_current_offset_raw);
lv_terminal_current += dcdc.inductor_current;
hv_terminal.current = -dcdc.inductor_current * lv_terminal.bus->voltage /
hv_terminal.bus->voltage;
dcdc.power = dcdc.lvb->voltage * dcdc.inductor_current;
hv_terminal.power = hv_terminal.bus->voltage * hv_terminal.current;
#endif
lv_terminal.current = lv_terminal_current;
lv_terminal.power = lv_terminal.bus->voltage * lv_terminal.current;
lv_terminal.current_filtered = LV_TERMINAL_CURRENT_FILTER_CONST * lv_terminal.current +
(1.0F - LV_TERMINAL_CURRENT_FILTER_CONST) * lv_terminal.current_filtered;
#if BOARD_HAS_LOAD_OUTPUT
load.power = load.bus->voltage * load.current;
#endif
#if BOARD_HAS_TEMP_BAT
// battery temperature calculation
float bat_temp = ntc_temp(ADC_POS(temp_bat), vref, ADC_GAIN(temp_bat));
if (bat_temp > -50) {
// external sensor connected: take measured value
charger.bat_temperature = bat_temp;
charger.ext_temp_sensor = true;
}
else {
// no external sensor: assume typical room temperature
charger.bat_temperature = 25;
charger.ext_temp_sensor = false;
}
#endif
#if BOARD_HAS_TEMP_FETS
dcdc.temp_mosfets = ntc_temp(ADC_POS(temp_fets), vref, 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;
if (dev_stat.internal_temp > 80) {
dev_stat.set_error(ERR_INT_OVERTEMP);
}
else if (dev_stat.internal_temp < 70 && (dev_stat.has_error(ERR_INT_OVERTEMP))) {
// remove error flag with hysteresis of 10°C
dev_stat.clear_error(ERR_INT_OVERTEMP);
}
// else: keep previous setting
}
void lv_overvoltage_alert()
{
// disable any sort of input
#if BOARD_HAS_DCDC
dcdc.stop();
#endif
#if BOARD_HAS_PWM_PORT
pwm_switch.stop();
#endif
// do not use enter_state function, as we don't want to wait entire recharge delay
charger.state = CHG_STATE_IDLE;
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);
}
void lv_undervoltage_alert()
{
#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);
}
#if BOARD_HAS_DCDC
void hv_overvoltage_alert()
{
dcdc.stop();
// do not use enter_state function, as we don't want to wait entire recharge delay
charger.state = CHG_STATE_IDLE;
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;
}
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;
}
#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.3 * 4096) << 4;
adc_readings[ADC_POS(v_low)] =
(uint16_t)((values.battery_voltage / ADC_GAIN(v_low)) / 3.3 * 4096) << 4;
adc_readings[ADC_POS(i_dcdc)] =
(uint16_t)((values.dcdc_current / ADC_GAIN(i_dcdc)) / 3.3 * 4096) << 4;
adc_readings[ADC_POS(i_load)] =
(uint16_t)((values.load_current / ADC_GAIN(i_load)) / 3.3 * 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 */
+153
View File
@@ -0,0 +1,153 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @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.
*/
#ifndef DAQ_H_
#define DAQ_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <zephyr.h>
#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
};
/**
* Struct to define upper and lower limit alerts for any ADC channel
*/
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;
}
/**
* Set offset vs. actual measured value, i.e. sets zero current point.
*
* All input/output switches and consumers should be switched off before calling this function
*/
void calibrate_current_sensors(void);
/**
* Updates structures with data read from ADC
*/
void daq_update(void);
/**
* Initializes ADC, DAC and DMA
*/
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
*
* @param lv_overvoltage Upper voltage limit
* @param lv_undervoltage Lower voltage limit
*/
void daq_set_lv_limits(float lv_overvoltage, float lv_undervoltage);
/**
* Set hv side (grid/solar) voltage limit where an alert should be triggered
*
* @param hv_overvoltage Upper voltage limit
*/
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
#endif /* DAQ_H_ */
+383
View File
@@ -0,0 +1,383 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "daq.h"
#ifndef UNIT_TEST
#include <stdint.h>
#include <inttypes.h>
#include <zephyr.h>
#include <drivers/gpio.h>
#include <stm32_ll_system.h>
#include <stm32_ll_adc.h>
#include <stm32_ll_dac.h>
#include <stm32_ll_dma.h>
#include <stm32_ll_bus.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_GPIO DT_CHILD(DT_PATH(adc_inputs), v_high)
static void adc_setup()
{
#if DT_NODE_EXISTS(DT_PROP(V_HIGH_ENABLE_GPIO, enable_gpios))
const struct device *dev = device_get_binding(DT_GPIO_LABEL(V_HIGH_ENABLE_GPIO, enable_gpios));
gpio_pin_configure(dev, DT_GPIO_PIN(V_HIGH_ENABLE_GPIO, enable_gpios),
DT_GPIO_FLAGS(V_HIGH_ENABLE_GPIO, enable_gpios) | 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
File diff suppressed because it is too large Load Diff
+86
View File
@@ -0,0 +1,86 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef DATA_OBJECTS_H_
#define DATA_OBJECTS_H_
/** @file
*
* @brief Handling of ThingSet data objects
*/
#include <stdint.h>
#include <string.h>
/*
* Categories / first layer node IDs
*/
#define ID_ROOT 0x00
#define ID_INFO 0x01 // read-only device information (e.g. manufacturer, device ID)
#define ID_MEAS 0x02 // output data (e.g. measurement values)
#define ID_STATE 0x03 // recorded data (history-dependent)
#define ID_REC 0x04 // recorded data (history-dependent)
#define ID_INPUT 0x05 // input data (e.g. set-points)
#define ID_CONF 0x06 // configurable settings
#define ID_CAL 0x07 // calibration
#define ID_REPORT 0x0A // reports
#define ID_RPC 0x0E // remote procedure calls
#define ID_DFU 0x0F // device firmware upgrade
#define ID_PUB 0x100 // publication setup
#define ID_CTRL 0x8000 // control functions
/*
* Subset definitions for statements and publish/subscribe
*/
#define SUBSET_SER (1U << 0) // UART serial
#define SUBSET_CAN (1U << 1) // CAN bus
#define SUBSET_NVM (1U << 2) // data that should be stored in EEPROM
#define SUBSET_CTRL (1U << 3) // control data sent and received via CAN
/*
* Data object versioning for EEPROM
*
* Increment the version number each time any data object IDs stored in NVM are changed. Otherwise
* data might get corrupted.
*/
#define DATA_OBJECTS_VERSION 05
extern bool pub_serial_enable;
extern bool pub_can_enable;
/**
* Callback function to be called when conf values were changed
*/
void data_objects_update_conf();
/**
* Initializes and reads data objects from EEPROM
*/
void data_objects_init();
/**
* Callback to provide authentication mechanism via ThingSet
*/
void thingset_auth();
/**
* Alphabet used for base32 encoding
*
* https://en.wikipedia.org/wiki/Base32#Crockford's_Base32
*/
const char alphabet_crockford[] = "0123456789abcdefghjkmnpqrstvwxyz";
/**
* Convert numeric device ID to base32 string
*/
void uint64_to_base32(uint64_t in, char *out, size_t size, const char *alphabet);
/**
* Update control values received via CAN
*/
void update_control();
#endif /* DATA_OBJECTS_H */
+265
View File
@@ -0,0 +1,265 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "data_storage.h"
#include <zephyr.h>
#include "mcu.h"
#include "thingset.h"
#include "data_objects.h"
#include "helper.h"
#include <stdio.h>
#ifdef CONFIG_SOC_FAMILY_STM32
#include <device.h>
#include <stm32_ll_bus.h>
LOG_MODULE_REGISTER(nvs, CONFIG_DATA_STORAGE_LOG_LEVEL);
K_MUTEX_DEFINE(data_buf_lock);
// Buffer used by store and restore functions (must be word-aligned for hardware CRC calculation)
static uint8_t buf[512] __aligned(sizeof(uint32_t));
extern ThingSet ts;
uint32_t _calc_crc(const uint8_t *buf, size_t len)
{
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_CRC);
// we keep standard polynomial 0x04C11DB7 (same for STM32L0 and STM32F0)
// and we don't care for endianness here
CRC->CR |= CRC_CR_RESET;
for (size_t i = 0; i < len; i += 4) {
//printf("CRC buf: %.8x, CRC->DR: %.8x\n", *((uint32_t*)&buf[i]), CRC->DR);
size_t remaining_bytes = len - i;
if (remaining_bytes >= 4) {
CRC->DR = *((uint32_t*)&buf[i]);
}
else {
// ignore bytes >= len if len is not a multiple of 4
CRC->DR = *((uint32_t*)&buf[i]) & (0xFFFFFFFFU >> (32 - remaining_bytes * 8));
}
}
LL_AHB1_GRP1_DisableClock(LL_AHB1_GRP1_PERIPH_CRC);
return CRC->DR;
}
#endif /* UNIT_TEST */
#ifdef CONFIG_EEPROM
#include <drivers/eeprom.h>
/*
* EEPROM header bytes:
* - 0-1: Data objects version number
* - 2-3: Number of data bytes
* - 4-7: CRC32
*
* Data starts from byte 8
*/
#define EEPROM_HEADER_SIZE 8
void data_storage_read()
{
int err;
const struct device *eeprom_dev = device_get_binding("EEPROM_0");
uint8_t buf_header[EEPROM_HEADER_SIZE] = {};
err = eeprom_read(eeprom_dev, 0, buf_header, EEPROM_HEADER_SIZE);
if (err != 0) {
LOG_ERR("EEPROM read error %d", err);
return;
}
uint16_t version = *((uint16_t*)&buf_header[0]);
uint16_t len = *((uint16_t*)&buf_header[2]);
uint32_t crc = *((uint32_t*)&buf_header[4]);
LOG_DBG("EEPROM header restore: ver %d, len %d, CRC %.8x", version, len, (unsigned int)crc);
LOG_DBG("Header: %.2x %.2x %.2x %.2x %.2x %.2x %.2x %.2x",
buf_header[0], buf_header[1], buf_header[2], buf_header[3],
buf_header[4], buf_header[5], buf_header[6], buf_header[7]);
if (version == DATA_OBJECTS_VERSION && len <= sizeof(buf)) {
k_mutex_lock(&data_buf_lock, K_FOREVER);
err = eeprom_read(eeprom_dev, EEPROM_HEADER_SIZE, buf, len);
//printf("Data (len=%d): ", len);
//for (int i = 0; i < len; i++) printf("%.2x ", buf[i]);
if (_calc_crc(buf, len) == crc) {
int status = ts.bin_import(buf, sizeof(buf), TS_WRITE_MASK, SUBSET_NVM);
LOG_INF("EEPROM read and data objects updated, ThingSet result: 0x%x", status);
}
else {
LOG_ERR("EEPROM data CRC invalid, expected 0x%x (data_len = %d)",
(unsigned int)crc, len);
}
k_mutex_unlock(&data_buf_lock);
}
else {
LOG_INF("EEPROM empty or data layout version changed");
}
}
void data_storage_write()
{
int err;
const struct device *eeprom_dev = device_get_binding("EEPROM_0");
k_mutex_lock(&data_buf_lock, K_FOREVER);
int len = ts.bin_export(buf + EEPROM_HEADER_SIZE, sizeof(buf) - EEPROM_HEADER_SIZE, SUBSET_NVM);
uint32_t crc = _calc_crc(buf + EEPROM_HEADER_SIZE, len);
*((uint16_t*)&buf[0]) = (uint16_t)DATA_OBJECTS_VERSION;
*((uint16_t*)&buf[2]) = (uint16_t)(len);
*((uint32_t*)&buf[4]) = crc;
//printf("Data (len=%d): ", len);
//for (int i = 0; i < len; i++) printf("%.2x ", buf[i + EEPROM_HEADER_SIZE]);
LOG_DBG("Header: %.2x %.2x %.2x %.2x %.2x %.2x %.2x %.2x",
buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]);
if (len == 0) {
LOG_ERR("EEPROM data could not be stored. ThingSet error (len = %d)", len);
}
else {
err = eeprom_write(eeprom_dev, 0, buf, len + EEPROM_HEADER_SIZE);
if (err == 0) {
LOG_INF("EEPROM data successfully stored");
}
else {
LOG_ERR("EEPROM write error %d", err);
}
}
k_mutex_unlock(&data_buf_lock);
}
#elif defined(CONFIG_NVS)
#include <drivers/flash.h>
#include <storage/flash_map.h>
#include <fs/nvs.h>
/*
* NVS header bytes:
* - 0-1: Data objects version number
*
* Data starts from byte 2
*/
#define NVS_HEADER_SIZE 2
#define FLASH_PARTITION_NODE DT_NODE_BY_FIXED_PARTITION_LABEL(storage)
#define FLASH_DEVICE_NODE DT_MTD_FROM_FIXED_PARTITION(FLASH_PARTITION_NODE)
#define THINGSET_DATA_ID 1
static const struct device *flash_dev = DEVICE_DT_GET(FLASH_DEVICE_NODE);
static struct nvs_fs fs;
static bool nvs_initialized = false;
static void data_storage_init()
{
int err;
struct flash_pages_info page_info;
fs.offset = FLASH_AREA_OFFSET(storage);
err = flash_get_page_info_by_offs(flash_dev, fs.offset, &page_info);
if (err) {
LOG_ERR("Unable to get flash page info");
}
fs.sector_size = page_info.size;
fs.sector_count = FLASH_AREA_SIZE(storage) / page_info.size;
err = nvs_init(&fs, DT_LABEL(FLASH_DEVICE_NODE));
if (err) {
LOG_ERR("NVS init failed");
}
nvs_initialized = true;
}
void data_storage_read()
{
if (!nvs_initialized) {
data_storage_init();
}
int num_bytes = nvs_read(&fs, THINGSET_DATA_ID, &buf, sizeof(buf));
if (num_bytes < 0) {
LOG_INF("NVS empty (read error %d)", num_bytes);
return;
}
uint16_t version = *((uint16_t*)&buf[0]);
if (version == DATA_OBJECTS_VERSION) {
k_mutex_lock(&data_buf_lock, K_FOREVER);
int status = ts.bin_import(buf + NVS_HEADER_SIZE, num_bytes - NVS_HEADER_SIZE,
TS_WRITE_MASK, SUBSET_NVM);
LOG_INF("NVS read and data objects updated, ThingSet result: 0x%x", status);
k_mutex_unlock(&data_buf_lock);
}
else {
LOG_INF("NVS data layout version changed");
}
}
void data_storage_write()
{
if (!nvs_initialized) {
data_storage_init();
}
k_mutex_lock(&data_buf_lock, K_FOREVER);
*((uint16_t*)&buf[0]) = (uint16_t)DATA_OBJECTS_VERSION;
int len = ts.bin_export(buf + NVS_HEADER_SIZE, sizeof(buf) - NVS_HEADER_SIZE, SUBSET_NVM);
if (len == 0) {
LOG_ERR("NVS data could not be stored. ThingSet error (len = %d)", len);
}
else {
int ret = nvs_write(&fs, THINGSET_DATA_ID, &buf, len + NVS_HEADER_SIZE);
if (ret == len + NVS_HEADER_SIZE) {
LOG_INF("NVS data successfully stored");
}
else {
LOG_ERR("NVS write error %d", ret);
}
}
k_mutex_unlock(&data_buf_lock);
}
#else
void data_storage_write() {;}
void data_storage_read() {;}
#endif
void data_storage_update()
{
if (uptime() % DATA_UPDATE_INTERVAL == 0 && uptime() > 0) {
data_storage_write();
}
}
+33
View File
@@ -0,0 +1,33 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef DATA_STORAGE_H_
#define DATA_STORAGE_H_
#define DATA_UPDATE_INTERVAL (6*60*60) // update every 6 hours
/**
* @file
*
* @brief Handling of internal or external EEPROM to store device configuration
*/
/**
* Store current charge controller data to EEPROM
*/
void data_storage_write();
/**
* Restore charge controller data from EEPROM and write to variables in RAM
*/
void data_storage_read();
/**
* Stores data to EEPROM every 6 hours (can be called regularly)
*/
void data_storage_update();
#endif /* DATA_STORAGE_H_ */
+373
View File
@@ -0,0 +1,373 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "dcdc.h"
#include <zephyr.h>
#include <device.h>
#include <drivers/gpio.h>
#include <math.h> // for fabs function
#include <stdlib.h> // for min/max function
#include <stdio.h>
#include "device_status.h"
#include "helper.h"
#include "half_bridge.h"
#include "data_storage.h"
#include "setup.h"
LOG_MODULE_REGISTER(dcdc, CONFIG_DCDC_LOG_LEVEL);
extern DeviceStatus dev_stat;
#if BOARD_HAS_DCDC
#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), hv_out))
#define HV_OUT_NODE DT_CHILD(DT_PATH(outputs), hv_out)
#endif
Dcdc::Dcdc(DcBus *high, DcBus *low, DcdcOperationMode op_mode)
{
hvb = high;
lvb = low;
mode = op_mode;
enable = true;
state = DCDC_CONTROL_OFF;
inductor_current_max = DT_PROP(DT_PATH(pcb), dcdc_current_max);
hs_voltage_max = DT_PROP(DT_PATH(pcb), hs_voltage_max);
ls_voltage_max = DT_PROP(DT_PATH(pcb), ls_voltage_max);
ls_voltage_min = 9.0;
output_power_min = 1; // switch off if power < 1 W
restart_interval = 60;
off_timestamp = -10000; // start immediately
pwm_delta = 1; // start-condition of duty cycle pwr_inc_pwm_direction
// lower duty limit might have to be adjusted dynamically depending on LS voltage
half_bridge_init(DT_PROP(DT_INST(0, half_bridge), frequency) / 1000,
DT_PROP(DT_INST(0, half_bridge), deadtime), 12 / hs_voltage_max, 0.97);
}
int Dcdc::perturb_observe_controller()
{
int pwr_inc_pwm_direction; // direction of PWM duty cycle change for increasing power
DcBus *in;
DcBus *out;
float out_power;
if (mode == DCDC_MODE_BUCK || (mode == DCDC_MODE_AUTO && inductor_current > 0.1)) {
// buck mode
pwr_inc_pwm_direction = 1;
in = hvb;
out = lvb;
out_power = power;
}
else {
// boost mode
pwr_inc_pwm_direction = -1;
in = lvb;
out = hvb;
out_power = -power;
}
if (out_power >= output_power_min) {
power_good_timestamp = uptime(); // reset the time
}
int pwr_inc_goal = 0; // stores if we want to increase (+1) or decrease (-1) power
if ((uptime() - power_good_timestamp > 10 || out_power < -10.0) && mode != DCDC_MODE_AUTO) {
// switch off after 10s low power or negative power (if not in nanogrid mode)
pwr_inc_goal = 0;
}
else if (out->voltage > out->sink_control_voltage()) {
// output voltage target reached
state = (out == lvb) ? DCDC_CONTROL_CV_LS : DCDC_CONTROL_CV_HS;
pwr_inc_goal = -1; // decrease output power
}
else if (out->sink_current_margin < 0) {
// output charge current limit reached
state = (out == lvb) ? DCDC_CONTROL_CC_LS : DCDC_CONTROL_CC_HS;
pwr_inc_goal = -1; // decrease output power
}
else if (in->src_current_margin > 0) {
// input current (negative signs) limit exceeded
state = (in == hvb) ? DCDC_CONTROL_CC_HS : DCDC_CONTROL_CC_LS;
pwr_inc_goal = -1; // decrease output power
}
else if (fabs(inductor_current) > inductor_current_max) {
// current above hardware maximum
state = DCDC_CONTROL_CC_LS;
pwr_inc_goal = -1; // decrease output power
}
else if (in->voltage < in->src_control_voltage() && out_power > output_power_min) {
// input voltage below limit
state = (in == hvb) ? DCDC_CONTROL_CV_HS : DCDC_CONTROL_CV_LS;
pwr_inc_goal = -1;
}
else if (temp_mosfets > 80) {
// temperature limits exceeded
state = DCDC_CONTROL_DERATING;
pwr_inc_goal = -1;
}
else if (out_power < output_power_min && out->voltage < out->src_control_voltage()) {
// no load condition (e.g. start-up of nanogrid) --> raise voltage
pwr_inc_goal = 1; // increase output power
}
else {
// start MPPT
state = DCDC_CONTROL_MPPT;
if (power_prev > out_power) {
pwm_delta = -pwm_delta;
}
pwr_inc_goal = pwm_delta;
}
#if CONFIG_DCDC_LOG_LEVEL == LOG_LEVEL_DBG
// workaround as LOG_DBG does not support float printing
printf("P: %.2fW (prev %.2fW), ind. current: %.2f, "
"in: %.2fV, %.2fA margin, out: %.2fV (target %.2fV), %.2fA margin, "
"PWM: %.1f, chg_state: %d, pwr_inc: %d, buck/boost: %d\n",
out_power, power_prev, inductor_current, in->voltage, in->src_current_margin,
out->voltage, out->sink_voltage_intercept, out->sink_current_margin,
half_bridge_get_duty_cycle() * 100.0, state, pwr_inc_goal, pwr_inc_pwm_direction);
#endif
power_prev = out_power;
#ifdef CONFIG_SOC_SERIES_STM32G4X
// reduced step size for fast microcontroller
half_bridge_set_ccr(half_bridge_get_ccr() + pwr_inc_goal * pwr_inc_pwm_direction * 3);
#else
// change duty cycle by single minimum step
half_bridge_set_ccr(half_bridge_get_ccr() + pwr_inc_goal * pwr_inc_pwm_direction);
#endif
return (pwr_inc_goal == 0);
}
__weak DcdcOperationMode Dcdc::check_start_conditions()
{
if (enable == false ||
hvb->voltage > hs_voltage_max || // also critical for buck mode because of ringing
lvb->voltage > ls_voltage_max ||
lvb->voltage < ls_voltage_min ||
dev_stat.has_error(ERR_BAT_UNDERVOLTAGE | ERR_BAT_OVERVOLTAGE) ||
(int)uptime() < (off_timestamp + (int)restart_interval))
{
return DCDC_MODE_OFF;
}
if (lvb->sink_current_margin > 0 &&
lvb->voltage < lvb->sink_control_voltage() &&
hvb->src_current_margin < 0 &&
hvb->voltage > hvb->src_control_voltage() &&
hvb->voltage * 0.85 > lvb->voltage)
{
return DCDC_MODE_BUCK;
}
if (hvb->sink_current_margin > 0 &&
hvb->voltage < hvb->sink_control_voltage() &&
lvb->src_current_margin < 0 &&
lvb->voltage > lvb->src_control_voltage())
{
return DCDC_MODE_BOOST;
}
return DCDC_MODE_OFF;
}
bool Dcdc::check_hs_mosfet_short()
{
static uint32_t first_time_detected = 0;
if (inductor_current > 0.5 && half_bridge_enabled() == false) {
// if there is current even though the DC/DC is switched off, the
// high-side MOSFET must be broken --> set flag and let main() decide
// what to do... (e.g. call dcdc_self_destruction)
uint32_t now = uptime();
if (first_time_detected == 0) {
first_time_detected = now;
}
else if (now - first_time_detected > 2) {
// waited >1s before setting the flag
dev_stat.set_error(ERR_DCDC_HS_MOSFET_SHORT);
}
}
return dev_stat.has_error(ERR_DCDC_HS_MOSFET_SHORT);
}
bool Dcdc::startup_inhibit(bool reset)
{
static uint32_t inhibit_start;
if (reset) {
inhibit_start = uptime();
return true;
}
else {
return (uptime() < inhibit_start + DCDC_STARTUP_INHIBIT_TIME);
}
}
__weak void Dcdc::control()
{
if (half_bridge_enabled() == false) {
if (check_hs_mosfet_short()) {
return;
}
int startup_mode = check_start_conditions();
if (startup_mode != DCDC_MODE_OFF) {
// startup allowed, but we need to wait until voltages settle
if (startup_inhibit()) {
return;
}
const char *mode_name = NULL;
if (startup_mode == DCDC_MODE_BUCK) {
mode_name = "buck";
// Don't start directly at Vmpp (approx. 0.8 * Voc) to prevent high inrush
// currents and stress on MOSFETs
half_bridge_set_duty_cycle(lvb->voltage / (hvb->voltage - 1));
}
else {
mode_name = "boost";
// Will automatically start with max. duty (0.97) if connected to a
// nanogrid not yet started up (zero voltage)
half_bridge_set_duty_cycle(lvb->voltage / (hvb->voltage + 1));
}
half_bridge_start();
power_good_timestamp = uptime();
printf("DC/DC %s mode start (HV: %.2fV, LV: %.2fV, PWM: %.1f).\n", mode_name,
hvb->voltage, lvb->voltage, half_bridge_get_duty_cycle() * 100);
}
else {
startup_inhibit(true); // reset inhibit counter
}
}
else { // half bridge is on
const char *stop_reason = NULL;
if (lvb->voltage > ls_voltage_max || hvb->voltage > hs_voltage_max) {
stop_reason = "emergency (voltage limits exceeded)";
}
else if (enable == false) {
stop_reason = "disabled";
}
else {
int err = perturb_observe_controller();
if (err != 0) {
stop_reason = "low power";
}
}
if (stop_reason != NULL) {
stop();
printf("DC/DC Stop: %s.\n", stop_reason);
}
}
}
void Dcdc::test()
{
if (half_bridge_enabled()) {
const char *stop_reason = NULL;
if (lvb->voltage > ls_voltage_max || hvb->voltage > hs_voltage_max) {
stop_reason = "emergency (voltage limits exceeded)";
}
else if (enable == false) {
stop_reason = "disabled";
}
else {
if (half_bridge_get_duty_cycle() > 0.50) {
half_bridge_set_ccr(half_bridge_get_ccr() - 1);
}
else {
half_bridge_set_ccr(half_bridge_get_ccr() + 1);
}
}
if (stop_reason != NULL) {
stop();
printf("DC/DC Stop: %s.\n", stop_reason);
}
}
else {
if (check_start_conditions() != DCDC_MODE_OFF) {
// startup allowed, but we need to wait until voltages settle
if (startup_inhibit()) {
return;
}
half_bridge_set_duty_cycle(lvb->voltage / hvb->voltage);
half_bridge_start();
printf("DC/DC test mode start (HV: %.2fV, LV: %.2fV, PWM: %.1f).\n",
hvb->voltage, lvb->voltage, half_bridge_get_duty_cycle() * 100);
}
else {
startup_inhibit(true); // reset inhibit counter
}
}
}
void Dcdc::stop()
{
half_bridge_stop();
state = DCDC_CONTROL_OFF;
off_timestamp = uptime();
}
void Dcdc::fuse_destruction()
{
static int counter = 0;
if (counter > 20) { // wait 20s to be able to send out data
LOG_ERR("Charge controller fuse destruction called!\n");
data_storage_write();
half_bridge_stop();
half_bridge_init(50, 0, 0, 0.98); // reset safety limits to allow 0% duty cycle
half_bridge_set_duty_cycle(0);
half_bridge_start();
// now the fuse should be triggered and we disappear
}
counter++;
}
void Dcdc::output_hvs_enable()
{
#ifdef HV_OUT_NODE
const struct device *hv_out = DEVICE_DT_GET(DT_GPIO_CTLR(HV_OUT_NODE, gpios));
if (device_is_ready(hv_out)) {
gpio_pin_configure(hv_out, DT_GPIO_PIN(HV_OUT_NODE, gpios),
DT_GPIO_FLAGS(HV_OUT_NODE, gpios) | GPIO_OUTPUT_ACTIVE);
}
#endif
}
void Dcdc::output_hvs_disable()
{
#ifdef HV_OUT_NODE
const struct device *hv_out = DEVICE_DT_GET(DT_GPIO_CTLR(HV_OUT_NODE, gpios));
if (device_is_ready(hv_out)) {
gpio_pin_configure(hv_out, DT_GPIO_PIN(HV_OUT_NODE, gpios),
DT_GPIO_FLAGS(HV_OUT_NODE, gpios) | GPIO_OUTPUT_INACTIVE);
}
#endif
}
#else
Dcdc::Dcdc(DcBus *high, DcBus *low, DcdcOperationMode op_mode) {}
#endif /* BOARD_HAS_DCDC */
+225
View File
@@ -0,0 +1,225 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef DCDC_H
#define DCDC_H
/**
* @file
*
* @brief DC/DC buck/boost control functions
*/
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
#include "power_port.h"
#define DCDC_STARTUP_INHIBIT_TIME 3 // seconds
/**
* DC/DC operation mode
*
* Defines which type of device is connected to the high side and low side ports
*/
enum DcdcOperationMode
{
/**
* DC/DC converter switched off
*/
DCDC_MODE_OFF,
/**
* Buck converter mode
*
* Solar panel at high side port, battery / load at low side port (typical MPPT).
*/
DCDC_MODE_BUCK,
/**
* Boost converter mode
*
* Battery at high side port, solar panel at low side (e.g. e-bike charging).
*/
DCDC_MODE_BOOST,
/**
* Automatic mode selection
*
* Boost or buck mode is automatically chosen based on high-side and low-side port settings.
*
* May be used in nanogrid applications: Accept input power (if available and need for charging)
* or provide output power (if no other power source available on the grid and battery charged)
*/
DCDC_MODE_AUTO
};
/**
* DC/DC control state
*
* Allows to determine the current control state (off, CC, CV and MPPT)
*/
enum DcdcControlState
{
DCDC_CONTROL_OFF, ///< DC/DC switched off (low input power or actively disabled)
DCDC_CONTROL_MPPT, ///< Maximum Power Point Tracking
DCDC_CONTROL_CC_LS, ///< Constant-Current control at low-side
DCDC_CONTROL_CV_LS, ///< Constant-Voltage control at low-side
DCDC_CONTROL_CC_HS, ///< Constant-Current control at high-side
DCDC_CONTROL_CV_HS, ///< Constant-Voltage control at high-side
DCDC_CONTROL_DERATING ///< Hardware-limits (current or temperature) reached
};
/**
* DC/DC class
*
* Contains all data belonging to the DC/DC sub-component of the PCB, incl.
* actual measurements and calibration parameters.
*/
class Dcdc
{
public:
/**
* Initialize DC/DC and DC/DC port structs
*
* See http://libre.solar/docs/dcdc_control for detailed information
*
* @param high High voltage bus (e.g. solar input for MPPT buck)
* @param low Low voltage bus (e.g. battery output for MPPT buck)
* @param mode Operation mode (buck, boost or nanogrid)
*/
Dcdc(DcBus *high, DcBus* low, DcdcOperationMode mode);
/**
* Check for valid start conditions of the DC/DC converter
*
* @returns operation mode that is valid for starting up
*/
DcdcOperationMode check_start_conditions();
/**
* Main control function for the DC/DC converter
*
* If DC/DC is off, this function checks start conditions and starts conversion if possible.
*/
void control();
/**
* Test mode for DC/DC, ramping up/down to 50% duty cycle
*/
void test();
/**
* Fast stop function (bypassing control loop)
*
* May be called from an ISR which detected overvoltage / overcurrent conditions.
*
* DC/DC will be restarted automatically from control function if condtions are valid.
*/
void stop();
/**
* Prevent overcharging of battery in case of shorted HS MOSFET
*
* This function switches the LS MOSFET continuously on to blow the battery input fuse. The
* reason for self destruction should be logged and stored to EEPROM prior to calling this
* function, as the charge controller power supply will be cut after the fuse is destroyed.
*/
void fuse_destruction();
DcdcOperationMode mode; ///< DC/DC mode (buck, boost or nanogrid)
bool enable; ///< Can be used to disable the DC/DC power stage
uint16_t state; ///< Control state (off / MPPT / CC / CV)
// actual measurements
DcBus *hvb; ///< Pointer to DC bus at high voltage side
DcBus *lvb; ///< Pointer to DC bus at low voltage (inductor) side
float inductor_current; ///< Inductor current
float power; ///< Low-side power
float temp_mosfets; ///< MOSFET temperature measurement (if existing)
// current state
float power_prev; ///< Stores previous conversion power (set via dcdc_control)
int32_t pwm_delta; ///< Direction of PWM change for MPPT
int32_t off_timestamp; ///< Last time the DC/DC was switched off
int32_t power_good_timestamp; ///< Last time the DC/DC reached above minimum output power
// maximum allowed values
float inductor_current_max = 0; ///< Maximum low-side (inductor) current
float hs_voltage_max = 0; ///< Maximum high-side voltage
float ls_voltage_max; ///< Maximum low-side voltage
float ls_voltage_min; ///< Minimum low-side voltage, e.g. for driver supply
float output_power_min; ///< Minimum output power (if lower, DC/DC is switched off)
// calibration parameters
uint32_t restart_interval; ///< Restart interval (s): When should we retry to start
///< charging after low output power cut-off?
private:
/**
* MPPT perturb & observe control
*
* Calculates the duty cycle change depending on operating mode and actual measurements and
* changes the half bridge PWM signal accordingly
*
* @returns 0 if everything is fine, error number otherwise
*/
int perturb_observe_controller();
/**
* If manual control of the reverse polarity MOSFET on the high-side is available, this
* function enables it to use the high voltage side as output.
*/
void output_hvs_enable();
/**
* Disable the reverse polarity MOSFET on the high-sied (if option available)
*/
void output_hvs_disable();
/**
* Check if the high-side MOSFET is shorted
*/
bool check_hs_mosfet_short();
/**
* Check if we need to wait for voltages to settle before starting the DC/DC
*
* @param reset Reset the inhibit counter if set to true
*
* @returns true if we need to wait
*/
bool startup_inhibit(bool reset = false);
};
#endif // __cplusplus
#ifdef __cplusplus
extern "C" {
#endif
#ifdef CONFIG_CUSTOM_DCDC_CONTROLLER
/**
* Low-level control function
*
* Implement this function e.g. for cycle-by-cylce current limitation.
*
* It is called from the DMA after each new current reading, i.e. it runs in ISR context with
* high frequency and must be VERY fast!
*/
void dcdc_low_level_controller();
#endif // CONFIG_CUSTOM_DCDC_CONTROLLER
#ifdef __cplusplus
}
#endif
#endif /* DCDC_H */
+165
View File
@@ -0,0 +1,165 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "device_status.h"
#include <zephyr.h>
#include <math.h> // for fabs function
#include <stdio.h>
#include "setup.h"
#include "helper.h"
//----------------------------------------------------------------------------
// must be called exactly once per second, otherwise energy calculation gets wrong
void DeviceStatus::update_energy()
{
// static variables so that it is not reset for each function call
static int seconds_zero_solar = 0;
// stores the input/output energy status of previous day and to add
// xxx_day_Wh only once per day and increase accuracy
static uint32_t solar_in_total_Wh_prev;
static uint32_t load_out_total_Wh_prev;
static uint32_t bat_chg_total_Wh_prev;
static uint32_t bat_dis_total_Wh_prev;
#if CONFIG_HV_TERMINAL_NANOGRID
static uint32_t grid_import_total_Wh_prev;
static uint32_t grid_export_total_Wh_prev;
#endif
static bool first_call = true;
if (first_call) {
// initialize values with values we got from EEPROM
solar_in_total_Wh_prev = solar_in_total_Wh;
load_out_total_Wh_prev = load_out_total_Wh;
bat_chg_total_Wh_prev = bat_chg_total_Wh;
bat_dis_total_Wh_prev = bat_dis_total_Wh;
#if CONFIG_HV_TERMINAL_NANOGRID
grid_import_total_Wh_prev = grid_import_total_Wh;
grid_export_total_Wh_prev = grid_export_total_Wh;
#endif
first_call = false;
}
#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR
#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR
if (solar_terminal.bus->voltage < bat_terminal.bus->voltage) {
#else
if (pwm_switch.ext_voltage < bat_terminal.bus->voltage) {
#endif
seconds_zero_solar += 1;
}
else {
// solar voltage > battery voltage after 5 hours of night time means sunrise in the morning
// --> reset daily energy counters
if (seconds_zero_solar > 60*60*5) {
day_counter++;
solar_in_total_Wh_prev = solar_in_total_Wh;
load_out_total_Wh_prev = load_out_total_Wh;
bat_chg_total_Wh_prev = bat_chg_total_Wh;
bat_dis_total_Wh_prev = bat_dis_total_Wh;
#if CONFIG_HV_TERMINAL_NANOGRID
grid_import_total_Wh_prev = grid_import_total_Wh;
grid_export_total_Wh_prev = grid_export_total_Wh;
#endif
solar_terminal.neg_energy_Wh = 0.0;
#if BOARD_HAS_LOAD_OUTPUT
load.pos_energy_Wh = 0.0;
#endif
bat_terminal.pos_energy_Wh = 0.0;
bat_terminal.neg_energy_Wh = 0.0;
#if CONFIG_HV_TERMINAL_NANOGRID
grid_terminal.pos_energy_Wh = 0.0;
grid_terminal.neg_energy_Wh = 0.0;
#endif
}
seconds_zero_solar = 0;
}
#endif
bat_chg_total_Wh = bat_chg_total_Wh_prev +
(bat_terminal.pos_energy_Wh > 0 ? bat_terminal.pos_energy_Wh : 0);
bat_dis_total_Wh = bat_dis_total_Wh_prev +
(bat_terminal.neg_energy_Wh > 0 ? bat_terminal.neg_energy_Wh : 0);
#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR
solar_in_total_Wh = solar_in_total_Wh_prev +
(solar_terminal.neg_energy_Wh > 0 ? solar_terminal.neg_energy_Wh : 0);
#endif
#if BOARD_HAS_LOAD_OUTPUT
load_out_total_Wh = load_out_total_Wh_prev +
(load.pos_energy_Wh > 0 ? load.pos_energy_Wh : 0);
#endif
#if CONFIG_HV_TERMINAL_NANOGRID
grid_import_total_Wh = grid_import_total_Wh_prev +
(grid_terminal.neg_energy_Wh > 0 ? grid_terminal.neg_energy_Wh : 0);
grid_export_total_Wh = grid_export_total_Wh_prev +
(grid_terminal.pos_energy_Wh > 0 ? grid_terminal.pos_energy_Wh : 0);
#endif
}
void DeviceStatus::update_min_max_values()
{
if (bat_terminal.bus->voltage > battery_voltage_max) {
battery_voltage_max = bat_terminal.bus->voltage;
}
#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR
if (solar_terminal.bus->voltage > solar_voltage_max) {
solar_voltage_max = solar_terminal.bus->voltage;
}
#elif CONFIG_PWM_TERMINAL_SOLAR
if (pwm_switch.ext_voltage > solar_voltage_max) {
solar_voltage_max = pwm_switch.ext_voltage;
}
#endif
#if BOARD_HAS_DCDC
if (dcdc.inductor_current > dcdc_current_max) {
dcdc_current_max = dcdc.inductor_current;
}
if (dcdc.temp_mosfets > mosfet_temp_max) {
mosfet_temp_max = dcdc.temp_mosfets;
}
#endif
#if BOARD_HAS_LOAD_OUTPUT
if (load.current > load_current_max) {
load_current_max = load.current;
}
#endif
#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR
if (-solar_terminal.power > solar_power_max_day) {
solar_power_max_day = -solar_terminal.power;
if (solar_power_max_day > solar_power_max_total) {
solar_power_max_total = solar_power_max_day;
}
}
#endif
#if BOARD_HAS_LOAD_OUTPUT
if (load.power > load_power_max_day) {
load_power_max_day = load.power;
if (load_power_max_day > load_power_max_total) {
load_power_max_total = load_power_max_day;
}
}
#endif
if (charger.bat_temperature > static_cast<float>(bat_temp_max)) {
bat_temp_max = charger.bat_temperature;
}
if (internal_temp > static_cast<float>(int_temp_max)) {
int_temp_max = internal_temp;
}
}
+174
View File
@@ -0,0 +1,174 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef DEVICE_STATUS_H
#define DEVICE_STATUS_H
/** @file
*
* @brief
* Device-level data storage and functions (like max/min values, error flags, etc.)
*/
#include "bat_charger.h"
#include "power_port.h"
#include "load.h"
#include "dcdc.h"
#include <stdbool.h>
#include <stdint.h>
/** Error Flags
*
* When adding new flags, please make sure to use only up to 32 errors
* Each enum must represent a unique power of 2 number
*/
enum ErrorFlag {
/** Battery voltage too low
*
* Set and cleared in Charger::discharge_control() if the battery voltage dropped to lower than
* absolute minimum. Load outputs should have switched off earlier.
*/
ERR_BAT_UNDERVOLTAGE = 1U << 0,
/** Battery voltage too high
*
* Set directly in ISR after ADC conversion finished, cleared in Charger::charge_control() when
* voltage reached lower level again.
*/
ERR_BAT_OVERVOLTAGE = 1U << 1,
/** Battery discharge overcurrent
*
* Not used yet, reserved for future.
*/
ERR_BAT_DIS_OVERCURRENT = 1U << 2,
/** Battery charge overcurrent
*
* Not used yet, reserved for future.
*/
ERR_BAT_CHG_OVERCURRENT = 1U << 3,
/** Temperature below discharge minimum limit
*
* Set and cleared in Charger::discharge_control (with 2°C hysteresis)
*/
ERR_BAT_DIS_UNDERTEMP = 1U << 4,
/** Temperature above discharge maximum limit
*
* Set and cleared in Charger::discharge_control (with 2°C hysteresis)
*/
ERR_BAT_DIS_OVERTEMP = 1U << 5,
/** Temperature below charge minimum limit
*
* Set and cleared in Charger::charge_control (with 2°C hysteresis)
*/
ERR_BAT_CHG_UNDERTEMP = 1U << 6,
/** Temperature above charge maximum limit
*
* Set and cleared in Charger::charge_control (with 2°C hysteresis)
*/
ERR_BAT_CHG_OVERTEMP = 1U << 7,
/** Charge controller internal temperature too high
*
* Set and cleared by daq_update()
*/
ERR_INT_OVERTEMP = 1U << 13,
/** Short-circuit in HS MOSFET
*
* Set in Dcdc::control() and never cleared
*/
ERR_DCDC_HS_MOSFET_SHORT = 1U << 14,
/** Overvoltage in HS MOSFET
*
* Set in DAQ alert and never cleared
*/
ERR_DCDC_HS_OVERVOLTAGE = 1U << 15,
/** Overvoltage caused by PWM switch
*
* Set and cleared in PwmSwitch::control()
*/
ERR_PWM_SWITCH_OVERVOLTAGE = 1U << 16,
/** Mask to catch all error flags (up to 32 errors)
*/
ERR_ANY_ERROR = UINT32_MAX,
};
/** Device Status data
*
* Stores error counters and some maximum ever measured values to EEPROM
*/
class DeviceStatus
{
public:
/** Updates the total energy counters for solar, battery and load bus
*/
void update_energy();
/** Updates the logged min/max values for voltages, power, temperatures etc.
*/
void update_min_max_values();
// total energy
uint32_t bat_chg_total_Wh;
uint32_t bat_dis_total_Wh;
uint32_t solar_in_total_Wh;
uint32_t load_out_total_Wh;
#if CONFIG_HV_TERMINAL_NANOGRID
uint32_t grid_import_total_Wh;
uint32_t grid_export_total_Wh;
#endif
// maximum/minimum values
uint16_t solar_power_max_day;
uint16_t load_power_max_day;
uint16_t solar_power_max_total;
uint16_t load_power_max_total;
float battery_voltage_max;
float solar_voltage_max;
float dcdc_current_max;
float load_current_max;
int16_t bat_temp_max; // °C
int16_t int_temp_max; // °C
int16_t mosfet_temp_max;
uint32_t day_counter;
// instantaneous device-level data
uint32_t error_flags; ///< Currently detected errors
float internal_temp; ///< Internal temperature (measured in MCU)
/**
* @brief sets one or more error flags in device state
* @param e a single ErrorFlag or "bitwise ORed" ERR_XXX | ERR_YYY
*/
void set_error(uint32_t e) { error_flags |= e; }
/**
* @brief clears one or more error flags in device state
* @param e a single ErrorFlag or "bitwise ORed" ERR_XXX | ERR_YYY
*/
void clear_error(uint32_t e) { error_flags &= ~e; }
/**
* @brief queries one or more error flags in device state
* @param e a single ErrorFlag or "bitwise ORed" ERR_XXX | ERR_YYY
* @return true if any of the error flags given in e are set in device state
*/
bool has_error(uint32_t e) { return (error_flags & e) != 0; }
};
#endif /* DEVICE_STATUS_H */
+7
View File
@@ -0,0 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
target_sources(app PRIVATE
oled.cpp
serial.cpp
can.cpp
)
+3
View File
@@ -0,0 +1,3 @@
# Folder src/ext
This folder contains code for all **ext**ensions (displays etc. connected to UEXT port) and **ext**ernal communication interfaces (UART or CAN).
+264
View File
@@ -0,0 +1,264 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#if CONFIG_THINGSET_CAN
#include <zephyr.h>
#include <device.h>
#include <drivers/gpio.h>
#include <drivers/can.h>
#include <task_wdt/task_wdt.h>
#ifdef CONFIG_ISOTP
#include <canbus/isotp.h>
#endif
#include <logging/log.h>
LOG_MODULE_REGISTER(ext_can, CONFIG_CAN_LOG_LEVEL);
#include "data_objects.h"
#include "hardware.h"
#include "thingset.h"
#include "bat_charger.h"
#include "helper.h"
#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), can_en))
#define CAN_EN_GPIO DT_CHILD(DT_PATH(outputs), can_en)
#endif
extern ThingSet ts;
extern uint16_t can_node_addr;
extern Charger charger;
static const struct device *can_dev = DEVICE_DT_GET(DT_NODELABEL(can1));
#ifdef CONFIG_ISOTP
#define RX_THREAD_STACK_SIZE 1024
#define RX_THREAD_PRIORITY 2
const struct isotp_fc_opts fc_opts = {
.bs = 8, // block size
.stmin = 1 // minimum separation time = 100 ms
};
struct isotp_msg_id rx_addr = {
.id_type = CAN_EXTENDED_IDENTIFIER,
.use_ext_addr = 0, // Normal ISO-TP addressing (using only CAN ID)
.use_fixed_addr = 1, // enable SAE J1939 compatible addressing
};
struct isotp_msg_id tx_addr = {
.id_type = CAN_EXTENDED_IDENTIFIER,
.use_ext_addr = 0, // Normal ISO-TP addressing (using only CAN ID)
.use_fixed_addr = 1, // enable SAE J1939 compatible addressing
};
static struct isotp_recv_ctx recv_ctx;
static struct isotp_send_ctx send_ctx;
void send_complete_cb(int error_nr, void *arg)
{
ARG_UNUSED(arg);
LOG_DBG("TX complete callback, err: %d", error_nr);
}
void can_isotp_thread()
{
int ret, rem_len, resp_len;
unsigned int req_len;
struct net_buf *buf;
static uint8_t rx_buffer[600]; // large enough to receive a 512k flash page for DFU
static uint8_t tx_buffer[1000];
if (!device_is_ready(can_dev)) {
return;
}
while (1) {
/* re-assign address in every loop as it may have been changed via ThingSet */
rx_addr.ext_id = TS_CAN_BASE_REQRESP | TS_CAN_PRIO_REQRESP |
TS_CAN_TARGET_SET(can_node_addr);
tx_addr.ext_id = TS_CAN_BASE_REQRESP | TS_CAN_PRIO_REQRESP |
TS_CAN_SOURCE_SET(can_node_addr);
ret = isotp_bind(&recv_ctx, can_dev, &rx_addr, &tx_addr, &fc_opts, K_FOREVER);
if (ret != ISOTP_N_OK) {
LOG_DBG("Failed to bind to rx ID %d [%d]", rx_addr.ext_id, ret);
return;
}
req_len = 0;
do {
rem_len = isotp_recv_net(&recv_ctx, &buf, K_FOREVER);
if (rem_len < 0) {
LOG_DBG("Receiving error [%d]", rem_len);
break;
}
if (req_len + buf->len <= sizeof(rx_buffer)) {
memcpy(&rx_buffer[req_len], buf->data, buf->len);
}
req_len += buf->len;
net_buf_unref(buf);
} while (rem_len);
// we need to unbind the receive ctx so that control frames are received in the send ctx
isotp_unbind(&recv_ctx);
if (req_len > sizeof(rx_buffer)) {
LOG_DBG("RX buffer too small");
tx_buffer[0] = TS_STATUS_REQUEST_TOO_LARGE;
resp_len = 1;
}
else if (req_len > 0 && rem_len == 0) {
LOG_INF("Got %d bytes via ISO-TP. Processing ThingSet message.", req_len);
resp_len = ts.process(rx_buffer, req_len, tx_buffer, sizeof(tx_buffer));
LOG_DBG("TX buf: %x %x %x %x", tx_buffer[0], tx_buffer[1], tx_buffer[2], tx_buffer[3]);
}
else {
tx_buffer[0] = TS_STATUS_INTERNAL_SERVER_ERR;
resp_len = 1;
}
if (resp_len > 0) {
ret = isotp_send(&send_ctx, can_dev, tx_buffer, resp_len,
&recv_ctx.tx_addr, &recv_ctx.rx_addr, send_complete_cb, NULL);
if (ret != ISOTP_N_OK) {
LOG_DBG("Error while sending data to ID %d [%d]", tx_addr.ext_id, ret);
}
}
}
}
K_THREAD_DEFINE(can_isotp, RX_THREAD_STACK_SIZE, can_isotp_thread, NULL, NULL, NULL,
RX_THREAD_PRIORITY, 0, 1500);
#endif /* CONFIG_ISOTP */
// below defines should go into the ThingSet library
#define TS_CAN_SOURCE_GET(id) (((uint32_t)id & TS_CAN_SOURCE_MASK) >> TS_CAN_SOURCE_POS)
#define TS_CAN_DATA_ID_GET(id) (((uint32_t)id & TS_CAN_DATA_ID_MASK) >> TS_CAN_DATA_ID_POS)
CAN_DEFINE_MSGQ(sub_msgq, 10);
const struct zcan_filter ctrl_filter = {
.id = TS_CAN_BASE_CONTROL,
.rtr = CAN_DATAFRAME,
.id_type = CAN_EXTENDED_IDENTIFIER,
.id_mask = TS_CAN_TYPE_MASK,
.rtr_mask = 1
};
void can_pub_isr(uint32_t err_flags, void *arg)
{
// Do nothing. Publication messages are fire and forget.
}
void can_pub_send(uint32_t can_id, uint8_t can_data[8], uint8_t data_len)
{
struct zcan_frame frame = {0};
frame.id_type = CAN_EXTENDED_IDENTIFIER;
frame.rtr = CAN_DATAFRAME;
frame.id = can_id;
memcpy(frame.data, can_data, 8);
if (data_len >= 0) {
frame.dlc = data_len;
if (can_send(can_dev, &frame, K_MSEC(10), can_pub_isr, NULL) != CAN_TX_OK) {
LOG_DBG("Error sending CAN frame");
}
}
}
void can_pubsub_thread()
{
int wdt_channel = task_wdt_add(2000, task_wdt_callback, (void *)k_current_get());
unsigned int can_id;
uint8_t can_data[8];
struct zcan_frame rx_frame;
const struct device *can_en_dev = device_get_binding(DT_GPIO_LABEL(CAN_EN_GPIO, gpios));
gpio_pin_configure(can_en_dev, DT_GPIO_PIN(CAN_EN_GPIO, gpios),
DT_GPIO_FLAGS(CAN_EN_GPIO, gpios) | GPIO_OUTPUT_ACTIVE);
if (!device_is_ready(can_dev)) {
return;
}
int filter_id = can_attach_msgq(can_dev, &sub_msgq, &ctrl_filter);
if (filter_id < 0) {
LOG_ERR("Unable to attach ISR [%d]", filter_id);
return;
}
int64_t next_pub = k_uptime_get();
uint32_t count = 0;
while (1) {
task_wdt_feed(wdt_channel);
if (pub_can_enable) {
int data_len = 0;
int start_pos = 0;
while (count % 10 == 0) {
// normal objects: only every second
data_len = ts.bin_pub_can(start_pos, SUBSET_CAN, can_node_addr, can_id, can_data);
if (data_len < 0) {
// finished with all IDs
break;
}
else {
can_pub_send(can_id, can_data, data_len);
}
}
data_len = 0;
start_pos = 0;
while (true) {
// control objects: every 100 ms
data_len = ts.bin_pub_can(start_pos, SUBSET_CTRL, can_node_addr, can_id, can_data);
if (data_len < 0) {
break;
}
else {
can_pub_send(can_id, can_data, data_len);
}
}
}
// wait for incoming messages until the next pub message has to be sent out
while (k_msgq_get(&sub_msgq, &rx_frame, K_TIMEOUT_ABS_MS(next_pub)) != -EAGAIN) {
// process message
uint16_t data_id = TS_CAN_DATA_ID_GET(rx_frame.id);
uint8_t sender_addr = TS_CAN_SOURCE_GET(rx_frame.id);
// control message received?
if (data_id > 0x8000 && sender_addr < can_node_addr) {
uint8_t buf[4 + 8]; // ThingSet bin headers + CAN frame payload
buf[0] = 0xA1; // CBOR: map with 1 element
buf[1] = 0x19; // CBOR: uint16 follows
buf[2] = data_id >> 8;
buf[3] = data_id;
memcpy(&buf[4], rx_frame.data, 8);
int status = ts.bin_import(buf, 4 + rx_frame.dlc, TS_WRITE_MASK, SUBSET_CTRL);
if (status == TS_STATUS_CHANGED) {
charger.time_last_ctrl_msg = uptime();
}
}
}
next_pub += 100; // 100 ms period (currently fixed)
count++;
}
}
K_THREAD_DEFINE(can_pubsub, 1024, can_pubsub_thread, NULL, NULL, NULL, 6, 0, 1000);
#endif /* CONFIG_THINGSET_CAN */
+191
View File
@@ -0,0 +1,191 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#if CONFIG_UEXT_OLED_DISPLAY
#include <math.h>
#include <stdio.h>
#include <zephyr.h>
#include <device.h>
#include <drivers/gpio.h>
#include "oled_ssd1306.h"
#include "setup.h"
#include "half_bridge.h"
#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), uext_en))
#define UEXT_EN_GPIO DT_CHILD(DT_PATH(outputs), uext_en)
#endif
const unsigned char bmp_load [] = {
0x20, 0x22, 0x04, 0x70, 0x88, 0x8B, 0x88, 0x70, 0x04, 0x22, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
const unsigned char bmp_arrow_right [] = {
0x41, 0x63, 0x36, 0x1C
};
const unsigned char bmp_pv_panel [] = {
0x60, 0x98, 0x86, 0xC9, 0x31, 0x19, 0x96, 0x62, 0x32, 0x2C, 0xC4, 0x64, 0x98, 0x08, 0xC8, 0x30,
0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x02, 0x02, 0x03, 0x04, 0x04, 0x04, 0x03, 0x00, 0x00
};
const unsigned char bmp_disconnected [] = {
0x08, 0x08, 0x08, 0x08, 0x00, 0x41, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x41, 0x00, 0x08, 0x08,
0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
OledSSD1306 oled(DT_LABEL(DT_ALIAS(i2c_uext)));
void oled_update()
{
char buf[30];
unsigned int len;
#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR
PowerPort &in_terminal = solar_terminal;
#elif CONFIG_HV_TERMINAL_NANOGRID
PowerPort &in_terminal = grid_terminal;
#endif
oled.clear();
oled.drawBitmap(6, 0, bmp_pv_panel, 16, 16, 1);
oled.drawBitmap(104, 0, bmp_load, 16, 16, 1);
if (half_bridge_enabled() == false) {
oled.drawBitmap(27, 3, bmp_disconnected, 32, 8, 1);
}
else {
oled.drawBitmap(34, 3, bmp_arrow_right, 5, 7, 1);
}
if (load.state == LOAD_STATE_ON) {
oled.drawBitmap(84, 3, bmp_arrow_right, 5, 7, 1);
}
else {
oled.drawBitmap(81, 3, bmp_disconnected, 17, 7, 1);
}
oled.drawRect(52, 2, 18, 9, 1); // battery shape
oled.drawRect(69, 3, 3, 7, 1); // battery terminal
if (charger.soc >= 20) {
oled.drawRect(54, 4, 2, 5, 1); // bar 1
}
if (charger.soc >= 40) {
oled.drawRect(57, 4, 2, 5, 1); // bar 2
}
if (charger.soc >= 60) {
oled.drawRect(60, 4, 2, 5, 1); // bar 3
}
if (charger.soc >= 80) {
oled.drawRect(63, 4, 2, 5, 1); // bar 4
}
if (charger.soc >= 95) {
oled.drawRect(66, 4, 2, 5, 1); // bar 5
}
// solar panel data
#if BOARD_HAS_PWM_PORT
if (pwm_switch.active()) {
#else
if (half_bridge_enabled()) {
#endif
oled.setTextCursor(0, 18);
len = snprintf(buf, sizeof(buf), "%4.0fW",
(abs(in_terminal.power) < 1) ? 0 : -in_terminal.power); // remove negative zeros
oled.writeString(buf, len);
}
else {
oled.setTextCursor(8, 18);
len = snprintf(buf, sizeof(buf), "n/a");
oled.writeString(buf, len);
}
#if BOARD_HAS_PWM_PORT
if (in_terminal.bus->voltage > bat_terminal.bus->voltage)
#endif
{
oled.setTextCursor(0, 26);
len = snprintf(buf, sizeof(buf), "%4.1fV", in_terminal.bus->voltage);
oled.writeString(buf, len);
}
// battery data
oled.setTextCursor(42, 18);
len = snprintf(buf, sizeof(buf), "%5.1fW",
(abs(bat_terminal.power) < 0.1) ? 0 : bat_terminal.power); // remove negative zeros
oled.writeString(buf, len);
oled.setTextCursor(42, 26);
len = snprintf(buf, sizeof(buf), "%5.1fV", bat_terminal.bus->voltage);
oled.writeString(buf, len);
// load data
oled.setTextCursor(90, 18);
len = snprintf(buf, sizeof(buf), "%5.1fW",
(abs(load.power) < 0.1) ? 0 : load.power); // remove negative zeros
oled.writeString(buf, len);
oled.setTextCursor(90, 26);
len = snprintf(buf, sizeof(buf), "%5.1fA\n",
(abs(load.current) < 0.1) ? 0 : load.current);
oled.writeString(buf, len);
oled.setTextCursor(0, 36);
len = snprintf(buf, sizeof(buf), "Day +%5.0fWh -%5.0fWh",
in_terminal.neg_energy_Wh, fabs(load.pos_energy_Wh));
oled.writeString(buf, len);
len = snprintf(buf, sizeof(buf), "Tot +%4.1fkWh -%4.1fkWh",
dev_stat.solar_in_total_Wh / 1000.0, fabs(dev_stat.load_out_total_Wh) / 1000.0);
oled.writeString(buf, len);
oled.setTextCursor(0, 56);
#if BOARD_HAS_PWM_PORT
bool pwm_enabled = pwm_switch.active();
float duty_cycle = pwm_switch.get_duty_cycle();
#else
bool pwm_enabled = half_bridge_enabled();
float duty_cycle = half_bridge_get_duty_cycle();
#endif
float temp = charger.ext_temp_sensor ? charger.bat_temperature:dev_stat.internal_temp;
char tC = charger.ext_temp_sensor ? 'T' : 't';
if (pwm_enabled == true) {
len = snprintf(buf, sizeof(buf), "%c %.0fC PWM %.0f%% SOC %d%%",
tC, temp, duty_cycle * 100.0, charger.soc);
oled.writeString(buf, len);
}
else {
len = snprintf(buf, sizeof(buf), "%c %.0fC PWM OFF SOC %d%%", tC, temp, charger.soc);
oled.writeString(buf, len);
}
oled.display();
}
void oled_thread()
{
#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), uext_en))
const struct device *dev_uext_en = device_get_binding(DT_GPIO_LABEL(UEXT_EN_GPIO, gpios));
gpio_pin_configure(dev_uext_en, DT_GPIO_PIN(UEXT_EN_GPIO, gpios),
DT_GPIO_FLAGS(UEXT_EN_GPIO, gpios) | GPIO_OUTPUT_ACTIVE);
#endif
oled.init(CONFIG_UEXT_OLED_BRIGHTNESS);
while (true) {
oled_update();
k_sleep(K_MSEC(1000));
}
}
K_THREAD_DEFINE(oled_thread_id, 1024, oled_thread, NULL, NULL, NULL, 6, 0, 1000);
#endif /* CONFIG_UEXT_OLED_DISPLAY */
+151
View File
@@ -0,0 +1,151 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#if CONFIG_THINGSET_SERIAL
#include <string.h>
#include <stdio.h>
#include <zephyr.h>
#include <sys/printk.h>
#include <drivers/uart.h>
#include <task_wdt/task_wdt.h>
#include "thingset.h"
#include "hardware.h"
#include "data_objects.h"
#if CONFIG_UEXT_SERIAL_THINGSET
#define UART_DEVICE_NODE DT_ALIAS(uart_uext)
#elif DT_NODE_EXISTS(DT_ALIAS(uart_dbg))
#define UART_DEVICE_NODE DT_ALIAS(uart_dbg)
#else
// cppcheck-suppress preprocessorErrorDirective
#error "No UART for ThingSet serial defined."
#endif
static const struct device *uart_dev = DEVICE_DT_GET(UART_DEVICE_NODE);
static char tx_buf[CONFIG_THINGSET_SERIAL_TX_BUF_SIZE];
static char rx_buf[CONFIG_THINGSET_SERIAL_RX_BUF_SIZE];
static volatile size_t rx_buf_pos = 0;
static struct k_sem command_flag; // used as an event to signal a received command
static struct k_sem rx_buf_mutex; // binary semaphore used as mutex in ISR context
extern ThingSet ts;
const char serial_subset_path[] = "serial";
static ThingSetDataObject *serial_subset;
void serial_pub_msg()
{
if (pub_serial_enable) {
int len = ts.txt_statement(tx_buf, sizeof(tx_buf), serial_subset);
for (int i = 0; i < len; i++) {
uart_poll_out(uart_dev, tx_buf[i]);
}
uart_poll_out(uart_dev, '\n');
}
}
void serial_process_command()
{
// commands must have 2 or more characters
if (rx_buf_pos > 1) {
printf("Received Request (%d bytes): %s\n", strlen(rx_buf), rx_buf);
int len = ts.process((uint8_t *)rx_buf, strlen(rx_buf),
(uint8_t *)tx_buf, sizeof(tx_buf));
for (int i = 0; i < len; i++) {
uart_poll_out(uart_dev, tx_buf[i]);
}
uart_poll_out(uart_dev, '\n');
}
// release buffer and start waiting for new commands
rx_buf_pos = 0;
k_sem_give(&rx_buf_mutex);
}
/*
* Read characters from stream until line end \n is detected, afterwards signal available command.
*/
void serial_cb(const struct device *dev, void* user_data)
{
uint8_t c;
if (!uart_irq_update(uart_dev)) {
return;
}
while (uart_irq_rx_ready(uart_dev) && k_sem_take(&rx_buf_mutex, K_NO_WAIT) == 0) {
uart_fifo_read(uart_dev, &c, 1);
// \r\n and \n are markers for line end, i.e. command end
// we accept this at any time, even if the buffer is 'full', since
// there is always one last character left for the \0
if (c == '\n') {
if (rx_buf_pos > 0 && rx_buf[rx_buf_pos-1] == '\r') {
rx_buf[rx_buf_pos-1] = '\0';
}
else {
rx_buf[rx_buf_pos] = '\0';
}
// start processing command and keep the rx_buf_mutex locked
k_sem_give(&command_flag);
return;
}
// backspace allowed if there is something in the buffer already
else if (rx_buf_pos > 0 && c == '\b') {
rx_buf_pos--;
}
// Fill the buffer up to all but 1 character (the last character is reserved for '\0')
// Characters beyond the size of the buffer are dropped.
else if (rx_buf_pos < (sizeof(rx_buf) - 1)) {
rx_buf[rx_buf_pos++] = c;
}
k_sem_give(&rx_buf_mutex);
}
}
void serial_thread()
{
k_sem_init(&command_flag, 0, 1);
k_sem_init(&rx_buf_mutex, 1, 1);
__ASSERT_NO_MSG(device_is_ready(uart_dev));
uart_irq_callback_user_data_set(uart_dev, serial_cb, NULL);
uart_irq_rx_enable(uart_dev);
serial_subset = ts.get_endpoint(serial_subset_path, strlen(serial_subset_path));
// below process loop should be run at least once per sec, setting watchdog timeout to 1.5s
int wdt_channel = task_wdt_add(1500, task_wdt_callback, (void *)k_current_get());
int64_t t_start = k_uptime_get();
while (true) {
if (k_sem_take(&command_flag, K_TIMEOUT_ABS_MS(t_start)) == 0) {
serial_process_command();
}
else {
// semaphore timed out (should happen exactly every 1 second)
t_start += 1000;
serial_pub_msg();
}
task_wdt_feed(wdt_channel);
}
}
K_THREAD_DEFINE(serial_thread_id, 1280, serial_thread, NULL, NULL, NULL, 6, 0, 1000);
#endif /* CONFIG_THINGSET_SERIAL */
+399
View File
@@ -0,0 +1,399 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "half_bridge.h"
#include <zephyr.h>
#include <stdio.h>
#include "mcu.h"
#include "setup.h"
#ifdef CONFIG_SOC_FAMILY_STM32
#include <soc.h>
#include <pinmux/pinmux_stm32.h>
#include <stm32_ll_bus.h>
#endif
#if BOARD_HAS_DCDC
#define DT_DRV_COMPAT half_bridge
// Get address of used timer from board dts
#define TIMER_ADDR DT_REG_ADDR(DT_PARENT(DT_DRV_INST(0)))
static uint16_t tim_ccr_min; // capture/compare register min/max
static uint16_t tim_ccr_max;
static uint16_t tim_dt_clocks = 0;
static uint16_t clamp_ccr(uint16_t ccr_target)
{
// protection against wrong settings which could destroy the hardware
if (ccr_target <= tim_ccr_min) {
return tim_ccr_min;
}
else if (ccr_target >= tim_ccr_max) {
return tim_ccr_max;
}
else {
return ccr_target;
}
}
#ifdef CONFIG_SOC_FAMILY_STM32
static const struct soc_gpio_pinctrl tim_pinctrl[] = ST_STM32_DT_INST_PINCTRL(0, 0);
#if TIMER_ADDR == TIM3_BASE
static void tim_init_registers(int freq_kHz)
{
stm32_dt_pinctrl_configure(tim_pinctrl, ARRAY_SIZE(tim_pinctrl), TIMER_ADDR);
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM3);
// No prescaler --> timer frequency == SystemClock
TIM3->PSC = 0;
// Capture/Compare Mode Register 1
// OCxM = 110: Select PWM mode 1 on OCx
// OCxPE = 1: Enable preload register on OCx (reset value)
TIM3->CCMR2 |= TIM_CCMR2_OC3M_2 | TIM_CCMR2_OC3M_1 | TIM_CCMR2_OC3PE;
TIM3->CCMR2 |= TIM_CCMR2_OC4M_2 | TIM_CCMR2_OC4M_1 | TIM_CCMR2_OC4PE;
// Capture/Compare Enable Register
// CCxP: Active high polarity on OCx (default = 0)
TIM3->CCER &= ~(TIM_CCER_CC3P); // PB0 / TIM3_CH3: high-side
TIM3->CCER |= TIM_CCER_CC4P; // PB1 / TIM3_CH4: low-side
// Control Register 1
// TIM_CR1_CMS = 01: Select center-aligned mode 1
// TIM_CR1_CEN = 1: Counter enable
TIM3->CR1 |= TIM_CR1_CMS_0 | TIM_CR1_CEN;
// Force update generation (UG = 1)
TIM3->EGR |= TIM_EGR_UG;
// Auto Reload Register
// center-aligned mode counts up and down in each period, so we need half the clocks as
// resolution for the given frequency.
TIM3->ARR = SystemCoreClock / (freq_kHz * 1000) / 2;;
}
void half_bridge_start()
{
if (TIM3->CCR3 != 0U) {
// Capture/Compare Enable Register
// CCxE = 1: Enable the output on OCx
// CCxP = 0: Active high polarity on OCx (default)
TIM3->CCER |= TIM_CCER_CC3E;
TIM3->CCER |= TIM_CCER_CC4E;
}
}
void half_bridge_stop()
{
TIM3->CCER &= ~(TIM_CCER_CC3E);
TIM3->CCER &= ~(TIM_CCER_CC4E);
}
uint16_t half_bridge_get_arr()
{
return TIM3->ARR;
}
uint16_t half_bridge_get_ccr()
{
return TIM3->CCR3;
}
void half_bridge_set_ccr(uint16_t ccr)
{
uint16_t ccr_clamped = clamp_ccr(ccr);
TIM3->CCR3 = ccr_clamped; // high-side
TIM3->CCR4 = ccr_clamped + tim_dt_clocks; // low-side
}
bool half_bridge_enabled()
{
return TIM3->CCER & TIM_CCER_CC3E;
}
#elif TIMER_ADDR == TIM1_BASE
static void tim_init_registers(int freq_kHz)
{
stm32_dt_pinctrl_configure(tim_pinctrl, ARRAY_SIZE(tim_pinctrl), TIMER_ADDR);
#ifdef LL_APB2_GRP1_PERIPH_TIM1
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_TIM1);
#else
LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_TIM1);
#endif
// No prescaler --> timer frequency == SystemClock
TIM1->PSC = 0;
// Capture/Compare Mode Register 1
// OC1M = 110: Select PWM mode 1 on OC1
// OC1PE = 1: Enable preload register on OC1 (reset value)
TIM1->CCMR1 |= TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1PE;
// Capture/Compare Enable Register
// CC1E = 1: Enable the output on OC1
// CC1P = 0: Active high polarity on OC1 (default)
// CC1NE = 1: Enable the output on OC1N
// CC1NP = 0: Active high polarity on OC1N (default)
TIM1->CCER |= TIM_CCER_CC1E | TIM_CCER_CC1NE;
// Control Register 1
// TIM_CR1_CMS = 00: Select edge-aligned mode
// TIM_CR1_CEN = 1: Counter enable
TIM1->CR1 |= TIM_CR1_CEN;
#ifdef CONFIG_SOC_SERIES_STM32G4X
// Boards with STM32G4 MCU use ADC2 for synchronized ADC sampling. We use OC6
// for triggering, but but don't configure any pin for PWM mode
TIM1->CCMR3 |= TIM_CCMR3_OC6M_2 | TIM_CCMR3_OC6M_1 | TIM_CCMR3_OC6PE;
TIM1->CCER |= TIM_CCER_CC6E;
// Trigger ADC via TIM1_TRGO2 on OC6ref falling edge signal event
TIM1->CR2 |= TIM_CR2_MMS2_3 | TIM_CR2_MMS2_2 | TIM_CR2_MMS2_0;
#endif
// Force update generation (UG = 1)
TIM1->EGR |= TIM_EGR_UG;
// Auto Reload Register
// edge-aligned mode possible with TIM1 to increase resolution (no division by 2 necessary)
TIM1->ARR = SystemCoreClock / (freq_kHz * 1000);
// Break and Dead-Time Register
// DTG[7:0]: Dead-time generator setup
TIM1->BDTR |= (tim_dt_clocks & (uint32_t)0x7F); // ensure that only the last 7 bits are changed
// Lock Break and Dead-Time Register
// TODO: does not work properly... maybe HW bug?
TIM1->BDTR |= TIM_BDTR_LOCK_1 | TIM_BDTR_LOCK_0;
}
void half_bridge_start()
{
if (TIM1->CCR1 != 0U) {
// Break and Dead-Time Register
// MOE = 1: Main output enable
TIM1->BDTR |= TIM_BDTR_MOE;
}
}
void half_bridge_stop()
{
// Break and Dead-Time Register
// MOE = 1: Main output enable
TIM1->BDTR &= ~(TIM_BDTR_MOE);
}
uint16_t half_bridge_get_arr()
{
return TIM1->ARR;
}
uint16_t half_bridge_get_ccr()
{
return TIM1->CCR1;
}
void half_bridge_set_ccr(uint16_t ccr)
{
TIM1->CCR1 = clamp_ccr(ccr);
#ifdef CONFIG_SOC_SERIES_STM32G4X
// Trigger ADC for current measurement in the middle of the cycle.
TIM1->CCR6 = TIM1->CCR1 / 2;
#endif
}
bool half_bridge_enabled()
{
return TIM1->BDTR & TIM_BDTR_MOE;
}
#elif TIMER_ADDR == HRTIM1_BASE
/*
* Below initial HRTIM implementation only works for channel A and it does not make use of the
* possible higher resolution yet.
*/
#include <stm32_ll_system.h>
#include <stm32_ll_bus.h>
static void tim_init_registers(int freq_kHz)
{
stm32_dt_pinctrl_configure(tim_pinctrl, ARRAY_SIZE(tim_pinctrl), TIMER_ADDR);
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_HRTIM1);
// Enable periodic calibration of delay-locked loop (DLL) with lowest calibration period
HRTIM1->sCommonRegs.DLLCR |= HRTIM_DLLCR_CALEN | HRTIM_DLLCR_CALRTE_0 | HRTIM_DLLCR_CALRTE_1;
// Wait for calibration to finish
while ((HRTIM1_COMMON->ISR & HRTIM_ISR_DLLRDY) == 0) {;}
// Prescaler 32 --> SystemClock (same as normal timers like TIM1)
HRTIM1_TIMA->TIMxCR |= (5U << HRTIM_TIMCR_CK_PSC_Pos);
// Prescaler 8 / 2^3 --> same frequency as HRTIM
HRTIM1_TIMA->DTxR |= (3U << HRTIM_DTR_DTPRSC_Pos);
// Continuous mode operation
HRTIM1_TIMA->TIMxCR |= HRTIM_TIMCR_CONT;
// Enable preloading with timer reset update trigger
//HRTIM1_TIMA->TIMxCR |= HRTIM_TIMCR_PREEN | HRTIM_TIMCR_TRSTU;
// Enable preloading with timer E update trigger
//HRTIM1_TIMA->TIMxCR |= HRTIM_TIMCR_PREEN | HRTIM_TIMCR_TEU;
// Timer period register
HRTIM1_TIMA->PERxR = SystemCoreClock / (freq_kHz * 1000) + 1;
HRTIM1_TIMA->SETx1R = HRTIM_SET1R_PER;
HRTIM1_TIMA->RSTx1R = HRTIM_SET1R_CMP1;
HRTIM1_TIMA->OUTxR = HRTIM_OUTR_DTEN;
// Set deadtime values and lock deadtime signs
HRTIM1_TIMA->DTxR |=
HRTIM_DTR_DTFSLK | (tim_dt_clocks << 16U) |
HRTIM_DTR_DTRSLK | tim_dt_clocks;
// activate trigger for ADC
HRTIM1_COMMON->CR1 = HRTIM_CR1_ADC1USRC_0; // ADC trigger update: Timer A
HRTIM1_COMMON->ADC1R = HRTIM_ADC1R_AD1TAC3; // ADC trigger event: Timer A compare 3
// Start timer A
HRTIM1->sMasterRegs.MCR = HRTIM_MCR_TACEN;
}
void half_bridge_start()
{
HRTIM1->sCommonRegs.OENR = HRTIM_OENR_TA1OEN | HRTIM_OENR_TA2OEN;
}
void half_bridge_stop()
{
HRTIM1->sCommonRegs.ODISR = HRTIM_ODISR_TA1ODIS | HRTIM_ODISR_TA2ODIS;
}
uint16_t half_bridge_get_arr()
{
return HRTIM1_TIMA->PERxR;
}
uint16_t half_bridge_get_ccr()
{
return HRTIM1_TIMA->CMP1xR;
}
void half_bridge_set_ccr(uint16_t ccr)
{
HRTIM1_TIMA->CMP1xR = clamp_ccr(ccr);
// Trigger ADC for current measurement in the middle of the cycle.
// A negative offset of 80 clocks was found to improve current measurement accuracy and
// compensate the ADC delay (no risk of underflow as CCR is around 214 even at 0.1% duty).
HRTIM1_TIMA->CMP3xR = HRTIM1_TIMA->CMP1xR / 2 - 80;
}
bool half_bridge_enabled()
{
return (HRTIM1->sCommonRegs.OENR & (HRTIM_OENR_TA1OEN | HRTIM_OENR_TA2OEN)) > 0;
}
#endif // HRTIM1
#else // UNIT_TEST
const uint32_t SystemCoreClock = 24000000;
// dummy registers
uint32_t tim_ccr = 0;
uint32_t tim_arr = 0;
bool pwm_enabled = false;
static void tim_init_registers(int freq_kHz)
{
// assuming edge-aligned PWM like with TIM1
tim_arr = SystemCoreClock / (freq_kHz * 1000);
}
void half_bridge_start()
{
pwm_enabled = true;
}
void half_bridge_stop()
{
pwm_enabled = false;
}
uint16_t half_bridge_get_arr()
{
return tim_arr;
}
uint16_t half_bridge_get_ccr()
{
return tim_ccr;
}
void half_bridge_set_ccr(uint16_t ccr)
{
tim_ccr = clamp_ccr(ccr); // high-side
}
bool half_bridge_enabled()
{
return pwm_enabled;
}
#endif /* UNIT_TEST */
static void tim_calculate_dt_clocks(int deadtime_ns)
{
// (clocks per ms * deadtime in ns) / 1000 == (clocks per ms * deadtime in ms)
// although the C operator precedence does the "right thing" to allow deadtime_ns < 1000 to
// be handled nicely, parentheses make this more explicit
tim_dt_clocks = ((SystemCoreClock / (1000000)) * deadtime_ns) / 1000;
}
void half_bridge_init(int freq_kHz, int deadtime_ns, float min_duty, float max_duty)
{
tim_calculate_dt_clocks(deadtime_ns);
tim_init_registers(freq_kHz);
tim_ccr_min = min_duty * half_bridge_get_arr();
tim_ccr_max = max_duty * half_bridge_get_arr();
half_bridge_set_duty_cycle(max_duty); // init with allowed value
}
void half_bridge_set_duty_cycle(float duty)
{
if (duty >= 0.0 && duty <= 1.0) {
half_bridge_set_ccr(half_bridge_get_arr() * duty);
}
}
float half_bridge_get_duty_cycle()
{
return (float)(half_bridge_get_ccr()) / half_bridge_get_arr();
}
#endif // BOARD_HAS_DCDC
+85
View File
@@ -0,0 +1,85 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef HALF_BRIDGE_H_
#define HALF_BRIDGE_H_
#include <stdint.h>
/**
* @file
*
* @brief PWM timer functions for half bridge of DC/DC converter
*/
/**
* Initiatializes the registers to generate the PWM signal and sets duty
* cycle limits
*
* @param freq_kHz Switching frequency in kHz
* @param deadtime_ns Deadtime in ns between switching the two FETs on/off
* @param min_duty Minimum duty cycle (e.g. 0.5 for limiting input voltage)
* @param max_duty Maximum duty cycle (e.g. 0.97 for charge pump)
*/
void half_bridge_init(int freq_kHz, int deadtime_ns, float min_duty, float max_duty);
/**
* Set raw timer capture/compare register
*
* This function allows to change the PWM with minimum step size.
*
* @param ccr Timer CCR value (between 0 and ARR)
*/
void half_bridge_set_ccr(uint16_t ccr);
/**
* Get raw timer capture/compare register
*
* @returns Timer CCR value (between 0 and ARR)
*/
uint16_t half_bridge_get_ccr();
/**
* Get raw timer auto-reload register
*
* @returns Timer ARR value
*/
uint16_t half_bridge_get_arr();
/**
* Set the duty cycle of the PWM signal
*
* @param duty Duty cycle between 0.0 and 1.0
*/
void half_bridge_set_duty_cycle(float duty);
/**
* Read the currently set duty cycle
*
* @returns Duty cycle between 0.0 and 1.0
*/
float half_bridge_get_duty_cycle();
/**
* Start the PWM generation
*
* Important: Valid duty cycle / CCR has to be set before starting
*/
void half_bridge_start();
/**
* Stop the PWM generation
*/
void half_bridge_stop();
/**
* Get status of the PWM output
*
* @returns True if PWM output enabled
*/
bool half_bridge_enabled();
#endif /* HALF_BRIDGE_H_ */
+93
View File
@@ -0,0 +1,93 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "hardware.h"
#include "mcu.h"
#include "load.h"
#include "helper.h"
#include "half_bridge.h"
#include "leds.h"
#include "setup.h"
#ifndef UNIT_TEST
#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), boot0))
#define BOOT0_GPIO DT_CHILD(DT_PATH(outputs), boot0)
#endif
#include <power/reboot.h>
#include <drivers/gpio.h>
LOG_MODULE_REGISTER(hardware, CONFIG_HW_LOG_LEVEL);
void start_stm32_bootloader()
{
#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), boot0))
// pin is connected to BOOT0 via resistor and capacitor
const struct device *dev = device_get_binding(DT_GPIO_LABEL(BOOT0_GPIO, gpios));
gpio_pin_configure(dev, DT_GPIO_PIN(BOOT0_GPIO, gpios),
DT_GPIO_FLAGS(BOOT0_GPIO, gpios) | GPIO_OUTPUT_ACTIVE);
k_sleep(K_MSEC(100)); // wait for capacitor at BOOT0 pin to charge up
reset_device();
#elif defined(CONFIG_SOC_SERIES_STM32G4X)
if ((FLASH->CR & FLASH_CR_OPTLOCK) != 0U) {
/* Authorizes the Option Byte register programming */
FLASH->OPTKEYR = FLASH_OPTKEY1;
FLASH->OPTKEYR = FLASH_OPTKEY2;
}
// Set proper bits for booting the embedded bootloader (see table
// 5 in section 2.6.1 in document RM0440)
// nBOOT0: nBOOT0 option bit (equivalent to the BOOT0 pin)
// nSWBOOT0: 0: BOOT0 taken from the option bit nBOOT0
// nSWBOOT0: 1: BOOT0 taken from PB8/BOOT0 pin
// nBOOT1: Together with the BOOT0 pin, this bit selects boot mode
// from the Flash main memory, SRAM1 or the System memory.
FLASH->OPTR &= ~(FLASH_OPTR_nSWBOOT0 | FLASH_OPTR_nBOOT0);
FLASH->OPTR |= FLASH_OPTR_nBOOT1;
// Save the current registers in flash, to be reloaded at reset
FLASH->CR |= FLASH_CR_OPTSTRT;
k_sleep(K_MSEC(20));
// Reload the option registers from flash; should trigger a system
// reset.
FLASH->CR |= FLASH_CR_OBL_LAUNCH;
// If OBL_LAUNCH did not reset (it should), we'll force it by
// first locking back the flash registers and going for a reboot.
FLASH->CR |= FLASH_CR_OPTLOCK;
reset_device();
#endif
}
void reset_device()
{
sys_reboot(SYS_REBOOT_COLD);
}
void task_wdt_callback(int channel_id, void *user_data)
{
printk("Task watchdog callback (channel: %d, thread: %s)\n",
channel_id, k_thread_name_get((k_tid_t)user_data));
printk("Resetting device...\n");
sys_reboot(SYS_REBOOT_COLD);
}
#else
// dummy functions for unit tests
void start_stm32_bootloader() {}
void reset_device() {}
void task_wdt_callback(int channel_id, void *user_data) {}
#endif /* UNIT_TEST */
+34
View File
@@ -0,0 +1,34 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef HARDWARE_H
#define HARDWARE_H
/** @file
*
* @brief
* Hardware-specific functions like timers, watchdog, bootloader
*/
/** DC/DC or PWM control loop (implemented in main.cpp)
*/
void system_control();
/** Reset device and start STM32 internal bootloader
*/
void start_stm32_bootloader();
/**
* Reset device
*/
void reset_device();
/**
* Callback for task watchdogs used in multiple threads
*/
void task_wdt_callback(int channel_id, void *user_data);
#endif /* HARDWARE_H */
+91
View File
@@ -0,0 +1,91 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef HELPER_H
#define HELPER_H
/** @file
*
* @brief
* General helper functions
*/
#include <string.h>
#include <stdint.h>
#include <time.h>
#ifdef __INTELLISENSE__
/*
* VS Code intellisense can't cope with all the Zephyr macro layers for logging, so provide it
* with something more simple and make it silent.
*/
#define LOG_DBG(...) printf(__VA_ARGS__)
#define LOG_INF(...) printf(__VA_ARGS__)
#define LOG_WRN(...) printf(__VA_ARGS__)
#define LOG_ERR(...) printf(__VA_ARGS__)
#define LOG_MODULE_REGISTER(...)
#else
#include <logging/log.h>
#endif /* VSCODE_INTELLISENSE_HACK */
#include <zephyr.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Framework-independent system uptime
*
* @returns seconds since the system booted
*/
static inline uint32_t uptime()
{
#ifndef UNIT_TEST
return k_uptime_get() / 1000;
#else
return time(NULL);
#endif
}
/**
* Sets one or more flags in given field
*
* @param field pointer to the field that will be manipulated
* @param mask a single flag or bitwise OR-ed flags
*/
inline void flags_set(uint32_t *field, uint32_t mask) { *field |= mask; }
/**
* Clears one or more flags in the bit field
*
* @param field pointer to the field that will be manipulated
* @param mask a single flag or bitwise OR-ed flags
*/
inline void flags_clear(uint32_t *field, uint32_t mask) { *field &= ~mask; }
/**
* Queries one or more flags in the bit field
*
* @param field pointer to the field that will be manipulated
* @param mask a single flag or bitwise OR-ed
* @returns true if any of the flags given in mask are set in the bit field
*/
inline bool flags_check(uint32_t *field, uint32_t mask) { return (*field & mask) != 0; }
#ifdef __cplusplus
}
#endif
#endif /* HELPER_H */
+314
View File
@@ -0,0 +1,314 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "leds.h"
#include <zephyr.h>
#include <drivers/gpio.h>
#include <task_wdt/task_wdt.h>
#include "hardware.h"
#define SLEEP_TIME_MS (1000/60/NUM_LEDS) // 60 Hz
/*
* The LED setup is derived from the devicetree configuration in board.dts file
*
* Example devicetree fragment:
*
* leds {
* compatible = "charlieplexing-leds";
* gpios = <&gpioa 1 GPIO_ACTIVE_HIGH>,
* <&gpiob 2 GPIO_ACTIVE_HIGH>,
* <&gpioc 3 GPIO_ACTIVE_HIGH>;
* soc_1 {
* states = <1 0 2>;
* };
* soc_2 {
* states = <0 1 2>;
* };
* soc_3 {
* states = <1 2 0>;
* };
* load {
* states = <2 0 1>;
* };
* };
*/
/*
* Number of LED pins = length of "gpios" array in "leds" devicetree node
*/
#define NUM_LED_PINS DT_PROP_LEN(DT_PATH(leds), gpios)
/*
* LED pin states to switch a specific LED on
*
* 0 = low, 1 = high, 2 = floating (see enum PinState in leds.h)
*
* Above example board.dts expands to:
*
* static const int led_pin_states[4][3] {
* {1, 0, 2},
* {0, 1, 2},
* {1, 2, 0},
* {2, 0, 1},
* };
*/
#define LED_STATES(node_id) DT_PROP(node_id, states),
static const int led_pin_states[NUM_LEDS][NUM_LED_PINS] = {
DT_FOREACH_CHILD(DT_PATH(leds), LED_STATES)
};
/*
* GPIO pin numbers (for up to 5 LED pins)
*/
static const gpio_pin_t led_pins[] = {
DT_PHA_BY_IDX(DT_PATH(leds), gpios, 0, pin),
#if NUM_LED_PINS >= 2
DT_PHA_BY_IDX(DT_PATH(leds), gpios, 1, pin),
#endif
#if NUM_LED_PINS >= 3
DT_PHA_BY_IDX(DT_PATH(leds), gpios, 2, pin),
#endif
#if NUM_LED_PINS >= 4
DT_PHA_BY_IDX(DT_PATH(leds), gpios, 3, pin),
#endif
#if NUM_LED_PINS >= 5
DT_PHA_BY_IDX(DT_PATH(leds), gpios, 4, pin),
#endif
};
/*
* GPIO port labels (for up to 5 LED pins)
*/
static const char *const led_ports[] = {
DT_PROP_BY_PHANDLE_IDX(DT_PATH(leds), gpios, 0, label),
#if NUM_LED_PINS >= 2
DT_PROP_BY_PHANDLE_IDX(DT_PATH(leds), gpios, 1, label),
#endif
#if NUM_LED_PINS >= 3
DT_PROP_BY_PHANDLE_IDX(DT_PATH(leds), gpios, 2, label),
#endif
#if NUM_LED_PINS >= 4
DT_PROP_BY_PHANDLE_IDX(DT_PATH(leds), gpios, 3, label),
#endif
#if NUM_LED_PINS >= 5
DT_PROP_BY_PHANDLE_IDX(DT_PATH(leds), gpios, 4, label),
#endif
};
/*
* GPIO pin flags (for up to 5 LED pins)
*/
static const gpio_flags_t led_flags[] = {
DT_PHA_BY_IDX(DT_PATH(leds), gpios, 0, flags),
#if NUM_LED_PINS >= 2
DT_PHA_BY_IDX(DT_PATH(leds), gpios, 1, flags),
#endif
#if NUM_LED_PINS >= 3
DT_PHA_BY_IDX(DT_PATH(leds), gpios, 2, flags),
#endif
#if NUM_LED_PINS >= 4
DT_PHA_BY_IDX(DT_PATH(leds), gpios, 3, flags),
#endif
#if NUM_LED_PINS >= 5
DT_PHA_BY_IDX(DT_PATH(leds), gpios, 4, flags),
#endif
};
static int led_states[NUM_LEDS]; // must be one of enum LedState
static int trigger_timeout[NUM_LEDS]; // seconds until trigger should end
static bool blink_state = true; // global state of all blinking LEDs
static bool charging = false;
void leds_update_thread()
{
#ifndef UNIT_TEST
unsigned int led_count = 0;
int flicker_count = 0;
bool flicker_state = true;
const struct device *led_devs[NUM_LED_PINS];
int wdt_channel = task_wdt_add(1000, task_wdt_callback, (void *)k_current_get());
for (int pin = 0; pin < NUM_LED_PINS; pin++) {
led_devs[pin] = device_get_binding(led_ports[pin]);
}
leds_init(true);
while (true) {
task_wdt_feed(wdt_channel);
// could be increased to value >NUM_LEDS to reduce on-time
if (led_count >= NUM_LEDS) {
led_count = 0;
}
if (flicker_count > 30) {
flicker_count = 0;
flicker_state = !flicker_state;
}
if (led_count < NUM_LEDS && (
led_states[led_count] == LED_STATE_ON ||
(led_states[led_count] == LED_STATE_FLICKER && flicker_state == 1) ||
(led_states[led_count] == LED_STATE_BLINK && blink_state == 1)
))
{
for (unsigned int pin_number = 0; pin_number < NUM_LED_PINS; pin_number++) {
switch (led_pin_states[led_count][pin_number]) {
case PIN_HIGH:
gpio_pin_configure(led_devs[pin_number], led_pins[pin_number],
led_flags[pin_number] | GPIO_OUTPUT);
gpio_pin_set(led_devs[pin_number], led_pins[pin_number], 1);
break;
case PIN_LOW:
gpio_pin_configure(led_devs[pin_number], led_pins[pin_number],
led_flags[pin_number] | GPIO_OUTPUT);
gpio_pin_set(led_devs[pin_number], led_pins[pin_number], 0);
break;
case PIN_FLOAT:
gpio_pin_configure(led_devs[pin_number], led_pins[pin_number], GPIO_INPUT);
break;
}
}
}
else {
// all pins floating
for (unsigned int pin_number = 0; pin_number < NUM_LED_PINS; pin_number++) {
gpio_pin_configure(led_devs[pin_number], led_pins[pin_number], GPIO_INPUT);
}
}
led_count++;
flicker_count++;
k_sleep(K_MSEC(SLEEP_TIME_MS));
}
#endif // UNIT_TEST
}
void leds_init(bool enabled)
{
for (unsigned int led = 0; led < NUM_LEDS; led++) {
if (enabled) {
led_states[led] = LED_STATE_ON;
trigger_timeout[led] = 0; // switched off the first time the main loop is called
}
else {
led_states[led] = LED_STATE_OFF;
trigger_timeout[led] = -1;
}
}
}
void leds_set_charging(bool enabled)
{
charging = enabled;
}
void leds_set(unsigned int led, bool enabled, int timeout)
{
if (led >= NUM_LEDS || led < 0) {
return;
}
if (enabled) {
led_states[led] = LED_STATE_ON;
}
else {
led_states[led] = LED_STATE_OFF;
}
trigger_timeout[led] = timeout;
}
void leds_on(unsigned int led, int timeout)
{
leds_set(led, true, timeout);
}
void leds_off(unsigned int led)
{
leds_set(led, false, -1);
}
void leds_blink(unsigned int led, int timeout)
{
if (led < NUM_LEDS && led >= 0) {
led_states[led] = LED_STATE_BLINK;
trigger_timeout[led] = timeout;
}
}
void leds_flicker(unsigned int led, int timeout)
{
if (led < NUM_LEDS && led >= 0) {
led_states[led] = LED_STATE_FLICKER;
trigger_timeout[led] = timeout;
}
}
void leds_update_1s()
{
blink_state = !blink_state;
for (unsigned int led = 0; led < NUM_LEDS; led++) {
if (trigger_timeout[led] > 0) {
trigger_timeout[led]--;
}
else if (trigger_timeout[led] == 0) {
led_states[led] = LED_STATE_OFF;
}
}
}
void leds_toggle_error()
{
for (unsigned int led = 0; led < NUM_LEDS; led++) {
led_states[led] = (led % 2) ^ blink_state;
}
blink_state = !blink_state;
}
void leds_update_soc(int soc, bool load_off_low_soc)
{
// blink SOC or power LED when charger (DC/DC or PWM switch) is enabled
int blink_chg = (charging) ? LED_STATE_BLINK : LED_STATE_ON;
#if LED_EXISTS(pwr)
led_states[LED_POS(pwr)] = blink_chg;
trigger_timeout[LED_POS(pwr)] = -1;
#elif LED_EXISTS(soc_3) // 3-bar SOC gauge
trigger_timeout[LED_POS(soc_1)] = -1;
trigger_timeout[LED_POS(soc_2)] = -1;
trigger_timeout[LED_POS(soc_3)] = -1;
if (soc > 80 && !load_off_low_soc) {
led_states[LED_POS(soc_1)] = blink_chg;
led_states[LED_POS(soc_2)] = LED_STATE_ON;
led_states[LED_POS(soc_3)] = LED_STATE_ON;
}
else if (soc > 20 && !load_off_low_soc) {
led_states[LED_POS(soc_1)] = LED_STATE_OFF;
led_states[LED_POS(soc_2)] = blink_chg;
led_states[LED_POS(soc_3)] = LED_STATE_ON;
}
else {
led_states[LED_POS(soc_1)] = LED_STATE_OFF;
led_states[LED_POS(soc_2)] = LED_STATE_OFF;
led_states[LED_POS(soc_3)] = blink_chg;
}
#endif
}
#ifndef UNIT_TEST
K_THREAD_DEFINE(leds_thread, 256, leds_update_thread, NULL, NULL, NULL, 4, 0, 100);
#endif
+146
View File
@@ -0,0 +1,146 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef LEDS_H
#define LEDS_H
/**
* @file
*
* @brief
* Control of status LEDs with charlieplexing
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <zephyr.h>
/*
* Find out if LED was specified in board devicetree file
*/
#define LED_EXISTS(node) DT_NODE_EXISTS(DT_CHILD(DT_PATH(leds), node))
#define LED_TIMEOUT_INFINITE (-1)
/*
* Find out the position of an LED in the LED states array (using below enum)
*/
#define LED_POS(node) DT_N_S_leds_S_##node##_LED_POS
/*
* Creates a unique name used by LED_POS macro for below enum
*/
#define LED_ENUM(node) node##_LED_POS,
/*
* Enum for numbering of LEDs in the order specified in board.dts
*/
// cppcheck-suppress syntaxError
enum {
DT_FOREACH_CHILD(DT_PATH(leds), LED_ENUM)
NUM_LEDS // trick to get the number of elements
};
/**
* LED states
*/
enum LedState {
LED_STATE_OFF = 0,
LED_STATE_ON,
LED_STATE_BLINK,
LED_STATE_FLICKER
};
/**
* Pin states
*/
enum PinState {
PIN_LOW = 0,
PIN_HIGH,
PIN_FLOAT
};
/**
* Initialize LEDs (called at the beginning of leds_update_thread)
*/
void leds_init(bool enabled);
/**
* Main thread for LED control. Performs pin initializations and charlieplexing at 60 Hz
*/
void leds_update_thread();
/**
* Enables/disables dedicated charging LED if existing or blinks SOC LED when solar power is coming
* in.
*/
void leds_set_charging(bool enabled);
/**
* Enables/disables LED
*
* @param led Number of LED in array defined in PCB configuration
* @param enabled LED is switched on if enabled is set to true
* @param timeout Defines for how long this state should be set (-1 for permanent setting)
*/
void leds_set(unsigned int led, bool enabled, int timeout);
/**
* Enable LED
*
* @param led Number of LED in array defined in PCB configuration
* @param timeout Defines for how long this state should be set (-1 for permanent setting)
*/
void leds_on(unsigned int led, int timeout);
/**
* Disable LED
*
* @param led Number of LED in array defined in PCB configuration
*/
void leds_off(unsigned int led);
/**
* Blink LED
*
* @param led Number of LED in array defined in PCB configuration
* @param timeout Defines for how long this state should be set (-1 for permanent setting)
*/
void leds_blink(unsigned int led, int timeout);
/**
* Flicker LED
*
* @param led Number of LED in array defined in PCB configuration
* @param timeout Defines for how long this state should be set (-1 for permanent setting)
*/
void leds_flicker(unsigned int led, int timeout);
/** Updates LED blink and timeout states, must be called every second
*/
void leds_update_1s();
/**
* Update SOC LED bar (if existing)
*
* @param soc SOC in percent
* @param load_off_low_soc Prevents showing two SOC LEDs if load is switched off because of low SOC
*/
void leds_update_soc(int soc, bool load_off_low_soc);
/**
* Toggle between even and uneven LEDs switched on/off to create
* annoying flashing in case of an error.
*/
void leds_toggle_error();
#ifdef __cplusplus
}
#endif
#endif /* LEDS_H */
+179
View File
@@ -0,0 +1,179 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "load.h"
#include <zephyr.h>
#include "board.h"
#if BOARD_HAS_LOAD_OUTPUT || UNIT_TEST
#include "leds.h"
#include "device_status.h"
#include "helper.h"
#define LOAD_CURRENT_MAX DT_PROP(DT_CHILD(DT_PATH(outputs), load), current_max)
#define PCB_LS_VOLTAGE_MAX DT_PROP(DT_PATH(pcb), ls_voltage_max)
#define PCB_MOSFETS_TJ_MAX DT_PROP(DT_PATH(pcb), mosfets_tj_max)
#define PCB_MOSFETS_TAU_JA DT_PROP(DT_PATH(pcb), mosfets_tau_ja)
#define PCB_INTERNAL_TREF_MAX DT_PROP(DT_PATH(pcb), internal_tref_max)
extern DeviceStatus dev_stat;
LoadOutput::LoadOutput(DcBus *dc_bus, void (*switch_fn)(bool), void (*init_fn)(), bool (*pgood_fn)()) :
PowerPort(dc_bus),
switch_set(switch_fn),
pgood_check(pgood_fn)
{
state = LOAD_STATE_OFF;
// call driver initialization function
init_fn();
switch_set(false);
junction_temperature = 25; // starting point: 25°C
oc_recovery_delay = CONFIG_LOAD_OC_RECOVERY_DELAY;
lvd_recovery_delay = CONFIG_LOAD_LVD_RECOVERY_DELAY;
ov_hysteresis = 0.3;
enable = true; // switch on in next control() call if everything is fine
}
// this function is called more often than the state machine
void LoadOutput::control()
{
if (state == LOAD_STATE_ON) {
// junction temperature calculation model for overcurrent detection
junction_temperature = junction_temperature +
(dev_stat.internal_temp - junction_temperature + current * current /
(LOAD_CURRENT_MAX * LOAD_CURRENT_MAX) * (PCB_MOSFETS_TJ_MAX - PCB_INTERNAL_TREF_MAX))
/ (PCB_MOSFETS_TAU_JA * CONFIG_CONTROL_FREQUENCY);
if (junction_temperature > PCB_MOSFETS_TJ_MAX ||
current > LOAD_CURRENT_MAX * 2)
{
flags_set(&error_flags, ERR_LOAD_OVERCURRENT);
oc_timestamp = uptime();
}
if (pgood_check != NULL && !pgood_check()) {
flags_set(&error_flags, ERR_LOAD_OVERCURRENT);
oc_timestamp = uptime();
}
// negative margin means sourcing current from bus is allowed
if (bus->src_current_margin > -0.1F) {
flags_set(&error_flags, ERR_LOAD_BUS_SRC_CURRENT);
}
if (bus->voltage < bus->src_control_voltage(disconnect_voltage)) {
flags_set(&error_flags, ERR_LOAD_SHEDDING);
lvd_timestamp = uptime();
}
// long-term overvoltage (overvoltage transients are detected as an ADC alert and switch
// off the solar input instead of the load output)
if (bus->voltage > bus->series_voltage(overvoltage) ||
bus->voltage > PCB_LS_VOLTAGE_MAX)
{
ov_debounce_counter++;
if (ov_debounce_counter > CONFIG_CONTROL_FREQUENCY) {
// waited 1s before setting the flag
flags_set(&error_flags, ERR_LOAD_OVERVOLTAGE);
}
}
else {
ov_debounce_counter = 0;
}
if (error_flags) {
stop();
}
if (enable == false) {
switch_set(false);
state = LOAD_STATE_OFF;
}
}
else {
// load is off: check if errors are resolved and if load can be switched on
if (flags_check(&error_flags, ERR_LOAD_SHEDDING) &&
bus->voltage > bus->src_control_voltage(reconnect_voltage) &&
uptime() - lvd_timestamp > lvd_recovery_delay)
{
flags_clear(&error_flags, ERR_LOAD_SHEDDING);
}
if (flags_check(&error_flags, ERR_LOAD_OVERCURRENT | ERR_LOAD_VOLTAGE_DIP) &&
uptime() - oc_timestamp > oc_recovery_delay)
{
flags_clear(&error_flags, ERR_LOAD_OVERCURRENT | ERR_LOAD_VOLTAGE_DIP);
}
if (flags_check(&error_flags, ERR_LOAD_OVERVOLTAGE) &&
bus->voltage < (bus->series_voltage(overvoltage) - ov_hysteresis) &&
bus->voltage < (PCB_LS_VOLTAGE_MAX - ov_hysteresis))
{
flags_clear(&error_flags, ERR_LOAD_OVERVOLTAGE);
}
if (flags_check(&error_flags, ERR_LOAD_BUS_SRC_CURRENT) && bus->src_current_margin < 0) {
flags_clear(&error_flags, ERR_LOAD_BUS_SRC_CURRENT);
}
if (flags_check(&error_flags, ERR_LOAD_SHORT_CIRCUIT) && enable == false) {
// stay here until the charge controller is reset or load is manually switched off
flags_clear(&error_flags, ERR_LOAD_SHORT_CIRCUIT);
}
// finally switch on if all errors were resolved and at least 1A src current is available
if (enable == true && !error_flags && bus->src_current_margin < -1.0F) {
switch_set(true);
state = LOAD_STATE_ON;
}
}
info = error_flags > 0 ? -error_flags : state;
}
void LoadOutput::stop(uint32_t flag)
{
switch_set(false);
state = LOAD_STATE_OFF;
flags_set(&error_flags, flag);
// flicker the load LED if failure was most probably caused by the user
if (flags_check(&error_flags,
ERR_LOAD_OVERCURRENT | ERR_LOAD_VOLTAGE_DIP | ERR_LOAD_SHORT_CIRCUIT))
{
#if LED_EXISTS(load)
leds_flicker(LED_POS(load), LED_TIMEOUT_INFINITE);
#endif
oc_timestamp = uptime();
}
}
void LoadOutput::set_voltage_limits(float lvd, float lvr, float ov)
{
disconnect_voltage = lvd;
reconnect_voltage = lvr;
overvoltage = ov;
}
extern LoadOutput load;
void load_short_circuit_stop()
{
load.stop(ERR_LOAD_SHORT_CIRCUIT);
}
#endif /* BOARD_HAS_LOAD_OUTPUT */
+198
View File
@@ -0,0 +1,198 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef LOAD_H
#define LOAD_H
/** @file
*
* @brief
* Load/USB output functions and data types
*/
#include <stdint.h>
#include <stdbool.h>
#include <time.h>
#ifdef __cplusplus
#include "power_port.h"
/**
* Load/USB output states
*/
enum LoadState {
LOAD_STATE_OFF = 0, ///< Actively disabled
LOAD_STATE_ON = 1, ///< Normal state: On
};
/** Load error flags
*
* When adding new flags, please make sure to use only up to 32 errors
* Each enum must represent a unique power of 2 number
*/
enum LoadErrorFlag {
/**
* Available energy or power too low
*
* Switching off the load can be triggered either by a low battery voltage or by low state of
* charge (SOC) in case of more advanced battery management.
*
* Set in LoadOutput::control() and cleared after reconnect delay passed and voltage is above
* reconnect threshold again.
*/
ERR_LOAD_SHEDDING = 1U << 0,
/**
* Too high voltage for load
*
* Set and cleared in LoadOutput::control()
*/
ERR_LOAD_OVERVOLTAGE = 1U << 1,
/**
* Long-term overcurrent at load port
*
* Set in LoadOutput::control() and cleared after configurable delay.
*/
ERR_LOAD_OVERCURRENT = 1U << 2,
/**
* Short circuit detected at load port
*
* Set by LoadOutput::control() after overcurrent comparator triggered, cleared only if
* load output is manually disabled and enabled again.
*/
ERR_LOAD_SHORT_CIRCUIT = 1U << 3,
/**
* Overcurrent identified via voltage dip (may be caused by too small battery)
*
* Set and cleared in LoadOutput::control(). Treated same as load overcurrent.
*/
ERR_LOAD_VOLTAGE_DIP = 1U << 4,
/**
* The bus the load is connected to disabled sourcing current from it
*
* Reasons can be that battery temperature limits were exceeded. Voltage limits should be
* covered by the load directly.
*/
ERR_LOAD_BUS_SRC_CURRENT = 1U << 5
};
/** Load output type
*
* Stores status of load output incl. 5V USB output (if existing on PCB)
*/
class LoadOutput : public PowerPort
{
public:
/**
* Initialize LoadOutput struct and overcurrent / short circuit protection comparator (if existing)
*
* @param dc_bus DC bus the load is connected to
* @param switch_fn Pointer to function for enabling/disabling load switch
* @param init_fn Pointer to function for load driver initialization
* @param pgood_fn Pointer to pgood check
*/
LoadOutput(DcBus *dc_bus, void (*switch_fn)(bool), void (*init_fn)(), bool (*pgood_fn)());
/** Main load control function, should be called by control timer
*
* This function includes the load state machine
*/
void control();
/** Fast emergency stop function
*
* May be called from an ISR which detected overvoltage / overcurrent conditions
*
* @param error_flag Optional error flag that should be set
*/
void stop(uint32_t error_flag = 0);
/**
* Update of load voltage limits (typically based on battery configuration)
*
* @param lvd Low voltage disconnect setpoint
* @param lvr Low voltage reconnect setpoint
* @param ov Overvoltage setpoint
*/
void set_voltage_limits(float lvd, float lvr, float ov);
uint32_t state; ///< Current state of load output switch
uint32_t error_flags = 0; ///< Stores error flags as bits according to LoadErrorFlag enum
int32_t info; ///< Contains either the state or negative value of error_flags
///< in case of error_flags > 0. This allows to have a single
///< variable for load state diagnosis.
bool enable = false; ///< Target on state set via communication port (overruled if
///< battery is empty or any errors occured)
time_t oc_timestamp; ///< Time when last overcurrent event occured
uint32_t oc_recovery_delay; ///< Seconds before we attempt to re-enable the load
///< after an overcurrent event
float disconnect_voltage = 0; ///< Low voltage disconnect (LVD) setpoint
float reconnect_voltage = 0; ///< Low voltage reconnect (LVD) setpoint
time_t lvd_timestamp; ///< Time when last low voltage disconnect happened
uint32_t lvd_recovery_delay;///< Seconds before we re-enable the load after a low voltage
///< disconnect
float junction_temperature; ///< calculated using thermal model based on current and ambient
///< temperature measurement (unit: °C)
float overvoltage = 0; ///< Upper voltage limit
float ov_hysteresis; ///< Hysteresis to switch back on after an overvoltage event
private:
/**
* Pointer to the load switch function
*/
void (*switch_set)(bool);
/**
* Pointer to the function to check the power output status
*/
bool (*pgood_check)(void);
/**
* Used to prevent switching of because of very short voltage dip
*/
int uv_debounce_counter = 0;
/**
* Used to prevent switching off because of short voltage spike
*/
int ov_debounce_counter = 0;
};
#endif
#ifdef __cplusplus
extern "C" {
#endif
void load_out_init();
void usb_out_init();
void load_out_set(bool);
void usb_out_set(bool);
void load_short_circuit_stop();
bool pgood_check();
#ifdef __cplusplus
}
#endif
#endif /* LOAD_H */
+242
View File
@@ -0,0 +1,242 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "load.h"
#ifdef CONFIG_SOC_FAMILY_STM32
#include <zephyr.h>
#include <device.h>
#include <drivers/gpio.h>
#include <drivers/pwm.h>
#include "board.h"
#include "hardware.h"
#include "leds.h"
#include "mcu.h"
#include <stm32_ll_system.h>
#include <stm32_ll_bus.h>
#if BOARD_HAS_LOAD_OUTPUT
#define LOAD_GPIO DT_CHILD(DT_PATH(outputs), load)
static const struct device *dev_load;
#endif
#if BOARD_HAS_USB_OUTPUT
#define USB_GPIO DT_CHILD(DT_PATH(outputs), usb_pwr)
static const struct device *dev_usb;
#endif
// short circuit detection comparator only present in PWM 2420 LUS board so far
#ifdef CONFIG_BOARD_PWM_2420_LUS
static void lptim_init()
{
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_LPTIM1);
LL_IOP_GRP1_EnableClock(LL_IOP_GRP1_PERIPH_GPIOB);
// Select alternate function mode on PB2 (first bit _1 = 1, second bit _0 = 0)
GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODE2)) | GPIO_MODER_MODE2_1;
// Select AF2 (LPTIM_OUT) on PB2
GPIOB->AFR[0] |= 0x2U << GPIO_AFRL_AFSEL2_Pos;
// Set prescaler to 32 (resulting in 1 MHz timer frequency)
LPTIM1->CFGR |= 0x5U << LPTIM_CFGR_PRESC_Pos;
// Enable trigger (rising edge)
LPTIM1->CFGR |= LPTIM_CFGR_TRIGEN_0;
// Select trigger 7 (COMP2_OUT)
LPTIM1->CFGR |= 0x7U << LPTIM_CFGR_TRIGSEL_Pos;
//LPTIM1->CFGR |= LPTIM_CFGR_WAVPOL;
LPTIM1->CFGR |= LPTIM_CFGR_PRELOAD;
// Glitch filter of 8 cycles
LPTIM1->CFGR |= LPTIM_CFGR_TRGFLT_0 | LPTIM_CFGR_TRGFLT_1;
// Enable set-once mode
LPTIM1->CFGR |= LPTIM_CFGR_WAVE;
// Enable timer (must be done *before* changing ARR or CMP, but *after*
// changing CFGR)
LPTIM1->CR |= LPTIM_CR_ENABLE;
// Auto Reload Register
LPTIM1->ARR = 1000;
// Set load switch-off delay in microseconds
// (actually takes approx. 4 us longer than this setting)
LPTIM1->CMP = 10;
// Continuous mode
//LPTIM1->CR |= LPTIM_CR_CNTSTRT;
//LPTIM1->CR |= LPTIM_CR_SNGSTRT;
}
void ADC1_COMP_IRQHandler(void *args)
{
// interrupt called because of COMP2?
if (COMP2->CSR & COMP_CSR_COMP2VALUE) {
// Load should be switched off by LPTIM trigger already. This interrupt
// is mainly used to indicate the failure.
load_short_circuit_stop();
}
// clear interrupt flag
EXTI->PR |= EXTI_PR_PIF22;
}
void short_circuit_comp_init()
{
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_SYSCFG);
LL_IOP_GRP1_EnableClock(LL_IOP_GRP1_PERIPH_GPIOB);
// set GPIO pin to analog
GPIOB->MODER &= ~(GPIO_MODER_MODE4);
// enable VREFINT buffer
SYSCFG->CFGR3 |= SYSCFG_CFGR3_ENBUFLP_VREFINT_COMP;
// select PB4 as positive input
COMP2->CSR |= COMP_INPUT_PLUS_IO2;
// select VREFINT divider as negative input
COMP2->CSR |= COMP_INPUT_MINUS_1_4VREFINT;
// propagate comparator value to LPTIM input
COMP2->CSR |= COMP_CSR_COMP2LPTIM1IN1;
// normal polarity
//COMP2->CSR |= COMP_CSR_COMP2POLARITY;
// set high-speed mode (1.2us instead of 2.5us propagation delay, but 3.5uA instead of 0.5uA
// current consumption)
//COMP2->CSR |= COMP_CSR_COMP2SPEED;
// enable COMP2
COMP2->CSR |= COMP_CSR_COMP2EN;
// enable EXTI software interrupt / event
EXTI->IMR |= EXTI_IMR_IM22;
EXTI->EMR |= EXTI_EMR_EM22;
EXTI->RTSR |= EXTI_RTSR_RT22;
EXTI->FTSR |= EXTI_FTSR_FT22;
EXTI->SWIER |= EXTI_SWIER_SWI22;
// 1 = second-highest priority of STM32L0/F0
IRQ_CONNECT(ADC1_COMP_IRQn, 1, ADC1_COMP_IRQHandler, 0, 0);
irq_enable(ADC1_COMP_IRQn);
}
#endif
void load_out_set(bool status)
{
#if LED_EXISTS(load)
leds_set(LED_POS(load), status, LED_TIMEOUT_INFINITE);
#endif
#if BOARD_HAS_LOAD_OUTPUT
gpio_pin_configure(dev_load, DT_GPIO_PIN(LOAD_GPIO, gpios),
DT_GPIO_FLAGS(LOAD_GPIO, gpios) | GPIO_OUTPUT_INACTIVE);
if (status == true) {
#ifdef CONFIG_BOARD_PWM_2420_LUS
lptim_init();
#else
gpio_pin_set(dev_load, DT_GPIO_PIN(LOAD_GPIO, gpios), 1);
#endif
}
else {
gpio_pin_set(dev_load, DT_GPIO_PIN(LOAD_GPIO, gpios), 0);
}
#endif
}
void usb_out_set(bool status)
{
#if BOARD_HAS_USB_OUTPUT
gpio_pin_configure(dev_usb, DT_GPIO_PIN(USB_GPIO, gpios),
DT_GPIO_FLAGS(USB_GPIO, gpios) | GPIO_OUTPUT_INACTIVE);
if (status == true) {
gpio_pin_set(dev_usb, DT_GPIO_PIN(USB_GPIO, gpios), 1);
#if DT_PROP(DT_CHILD(DT_PATH(outputs), usb_pwr), latching_pgood)
k_sleep(K_MSEC(50));
gpio_pin_configure(dev_usb, DT_GPIO_PIN(USB_GPIO, gpios), GPIO_INPUT);
#endif
}
else {
gpio_pin_set(dev_usb, DT_GPIO_PIN(USB_GPIO, gpios), 0);
}
#endif
}
#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), charge_pump))
#define CP_PWMS DT_CHILD(DT_PATH(outputs), charge_pump)
#define CP_PWM_CONTROLLER DT_PWMS_CTLR(CP_PWMS)
#define CP_PWM_PERIOD DT_PWMS_PERIOD(CP_PWMS)
#define CP_PWM_CHANNEL DT_PWMS_CHANNEL(CP_PWMS)
void load_cp_enable()
{
const struct device *pwm_dev = DEVICE_DT_GET(CP_PWM_CONTROLLER);
if (device_is_ready(pwm_dev)) {
// set to 50% duty cycle
pwm_pin_set_nsec(pwm_dev, CP_PWM_CHANNEL, CP_PWM_PERIOD, CP_PWM_PERIOD / 2, 0);
}
}
#endif
void load_out_init()
{
#if BOARD_HAS_LOAD_OUTPUT
dev_load = device_get_binding(DT_GPIO_LABEL(LOAD_GPIO, gpios));
#endif
// analog comparator to detect short circuits and trigger immediate load switch-off
#ifdef CONFIG_BOARD_PWM_2420_LUS
short_circuit_comp_init();
#endif
#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), charge_pump))
// enable charge pump for high-side switches (if existing)
load_cp_enable();
#endif
}
void usb_out_init()
{
#if BOARD_HAS_USB_OUTPUT
dev_usb = device_get_binding(DT_GPIO_LABEL(USB_GPIO, gpios));
#endif
}
bool pgood_check()
{
#if BOARD_HAS_USB_OUTPUT
return gpio_pin_get(dev_usb, DT_GPIO_PIN(USB_GPIO, gpios));
#else
return false;
#endif
}
#else // CONFIG_SOC_FAMILY_STM32
void load_out_init() {;}
void usb_out_init() {;}
void load_out_set(bool value) {;}
void usb_out_set(bool value) {;}
bool pgood_check() { return false; }
#endif
+180
View File
@@ -0,0 +1,180 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef UNIT_TEST
#include <zephyr.h>
#include <stdio.h>
#include <device.h>
#include <drivers/gpio.h>
#include <task_wdt/task_wdt.h>
#include "thingset.h" // handles access to internal data via communication interfaces
#include "setup.h"
#include "helper.h"
#include "half_bridge.h" // PWM generation for DC/DC converter
#include "hardware.h" // hardware-related functions like load switch, LED control, watchdog, etc.
#include "dcdc.h" // DC/DC converter control (hardware independent)
#include "pwm_switch.h" // PWM charge controller
#include "bat_charger.h" // battery settings and charger state machine
#include "daq.h" // ADC using DMA and conversion to measurement values
#include "data_storage.h" // non-volatile data storage (e.g. EEPROM)
#include "load.h" // load and USB output management
#include "leds.h" // LED switching using charlieplexing
#include "device_status.h" // log data (error memory, min/max measurements, etc.)
#include "data_objects.h" // for access to internal data via ThingSet
void main(void)
{
printf("Hardware: Libre Solar %s (%s)\n",
DT_PROP(DT_PATH(pcb), type), DT_PROP(DT_PATH(pcb), version_str));
printf("Firmware: %s\n", FIRMWARE_VERSION_ID);
task_wdt_init(device_get_binding(DT_LABEL(DT_NODELABEL(iwdg))));
setup();
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
#if CONFIG_HV_TERMINAL_NANOGRID
grid_terminal.init_nanogrid();
#endif
// read custom configuration from EEPROM
data_objects_init();
// Data Acquisition (DAQ) setup
daq_setup();
charger.detect_num_batteries(&bat_conf); // check if we have 24V instead of 12V system
charger.init_terminal(&bat_conf);
#if BOARD_HAS_LOAD_OUTPUT
load.set_voltage_limits(bat_conf.load_disconnect_voltage, bat_conf.load_reconnect_voltage,
bat_conf.absolute_max_voltage);
#endif
#if BOARD_HAS_USB_OUTPUT
usb_pwr.set_voltage_limits(bat_conf.load_disconnect_voltage - 0.1, // keep on longer than load
bat_conf.load_reconnect_voltage, bat_conf.absolute_max_voltage);
#endif
// wait until all threads are spawned before activating the watchdog
k_sleep(K_MSEC(2500));
int64_t t_start = k_uptime_get();
while (true) {
// loop runs exactly once per second and includes slow control tasks and energy calculation
charger.discharge_control(&bat_conf);
charger.charge_control(&bat_conf);
// energy + soc calculation must be called exactly once per second
#if BOARD_HAS_DCDC
if (dcdc.state != DCDC_CONTROL_OFF) {
hv_terminal.energy_balance();
}
#endif
#if BOARD_HAS_PWM_PORT
if (pwm_switch.active() == 1) {
pwm_switch.energy_balance();
}
#endif
lv_terminal.energy_balance();
#if BOARD_HAS_LOAD_OUTPUT
if (load.state == 1) {
load.energy_balance();
}
#endif
dev_stat.update_energy();
dev_stat.update_min_max_values();
charger.update_soc(&bat_conf);
#if CONFIG_HS_MOSFET_FAIL_SAFE_PROTECTION && BOARD_HAS_DCDC
if (dev_stat.has_error(ERR_DCDC_HS_MOSFET_SHORT)) {
dcdc.fuse_destruction();
}
#endif
leds_update_1s();
#if BOARD_HAS_LOAD_OUTPUT
leds_update_soc(charger.soc, flags_check(&load.error_flags, ERR_LOAD_SHEDDING));
#else
leds_update_soc(charger.soc, false);
#endif
data_storage_update();
t_start += 1000;
k_sleep(K_TIMEOUT_ABS_MS(t_start));
}
}
void control_thread()
{
int wdt_channel = task_wdt_add(200, task_wdt_callback, (void *)k_current_get());
while (true) {
// control loop runs at approx. 10 Hz
bool charging = false;
task_wdt_feed(wdt_channel);
// convert ADC readings to meaningful measurement values
daq_update();
// alerts should trigger only for transients, so update based on actual voltage
daq_set_lv_limits(lv_terminal.bus->voltage * 1.2F, lv_terminal.bus->voltage * 0.8F);
lv_terminal.update_bus_current_margins();
#if BOARD_HAS_PWM_PORT
pwm_switch.control();
charging |= pwm_switch.active();
#endif
#if BOARD_HAS_DCDC
hv_terminal.update_bus_current_margins();
dcdc.control(); // control of DC/DC including MPPT algorithm
charging |= half_bridge_enabled();
#endif
leds_set_charging(charging);
#if BOARD_HAS_LOAD_OUTPUT
load.control();
#endif
#if BOARD_HAS_USB_OUTPUT
usb_pwr.control();
#endif
k_sleep(K_MSEC(100));
}
}
// 2s delay for control thread as a safety feature: be able to re-flash before starting
// priority is set to -1 (=cooperative) to have higher priority than other threads incl. main
K_THREAD_DEFINE(control_thread_id, 1024, control_thread, NULL, NULL, NULL, -1, 0, 2000);
#endif // UNIT_TEST
+56
View File
@@ -0,0 +1,56 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef MCU_H_
#define MCU_H_
#ifdef CONFIG_SOC_STM32F072XB
#include "stm32f072xb.h"
#endif
#ifdef CONFIG_SOC_STM32L072XX
#include "stm32l072xx.h"
#endif
#if defined(CONFIG_SOC_STM32G431XX)
#include "stm32g431xx.h"
#elif defined(CONFIG_SOC_STM32G474XX)
#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_
+49
View File
@@ -0,0 +1,49 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "power_port.h"
void PowerPort::init_solar()
{
neg_current_limit = -50; // derating based on max. DC/DC or PWM switch current only
pos_current_limit = 0; // no current towards solar panel allowed
}
void PowerPort::init_nanogrid()
{
pos_current_limit = 5.0;
neg_current_limit = -5.0;
// 1 Ohm means 1V change of target voltage per amp, same droop for both current directions.
bus->sink_droop_res = 0.1;
bus->src_droop_res = 0.1;
// also initialize the connected bus
bus->src_voltage_intercept = 30.0; // starting buck mode above this point
bus->sink_voltage_intercept = 28.0; // boost mode until this voltage is reached
}
void PowerPort::energy_balance()
{
// remark: timespan = 1s, so no multiplication with time necessary for energy calculation
if (current >= 0.0F) {
pos_energy_Wh += bus->voltage * current / 3600.0F;
}
else {
neg_energy_Wh -= bus->voltage * current / 3600.0F;
}
}
void PowerPort::update_bus_current_margins() const
{
// charging direction of battery
bus->sink_current_margin = pos_current_limit - current;
// discharging direction of battery
bus->src_current_margin = neg_current_limit - current;
//printf("pos: %.3f neg: %.3f current: %.3f\n", pos_current_limit, neg_current_limit, current);
}
+268
View File
@@ -0,0 +1,268 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef POWER_PORT_H
#define POWER_PORT_H
/** @file
*
* @brief Definition of charge controller terminals and internal DC buses
*/
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
class PowerPort; // forward-declaration
/**
* DC bus class
*
* Stores measurement data and settings necessary for voltage control
*/
class DcBus
{
public:
/**
* Measured bus voltage
*/
float voltage = 0;
/**
* Filtered bus voltage
*
* Suitable filter time constants depend on type of DC bus. This filtering is applied in
* addition to the raw ADC value filtering.
*/
float voltage_filtered = 0;
/**
* Multiplier for series connection of batteries
*
* Used for automatic 12V/24V battery detection at start-up (can be 1 or 2 only)
*
* This factor must be applied to all voltage setpoints
*/
int16_t series_multiplier = 1;
/**
* Upper voltage boundary where this bus may be used to sink current.
*
* This value is the voltage at zero current. Values for other currents are calculated
* using the droop resistance.
*/
float sink_voltage_intercept = 0;
/**
* Lower voltage boundary where this bus may be used to source current.
*
* This value is the voltage at zero current. Values for other currents are calculated
* using the droop resistance.
*/
float src_voltage_intercept = 0;
/**
* Droop resistance to adjust voltage bounds for current in sourcing direction
*
* control voltage = nominal voltage - droop_res * current
*/
float src_droop_res = 0;
/**
* Droop resistance to adjust voltage bounds for current in sinking direction
*
* control voltage = nominal voltage - droop_res * current
*/
float sink_droop_res = 0;
/**
* Pointer to current measurement that is used to determine the droop. This is typically the
* battery or nanogrid terminal.
*/
float *ref_current = NULL;
/**
* Available additional current towards the DC bus until limits of the connected ports are
* reached
*/
float sink_current_margin = 0;
/**
* Available additional current from the DC bus until limits of the connected ports are reached
* (has a negative sign)
*
* If for example a battery connected to the bus is not allowed to be discharged anymore, but
* we still get power via solar, current up to the amount of solar input can be diverted into
* the load (until the margin gets 0 and the battery would be discharged).
*/
float src_current_margin = 0;
/**
* Calculate current-compensated src control voltage, considering droop and series multiplier
*
* @param voltage_zero_current Voltage at zero current (without droop). If this parameter is
* left empty, the src_voltage_intercept is considered.
*/
inline float src_control_voltage(float voltage_zero_current = 0)
{
float v0 = (voltage_zero_current == 0) ? src_voltage_intercept : voltage_zero_current;
if (ref_current != nullptr) {
return (v0 - src_droop_res * (*ref_current)) * series_multiplier;
}
else {
return v0 * series_multiplier;
}
}
/**
* Calculate current-compensated sink control voltage, considering droop and series multiplier
*
* @param voltage_zero_current Voltage at zero current (without droop). If this parameter is
* left empty, the sink_voltage_intercept is considered.
*/
inline float sink_control_voltage(float voltage_zero_current = 0)
{
float v0 = (voltage_zero_current == 0) ? sink_voltage_intercept : voltage_zero_current;
if (ref_current != nullptr) {
return (v0 - sink_droop_res * (*ref_current)) * series_multiplier;
}
else {
return v0 * series_multiplier;
}
}
/**
* Calculate voltage for series connected batteries based on setpoint for single battery
*
* @param single_voltage Voltage for single battery
*
* @returns Total voltage
*/
inline float series_voltage(float single_voltage)
{
return single_voltage * series_multiplier;
}
};
/**
* Power Port class
*
* Stores current measurements and limits for external terminals or internal ports
*
* The signs follow the passive sign convention. Current or power from the considered system or
* circuit towards an external device connected to the port has a positive sign. For all terminals,
* the entire charge controller is considered as the system boundary and acts as a source or a sink.
* For internal sub-circuits, e.g. the DC/DC converter circuit defines the sub-system boundaries.
*
* -----------------
* | | >> positive current/power direction
* | o---->----
* | | + |
* | considered | | | external device: battery / solar panel / load / DC grid
* | system or | | |
* | sub-circuit | | | (the port should be named after the external device)
* | | - |
* | o---------
* | |
* -----------------
*
* Examples:
* - Charging a connected battery has a positive sign, as current flows from the charge controller
* into the battery, i.e. the battery acts as a sink.
* - Power from a solar panel (power source) has a negative sign, as the charge controller acts as
* the sink and power flows from the external device into the charge controller.
* - A DC/DC converter in buck mode results in a positive current flow at the low voltage side and
* a negative current at the high voltage side. The system boundary is the DC/DC sub-circuit,
* which sources current from the high side port and sinks it through the low side port.
*/
class PowerPort
{
public:
/**
* Each power port is connected to a DC bus, containing relevant voltage information
*/
DcBus *bus = NULL;
/**
* Measured current through this port (positive sign = current into the external device)
*/
float current = 0;
/**
* Filtered port current
*
* Suitable filter time constants depend on type of port. This filtering is applied in
* addition to the raw ADC value filtering.
*/
float current_filtered = 0;
/**
* Product of port current and bus voltage
*/
float power = 0;
/**
* Maximum positive current (valid values >= 0.0)
*/
float pos_current_limit = 0;
/**
* Maximum negative current (valid values <= 0.0)
*/
float neg_current_limit = 0;
/**
* Cumulated energy in positive current direction since last counter reset (Wh)
*/
float pos_energy_Wh = 0;
/**
* Cumulated energy in negative current direction since last counter reset (Wh)
*/
float neg_energy_Wh = 0;
/**
* Constructor assigning the port to a DC bus
*
* @param dc_bus The DC bus this port is assigned to
* @param assign_ref_current defines if the bus ref_current should point to the current
* of this port (must be true for at least one port)
*/
PowerPort(DcBus *dc_bus, bool assign_ref_current = false) :
bus(dc_bus)
{
if (assign_ref_current) {
bus->ref_current = &current;
}
}
/**
* Initialize power port for solar panel connection
*/
void init_solar();
/**
* Initialize power port for nanogrid connection
*/
void init_nanogrid();
/**
* Energy balance calculation for power port
*
* Must be called exactly once per second, otherwise energy calculation gets wrong.
*/
void energy_balance();
/**
* Sets current limits for control of the bus voltage
*
* This function has to be called using the port defining the bus control targets, i.e.
* the battery, the solar panel or the DC grid.
*/
void update_bus_current_margins() const;
};
#endif /* POWER_PORT_H */
+160
View File
@@ -0,0 +1,160 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "pwm_switch.h"
#include <zephyr.h>
#include <stdio.h>
#include <time.h>
#include "mcu.h"
#include "daq.h"
#include "helper.h"
#include "setup.h"
LOG_MODULE_REGISTER(pwm_switch, CONFIG_PWM_LOG_LEVEL);
#if BOARD_HAS_PWM_PORT
#define PWM_CURRENT_MAX (DT_PROP(DT_CHILD(DT_PATH(outputs), pwm_switch), current_max))
#define PWM_PERIOD (DT_PHA(DT_CHILD(DT_PATH(outputs), pwm_switch), pwms, period))
bool PwmSwitch::active()
{
return pwm_active();
}
bool PwmSwitch::signal_high()
{
return pwm_signal_high();
}
PwmSwitch::PwmSwitch(DcBus *dc_bus) :
PowerPort(dc_bus)
{
// period stored in nanoseconds
pwm_signal_init_registers(1000 * 1000 * 1000 / PWM_PERIOD);
}
void PwmSwitch::test()
{
if (pwm_active() && enable == false) {
pwm_signal_stop();
off_timestamp = uptime();
LOG_INF("PWM test mode stop.");
}
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);
pwm_signal_start(0.9F);
LOG_INF("PWM test mode start.");
}
}
void PwmSwitch::control()
{
if (pwm_active()) {
if (current < -0.1F) {
power_good_timestamp = uptime(); // reset the time
}
if (neg_current_limit == 0
|| (uptime() - power_good_timestamp > 10) // low power since 10s
|| current > 0.5F // discharging battery into solar panel --> stop
|| bus->voltage < 9.0F // not enough voltage for MOSFET drivers anymore
|| enable == false)
{
pwm_signal_stop();
off_timestamp = uptime();
LOG_INF("PWM charger stop, current = %d mA", (int)(current * 1000.0F));
}
else if (bus->voltage > bus->sink_control_voltage() + 0.3F) {
pwm_signal_stop();
off_timestamp = uptime();
dev_stat.set_error(ERR_PWM_SWITCH_OVERVOLTAGE);
LOG_INF("PWM charger stop, overvoltage.");
}
else if (bus->voltage > bus->sink_control_voltage() // bus voltage above target
|| current < neg_current_limit // port current limit exceeded
|| current < -PWM_CURRENT_MAX) // PCB current limit exceeded
{
// decrease power, as limits were reached
// the gate driver switch-off time is quite high (fall time around 1ms), so very short
// on or off periods (duty cycle close to 0 and 1) should be avoided
if (pwm_signal_get_duty_cycle() > 0.95F) {
// prevent very short off periods
pwm_signal_set_duty_cycle(0.95F);
}
else if (pwm_signal_get_duty_cycle() < 0.05F) {
// prevent very short on periods and switch completely off instead
pwm_signal_stop();
off_timestamp = uptime();
// consider this as overvoltage in order to start again with 5% duty cycle
dev_stat.set_error(ERR_PWM_SWITCH_OVERVOLTAGE);
LOG_INF("PWM charger stop, no further derating possible.");
}
else {
// decrease the power with large steps to prevent long-term overvoltages if
// the PWM switch was started with full battery and high solar irradiation
pwm_signal_duty_cycle_step(-10);
}
}
else {
// increase power (if not yet at 100% duty cycle)
if (pwm_signal_get_duty_cycle() > 0.95F) {
// prevent very short off periods and switch completely on instead
pwm_signal_set_duty_cycle(1);
}
else {
pwm_signal_duty_cycle_step(1);
}
}
if (dev_stat.has_error(ERR_PWM_SWITCH_OVERVOLTAGE) &&
bus->voltage < bus->sink_control_voltage() - 0.5F)
{
dev_stat.clear_error(ERR_PWM_SWITCH_OVERVOLTAGE);
}
}
else {
if (bus->sink_current_margin > 0 // charging allowed
&& bus->voltage < bus->sink_control_voltage()
&& ext_voltage > bus->voltage + offset_voltage_start
&& 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);
if (dev_stat.has_error(ERR_PWM_SWITCH_OVERVOLTAGE)) {
// start with minimum duty cycle in order to prevent another overvoltage event
pwm_signal_start(0.05F);
}
else {
pwm_signal_start(1.0F);
}
power_good_timestamp = uptime();
LOG_INF("PWM charger start.");
}
}
}
void PwmSwitch::stop()
{
pwm_signal_stop();
off_timestamp = uptime();
}
float PwmSwitch::get_duty_cycle()
{
return pwm_signal_get_duty_cycle();
}
#endif /* BOARD_HAS_PWM_PORT */
+127
View File
@@ -0,0 +1,127 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef PWM_SWITCH_H
#define PWM_SWITCH_H
/**
* @file
*
* @brief PWM charger MOSFET switch control functions
*/
#include <stdbool.h>
#include <time.h>
#ifdef __cplusplus
#include "power_port.h"
/**
* PWM charger type
*
* Contains all data belonging to the PWM switching sub-component.
*/
class PwmSwitch : public PowerPort
{
public:
PwmSwitch(DcBus *dc_bus);
/**
* Main control function for the PWM switching algorithm
*/
void control();
/**
* Test mode for PWM switch
*
* Sets duty cycle to 90% and listens to enable/disable signal
*/
void test();
/**
* Fast stop function (bypassing control loop)
*
* May be called from an ISR which detected overvoltage / overcurrent conditions.
*
* PWM port will be restarted automatically from control function if condtions are valid.
*/
void stop();
/**
* Read the general on/off status of PWM switching
*
* @returns true if on
*/
bool active();
/**
* Read the current high or low state of the PWM signal
*
* @returns true if high, false if low
*/
bool signal_high();
/**
* Read the currently set duty cycle
*
* @returns Duty cycle between 0.0 and 1.0
*/
float get_duty_cycle();
/**
* Voltage measurement at terminal (external, usually solar panel voltage)
*/
float ext_voltage;
/**
* Enable switch, true by default. Can be used to completely disable the PWM power stage.
*/
bool enable = true;
/**
* Offset voltage of solar panel vs. battery to start charging (V)
*/
float offset_voltage_start = 2.0F;
/**
* Interval to wait before retrying charging after low solar power cut-off or overvoltage
* event (s)
*/
uint32_t restart_interval = 60;
/**
* Time when charger was switched off last time
*
* Initialized with large negative value to start immediately after reset.
*/
time_t off_timestamp = -10000;
/**
* Last time the current through the switch was above minimum
*/
time_t power_good_timestamp;
};
#endif
#ifdef __cplusplus
extern "C" {
#endif
float pwm_signal_get_duty_cycle();
void pwm_signal_set_duty_cycle(float duty);
void pwm_signal_duty_cycle_step(int delta);
void pwm_signal_init_registers(int freq_Hz);
void pwm_signal_start(float pwm_duty);
void pwm_signal_stop();
bool pwm_signal_high();
bool pwm_active();
#ifdef __cplusplus
}
#endif
#endif /* PWM_SWITCH_H */
+165
View File
@@ -0,0 +1,165 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "pwm_switch.h"
#include <zephyr.h>
#include <stdio.h>
#include <time.h>
#include "board.h"
#include "daq.h"
#include "helper.h"
#include "mcu.h"
#if BOARD_HAS_PWM_PORT
#ifndef UNIT_TEST
#include <stm32_ll_tim.h>
#include <stm32_ll_rcc.h>
#include <stm32_ll_bus.h>
#include <soc.h>
#include <pinmux/pinmux_stm32.h>
#define DT_DRV_COMPAT st_stm32_pwm
// all PWM charge controllers use TIM3 at the moment
static TIM_TypeDef *tim = TIM3;
#if DT_PWMS_CHANNEL(DT_CHILD(DT_PATH(outputs), pwm_switch)) == 1
#define LL_TIM_CHANNEL LL_TIM_CHANNEL_CH1
#define LL_TIM_OC_SetCompare LL_TIM_OC_SetCompareCH1
#define LL_TIM_OC_GetCompare LL_TIM_OC_GetCompareCH1
#elif DT_PWMS_CHANNEL(DT_CHILD(DT_PATH(outputs), pwm_switch)) == 2
#define LL_TIM_CHANNEL LL_TIM_CHANNEL_CH2
#define LL_TIM_OC_SetCompare LL_TIM_OC_SetCompareCH2
#define LL_TIM_OC_GetCompare LL_TIM_OC_GetCompareCH2
#elif DT_PWMS_CHANNEL(DT_CHILD(DT_PATH(outputs), pwm_switch)) == 3
#define LL_TIM_CHANNEL LL_TIM_CHANNEL_CH3
#define LL_TIM_OC_SetCompare LL_TIM_OC_SetCompareCH3
#define LL_TIM_OC_GetCompare LL_TIM_OC_GetCompareCH3
#elif DT_PWMS_CHANNEL(DT_CHILD(DT_PATH(outputs), pwm_switch)) == 4
#define LL_TIM_CHANNEL LL_TIM_CHANNEL_CH4
#define LL_TIM_OC_SetCompare LL_TIM_OC_SetCompareCH4
#define LL_TIM_OC_GetCompare LL_TIM_OC_GetCompareCH4
#else
#error "PWM Switch channel not defined properly!"
#endif
// to check if PWM signal is high or low (not sure how to get pin config from devicetree...)
#if defined(CONFIG_BOARD_PWM_2420_LUS)
#define PWM_GPIO_PIN_HIGH (GPIOB->IDR & GPIO_IDR_ID1)
#elif defined(CONFIG_BOARD_MPPT_2420_HPX)
#define PWM_GPIO_PIN_HIGH (GPIOC->IDR & GPIO_IDR_ID7)
#endif
static const struct soc_gpio_pinctrl pwm_pinctrl[] = ST_STM32_DT_PINCTRL(pwm3, 0);
static bool _pwm_active;
static int _pwm_resolution;
static void TIM3_IRQHandler(void *args)
{
LL_TIM_ClearFlag_UPDATE(tim);
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);
}
}
void pwm_signal_init_registers(int freq_Hz)
{
stm32_dt_pinctrl_configure(pwm_pinctrl, ARRAY_SIZE(pwm_pinctrl), (uint32_t)tim);
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM3);
// Set timer clock to 10 kHz
LL_TIM_SetPrescaler(TIM3, SystemCoreClock / 10000 - 1);
LL_TIM_OC_SetMode(tim, LL_TIM_CHANNEL, LL_TIM_OCMODE_PWM1);
LL_TIM_OC_EnablePreload(tim, LL_TIM_CHANNEL);
LL_TIM_OC_SetPolarity(tim, LL_TIM_CHANNEL, LL_TIM_OCPOLARITY_HIGH);
// Interrupt on timer update
LL_TIM_EnableIT_UPDATE(tim);
// Force update generation (UG = 1)
LL_TIM_GenerateEvent_UPDATE(tim);
// set PWM frequency and resolution
_pwm_resolution = 10000 / freq_Hz;
// Period goes from 0 to ARR (including ARR value), so substract 1 clock cycle
LL_TIM_SetAutoReload(tim, _pwm_resolution - 1);
// 1 = second-highest priority of STM32L0/F0
IRQ_CONNECT(TIM3_IRQn, 1, TIM3_IRQHandler, 0, 0);
irq_enable(TIM3_IRQn);
LL_TIM_EnableCounter(tim);
}
void pwm_signal_set_duty_cycle(float duty)
{
LL_TIM_OC_SetCompare(tim, _pwm_resolution * duty);
}
void pwm_signal_duty_cycle_step(int delta)
{
uint32_t ccr_new = (int)LL_TIM_OC_GetCompare(tim) + delta;
if (ccr_new <= _pwm_resolution && ccr_new >= 0) {
LL_TIM_OC_SetCompare(tim, ccr_new);
}
}
float pwm_signal_get_duty_cycle()
{
return (float)(LL_TIM_OC_GetCompare(tim)) / _pwm_resolution;
}
void pwm_signal_start(float pwm_duty)
{
pwm_signal_set_duty_cycle(pwm_duty);
LL_TIM_CC_EnableChannel(tim, LL_TIM_CHANNEL);
_pwm_active = true;
}
void pwm_signal_stop()
{
LL_TIM_CC_DisableChannel(tim, LL_TIM_CHANNEL);
_pwm_active = false;
}
bool pwm_signal_high()
{
return PWM_GPIO_PIN_HIGH;
}
bool pwm_active()
{
return _pwm_active;
}
#else
// dummy functions for unit tests
float pwm_signal_get_duty_cycle() { return 0; }
void pwm_signal_set_duty_cycle(float duty) {;}
void pwm_signal_duty_cycle_step(int delta) {;}
void pwm_signal_init_registers(int freq_Hz) {;}
void pwm_signal_start(float pwm_duty) {;}
void pwm_signal_stop() {;}
bool pwm_signal_high() { return false; }
bool pwm_active() { return false; }
#endif
#endif /* BOARD_HAS_PWM_PORT */
+115
View File
@@ -0,0 +1,115 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
/** @file
*
* @brief Setup of ports and other essential charge controller objects
*/
#include <zephyr.h>
#include "thingset.h" // handles access to internal data via communication interfaces
#include "board.h"
#include "half_bridge.h" // PWM generation for DC/DC converter
#include "hardware.h" // hardware-related functions like load switch, LED control, watchdog, etc.
#include "dcdc.h" // DC/DC converter control (hardware independent)
#include "pwm_switch.h" // PWM charge controller
#include "bat_charger.h" // battery settings and charger state machine
#include "daq.h" // ADC using DMA and conversion to measurement values
#include "data_storage.h" // external I2C EEPROM
#include "load.h" // load and USB output management
#include "leds.h" // LED switching using charlieplexing
#include "device_status.h" // log data (error memory, min/max measurements, etc.)
#include "data_objects.h" // for access to internal data via ThingSet
DcBus lv_bus;
PowerPort lv_terminal(&lv_bus, true); // low voltage terminal (battery for typical MPPT)
#if BOARD_HAS_DCDC
DcBus hv_bus;
PowerPort hv_terminal(&hv_bus, true); // high voltage terminal (solar for typical MPPT)
#if CONFIG_HV_TERMINAL_NANOGRID
Dcdc dcdc(&hv_bus, &lv_bus, DCDC_MODE_AUTO);
#elif CONFIG_HV_TERMINAL_BATTERY
Dcdc dcdc(&hv_bus, &lv_bus, DCDC_MODE_BOOST);
#else
Dcdc dcdc(&hv_bus, &lv_bus, DCDC_MODE_BUCK);
#endif // CONFIG_HV_TERMINAL
#endif
#if BOARD_HAS_PWM_PORT
PwmSwitch pwm_switch(&lv_bus);
#endif
#if BOARD_HAS_LOAD_OUTPUT
LoadOutput load(&lv_bus, &load_out_set, &load_out_init, NULL);
#endif
#if BOARD_HAS_USB_OUTPUT
LoadOutput usb_pwr(&lv_bus, &usb_out_set, &usb_out_init, &pgood_check);
#endif
#if CONFIG_HV_TERMINAL_SOLAR
PowerPort &solar_terminal = hv_terminal;
#elif CONFIG_LV_TERMINAL_SOLAR
PowerPort &solar_terminal = lv_terminal;
#elif CONFIG_PWM_TERMINAL_SOLAR
PowerPort &solar_terminal = pwm_switch;
#endif
#if CONFIG_HV_TERMINAL_NANOGRID
PowerPort &grid_terminal = hv_terminal;
#endif
#if CONFIG_LV_TERMINAL_BATTERY
PowerPort &bat_terminal = lv_terminal;
#elif CONFIG_HV_TERMINAL_BATTERY
PowerPort &bat_terminal = hv_terminal;
#endif
Charger charger(&bat_terminal);
BatConf bat_conf; // actual (used) battery configuration
BatConf bat_conf_user; // temporary storage where the user can write to
DeviceStatus dev_stat;
// current unix timestamp (independent of time(NULL), as it is user-configurable)
// uint32_t considered large enough, so we avoid 64-bit math (overflow in year 2106)
uint32_t timestamp;
#ifndef UNIT_TEST
#include <zephyr.h>
#include <soc.h>
static inline void timestamp_inc(struct k_timer *timer_id)
{
ARG_UNUSED(timer_id);
timestamp++;
}
void setup()
{
static struct k_timer timestamp_timer;
k_timer_init(&timestamp_timer, timestamp_inc, NULL);
k_timer_start(&timestamp_timer, K_MSEC(1000), K_MSEC(1000));
/*
* printf from newlib-nano requires malloc, but Zephyr garbage-collects heap management if it
* is not used anywhere in the code. Below dummy calls force Zephyr to build with heap support.
*/
void *temp = k_malloc(4);
k_free(temp);
#ifdef CONFIG_SOC_SERIES_STM32G4X
// disable 5k pull-down required for USB-C PD on PB4 and PB6 so that they can be used as inputs
PWR->CR3 |= PWR_CR3_UCPD_DBDIS;
#endif
}
#endif
+56
View File
@@ -0,0 +1,56 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr.h>
#include <stdio.h>
#include "bat_charger.h"
#include "device_status.h"
#include "load.h"
#include "power_port.h"
#include "pwm_switch.h"
#include "thingset.h"
#include "board.h"
extern DcBus lv_bus;
extern PowerPort lv_terminal;
#if BOARD_HAS_DCDC
extern DcBus hv_bus;
extern PowerPort hv_terminal;
extern Dcdc dcdc;
#endif
#if BOARD_HAS_PWM_PORT
extern PwmSwitch pwm_switch;
#endif
extern PowerPort &bat_terminal;
extern PowerPort &solar_terminal;
extern PowerPort &grid_terminal;
extern DeviceStatus dev_stat;
extern Charger charger;
extern BatConf bat_conf;
extern BatConf bat_conf_user;
#if BOARD_HAS_LOAD_OUTPUT
extern LoadOutput load;
#endif
#if BOARD_HAS_USB_OUTPUT
extern LoadOutput usb_pwr;
#endif
extern ThingSet ts; // defined in data_objects.cpp
extern uint32_t timestamp;
/**
* Perform some device setup tasks (currently only used in Zephyr)
*/
void setup();