app: use power switch driver for PWM switch

Replace the register-level timer code in pwm_switch_driver.c by the STM32
PWM power switch driver. The duty cycle steps of the control algorithm
are kept at 100 us on-time per step, independent of the timer resolution
of the driver.

The rising edges of the PWM signal are only reported while the switch
is on. Before, the overvoltage alert of the battery voltage was also
inhibited periodically while the switch was off.

The PWM switch is now a child node of the timer with the label
pwm_switch instead of a child of the outputs node referencing a Zephyr
PWM device. The unit tests use the emulated power switch, so that the
dummy PWM binding is not needed anymore. The obsolete kconfig-flag and
latching-pgood properties are removed from the outputs binding.

Note for out-of-tree boards: The pwm_switch child of the outputs node
must be converted to a libresolar,stm32-pwm-power-switch node below the
st,stm32-timers node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Martin Jäger
2026-11-01 14:20:21 +01:00
co-authored by Claude Opus 5.5
parent da59ab8276
commit 465a7f9ef7
13 changed files with 97 additions and 340 deletions
+1 -1
View File
@@ -73,7 +73,7 @@ endchoice
choice
prompt "PWM terminal"
depends on $(dt_node_bool_prop,/outputs/pwm_switch,kconfig-flag)
depends on $(dt_nodelabel_enabled,pwm_switch)
help
Select the device connected to the PWM switch (currently
only solar panel possible)
-1
View File
@@ -12,7 +12,6 @@ target_sources(app PRIVATE
load.cpp
main.cpp
power_port.cpp
pwm_switch_driver.c
pwm_switch.cpp
setup.cpp
)
+2 -1
View File
@@ -18,8 +18,9 @@
#define HALF_BRIDGE_NODE DT_NODELABEL(halfbridge)
#define LOAD_SWITCH_NODE DT_NODELABEL(load_switch)
#define USB_SWITCH_NODE DT_NODELABEL(usb_switch)
#define PWM_SWITCH_NODE DT_NODELABEL(pwm_switch)
#define BOARD_HAS_DCDC DT_NODE_HAS_STATUS_OKAY(HALF_BRIDGE_NODE)
#define BOARD_HAS_PWM_PORT DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), pwm_switch))
#define BOARD_HAS_PWM_PORT DT_NODE_HAS_STATUS_OKAY(PWM_SWITCH_NODE)
#define BOARD_HAS_LOAD_OUTPUT DT_NODE_HAS_STATUS_OKAY(LOAD_SWITCH_NODE)
#define BOARD_HAS_USB_OUTPUT DT_NODE_HAS_STATUS_OKAY(USB_SWITCH_NODE)
#define BOARD_HAS_TEMP_FETS DT_NODE_EXISTS(DT_CHILD(DT_PATH(adc_inputs), temp_fets))
+51 -27
View File
@@ -13,50 +13,72 @@
#include "daq.h"
#include "helper.h"
#include "mcu.h"
#include "setup.h"
#include <libresolar/drivers/power_switch.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))
#define PWM_CURRENT_MAX (DT_PROP(PWM_SWITCH_NODE, current_max))
// duty cycle step corresponding to 100 us on-time
#define PWM_DUTY_STEP (DT_PROP(PWM_SWITCH_NODE, frequency) / 10000.0F)
bool PwmSwitch::active()
{
return pwm_active();
return power_switch_is_on(power_switch);
}
bool PwmSwitch::signal_high()
{
return pwm_signal_high();
return power_switch_is_conducting(power_switch);
}
PwmSwitch::PwmSwitch(DcBus *dc_bus) : PowerPort(dc_bus)
PwmSwitch::PwmSwitch(DcBus *dc_bus, const struct device *sw) : PowerPort(dc_bus), power_switch(sw)
{
// period stored in nanoseconds
pwm_signal_init_registers(1000 * 1000 * 1000 / PWM_PERIOD);
if (!device_is_ready(power_switch)) {
LOG_ERR("PWM switch not ready");
enable = false;
return;
}
power_switch_set_callback(power_switch, POWER_SWITCH_EVENT_PWM_EDGE, pwm_edge_callback, this);
}
void PwmSwitch::pwm_edge_callback(const struct device *dev, uint32_t events, void *user_data)
{
// 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
daq_inhibit_alert(DAQ_DEV, DAQ_CH(v_low), DAQ_ALERT_UPPER, 10);
}
void PwmSwitch::duty_cycle_step(int steps)
{
// setting is ignored by the driver if the new duty cycle is out of range
power_switch_set_duty_cycle(power_switch, get_duty_cycle() + steps * PWM_DUTY_STEP);
}
void PwmSwitch::test()
{
if (pwm_active() && enable == false) {
pwm_signal_stop();
if (active() && enable == false) {
power_switch_off(power_switch);
off_timestamp = uptime();
LOG_INF("PWM test mode stop.");
}
else if (!pwm_active() && enable == true) {
else if (!active() && enable == true) {
// turning the PWM switch on creates a short voltage rise, so inhibit alerts by 50 ms
daq_inhibit_alert(DAQ_DEV, DAQ_CH(v_low), DAQ_ALERT_UPPER, 50);
pwm_signal_start(0.9F);
power_switch_set_duty_cycle(power_switch, 0.9F);
power_switch_on(power_switch);
LOG_INF("PWM test mode start.");
}
}
void PwmSwitch::control()
{
if (pwm_active()) {
if (active()) {
if (current < -0.1F) {
power_good_timestamp = uptime(); // reset the time
}
@@ -66,12 +88,12 @@ void PwmSwitch::control()
|| bus->voltage < 9.0F // not enough voltage for MOSFET drivers anymore
|| enable == false)
{
pwm_signal_stop();
power_switch_off(power_switch);
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();
power_switch_off(power_switch);
off_timestamp = uptime();
dev_stat.set_error(ERR_PWM_SWITCH_OVERVOLTAGE);
LOG_INF("PWM charger stop, overvoltage.");
@@ -84,13 +106,13 @@ void PwmSwitch::control()
// 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) {
if (get_duty_cycle() > 0.95F) {
// prevent very short off periods
pwm_signal_set_duty_cycle(0.95F);
power_switch_set_duty_cycle(power_switch, 0.95F);
}
else if (pwm_signal_get_duty_cycle() < 0.05F) {
else if (get_duty_cycle() < 0.05F) {
// prevent very short on periods and switch completely off instead
pwm_signal_stop();
power_switch_off(power_switch);
off_timestamp = uptime();
// consider this as overvoltage in order to start again with 5% duty cycle
dev_stat.set_error(ERR_PWM_SWITCH_OVERVOLTAGE);
@@ -99,18 +121,18 @@ void PwmSwitch::control()
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);
duty_cycle_step(-10);
}
}
else {
// increase power (if not yet at 100% duty cycle)
if (pwm_signal_get_duty_cycle() > 0.95F) {
if (get_duty_cycle() > 0.95F) {
// prevent very short off periods and switch completely on instead
pwm_signal_set_duty_cycle(1);
power_switch_set_duty_cycle(power_switch, 1);
}
else {
pwm_signal_duty_cycle_step(1);
duty_cycle_step(1);
}
}
@@ -131,10 +153,12 @@ void PwmSwitch::control()
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);
power_switch_set_duty_cycle(power_switch, 0.05F);
power_switch_on(power_switch);
}
else {
pwm_signal_start(1.0F);
power_switch_set_duty_cycle(power_switch, 1.0F);
power_switch_on(power_switch);
}
power_good_timestamp = uptime();
@@ -145,13 +169,13 @@ void PwmSwitch::control()
void PwmSwitch::stop()
{
pwm_signal_stop();
power_switch_off(power_switch);
off_timestamp = uptime();
}
float PwmSwitch::get_duty_cycle()
{
return pwm_signal_get_duty_cycle();
return power_switch_get_duty_cycle(power_switch);
}
#endif /* BOARD_HAS_PWM_PORT */
+21 -64
View File
@@ -22,6 +22,8 @@
#include "power_port.h"
#include <zephyr/device.h>
/**
* PWM charger type
*
@@ -30,7 +32,7 @@
class PwmSwitch : public PowerPort
{
public:
PwmSwitch(DcBus *dc_bus);
PwmSwitch(DcBus *dc_bus, const struct device *power_switch);
/**
* Main control function for the PWM switching algorithm
@@ -106,70 +108,25 @@ public:
* Last time the current through the switch was above minimum
*/
time_t power_good_timestamp;
private:
/**
* Increase or decrease the duty cycle by the specified number of steps
*
* The duty cycle is not changed if the result would be out of range.
*/
void duty_cycle_step(int steps);
/**
* Callback for the rising edges of the PWM signal
*/
static void pwm_edge_callback(const struct device *dev, uint32_t events, void *user_data);
/**
* Power switch device
*/
const struct device *power_switch;
};
#endif
#ifdef __cplusplus
extern "C" {
#endif
/**
* Read the currently set duty cycle
*
* @returns Duty cycle between 0.0 and 1.0
*/
float pwm_signal_get_duty_cycle();
/**
* Set the duty cycle of the PWM signal
*
* @param duty Duty cycle between 0.0 and 1.0
*/
void pwm_signal_set_duty_cycle(float duty);
/**
* Change raw timer capture/compare register by defined step
*
* @param delta Steps to be added/substracted from current CCR value
*/
void pwm_signal_duty_cycle_step(int delta);
/**
* Initiatializes the registers to generate the PWM signal and sets duty
* cycle limits
*
* @param freq_Hz Switching frequency in Hz
*/
void pwm_signal_init_registers(int freq_Hz);
/**
* Start the PWM generation
*
* @param duty Duty cycle between 0.0 and 1.0
*/
void pwm_signal_start(float pwm_duty);
/**
* Stop the PWM generation
*/
void pwm_signal_stop();
/**
* Check if the PWM pin voltage level is high (on-state)
*
* @returns true if pin is high, false if pin is low
*/
bool pwm_signal_high();
/**
* Check if the PWM generation is active
*
* @returns true if PWM signal generation is active
*/
bool pwm_active();
#ifdef __cplusplus
}
#endif
#endif /* PWM_SWITCH_H */
-188
View File
@@ -1,188 +0,0 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "pwm_switch.h"
#include <zephyr/kernel.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_bus.h>
#include <stm32_ll_rcc.h>
#include <stm32_ll_tim.h>
#include <soc.h>
#include <zephyr/drivers/pinctrl.h>
// 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
#define PINCTRL_NODE DT_NODELABEL(pwm3)
PINCTRL_DT_DEFINE(PINCTRL_NODE);
static const struct pinctrl_dev_config *pincfg = PINCTRL_DT_DEV_CONFIG_GET(PINCTRL_NODE);
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
daq_inhibit_alert(DAQ_DEV, DAQ_CH(v_low), DAQ_ALERT_UPPER, 10);
}
}
void pwm_signal_init_registers(int freq_Hz)
{
pinctrl_apply_state(pincfg, PINCTRL_STATE_DEFAULT);
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 */
+1 -1
View File
@@ -40,7 +40,7 @@ Dcdc dcdc(DEVICE_DT_GET(HALF_BRIDGE_NODE), &hv_bus, &lv_bus, DCDC_MODE_BUCK);
#endif
#if BOARD_HAS_PWM_PORT
PwmSwitch pwm_switch(&lv_bus);
PwmSwitch pwm_switch(&lv_bus, DEVICE_DT_GET(PWM_SWITCH_NODE));
#endif
#if BOARD_HAS_LOAD_OUTPUT
@@ -53,12 +53,6 @@
outputs {
compatible = "outputs";
pwm_switch {
pwms = <&pwm3 2 (20*1000*1000) PWM_POLARITY_NORMAL>; /* 20 ms period = 50 Hz */
current-max = <20>;
kconfig-flag; /* make node visible in Kconfig */
};
hv-out {
gpios = <&gpiob 12 GPIO_ACTIVE_LOW>;
};
@@ -238,10 +232,14 @@ uext_i2c: &i2c1 {
/* TIM3 (CH2) used for PWM power switch */
&timers3 {
status = "okay";
pwm3: pwm {
status = "okay";
pwm_switch: pwm-switch {
compatible = "libresolar,stm32-pwm-power-switch";
pinctrl-0 = <&tim3_ch2_pc7>;
pinctrl-names = "default";
channel = <2>;
frequency = <50>;
current-max = <20>;
};
};
@@ -78,14 +78,6 @@
outputs {
compatible = "outputs";
pwm_switch {
pwms = <&pwm3 4 (20*1000*1000) PWM_POLARITY_NORMAL>; /* 20 ms period = 50 Hz */
// Current reduced to 15A. Increase to 20A PCB max values
// only if attached to a big heat sink.
current-max = <15>;
kconfig-flag; /* make node visible in Kconfig */
};
boot0 {
gpios = <&gpiob 12 GPIO_ACTIVE_HIGH>;
};
@@ -211,11 +203,15 @@ uext_i2c: &i2c1 {
&timers3 {
status = "okay";
st,prescaler = <10000>;
pwm3: pwm {
status = "okay";
pwm_switch: pwm-switch {
compatible = "libresolar,stm32-pwm-power-switch";
pinctrl-0 = <&tim3_ch4_pb1>;
pinctrl-names = "default";
channel = <4>;
frequency = <50>;
/* reduced to 15A, increase to 20A PCB max value only if attached to a big heat sink */
current-max = <15>;
};
};
+4 -1
View File
@@ -174,7 +174,10 @@ Move all remaining hardware access from `app/src` into Zephyr drivers.
- [x] STM32 LPTIM backend with comparator-based short-circuit protection
(`libresolar,stm32-lptim-power-switch`, PWM 2420 LUS), needs hardware test
- [x] Load and USB outputs use the driver, `load_driver.c` removed
- [ ] PWM switch backend for PWM charge controllers (replaces `pwm_switch_driver.c`)
- [x] PWM support in the `power_switch` API
- [x] STM32 timer backend (`libresolar,stm32-pwm-power-switch`) for PWM charge controllers
(replaces `pwm_switch_driver.c`), needs hardware test
- [x] Emulated backend (`libresolar,power-switch-emul`) for tests on native_sim
- [ ] NTC thermistors via Zephyr sensor API (replaces `ntc_temp()` in `daq.cpp`)
- [ ] Bootloader entry and SoC-specific setup out of the application (`hardware.cpp`,
`setup.cpp`, `mcu.h`)
-6
View File
@@ -14,12 +14,6 @@ child-binding:
pwms:
type: phandle-array
description: PWM handle for PWM type output
latching-pgood:
type: boolean
description: Driver for latching power good pin (optional)
current-max:
type: int
description: Maximum current of driven power switch (A)
kconfig-flag:
type: boolean
description: This value can be checked by Kconfig parser using dt_node_has_bool_prop function
-18
View File
@@ -1,18 +0,0 @@
# Copyright (c) The Libre Solar Project Contributors
# SPDX-License-Identifier: Apache-2.0
description: PWM similar to STM32 for unit tests
compatible: "zephyr,dummy-pwm"
include: [pwm-controller.yaml, base.yaml]
properties:
"#pwm-cells":
const: 3
pwm-cells:
- channel
# period in terms of nanoseconds
- period
- flags
+4 -13
View File
@@ -52,12 +52,6 @@
outputs {
compatible = "outputs";
pwm_switch {
pwms = <&pwm3 2 (20*1000*1000) 0>; /* 20 ms period = 50 Hz */
current-max = <20>;
kconfig-flag; /* make node visible in Kconfig */
};
can_en {
gpios = <&gpio0 11 GPIO_ACTIVE_LOW>;
};
@@ -137,13 +131,10 @@
deadtime-ns = <300>;
};
timers3: timers {
status = "okay";
pwm3: pwm3 {
compatible = "zephyr,dummy-pwm";
#pwm-cells = <3>;
};
pwm_switch: pwm-switch {
compatible = "libresolar,power-switch-emul";
frequency = <50>;
current-max = <20>;
};
aliases {