Files
Sakimi-UAV/modules/zephyr-dshot/drivers/dshot/dshot_stm32.c
T
Misaki af5987b37b first
2026-10-27 00:34:27 +08:00

886 lines
26 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* SPDX-License-Identifier: Apache-2.0
*
* STM32 的 DShot 电调协议驱动。
*
* 实现:一个定时器、最多 4 路 PWM、DMA burst 传输。DMA 把预先算好的脉宽
* 缓冲写到 TIMx->DMAR;TIMx->DCR(由 LL_TIM_ConfigDMABurst 配置)把每次
* UPDATE 事件展开成 N 个 DMA 请求(每个 CCR 一个),于是一条 DMA 流同时喂
* 4 个通道。一帧 16bit DShot = 16 个 UPDATE 事件。
*
* 设备树节点是 &timersX 的子节点(与 st,stm32-pwm 同风格),因此定时器基址、
* 时钟与预分频都取自父节点。
*/
#define DT_DRV_COMPAT misaki_dshot
#include <zephyr/device.h>
#include <zephyr/kernel.h>
#include <zephyr/drivers/clock_control.h>
#include <zephyr/drivers/clock_control/stm32_clock_control.h>
#include <zephyr/drivers/dma.h>
#include <zephyr/drivers/pinctrl.h>
#include <zephyr/drivers/dshot.h>
#include <zephyr/cache.h>
#include <zephyr/logging/log.h>
#include <stm32_ll_tim.h>
#include <stm32_ll_rcc.h>
LOG_MODULE_REGISTER(dshot, CONFIG_DSHOT_LOG_LEVEL);
#define DSHOT_FRAME_BITS 16
/* 16 位之后追加几行全零:保证帧间低电平时间,供电调重新同步。 */
#define DSHOT_GAP_ROWS 2
#define DSHOT_BUF_ROWS (DSHOT_FRAME_BITS + DSHOT_GAP_ROWS)
/*
* 双向 DShot(BDShot):16 位帧之后,电调在同一条线上回发 GCR 编码的遥测
* 回复。飞控需要:
* 1. 释放信号线(定时器通道由输出切输入);
* 2. 捕获回复边沿并解码。
*
* 本驱动两件事都做了:burst 结束后,把选中的通道切到自由运行定时器的输入
* 捕获,轮询捕获回复边沿,RLL + GCR 解码后存为 eRPM。
*
* 通过 CONFIG_DSHOT_BIDIRECTIONAL 或设备树 dshot-bidirectional 开启;
* 每帧只捕获一个通道(轮询)。
*/
#define DSHOT_BDSHOT_WINDOW_US 100 /* 遥测回复捕获窗口 */
#define DSHOT_CAPTURE_SIZE 32
#define DSHOT_CAPTURE_TICKS_PER_BIT 20u
struct dshot_stm32_config {
TIM_TypeDef *timer;
uint32_t prescaler;
struct stm32_pclken pclken;
const struct pinctrl_dev_config *pcfg;
const struct device *dma_dev;
uint32_t dma_channel;
uint32_t dma_slot;
uint32_t dma_flags;
uint32_t dshot_speed; /* kbit/s:150/300/600/1200 */
uint32_t frame_interval_us;
bool bidirectional;
};
struct dshot_stm32_data {
const struct device *dev;
/* DMA burst 缓冲:每个 UPDATE 事件一行,每个 CCR 一个字。
* 必须 32 字节对齐(H7 D-Cache 行)且 DMA 可达。定时器在 APB2,
* 其 DMA1/DMA2 能访问 SRAM/AXI SRAM,因此普通静态缓冲即可,
* 只要每次传输前刷 cache。
*/
uint32_t dma_buf[DSHOT_BUF_ROWS][DSHOT_MAX_CHANNELS] __aligned(32);
uint16_t frame_value[DSHOT_MAX_CHANNELS]; /* 0..2047 或命令 */
bool tlm_request[DSHOT_MAX_CHANNELS];
uint16_t cmd_repeats[DSHOT_MAX_CHANNELS];
uint16_t saved_throttle[DSHOT_MAX_CHANNELS];
struct dshot_output_config out_cfg;
/* 双向 DShot 捕获(轮询,每帧一个通道)。 */
uint16_t cap_buf[DSHOT_CAPTURE_SIZE];
uint32_t base_x8[DSHOT_MAX_CHANNELS];
uint8_t cap_ch;
bool erpm_valid[DSHOT_MAX_CHANNELS];
int32_t erpm[DSHOT_MAX_CHANNELS];
uint32_t capture_prescaler;
uint32_t frame_us; /* 一帧(含 gap)实际占用时间,随 dshot-speed 变 */
struct k_timer frame_timer;
struct k_work frame_work;
uint32_t pulse_0; /* '0' 位的 CCR 值 */
uint32_t pulse_1; /* '1' 位的 CCR 值 */
uint32_t period; /* ARR + 1 */
uint32_t frames; /* 已发送帧数(诊断用) */
bool running;
};
/* DShot 帧组装 */
static uint16_t dshot_compose_frame(uint16_t value, bool tlm)
{
uint16_t frame = (value << 1) | (tlm ? 1 : 0);
uint16_t csum = (frame ^ (frame >> 4) ^ (frame >> 8)) & 0x0F;
return (frame << 4) | csum;
}
/* 双向 DShot 遥测解码(PX4/BF GCR + RLL) */
static const uint32_t dshot_gcr_decode[32] = {
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x9, 0xA, 0xB, 0x0, 0xD, 0xE, 0xF,
0x0, 0x0, 0x2, 0x3, 0x0, 0x5, 0x6, 0x7,
0x0, 0x0, 0x8, 0x1, 0x0, 0x4, 0xC, 0x0
};
/* 把捕获的边沿时间戳转换成 21bit 位流。 */
static uint32_t dshot_edges_to_bits(const uint16_t *buf, unsigned n,
uint32_t *base_x8)
{
uint32_t intervals[DSHOT_CAPTURE_SIZE];
unsigned icount = 0;
unsigned previous;
if (n < 3) {
return 0;
}
previous = buf[1];
for (unsigned i = 2; i < n; i++) {
if (buf[i] == 0) {
break;
}
uint32_t interval = buf[i] - previous;
if (interval >= 10 && interval <= 100) {
intervals[icount++] = interval;
}
previous = buf[i];
}
if (icount == 0) {
return 0;
}
uint32_t min_interval = intervals[0];
for (unsigned i = 1; i < icount; i++) {
if (intervals[i] < min_interval) {
min_interval = intervals[i];
}
}
/* 自适应基准间隔,低通滤波(alpha = 1/8)。 */
*base_x8 = *base_x8 - (*base_x8 >> 3) + min_interval;
uint32_t value = 0;
uint32_t high = 1;
uint32_t shifted = 0;
uint32_t bx8 = *base_x8;
for (unsigned i = 0; i < icount; i++) {
uint32_t bits = (intervals[i] * 8 + bx8 / 2) / bx8;
if (bits < 1) {
bits = 1;
} else if (bits > 4) {
bits = 4;
}
for (unsigned b = 0; b < bits; b++) {
value = (value << 1) | high;
shifted++;
}
high = !high;
}
if (shifted < 18 || shifted > 24) {
return 0;
}
if (shifted < 21) {
value <<= (21 - shifted);
} else if (shifted > 21) {
value >>= (shifted - 21);
}
return value;
}
/* 成功返回 eRPM(>= 0),回复无效返回 -1。 */
static int32_t dshot_decode_erpm(const uint16_t *buf, unsigned n,
uint32_t *base_x8)
{
uint32_t value = dshot_edges_to_bits(buf, n, base_x8);
if (value == 0) {
return -1;
}
value = value ^ (value >> 1); /* RLL 解码 */
uint32_t payload = dshot_gcr_decode[value & 0x1f];
payload |= dshot_gcr_decode[(value >> 5) & 0x1f] << 4;
payload |= dshot_gcr_decode[(value >> 10) & 0x1f] << 8;
payload |= dshot_gcr_decode[(value >> 15) & 0x1f] << 12;
uint32_t checksum = payload;
checksum = checksum ^ (checksum >> 8);
checksum = checksum ^ (checksum >> 4);
if ((checksum & 0xF) != 0xF) {
return -1;
}
value = (payload >> 4) & 0xFFF;
if (value == 0x0FFF) {
return 0; /* 电机停转 */
}
uint32_t period = (value & 0x1FF) << ((value >> 9) & 0x7);
if (period == 0) {
return -1;
}
/* eRPM = 60e6 / period(period 单位 1us)。BF 的 decode 返回值是
* eRPM/100(配合 ERPM_PER_LSB=100 再换算 rpm),这里直接返回 eRPM。 */
return (int32_t)((1000000 * 60 + period / 2) / period);
}
static void dshot_rebuild_buffer(const struct device *dev)
{
struct dshot_stm32_data *data = dev->data;
for (int bit = 0; bit < DSHOT_FRAME_BITS; bit++) {
for (int ch = 0; ch < DSHOT_MAX_CHANNELS; ch++) {
uint16_t frame =
dshot_compose_frame(data->frame_value[ch],
data->tlm_request[ch]);
/* 高位先发 */
bool one = frame & (0x8000 >> bit);
data->dma_buf[bit][ch] =
one ? data->pulse_1 : data->pulse_0;
}
}
/* 间隔行:所有 CCR = 0 -> 线保持低电平 */
for (int row = DSHOT_FRAME_BITS; row < DSHOT_BUF_ROWS; row++) {
for (int ch = 0; ch < DSHOT_MAX_CHANNELS; ch++) {
data->dma_buf[row][ch] = 0;
}
}
/* 把缓冲刷出 D-Cache,让 DMA 看到新值。
* 无 cache 的平台上 sys_cache_data_flush_range() 是空操作。
*/
sys_cache_data_flush_range(data->dma_buf, sizeof(data->dma_buf));
}
/* 通过把定时器通道在输入(高阻,电调可驱动)与 PWM 输出之间切换,
* 释放/重新占用 4 条信号线。 */
static void __maybe_unused dshot_line_release(TIM_TypeDef *tim, bool release)
{
uint32_t c1s = release ? TIM_CCMR1_CC1S_0 : 0U;
uint32_t c2s = release ? TIM_CCMR1_CC2S_0 : 0U;
uint32_t c3s = release ? TIM_CCMR2_CC3S_0 : 0U;
uint32_t c4s = release ? TIM_CCMR2_CC4S_0 : 0U;
MODIFY_REG(tim->CCMR1, TIM_CCMR1_CC1S, c1s);
MODIFY_REG(tim->CCMR1, TIM_CCMR1_CC2S, c2s);
MODIFY_REG(tim->CCMR2, TIM_CCMR2_CC3S, c3s);
MODIFY_REG(tim->CCMR2, TIM_CCMR2_CC4S, c4s);
}
/*
* 捕获某通道电调的双向回复(轮询)。
* 帧 burst 结束后把该通道切到高速自由运行计数器的输入捕获,轮询把回复
* 边沿存进 cap_buf,然后恢复输出时序。
*/
static void dshot_bdshot_capture(struct dshot_stm32_data *data)
{
const struct dshot_stm32_config *cfg = data->dev->config;
TIM_TypeDef *tim = cfg->timer;
uint8_t ch = data->cap_ch;
unsigned n = 0;
uint32_t start, timeout;
/* 等 burst(16 位 + 间隔行)发完。 */
k_busy_wait(data->frame_us);
/* 停掉 UPDATE DMA,并把该通道切到输入捕获(双边沿、回复是反相的)以
* 释放信号线。 */
LL_TIM_DisableDMAReq_UPDATE(tim);
for (int i = 0; i < DSHOT_CAPTURE_SIZE; i++) {
data->cap_buf[i] = 0;
}
/* 四个通道全部切到“输入捕获”,释放信号线让电调回包。
* 直接写 CCMR:CCxS=01(IC)、ICxF=0(无数字滤波)、ICxPSC=0。
* 关键:不能保留 PWM 的 OCxM,否则输入模式下它会被解释成 ICxF
* 数字滤波,把回包边沿滤掉(表现为捕获 n 极小)。 */
tim->CCMR1 = 0x0101;
tim->CCMR2 = 0x0101;
LL_TIM_IC_SetPolarity(tim, LL_TIM_CHANNEL_CH1,
LL_TIM_IC_POLARITY_BOTHEDGE);
LL_TIM_IC_SetPolarity(tim, LL_TIM_CHANNEL_CH2,
LL_TIM_IC_POLARITY_BOTHEDGE);
LL_TIM_IC_SetPolarity(tim, LL_TIM_CHANNEL_CH3,
LL_TIM_IC_POLARITY_BOTHEDGE);
LL_TIM_IC_SetPolarity(tim, LL_TIM_CHANNEL_CH4,
LL_TIM_IC_POLARITY_BOTHEDGE);
/* 清掉 PWM 输出比较残留的 CCxIF,否则第一个“捕获”是输出比较值。 */
LL_TIM_ClearFlag_CC1(tim);
LL_TIM_ClearFlag_CC2(tim);
LL_TIM_ClearFlag_CC3(tim);
LL_TIM_ClearFlag_CC4(tim);
/* 用于回复时间戳的高速自由运行计数器。 */
LL_TIM_SetPrescaler(tim, data->capture_prescaler - 1U);
LL_TIM_SetAutoReload(tim, 0xFFFF);
LL_TIM_GenerateEvent_UPDATE(tim);
timeout = (uint32_t)((uint64_t)DSHOT_BDSHOT_WINDOW_US *
sys_clock_hw_cycles_per_sec() / 1000000U);
start = k_cycle_get_32();
while (n < DSHOT_CAPTURE_SIZE) {
switch (ch) {
case 0:
if (LL_TIM_IsActiveFlag_CC1(tim)) {
data->cap_buf[n++] =
LL_TIM_IC_GetCaptureCH1(tim);
LL_TIM_ClearFlag_CC1(tim);
}
break;
case 1:
if (LL_TIM_IsActiveFlag_CC2(tim)) {
data->cap_buf[n++] =
LL_TIM_IC_GetCaptureCH2(tim);
LL_TIM_ClearFlag_CC2(tim);
}
break;
case 2:
if (LL_TIM_IsActiveFlag_CC3(tim)) {
data->cap_buf[n++] =
LL_TIM_IC_GetCaptureCH3(tim);
LL_TIM_ClearFlag_CC3(tim);
}
break;
default:
if (LL_TIM_IsActiveFlag_CC4(tim)) {
data->cap_buf[n++] =
LL_TIM_IC_GetCaptureCH4(tim);
LL_TIM_ClearFlag_CC4(tim);
}
break;
}
if ((uint32_t)(k_cycle_get_32() - start) > timeout) {
break;
}
}
/* 恢复 DShot 输出时基 */
LL_TIM_SetPrescaler(tim, cfg->prescaler);
LL_TIM_SetAutoReload(tim, data->period - 1U);
LL_TIM_GenerateEvent_UPDATE(tim);
/* 恢复 4 通道为 PWM1 输出:先清掉 BOTHEDGE 极性(CCxP/CCxNP),
* 再写回 OCxM=PWM1 + OCxPE + CCxS=0。不清极性会让 PWM 反相(不 arm)。 */
tim->CCER &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P |
TIM_CCER_CC2NP | TIM_CCER_CC3P | TIM_CCER_CC3NP |
TIM_CCER_CC4P | TIM_CCER_CC4NP);
tim->CCMR1 = 0x6868; /* OCxM=110(PWM1) | OCxPE | CCxS=00 */
tim->CCMR2 = 0x6868;
LL_TIM_ClearFlag_CC1(tim);
LL_TIM_ClearFlag_CC2(tim);
LL_TIM_ClearFlag_CC3(tim);
LL_TIM_ClearFlag_CC4(tim);
int32_t erpm = dshot_decode_erpm(data->cap_buf, n, &data->base_x8[ch]);
if (erpm >= 0) {
data->erpm[ch] = erpm;
data->erpm_valid[ch] = true;
}
LOG_DBG("bdshot ch%u: n=%u erpm=%d ticks[%u %u %u %u]", ch, n, erpm,
(unsigned)data->cap_buf[0], (unsigned)data->cap_buf[1],
(unsigned)data->cap_buf[2], (unsigned)data->cap_buf[3]);
data->cap_ch = (ch + 1) % DSHOT_MAX_CHANNELS;
}
/* 周期帧发送 */
static void dshot_frame_work_handler(struct k_work *work)
{
struct dshot_stm32_data *data =
CONTAINER_OF(work, struct dshot_stm32_data, frame_work);
const struct device *dev = data->dev;
const struct dshot_stm32_config *cfg = dev->config;
/* 处理待重复的命令 */
for (int ch = 0; ch < DSHOT_MAX_CHANNELS; ch++) {
if (data->cmd_repeats[ch] > 0) {
data->cmd_repeats[ch]--;
if (data->cmd_repeats[ch] == 0) {
data->frame_value[ch] =
data->saved_throttle[ch];
data->tlm_request[ch] = false;
}
}
}
dshot_rebuild_buffer(dev);
/* 重装序列(对齐 PX4 dshot.c):重装期间先关掉定时器的 update DMA 请求,
* dma_start 之后再开。若 UDE 开着重装,DMA 可能在 burst 中途响应一个旧
* 请求,使 CCR burst 错位一位、破坏帧。
*/
LL_TIM_DisableDMAReq_UPDATE(cfg->timer);
int ret = dma_reload(cfg->dma_dev, cfg->dma_channel,
(uintptr_t)data->dma_buf,
(uintptr_t)&cfg->timer->DMAR,
sizeof(data->dma_buf));
if (ret < 0) {
LOG_ERR("dma_reload failed: %d", ret);
LL_TIM_EnableDMAReq_UPDATE(cfg->timer);
return;
}
int ret_start = dma_start(cfg->dma_dev, cfg->dma_channel);
if (ret_start < 0) {
LOG_ERR("dma_start failed: %d", ret_start);
}
LL_TIM_EnableDMAReq_UPDATE(cfg->timer);
// 诊断:确认帧在发、DMA 在起、通道 0 帧值(前几帧 + 每秒一次)
data->frames++;
if (data->frames <= 3 || (data->frames % 1000U) == 0U) {
LOG_INF("%s: frame %u reload=%d start=%d v0=%u tlm0=%d",
dev->name, data->frames, ret, ret_start,
data->frame_value[0], data->tlm_request[0]);
}
if (cfg->bidirectional) {
dshot_bdshot_capture(data);
}
}
static void dshot_frame_timer_handler(struct k_timer *timer)
{
struct dshot_stm32_data *data =
CONTAINER_OF(timer, struct dshot_stm32_data, frame_timer);
k_work_submit(&data->frame_work);
}
/* 公共 API */
/**
* 把归一化输出映射为原始 DShot 值(PX4/BF 风格)。
* 普通:0.0=停 .. 1.0=全正转;
* 3D :-1.0=全反转、0.0=停、+1.0=全正转。
* @param cfg 输出映射配置。
* @param value 归一化输出。
* @return 原始 DShot 值(0..2047)。
*/
static uint16_t dshot_map_output(const struct dshot_output_config *cfg,
float value)
{
float idle = cfg->idle;
float mag;
if (idle < 0.0f) {
idle = 0.0f;
} else if (idle > 1.0f) {
idle = 1.0f;
}
if (value == 0.0f) {
return DSHOT_VALUE_STOP;
}
if (cfg->output_3d) {
mag = (value < 0.0f) ? -value : value;
if (mag <= cfg->deadband) {
return DSHOT_VALUE_STOP;
}
if (mag > 1.0f) {
mag = 1.0f;
}
mag = idle + mag * (1.0f - idle);
/* 正转:1048 最慢 .. 2047 最快
* 反转: 48 最慢 .. 1047 最快 */
if (value > 0.0f) {
return (uint16_t)(DSHOT_3D_FORWARD_MIN +
mag * (DSHOT_THROTTLE_MAX - DSHOT_3D_FORWARD_MIN) + 0.5f);
}
return (uint16_t)(DSHOT_THROTTLE_MIN +
mag * (DSHOT_3D_SPLIT - DSHOT_THROTTLE_MIN) + 0.5f);
}
if (value < 0.0f) {
return DSHOT_VALUE_STOP;
}
if (value > 1.0f) {
value = 1.0f;
}
value = idle + value * (1.0f - idle);
return (uint16_t)(DSHOT_THROTTLE_MIN +
value * (DSHOT_THROTTLE_MAX - DSHOT_THROTTLE_MIN) + 0.5f);
}
int dshot_set_output_config(const struct device *dev,
const struct dshot_output_config *cfg)
{
struct dshot_stm32_data *data = dev->data;
if (cfg == NULL) {
data->out_cfg.output_3d = false;
data->out_cfg.idle = 0.0f;
data->out_cfg.deadband = 0.0f;
} else {
data->out_cfg = *cfg;
}
return 0;
}
int dshot_set_output(const struct device *dev, uint8_t channel, float value)
{
struct dshot_stm32_data *data = dev->data;
uint16_t raw;
if (channel >= DSHOT_MAX_CHANNELS) {
return -EINVAL;
}
raw = dshot_map_output(&data->out_cfg, value);
data->saved_throttle[channel] = raw;
if (data->cmd_repeats[channel] == 0) {
data->frame_value[channel] = raw;
}
data->tlm_request[channel] = false;
return 0;
}
int dshot_set_throttle(const struct device *dev, uint8_t channel,
uint16_t throttle, bool telemetry_request)
{
struct dshot_stm32_data *data = dev->data;
if (channel >= DSHOT_MAX_CHANNELS) {
return -EINVAL;
}
if (throttle > DSHOT_THROTTLE_MAX) {
return -EINVAL;
}
/* 1..47 are command values */
if (throttle > 0 && throttle < DSHOT_THROTTLE_MIN) {
return -EINVAL;
}
data->saved_throttle[channel] = throttle;
if (data->cmd_repeats[channel] == 0) {
data->frame_value[channel] = throttle;
}
data->tlm_request[channel] = telemetry_request;
return 0;
}
int dshot_send_command(const struct device *dev, uint8_t channel,
enum dshot_command cmd, uint16_t repeats)
{
struct dshot_stm32_data *data = dev->data;
if (channel >= DSHOT_MAX_CHANNELS || cmd > DSHOT_CMD_MAX) {
return -EINVAL;
}
if (repeats == 0) {
repeats = 10;
}
/* 只在新命令开始时记住油门;若命令仍在重复,保留之前保存的油门,
* 否则连发两次命令会把油门恢复成命令值。
*/
if (data->cmd_repeats[channel] == 0) {
data->saved_throttle[channel] = data->frame_value[channel];
}
data->frame_value[channel] = (uint16_t)cmd;
data->tlm_request[channel] = (cmd != DSHOT_CMD_MOTOR_STOP);
data->cmd_repeats[channel] = repeats;
return 0;
}
int dshot_start(const struct device *dev)
{
struct dshot_stm32_data *data = dev->data;
const struct dshot_stm32_config *cfg = dev->config;
if (data->running) {
return 0;
}
LL_TIM_EnableCounter(cfg->timer);
k_timer_start(&data->frame_timer, K_NO_WAIT,
K_USEC(cfg->frame_interval_us));
data->running = true;
return 0;
}
int dshot_stop(const struct device *dev)
{
struct dshot_stm32_data *data = dev->data;
const struct dshot_stm32_config *cfg = dev->config;
k_timer_stop(&data->frame_timer);
dma_stop(cfg->dma_dev, cfg->dma_channel);
LL_TIM_DisableCounter(cfg->timer);
data->running = false;
return 0;
}
int dshot_get_erpm(const struct device *dev, uint8_t channel, int32_t *erpm)
{
struct dshot_stm32_data *data = dev->data;
if (channel >= DSHOT_MAX_CHANNELS || erpm == NULL) {
return -EINVAL;
}
if (!data->erpm_valid[channel]) {
return -EAGAIN;
}
*erpm = data->erpm[channel];
data->erpm_valid[channel] = false;
return 0;
}
int dshot_set_duty_permille(const struct device *dev, uint32_t t0h_permille)
{
struct dshot_stm32_data *data = dev->data;
uint32_t p0, p1;
if (t0h_permille < 100U || t0h_permille > 450U) {
return -EINVAL;
}
p0 = (data->period * t0h_permille) / 1000U;
p1 = p0 * 2U;
if (p0 == 0U || p1 >= data->period) {
return -EINVAL;
}
data->pulse_0 = p0;
data->pulse_1 = p1;
return 0;
}
/* 初始化 */
static int dshot_stm32_init(const struct device *dev)
{
const struct dshot_stm32_config *cfg = dev->config;
struct dshot_stm32_data *data = dev->data;
const struct device *clk =
DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
uint32_t tim_clk;
int ret;
data->dev = dev;
/* 1. 定时器外设时钟(取自父节点 &timersX) */
if (!device_is_ready(clk)) {
return -ENODEV;
}
ret = clock_control_on(clk, (clock_control_subsys_t)&cfg->pclken);
if (ret < 0) {
return ret;
}
ret = clock_control_get_rate(clk,
(clock_control_subsys_t)&cfg->pclken,
&tim_clk);
if (ret < 0) {
return ret;
}
/* STM32 规则:APB 预分频不为 1 时,定时器时钟是 APB 总线时钟的 2 倍。
* clock_control_get_rate() 返回的是总线时钟,这里补上倍增。
*/
switch (cfg->pclken.bus) {
case STM32_CLOCK_BUS_APB1:
if (LL_RCC_GetAPB1Prescaler() != LL_RCC_APB1_DIV_1) {
tim_clk *= 2;
}
break;
case STM32_CLOCK_BUS_APB2:
if (LL_RCC_GetAPB2Prescaler() != LL_RCC_APB2_DIV_1) {
tim_clk *= 2;
}
break;
default:
break;
}
LOG_INF("timer clock: %u Hz", tim_clk);
/* 2. 输出引脚 */
ret = pinctrl_apply_state(cfg->pcfg, PINCTRL_STATE_DEFAULT);
if (ret < 0) {
return ret;
}
/* 3. 时基:一个 DShot 位 = dshot_speed kbit/s */
uint32_t bit_freq = cfg->dshot_speed * 1000U;
uint32_t tick = tim_clk / (cfg->prescaler + 1U);
data->period = tick / bit_freq;
if (data->period < 10 || data->period > 65536) {
LOG_ERR("period %u out of range (tim_clk=%u)",
data->period, tim_clk);
return -EINVAL;
}
/* DShot 占空比,对齐 Betaflight 的 DShot bitbang:每位三个定时器状态,
* '0' 高 1/3 位周期、'1' 高 2/3。(BF: bbOutputDataInit /
* bbOutputDataSet,每符号 3 状态,'0' 在中间状态拉低。)
*/
data->pulse_0 = data->period / 3U;
data->pulse_1 = (data->period * 2U) / 3U;
/* 双向回复:电调以 DShot 位率的 5/4 发送;让捕获计数器每个回复位约 20
* 个 tick。 */
uint32_t response_cycles =
(bit_freq * 5U / 4U) * DSHOT_CAPTURE_TICKS_PER_BIT;
uint32_t cap_psc = (tim_clk + response_cycles / 2U) / response_cycles;
data->capture_prescaler = (cap_psc == 0U) ? 1U : cap_psc;
/* 一帧(16 bit + gap 行)实际时长,发包后据此等待 burst 结束。 */
data->frame_us = (DSHOT_BUF_ROWS * 1000000U + bit_freq / 2U) /
bit_freq + 5U; /* +5us 余量 */
for (int ch = 0; ch < DSHOT_MAX_CHANNELS; ch++) {
data->base_x8[ch] = DSHOT_CAPTURE_TICKS_PER_BIT * 8U;
data->erpm[ch] = 0;
data->erpm_valid[ch] = false;
}
data->cap_ch = 0;
LL_TIM_SetPrescaler(cfg->timer, cfg->prescaler);
LL_TIM_SetAutoReload(cfg->timer, data->period - 1U);
LL_TIM_SetCounterMode(cfg->timer, LL_TIM_COUNTERMODE_UP);
LL_TIM_SetRepetitionCounter(cfg->timer, 0);
LL_TIM_EnableARRPreload(cfg->timer);
/* 4. 四个通道:PWM 模式 1、预装载开、空闲低 */
LL_TIM_OC_InitTypeDef oc = {0};
oc.OCMode = LL_TIM_OCMODE_PWM1;
oc.OCState = LL_TIM_OCSTATE_ENABLE;
oc.OCNState = LL_TIM_OCSTATE_DISABLE;
oc.CompareValue = 0;
oc.OCPolarity = LL_TIM_OCPOLARITY_HIGH;
oc.OCNPolarity = LL_TIM_OCPOLARITY_HIGH;
oc.OCIdleState = LL_TIM_OCIDLESTATE_LOW;
oc.OCNIdleState = LL_TIM_OCIDLESTATE_LOW;
LL_TIM_OC_Init(cfg->timer, LL_TIM_CHANNEL_CH1, &oc);
LL_TIM_OC_Init(cfg->timer, LL_TIM_CHANNEL_CH2, &oc);
LL_TIM_OC_Init(cfg->timer, LL_TIM_CHANNEL_CH3, &oc);
LL_TIM_OC_Init(cfg->timer, LL_TIM_CHANNEL_CH4, &oc);
LL_TIM_OC_EnablePreload(cfg->timer, LL_TIM_CHANNEL_CH1);
LL_TIM_OC_EnablePreload(cfg->timer, LL_TIM_CHANNEL_CH2);
LL_TIM_OC_EnablePreload(cfg->timer, LL_TIM_CHANNEL_CH3);
LL_TIM_OC_EnablePreload(cfg->timer, LL_TIM_CHANNEL_CH4);
/* 高级定时器(TIM1/TIM8)需要主输出使能 */
LL_TIM_EnableAllOutputs(cfg->timer);
/* 5. DMA burst:每次 UPDATE 事件 -> 4 个请求(CCR1..CCR4) */
LL_TIM_ConfigDMABurst(cfg->timer,
LL_TIM_DMABURST_BASEADDR_CCR1,
LL_TIM_DMABURST_LENGTH_4TRANSFERS);
LL_TIM_EnableDMAReq_UPDATE(cfg->timer);
/* 6. Zephyr DMA 流:内存 -> TIMx->DMAR */
if (!device_is_ready(cfg->dma_dev)) {
LOG_ERR("DMA device not ready");
return -ENODEV;
}
struct dma_block_config blk = {
.source_address = (uintptr_t)data->dma_buf,
.dest_address = (uintptr_t)&cfg->timer->DMAR,
/* DMAR 是单个寄存器,外设地址不能自增。TIM 的 DCR burst 逻辑
* 会把每个字内部路由到下一个 CCR。
*/
.dest_addr_adj = DMA_ADDR_ADJ_NO_CHANGE,
.block_size = sizeof(data->dma_buf),
};
struct dma_config dma_cfg = {
.dma_slot = cfg->dma_slot,
.channel_direction = MEMORY_TO_PERIPHERAL,
.complete_callback_en = 0,
.source_data_size = 4,
.dest_data_size = 4,
.source_burst_length = DSHOT_MAX_CHANNELS,
.dest_burst_length = DSHOT_MAX_CHANNELS,
.block_count = 1,
.head_block = &blk,
};
ret = dma_config(cfg->dma_dev, cfg->dma_channel, &dma_cfg);
if (ret < 0) {
LOG_ERR("dma_config failed: %d", ret);
return ret;
}
#if defined(CONFIG_SOC_SERIES_STM32H7X)
/* 防御性:显式路由 DMAMUX 请求线。某些 dma_stm32/dmamux_stm32 版本
* 在 H7 V1 流上不会把 dma_slot 传到 mux,导致 CxCR 停留在复位值 0。
* 取值仍来自设备树(dmas cells)。
*/
{
DMAMUX_Channel_TypeDef *mux_ch =
(DMAMUX_Channel_TypeDef *)(DMAMUX1_BASE +
4U * cfg->dma_channel);
MODIFY_REG(mux_ch->CCR, DMAMUX_CxCR_DMAREQ_ID, cfg->dma_slot);
LOG_INF("DMAMUX ch%u CCR = 0x%08x (req %u)",
cfg->dma_channel, (unsigned)mux_ch->CCR, cfg->dma_slot);
}
#endif
/* 输出映射默认值(直通)。 */
data->out_cfg.output_3d = false;
data->out_cfg.idle = 0.0f;
data->out_cfg.deadband = 0.0f;
/* 7. Periodic frame engine */
k_work_init(&data->frame_work, dshot_frame_work_handler);
k_timer_init(&data->frame_timer, dshot_frame_timer_handler, NULL);
LOG_INF("DShot%u on TIM@%08x: period=%u ticks (%u Hz bit clock), "
"T0H=%u ticks, T1H=%u ticks",
cfg->dshot_speed, (unsigned)(uintptr_t)cfg->timer,
data->period, bit_freq, data->pulse_0, data->pulse_1);
return 0;
}
/* 设备树实例化 */
#define DSHOT_PARENT(inst) DT_PARENT(DT_DRV_INST(inst))
#define DSHOT_STM32_INIT(inst) \
PINCTRL_DT_INST_DEFINE(inst); \
\
static struct dshot_stm32_data dshot_data_##inst; \
\
static const struct dshot_stm32_config dshot_cfg_##inst = { \
.timer = (TIM_TypeDef *)DT_REG_ADDR(DSHOT_PARENT(inst)), \
.prescaler = DT_PROP(DSHOT_PARENT(inst), st_prescaler), \
.pclken = STM32_CLOCK_INFO(0, DSHOT_PARENT(inst)), \
.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(inst), \
.dma_dev = DEVICE_DT_GET(DT_INST_DMAS_CTLR_BY_NAME(inst, \
burst)), \
.dma_channel = DT_INST_DMAS_CELL_BY_NAME(inst, burst, \
channel), \
.dma_slot = DT_INST_DMAS_CELL_BY_NAME(inst, burst, \
slot), \
.dma_flags = DT_INST_DMAS_CELL_BY_NAME(inst, burst, \
channel_config), \
.dshot_speed = DT_INST_PROP_OR(inst, dshot_speed, 300), \
.frame_interval_us = \
DT_INST_PROP_OR(inst, frame_interval_us, 1000), \
.bidirectional = \
DT_INST_PROP_OR(inst, dshot_bidirectional, false), \
}; \
\
DEVICE_DT_INST_DEFINE(inst, dshot_stm32_init, NULL, \
&dshot_data_##inst, &dshot_cfg_##inst, \
POST_KERNEL, CONFIG_DSHOT_INIT_PRIORITY, NULL);
DT_INST_FOREACH_STATUS_OKAY(DSHOT_STM32_INIT)