tests: drivers: add half-bridge loop-back tests for Nucleo-G474RE

Verify the timing of the half-bridge outputs at the pins without
requiring a charge controller, where a wrong timer configuration could
destroy the power stage.

The outputs of the half bridge are wired to two input capture channels
of a 32-bit timer (TIM2 or TIM5) on a Nucleo-G474RE board. As both
channels share the same counter, the edges of the high-side and
low-side signals can be put into chronological order to measure:

- frequency and duty cycle (incl. duty cycle limits)
- dead time at both switching transitions of each period
- overlap of high-side and low-side on-time (shoot-through)
- output states when stopped and with forced low-side switch

The test covers the advtim (TIM1), gptim (TIM3) and HRTIM drivers with
separate overlays. It requires the half_bridge_loopback fixture, so it
is only built in CI and run with a twister hardware map on a board
with the loop-back wiring.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Martin Jäger
2026-10-21 20:22:39 +02:00
co-authored by Claude Opus 5.5
parent 55d69a01b3
commit 8213ec7383
11 changed files with 829 additions and 0 deletions
@@ -0,0 +1,286 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
* Input capture of the loop-back signals using an STM32 timer
*
* Both channels of the capture timer share the same 32-bit counter, so the captured timestamps of
* the high-side and low-side signals can be compared directly. Each channel captures both edges.
* The register is polled with interrupts locked, and the signal level is read via GPIO right
* after each edge to determine its direction.
*/
#include "capture.h"
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/clock_control.h>
#include <zephyr/drivers/clock_control/stm32_clock_control.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/drivers/pinctrl.h>
#include <zephyr/irq.h>
#include <zephyr/sys/util.h>
#include <soc.h>
#include <stm32_ll_tim.h>
#define LOOPBACK_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(test_half_bridge_loopback)
#define TIMER_NODE DT_PHANDLE(LOOPBACK_NODE, capture_timer)
#define HS_CHANNEL DT_PROP(LOOPBACK_NODE, high_side_channel)
#define LS_CHANNEL DT_PROP(LOOPBACK_NODE, low_side_channel)
BUILD_ASSERT(HS_CHANNEL != LS_CHANNEL, "Capture channels must be different");
PINCTRL_DT_DEFINE(LOOPBACK_NODE);
static const struct stm32_pclken pclken[] = STM32_DT_CLOCKS(TIMER_NODE);
static TIM_TypeDef *const tim = (TIM_TypeDef *)DT_REG_ADDR(TIMER_NODE);
static const struct gpio_dt_spec hs_gpio = GPIO_DT_SPEC_GET(LOOPBACK_NODE, high_side_gpios);
static const struct gpio_dt_spec ls_gpio = GPIO_DT_SPEC_GET(LOOPBACK_NODE, low_side_gpios);
static const uint32_t ll_channels[] = {
LL_TIM_CHANNEL_CH1,
LL_TIM_CHANNEL_CH2,
LL_TIM_CHANNEL_CH3,
LL_TIM_CHANNEL_CH4,
};
static uint32_t tim_clk;
/* capture/compare registers CCR1 to CCR4 are located at consecutive addresses */
static inline volatile uint32_t *ccr(uint8_t channel)
{
return &tim->CCR1 + (channel - 1);
}
static inline uint32_t flag_captured(uint8_t channel)
{
return TIM_SR_CC1IF << (channel - 1);
}
static inline uint32_t flag_overrun(uint8_t channel)
{
return TIM_SR_CC1OF << (channel - 1);
}
static inline bool read_level(const struct gpio_dt_spec *spec)
{
gpio_port_value_t value;
gpio_port_get_raw(spec->port, &value);
return (value & BIT(spec->pin)) != 0;
}
static void configure_channel(uint8_t channel)
{
uint32_t ll_channel = ll_channels[channel - 1];
LL_TIM_IC_SetActiveInput(tim, ll_channel, LL_TIM_ACTIVEINPUT_DIRECTTI);
LL_TIM_IC_SetPrescaler(tim, ll_channel, LL_TIM_ICPSC_DIV1);
LL_TIM_IC_SetFilter(tim, ll_channel, LL_TIM_IC_FILTER_FDIV1);
LL_TIM_IC_SetPolarity(tim, ll_channel, LL_TIM_IC_POLARITY_BOTHEDGE);
LL_TIM_CC_EnableChannel(tim, ll_channel);
}
int capture_init(void)
{
const struct device *clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
int err;
if (!IS_TIM_32B_COUNTER_INSTANCE(tim)) {
return -ENOTSUP;
}
if (!device_is_ready(clk) || !gpio_is_ready_dt(&hs_gpio) || !gpio_is_ready_dt(&ls_gpio)) {
return -ENODEV;
}
err = clock_control_on(clk, (clock_control_subsys_t)&pclken[0]);
if (err < 0) {
return err;
}
err = clock_control_get_rate(clk, (clock_control_subsys_t)&pclken[1], &tim_clk);
if (err < 0) {
return err;
}
err = pinctrl_apply_state(PINCTRL_DT_DEV_CONFIG_GET(LOOPBACK_NODE), PINCTRL_STATE_DEFAULT);
if (err < 0) {
return err;
}
LL_TIM_DisableCounter(tim);
LL_TIM_SetPrescaler(tim, 0);
LL_TIM_SetCounterMode(tim, LL_TIM_COUNTERMODE_UP);
LL_TIM_SetAutoReload(tim, UINT32_MAX);
configure_channel(HS_CHANNEL);
configure_channel(LS_CHANNEL);
LL_TIM_GenerateEvent_UPDATE(tim);
LL_TIM_EnableCounter(tim);
return 0;
}
static inline void store_edge(struct capture_signal *signal, uint32_t time, bool level)
{
if (signal->num_edges < CAPTURE_MAX_EDGES) {
signal->edges[signal->num_edges].time = time;
signal->edges[signal->num_edges].level = level;
signal->num_edges++;
}
}
void capture_record(struct capture_result *result, uint32_t timeout_us)
{
uint32_t timeout_clocks = (uint64_t)tim_clk * timeout_us / 1000000;
result->hs.num_edges = 0;
result->ls.num_edges = 0;
unsigned int key = irq_lock();
/* discard edges captured before */
(void)*ccr(HS_CHANNEL);
(void)*ccr(LS_CHANNEL);
tim->SR = 0;
result->hs.level_at_start = read_level(&hs_gpio);
result->ls.level_at_start = read_level(&ls_gpio);
uint32_t start = tim->CNT;
while ((result->hs.num_edges < CAPTURE_MAX_EDGES || result->ls.num_edges < CAPTURE_MAX_EDGES)
&& tim->CNT - start < timeout_clocks)
{
uint32_t sr = tim->SR;
/* reading the capture register clears the flag */
if (sr & flag_captured(HS_CHANNEL)) {
store_edge(&result->hs, *ccr(HS_CHANNEL), read_level(&hs_gpio));
}
if (sr & flag_captured(LS_CHANNEL)) {
store_edge(&result->ls, *ccr(LS_CHANNEL), read_level(&ls_gpio));
}
}
result->hs.level_at_end = read_level(&hs_gpio);
result->ls.level_at_end = read_level(&ls_gpio);
result->overrun = (tim->SR & (flag_overrun(HS_CHANNEL) | flag_overrun(LS_CHANNEL))) != 0;
irq_unlock(key);
}
static inline uint32_t clocks_to_ns(uint32_t clocks)
{
return (uint64_t)clocks * 1000000000 / tim_clk;
}
void capture_analyze(const struct capture_result *result, struct capture_timing *timing)
{
const struct capture_signal *signals[2] = { &result->hs, &result->ls };
size_t next[2] = { 0, 0 };
int level[2] = { -1, -1 }; /* unknown until first edge */
uint32_t last_rise[2] = { 0, 0 };
bool rise_seen[2] = { false, false };
uint64_t on_sum[2] = { 0, 0 };
int on_count[2] = { 0, 0 };
uint64_t period_sum = 0;
uint32_t last_time = 0;
bool started = false;
*timing = (struct capture_timing){ 0 };
if (result->hs.num_edges == 0 || result->ls.num_edges == 0) {
return;
}
timing->deadtime_min = UINT32_MAX;
/* timestamps relative to the first edge to handle counter overflow */
uint32_t t0 = (int32_t)(result->hs.edges[0].time - result->ls.edges[0].time) <= 0
? result->hs.edges[0].time
: result->ls.edges[0].time;
/* merge edges of both signals in chronological order */
while (next[0] < signals[0]->num_edges || next[1] < signals[1]->num_edges) {
int s;
if (next[0] >= signals[0]->num_edges) {
s = 1;
}
else if (next[1] >= signals[1]->num_edges) {
s = 0;
}
else {
s = (signals[0]->edges[next[0]].time - t0 <= signals[1]->edges[next[1]].time - t0) ? 0
: 1;
}
const struct capture_edge *edge = &signals[s]->edges[next[s]++];
uint32_t time = edge->time - t0;
/* time interval since last edge with constant levels of both signals */
if (started && level[0] >= 0 && level[1] >= 0) {
uint32_t duration = time - last_time;
if (level[0] == 0 && level[1] == 0) {
timing->num_deadtimes++;
timing->deadtime_min = MIN(timing->deadtime_min, duration);
timing->deadtime_max = MAX(timing->deadtime_max, duration);
}
else if (level[0] == 1 && level[1] == 1) {
timing->overlap += duration;
}
}
if (level[s] == (int)edge->level) {
/* no level change: an edge was missed */
timing->invalid = true;
}
if (edge->level) {
if (s == 0 && rise_seen[0]) {
period_sum += time - last_rise[0];
timing->num_periods++;
}
last_rise[s] = time;
rise_seen[s] = true;
}
else if (rise_seen[s]) {
on_sum[s] += time - last_rise[s];
on_count[s]++;
}
level[s] = edge->level;
last_time = time;
started = true;
}
if (timing->num_periods > 0) {
timing->period_avg = clocks_to_ns(period_sum / timing->num_periods);
}
if (on_count[0] > 0) {
timing->hs_on_avg = clocks_to_ns(on_sum[0] / on_count[0]);
}
if (on_count[1] > 0) {
timing->ls_on_avg = clocks_to_ns(on_sum[1] / on_count[1]);
}
if (timing->num_deadtimes > 0) {
timing->deadtime_min = clocks_to_ns(timing->deadtime_min);
timing->deadtime_max = clocks_to_ns(timing->deadtime_max);
}
else {
timing->deadtime_min = 0;
}
timing->overlap = clocks_to_ns(timing->overlap);
}
@@ -0,0 +1,86 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef CAPTURE_H_
#define CAPTURE_H_
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/* maximum number of edges recorded per signal */
#define CAPTURE_MAX_EDGES 32
struct capture_edge
{
uint32_t time; /* capture timer counter value */
bool level; /* signal level after the edge */
};
struct capture_signal
{
struct capture_edge edges[CAPTURE_MAX_EDGES];
size_t num_edges;
bool level_at_start;
bool level_at_end;
};
struct capture_result
{
struct capture_signal hs;
struct capture_signal ls;
/* an edge was missed because the capture register was not read in time */
bool overrun;
};
/**
* PWM timing derived from the captured edges (all values in nanoseconds)
*/
struct capture_timing
{
/* number of complete high-side periods */
int num_periods;
uint32_t period_avg;
uint32_t hs_on_avg;
uint32_t ls_on_avg;
/* number of intervals with both outputs off (should be 2 per period) */
int num_deadtimes;
uint32_t deadtime_min;
uint32_t deadtime_max;
/* total time with both outputs on */
uint32_t overlap;
/* captured edges are inconsistent (e.g. two rising edges in a row) */
bool invalid;
};
/**
* Initialize the capture timer and apply the pin configuration of the loop-back inputs
*
* @retval 0 on success
* @retval -errno otherwise
*/
int capture_init(void);
/**
* Record edges of the high-side and low-side signal
*
* Recording stops if CAPTURE_MAX_EDGES were captured for both signals or the timeout expired.
* Interrupts are locked while recording.
*
* @param result Captured edges
* @param timeout_us Maximum recording time in microseconds
*/
void capture_record(struct capture_result *result, uint32_t timeout_us);
/**
* Calculate the PWM timing from captured edges
*
* @param result Captured edges
* @param timing Calculated timing
*/
void capture_analyze(const struct capture_result *result, struct capture_timing *timing);
#endif /* CAPTURE_H_ */
@@ -0,0 +1,193 @@
/*
* Copyright (c) The Libre Solar Project Contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
* Loop-back tests for half-bridge drivers
*
* The outputs of the half bridge are measured with input capture of a separate timer, so that the
* timing at the pins (frequency, duty cycle, dead time) can be verified without the power stage.
*/
#include <libresolar/drivers/half_bridge.h>
#include <zephyr/device.h>
#include <zephyr/kernel.h>
#include <zephyr/ztest.h>
#include "capture.h"
#define LOOPBACK_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(test_half_bridge_loopback)
#define HALF_BRIDGE_NODE DT_PHANDLE(LOOPBACK_NODE, half_bridge)
#define PERIOD_NS (1000000000U / DT_PROP(HALF_BRIDGE_NODE, frequency))
#define DEADTIME_NS DT_PROP(HALF_BRIDGE_NODE, deadtime_ns)
/* tolerance for the period (1%) */
#define PERIOD_TOLERANCE_NS (PERIOD_NS / 100)
/* tolerance for the dead time (resolution and synchronization of the capture inputs) */
#define DEADTIME_TOLERANCE_NS 30
/* the on-time of the high side may be reduced by the dead time depending on the timer type */
#define ON_TIME_TOLERANCE_NS (DEADTIME_NS + DEADTIME_TOLERANCE_NS)
#define MIN_DUTY 0.1F
#define MAX_DUTY 0.9F
/* recording time, long enough for CAPTURE_MAX_EDGES at the lowest tested frequency */
#define RECORD_TIMEOUT_US 2000
/* time to wait until a new setting is applied at the outputs (several periods) */
#define SETTLING_TIME_US 200
static const struct device *const dev = DEVICE_DT_GET(HALF_BRIDGE_NODE);
static struct capture_result result;
static struct capture_timing timing;
static void measure(void)
{
k_busy_wait(SETTLING_TIME_US);
capture_record(&result, RECORD_TIMEOUT_US);
capture_analyze(&result, &timing);
TC_PRINT("edges HS/LS: %zu/%zu, periods: %d, period: %u ns, HS on: %u ns, LS on: %u ns, "
"dead time: %u..%u ns (%d), overlap: %u ns%s%s\n",
result.hs.num_edges, result.ls.num_edges, timing.num_periods, timing.period_avg,
timing.hs_on_avg, timing.ls_on_avg, timing.deadtime_min, timing.deadtime_max,
timing.num_deadtimes, timing.overlap, result.overrun ? ", OVERRUN" : "",
timing.invalid ? ", INVALID" : "");
zassert_false(result.overrun, "capture overrun, edges were missed");
zassert_false(timing.invalid, "inconsistent edges captured");
}
static void assert_no_switching(bool hs_level, bool ls_level)
{
measure();
zassert_equal(result.hs.num_edges, 0, "high side is switching");
zassert_equal(result.ls.num_edges, 0, "low side is switching");
zassert_equal(result.hs.level_at_start, hs_level, "wrong high-side level");
zassert_equal(result.ls.level_at_start, ls_level, "wrong low-side level");
}
static void assert_pwm_timing(float duty)
{
measure();
zassert_true(timing.num_periods >= 5, "not enough periods captured");
zassert_within(timing.period_avg, PERIOD_NS, PERIOD_TOLERANCE_NS, "wrong period: %u ns",
timing.period_avg);
uint32_t hs_on_expected = duty * timing.period_avg;
zassert_within(timing.hs_on_avg, hs_on_expected, ON_TIME_TOLERANCE_NS,
"wrong high-side on-time: %u ns (expected %u ns)", timing.hs_on_avg,
hs_on_expected);
/* outputs must never be on at the same time (shoot-through) */
zassert_equal(timing.overlap, 0, "outputs overlap for %u ns", timing.overlap);
/* dead time is inserted at both switching transitions of each period */
zassert_true(timing.num_deadtimes >= 2 * timing.num_periods, "dead time missing");
zassert_true(timing.deadtime_min >= DEADTIME_NS - DEADTIME_TOLERANCE_NS,
"dead time too short: %u ns", timing.deadtime_min);
zassert_true(timing.deadtime_max <= DEADTIME_NS + DEADTIME_TOLERANCE_NS,
"dead time too long: %u ns", timing.deadtime_max);
}
static void *loopback_setup(void)
{
zassert_true(device_is_ready(dev), "half bridge not ready");
zassert_ok(capture_init(), "capture init failed");
TC_PRINT("expected period: %u ns, dead time: %u ns\n", PERIOD_NS, DEADTIME_NS);
return NULL;
}
static void loopback_before(void *fixture)
{
ARG_UNUSED(fixture);
zassert_ok(half_bridge_stop(dev));
zassert_ok(half_bridge_set_duty_limits(dev, MIN_DUTY, MAX_DUTY));
zassert_ok(half_bridge_set_duty_cycle(dev, 0.5F));
}
static void loopback_after(void *fixture)
{
ARG_UNUSED(fixture);
half_bridge_stop(dev);
}
ZTEST(half_bridge_loopback, test_outputs_off_before_start)
{
assert_no_switching(false, false);
}
ZTEST(half_bridge_loopback, test_pwm_timing_mid_duty)
{
zassert_ok(half_bridge_start(dev));
assert_pwm_timing(0.5F);
}
ZTEST(half_bridge_loopback, test_pwm_timing_low_duty)
{
zassert_ok(half_bridge_set_duty_cycle(dev, 0.2F));
zassert_ok(half_bridge_start(dev));
assert_pwm_timing(0.2F);
}
ZTEST(half_bridge_loopback, test_pwm_timing_high_duty)
{
zassert_ok(half_bridge_set_duty_cycle(dev, 0.8F));
zassert_ok(half_bridge_start(dev));
assert_pwm_timing(0.8F);
}
ZTEST(half_bridge_loopback, test_duty_change_while_running)
{
zassert_ok(half_bridge_start(dev));
zassert_ok(half_bridge_set_duty_cycle(dev, 0.3F));
assert_pwm_timing(0.3F);
}
ZTEST(half_bridge_loopback, test_duty_limits_at_outputs)
{
zassert_ok(half_bridge_start(dev));
zassert_ok(half_bridge_set_duty_cycle(dev, 0.95F));
assert_pwm_timing(MAX_DUTY);
zassert_ok(half_bridge_set_duty_cycle(dev, 0.05F));
assert_pwm_timing(MIN_DUTY);
}
ZTEST(half_bridge_loopback, test_outputs_off_after_stop)
{
zassert_ok(half_bridge_start(dev));
zassert_ok(half_bridge_stop(dev));
assert_no_switching(false, false);
}
ZTEST(half_bridge_loopback, test_force_low_side)
{
zassert_ok(half_bridge_start(dev));
zassert_ok(half_bridge_force_low_side(dev));
assert_no_switching(false, true);
}
ZTEST(half_bridge_loopback, test_outputs_off_after_forced_low_side)
{
zassert_ok(half_bridge_force_low_side(dev));
zassert_ok(half_bridge_stop(dev));
assert_no_switching(false, false);
}
ZTEST_SUITE(half_bridge_loopback, NULL, loopback_setup, loopback_before, loopback_after, NULL);