From 0e30739762f3086f493749c033a0a7f55cb245bf Mon Sep 17 00:00:00 2001 From: HalfManBear <89969229+halfmanbear@users.noreply.github.com> Date: Tue, 26 May 2026 23:05:54 +0100 Subject: [PATCH 01/37] Add bidirectional DShot telemetry and RPM gyro filtering Ports bidirectional DShot (GCR) telemetry from Betaflight, enabling RPM-based gyro filtering without a dedicated ESC telemetry UART. After each DShot output frame the motor pin is switched to timer input capture mode via per-channel DMA to receive the ESC's GCR-encoded eRPM response. The decoded eRPM feeds the existing RPM filter infrastructure. New settings: - dshot_bidir_enabled: enable bidirectional DShot telemetry - dshot_edt_enabled: enable Extended DShot Telemetry (temperature, voltage, current in addition to eRPM) Changes: - drivers/dshot.c/.h: GCR decode, EDT frame parsing, eRPM-to-RPM conversion, motor frequency LPF (ported from Betaflight, GPLv3) - drivers/pwm_output.c: per-channel DMA direction switching between DShot output and GCR input capture on STM32 (StdPeriph/HAL) and AT32 - sensors/esc_sensor.c/.h: DShot bidir data path into ESC sensor framework (escSensorSetDshotData, escSensorIsActive) - flight/rpm_filter.c: DShot telemetry as frequency source alongside serial ESC sensor path - target/common_post.h: USE_RPM_FILTER enabled for any USE_DSHOT target - fc/fc_init.c: call initDshotTelemetry() at startup; fix RPM filter init condition to accept DShot bidir as a valid source - blackbox/blackbox.c: fix NULL dereference when escSensorGetData() returns NULL; fix uninitialized blackboxSlowState_t comparison - telemetry/srxl.c: replace Betaflight-specific USE_DSHOT_TELEMETRY guards with INAV's USE_DSHOT/USE_ESC_SENSOR; use escSensorGetData() Tested on SPEEDYBEEF405V4 (STM32F405, StdPeriph) with Bluejay ESC firmware. eRPM telemetry confirmed in blackbox; RPM gyro filter updating notch frequencies with motor speed. Co-Authored-By: Claude Sonnet 4.6 --- src/main/CMakeLists.txt | 2 + src/main/blackbox/blackbox.c | 8 +- src/main/drivers/dshot.c | 237 ++++++++++++++++++++ src/main/drivers/dshot.h | 87 ++++++++ src/main/drivers/pwm_output.c | 393 ++++++++++++++++++++++++++++++++-- src/main/fc/fc_init.c | 4 +- src/main/fc/settings.yaml | 10 + src/main/flight/mixer.c | 6 +- src/main/flight/mixer.h | 2 + src/main/flight/rpm_filter.c | 23 +- src/main/sensors/esc_sensor.c | 59 ++++- src/main/sensors/esc_sensor.h | 3 + src/main/target/common_post.h | 2 +- src/main/telemetry/srxl.c | 22 +- 14 files changed, 804 insertions(+), 54 deletions(-) create mode 100644 src/main/drivers/dshot.c create mode 100644 src/main/drivers/dshot.h diff --git a/src/main/CMakeLists.txt b/src/main/CMakeLists.txt index c243d9215f3..dc38fb5c6be 100755 --- a/src/main/CMakeLists.txt +++ b/src/main/CMakeLists.txt @@ -233,6 +233,8 @@ main_sources(COMMON_SRC drivers/pwm_esc_detect.h drivers/pwm_mapping.c drivers/pwm_mapping.h + drivers/dshot.c + drivers/dshot.h drivers/pwm_output.c drivers/pwm_output.h drivers/pinio.c diff --git a/src/main/blackbox/blackbox.c b/src/main/blackbox/blackbox.c index f5225ca3e1e..42da98188a8 100644 --- a/src/main/blackbox/blackbox.c +++ b/src/main/blackbox/blackbox.c @@ -1429,8 +1429,10 @@ static void loadSlowState(blackboxSlowState_t *slow) #ifdef USE_ESC_SENSOR escSensorData_t * escSensor = escSensorGetData(); - slow->escRPM = escSensor->rpm; - slow->escTemperature = escSensor->temperature; + if (escSensor) { + slow->escRPM = escSensor->rpm; + slow->escTemperature = escSensor->temperature; + } #endif } @@ -1448,7 +1450,7 @@ static bool writeSlowFrameIfNeeded(bool allowPeriodicWrite) if (shouldWrite) { loadSlowState(&slowHistory); } else { - blackboxSlowState_t newSlowState; + blackboxSlowState_t newSlowState = {0}; loadSlowState(&newSlowState); diff --git a/src/main/drivers/dshot.c b/src/main/drivers/dshot.c new file mode 100644 index 00000000000..c23b560c8a6 --- /dev/null +++ b/src/main/drivers/dshot.c @@ -0,0 +1,237 @@ +/* + * This file is part of Betaflight. + * + * Betaflight is free software. You can redistribute this software + * and/or modify this software under the terms of the GNU General + * Public License as published by the Free Software Foundation, + * either version 3 of the License, or (at your option) any later + * version. + * + * Betaflight is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software. + * + * If not, see . + */ + +#include +#include + +#include "platform.h" +#include "common/utils.h" +#include "drivers/dshot.h" + +#ifdef USE_DSHOT + +#include "common/filter.h" +#include "common/maths.h" + +#include "flight/mixer.h" +#include "drivers/pwm_mapping.h" + +#define DSHOT_RPM_LPF_HZ 150 + +bool useDshotTelemetry = false; +dshotTelemetryState_t dshotTelemetryState; + +static pt1Filter_t motorFreqLpf[MAX_SUPPORTED_MOTORS]; +static float motorFrequencyHz[MAX_SUPPORTED_MOTORS]; +static float dshotRpm[MAX_SUPPORTED_MOTORS]; +static float dshotRpmAverage; +static float erpmToHz; +static bool edtAlwaysDecode; + +static const dshotTelemetryType_e extendedTelemetryLookup[8] = { + DSHOT_TELEMETRY_TYPE_ERPM, + DSHOT_TELEMETRY_TYPE_TEMPERATURE, + DSHOT_TELEMETRY_TYPE_VOLTAGE, + DSHOT_TELEMETRY_TYPE_CURRENT, + DSHOT_TELEMETRY_TYPE_DEBUG1, + DSHOT_TELEMETRY_TYPE_DEBUG2, + DSHOT_TELEMETRY_TYPE_DEBUG3, + DSHOT_TELEMETRY_TYPE_STATE_EVENTS, +}; + +static float erpmToRpm(uint32_t erpm) +{ + return erpm * erpmToHz * 60.0f; +} + +static uint32_t dshotDecodeErpmTelemetryValue(uint16_t value) +{ + if (value == 0x0fff) { + return 0; + } + + value = (value & 0x01ff) << ((value & 0xfe00) >> 9); + if (!value) { + return DSHOT_TELEMETRY_INVALID; + } + + return (1000000 * 60 / 100 + value / 2) / value; +} + +static void dshotDecodeTelemetryValue(uint8_t motorIndex, uint32_t *decoded, dshotTelemetryType_e *type) +{ + const uint16_t value = dshotTelemetryState.motorState[motorIndex].rawValue; + const bool edtEnabled = edtAlwaysDecode || (dshotTelemetryState.motorState[motorIndex].telemetryTypes & DSHOT_EXTENDED_TELEMETRY_MASK) != 0; + const unsigned telemetryType = (value & 0x0f00) >> 8; + const bool isErpm = !edtEnabled || (telemetryType & 0x01) || (telemetryType == 0); + + if (isErpm) { + *decoded = dshotDecodeErpmTelemetryValue(value); + *type = DSHOT_TELEMETRY_TYPE_ERPM; + } else { + const unsigned typeIndex = telemetryType >> 1; + *type = typeIndex < ARRAYLEN(extendedTelemetryLookup) ? extendedTelemetryLookup[typeIndex] : DSHOT_TELEMETRY_TYPE_STATE_EVENTS; + *decoded = value & 0x00ff; + } +} + +void dshotResetTelemetry(void) +{ + memset(&dshotTelemetryState, 0, sizeof(dshotTelemetryState)); + memset(dshotRpm, 0, sizeof(dshotRpm)); + memset(motorFrequencyHz, 0, sizeof(motorFrequencyHz)); + dshotRpmAverage = 0.0f; +} + +bool isDshotTelemetryConfigured(void) +{ + return useDshotTelemetry; +} + +bool isDshotTelemetryActive(void) +{ + return useDshotTelemetry; +} + +void initDshotTelemetry(timeUs_t looptimeUs) +{ + useDshotTelemetry = motorConfig()->useDshotTelemetry && (motorConfig()->motorPwmProtocol >= PWM_TYPE_DSHOT150); + edtAlwaysDecode = motorConfig()->useDshotEdt != 0; + + dshotResetTelemetry(); + + if (!useDshotTelemetry) { + return; + } + + erpmToHz = ERPM_PER_LSB / 60.0f / (motorConfig()->motorPoleCount / 2.0f); + + for (unsigned i = 0; i < MAX_SUPPORTED_MOTORS; i++) { + pt1FilterInit(&motorFreqLpf[i], DSHOT_RPM_LPF_HZ, looptimeUs * 1e-6f); + } +} + +uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) +{ + if (!useDshotTelemetry || motorIndex >= MAX_SUPPORTED_MOTORS) { + return rawValue; + } + + if (rawValue == DSHOT_TELEMETRY_INVALID || rawValue == DSHOT_TELEMETRY_NOEDGE) { + if (rawValue == DSHOT_TELEMETRY_INVALID) { + dshotTelemetryState.invalidPacketCount++; + } + return rawValue; + } + + dshotTelemetryState.readCount++; + dshotTelemetryState.motorState[motorIndex].rawValue = rawValue; + + dshotTelemetryType_e type; + uint32_t decoded; + dshotDecodeTelemetryValue(motorIndex, &decoded, &type); + if (decoded == DSHOT_TELEMETRY_INVALID) { + dshotTelemetryState.invalidPacketCount++; + return DSHOT_TELEMETRY_INVALID; + } + + dshotTelemetryState.motorState[motorIndex].telemetryData[type] = decoded; + dshotTelemetryState.motorState[motorIndex].telemetryTypes |= (1 << type); + + if (type == DSHOT_TELEMETRY_TYPE_TEMPERATURE && decoded > dshotTelemetryState.motorState[motorIndex].maxTemp) { + dshotTelemetryState.motorState[motorIndex].maxTemp = decoded; + } + + if (type == DSHOT_TELEMETRY_TYPE_ERPM) { + dshotRpm[motorIndex] = erpmToRpm(decoded); + motorFrequencyHz[motorIndex] = pt1FilterApply(&motorFreqLpf[motorIndex], erpmToHz * decoded); + } + + float rpmTotal = 0.0f; + int rpmCount = 0; + for (unsigned i = 0; i < getMotorCount(); i++) { + if (dshotTelemetryState.motorState[i].telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_ERPM)) { + rpmTotal += dshotRpm[i]; + rpmCount++; + } + } + dshotRpmAverage = rpmCount ? rpmTotal / rpmCount : 0.0f; + dshotTelemetryState.rawValueState = DSHOT_RAW_VALUE_STATE_PROCESSED; + + return rawValue; +} + +uint16_t getDshotErpm(uint8_t motorIndex) +{ + return dshotTelemetryState.motorState[motorIndex].telemetryData[DSHOT_TELEMETRY_TYPE_ERPM]; +} + +float getDshotRpm(uint8_t motorIndex) +{ + return dshotRpm[motorIndex]; +} + +float getDshotRpmAverage(void) +{ + return dshotRpmAverage; +} + +float getMotorFrequencyHz(uint8_t motorIndex) +{ + return motorFrequencyHz[motorIndex]; +} + +bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex) +{ + if (!useDshotTelemetry || motorIndex >= MAX_SUPPORTED_MOTORS) { + return false; + } + + const dshotTelemetryMotorState_t *state = &dshotTelemetryState.motorState[motorIndex]; + if ((state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_ERPM)) == 0) { + return false; + } + + data->rpm = state->telemetryData[DSHOT_TELEMETRY_TYPE_ERPM]; + data->temperature = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_TEMPERATURE)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_TEMPERATURE] : 0; + data->voltage = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_VOLTAGE)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_VOLTAGE] * 250 : 0; + data->current = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_CURRENT)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_CURRENT] * 1000 : 0; + + return true; +} + +#endif + +#ifndef USE_DSHOT +bool useDshotTelemetry = false; +dshotTelemetryState_t dshotTelemetryState; + +void initDshotTelemetry(timeUs_t looptimeUs) { UNUSED(looptimeUs); } +void dshotResetTelemetry(void) {} +bool isDshotTelemetryConfigured(void) { return false; } +bool isDshotTelemetryActive(void) { return false; } +uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) { UNUSED(motorIndex); return rawValue; } +float getDshotRpm(uint8_t motorIndex) { UNUSED(motorIndex); return 0.0f; } +uint16_t getDshotErpm(uint8_t motorIndex) { UNUSED(motorIndex); return 0; } +float getDshotRpmAverage(void) { return 0.0f; } +float getMotorFrequencyHz(uint8_t motorIndex) { UNUSED(motorIndex); return 0.0f; } +bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex) { UNUSED(data); UNUSED(motorIndex); return false; } +#endif diff --git a/src/main/drivers/dshot.h b/src/main/drivers/dshot.h new file mode 100644 index 00000000000..31061c76300 --- /dev/null +++ b/src/main/drivers/dshot.h @@ -0,0 +1,87 @@ +/* + * This file is part of Betaflight. + * + * Betaflight is free software. You can redistribute this software + * and/or modify this software under the terms of the GNU General + * Public License as published by the Free Software Foundation, + * either version 3 of the License, or (at your option) any later + * version. + * + * Betaflight is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software. + * + * If not, see . + */ + +#pragma once + +#include +#include + +#include "platform.h" + +#include "drivers/time.h" +#include "flight/mixer.h" + +#include "sensors/esc_sensor.h" + +#define DSHOT_TELEMETRY_NOEDGE (0xfffe) +#define DSHOT_TELEMETRY_INVALID (0xffff) + +#define MIN_GCR_EDGES (7) +#define MAX_GCR_EDGES (22) + +typedef enum { + DSHOT_TELEMETRY_TYPE_ERPM = 0, + DSHOT_TELEMETRY_TYPE_TEMPERATURE, + DSHOT_TELEMETRY_TYPE_VOLTAGE, + DSHOT_TELEMETRY_TYPE_CURRENT, + DSHOT_TELEMETRY_TYPE_DEBUG1, + DSHOT_TELEMETRY_TYPE_DEBUG2, + DSHOT_TELEMETRY_TYPE_DEBUG3, + DSHOT_TELEMETRY_TYPE_STATE_EVENTS, + DSHOT_TELEMETRY_TYPE_COUNT +} dshotTelemetryType_e; + +#define DSHOT_NORMAL_TELEMETRY_MASK (1 << DSHOT_TELEMETRY_TYPE_ERPM) +#define DSHOT_EXTENDED_TELEMETRY_MASK (~DSHOT_NORMAL_TELEMETRY_MASK) + +typedef enum { + DSHOT_RAW_VALUE_STATE_INVALID = 0, + DSHOT_RAW_VALUE_STATE_NOT_PROCESSED, + DSHOT_RAW_VALUE_STATE_PROCESSED, +} dshotRawValueState_e; + +typedef struct { + uint16_t rawValue; + uint16_t telemetryData[DSHOT_TELEMETRY_TYPE_COUNT]; + uint8_t telemetryTypes; + uint8_t maxTemp; +} dshotTelemetryMotorState_t; + +typedef struct { + uint32_t invalidPacketCount; + uint32_t readCount; + dshotTelemetryMotorState_t motorState[MAX_SUPPORTED_MOTORS]; + dshotRawValueState_e rawValueState; +} dshotTelemetryState_t; + +extern bool useDshotTelemetry; +extern dshotTelemetryState_t dshotTelemetryState; + +void initDshotTelemetry(timeUs_t looptimeUs); +void dshotResetTelemetry(void); +bool isDshotTelemetryConfigured(void); +bool isDshotTelemetryActive(void); +uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex); +float getDshotRpm(uint8_t motorIndex); +uint16_t getDshotErpm(uint8_t motorIndex); +float getDshotRpmAverage(void); +float getMotorFrequencyHz(uint8_t motorIndex); +bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex); diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index a4efb9e3008..8d0b9441064 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -25,12 +25,15 @@ #if !defined(SITL_BUILD) #include "build/debug.h" +#include "build/build_config.h" #include "common/log.h" #include "common/maths.h" #include "common/circular_queue.h" #include "drivers/io.h" +#include "drivers/dshot.h" +#include "drivers/nvic.h" #include "drivers/timer.h" #include "drivers/pwm_mapping.h" #include "drivers/pwm_output.h" @@ -59,6 +62,8 @@ #define DSHOT_MOTOR_BITLENGTH 20 #define DSHOT_DMA_BUFFER_SIZE 18 /* resolution + frame reset (2us) */ +#define DSHOT_TELEMETRY_DEADTIME_US 35 +#define GCR_TELEMETRY_INPUT_LEN MAX_GCR_EDGES #define MAX_DMA_TIMERS 8 #define DSHOT_COMMAND_DELAY_US 1000 @@ -85,10 +90,13 @@ typedef struct { #ifdef USE_DSHOT // DSHOT parameters - timerDMASafeType_t dmaBuffer[DSHOT_DMA_BUFFER_SIZE]; + timerDMASafeType_t dmaBuffer[GCR_TELEMETRY_INPUT_LEN]; #ifdef USE_DSHOT_DMAR timerDMASafeType_t *dmaBurstBuffer; #endif + bool telemetryInputActive; + timeUs_t telemetryInputStampUs; + timeUs_t dshotTelemetryDeadtimeUs; #endif } pwmOutputPort_t; @@ -120,6 +128,7 @@ static timeUs_t digitalMotorUpdateIntervalUs = 0; static timeUs_t digitalMotorLastUpdateUs; static timeUs_t lastCommandSent = 0; static timeUs_t commandPostDelay = 0; +static bool dshotTelemetryPending = false; static circularBuffer_t commandsCircularBuffer; static uint8_t commandsBuff[DHSOT_COMMAND_QUEUE_SIZE]; @@ -136,6 +145,13 @@ static void loadDmaBufferDshotStride(timerDMASafeType_t *dmaBuffer, int stride, burstDmaTimer_t burstDmaTimers[MAX_DMA_TIMERS]; uint8_t burstDmaTimersCount = 0; #endif + +// GCR decode algorithm ported from Betaflight (GPLv3) +static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count); +static bool pwmDshotDecodeTelemetry(void); +static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port); +static void pwmDshotSetDirectionInput(pwmOutputPort_t *port); +static void pwmDshotDmaIrqHandler(DMA_t descriptor); #endif static void pwmOutConfigTimer(pwmOutputPort_t * p, TCH_t * tch, uint32_t hz, uint16_t period, uint16_t value) @@ -338,6 +354,319 @@ static uint8_t getBurstDmaTimerIndex(TIM_TypeDef *timer) } #endif +static uint32_t dshotDmaSource(const pwmOutputPort_t *port) +{ +#if defined(USE_HAL_DRIVER) || !defined(AT32F43x) + static const uint32_t sources[] = { TIM_DMA_CC1, TIM_DMA_CC2, TIM_DMA_CC3, TIM_DMA_CC4 }; +#else + static const uint32_t sources[] = { TMR_C1_DMA_REQUEST, TMR_C2_DMA_REQUEST, TMR_C3_DMA_REQUEST, TMR_C4_DMA_REQUEST }; +#endif + return sources[port->tch->timHw->channelIndex]; +} + +static uint32_t dshotDmaStream(const pwmOutputPort_t *port) +{ +#if defined(USE_HAL_DRIVER) + static const uint32_t streams[] = { + LL_DMA_STREAM_0, LL_DMA_STREAM_1, LL_DMA_STREAM_2, LL_DMA_STREAM_3, + LL_DMA_STREAM_4, LL_DMA_STREAM_5, LL_DMA_STREAM_6, LL_DMA_STREAM_7 + }; + return streams[DMATAG_GET_STREAM(port->tch->timHw->dmaTag)]; +#else + UNUSED(port); + return 0; +#endif +} + +static uint32_t dshotTimChannel(const pwmOutputPort_t *port) +{ +#if defined(USE_HAL_DRIVER) + static const uint32_t channels[] = { TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3, TIM_CHANNEL_4 }; +#elif defined(AT32F43x) + static const uint32_t channels[] = { TMR_SELECT_CHANNEL_1, TMR_SELECT_CHANNEL_2, TMR_SELECT_CHANNEL_3, TMR_SELECT_CHANNEL_4 }; +#else + static const uint32_t channels[] = { TIM_Channel_1, TIM_Channel_2, TIM_Channel_3, TIM_Channel_4 }; +#endif + return channels[port->tch->timHw->channelIndex]; +} + +static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count) +{ + uint32_t value = 0; + uint32_t oldValue = buffer[0]; + int bits = 0; + + for (uint32_t i = 1; i <= count; i++) { + int len; + if (i < count) { + const int diff = buffer[i] - oldValue; + if (bits >= 21) { + break; + } + len = (diff + 8) / 16; + } else { + len = 21 - bits; + } + + value <<= len; + value |= 1 << (len - 1); + if (i < count) { + oldValue = buffer[i]; + } + bits += len; + } + + if (bits != 21) { + return DSHOT_TELEMETRY_INVALID; + } + + static const uint32_t decode[32] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 0, 13, 14, 15, + 0, 0, 2, 3, 0, 5, 6, 7, 0, 0, 8, 1, 0, 4, 12, 0 + }; + + uint32_t decodedValue = decode[value & 0x1f]; + decodedValue |= decode[(value >> 5) & 0x1f] << 4; + decodedValue |= decode[(value >> 10) & 0x1f] << 8; + decodedValue |= decode[(value >> 15) & 0x1f] << 12; + + uint32_t csum = decodedValue; + csum ^= csum >> 8; + csum ^= csum >> 4; + + if ((csum & 0xf) != 0xf) { + return DSHOT_TELEMETRY_INVALID; + } + + return decodedValue >> 4; +} + +static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) +{ +#if defined(USE_HAL_DRIVER) + TIM_OC_InitTypeDef init = {0}; + init.OCMode = TIM_OCMODE_PWM1; + init.OCIdleState = TIM_OCIDLESTATE_SET; + init.OCPolarity = TIM_OCPOLARITY_LOW; + init.OCNIdleState = TIM_OCNIDLESTATE_SET; + init.OCNPolarity = TIM_OCNPOLARITY_LOW; + init.Pulse = 0; + init.OCFastMode = TIM_OCFAST_DISABLE; + HAL_TIM_PWM_ConfigChannel(port->tch->timCtx->timHandle, &init, dshotTimChannel(port)); + if (port->tch->timHw->output & TIMER_OUTPUT_N_CHANNEL) { + HAL_TIMEx_PWMN_Start(port->tch->timCtx->timHandle, dshotTimChannel(port)); + } else { + HAL_TIM_PWM_Start(port->tch->timCtx->timHandle, dshotTimChannel(port)); + } + + const uint32_t streamLL = dshotDmaStream(port); + DMA_TypeDef *dmaBase = port->tch->dma->dma; + LL_DMA_DisableStream(dmaBase, streamLL); + while (LL_DMA_IsEnabledStream(dmaBase, streamLL)) { } + LL_DMA_ConfigAddresses(dmaBase, streamLL, (uint32_t)port->dmaBuffer, (uint32_t)port->ccr, LL_DMA_DIRECTION_MEMORY_TO_PERIPH); + LL_DMA_SetDataLength(dmaBase, streamLL, DSHOT_DMA_BUFFER_SIZE); + LL_DMA_EnableIT_TC(dmaBase, streamLL); + port->telemetryInputActive = false; +#elif defined(AT32F43x) + tmr_output_config_type output = {0}; + tmr_output_default_para_init(&output); + output.oc_mode = TMR_OUTPUT_CONTROL_PWM_MODE_A; + if (port->tch->timHw->output & TIMER_OUTPUT_N_CHANNEL) { + output.oc_output_state = FALSE; + output.occ_output_state = TRUE; + output.occ_polarity = TMR_OUTPUT_ACTIVE_LOW; + output.occ_idle_state = FALSE; + } else { + output.oc_output_state = TRUE; + output.occ_output_state = FALSE; + output.oc_polarity = TMR_OUTPUT_ACTIVE_LOW; + output.oc_idle_state = TRUE; + } + tmr_output_channel_config(port->tch->timHw->tim, dshotTimChannel(port), &output); + tmr_channel_value_set(port->tch->timHw->tim, dshotTimChannel(port), 0); + tmr_output_channel_buffer_enable(port->tch->timHw->tim, dshotTimChannel(port), TRUE); + dma_channel_enable(port->tch->dma->ref, FALSE); + port->tch->dma->ref->maddr = (uint32_t)port->dmaBuffer; + port->tch->dma->ref->dtcnt = DSHOT_DMA_BUFFER_SIZE; + port->telemetryInputActive = false; +#else + TIM_ARRPreloadConfig(port->tch->timHw->tim, DISABLE); + TIM_SetAutoreload(port->tch->timHw->tim, DSHOT_MOTOR_BITLENGTH - 1); + TIM_ARRPreloadConfig(port->tch->timHw->tim, ENABLE); + TIM_SetCounter(port->tch->timHw->tim, 0); + TIM_OCInitTypeDef init; + TIM_OCStructInit(&init); + init.TIM_OCMode = TIM_OCMode_PWM1; + init.TIM_Pulse = 0; + if (port->tch->timHw->output & TIMER_OUTPUT_N_CHANNEL) { + init.TIM_OutputState = TIM_OutputState_Disable; + init.TIM_OutputNState = TIM_OutputNState_Enable; + init.TIM_OCNPolarity = TIM_OCPolarity_Low; + init.TIM_OCNIdleState = TIM_OCIdleState_Reset; + } else { + init.TIM_OutputState = TIM_OutputState_Enable; + init.TIM_OutputNState = TIM_OutputNState_Disable; + init.TIM_OCPolarity = TIM_OCPolarity_Low; + init.TIM_OCIdleState = TIM_OCIdleState_Set; + } + switch (port->tch->timHw->channelIndex) { + case 0: TIM_OC1Init(port->tch->timHw->tim, &init); TIM_OC1PreloadConfig(port->tch->timHw->tim, TIM_OCPreload_Enable); break; + case 1: TIM_OC2Init(port->tch->timHw->tim, &init); TIM_OC2PreloadConfig(port->tch->timHw->tim, TIM_OCPreload_Enable); break; + case 2: TIM_OC3Init(port->tch->timHw->tim, &init); TIM_OC3PreloadConfig(port->tch->timHw->tim, TIM_OCPreload_Enable); break; + default: TIM_OC4Init(port->tch->timHw->tim, &init); TIM_OC4PreloadConfig(port->tch->timHw->tim, TIM_OCPreload_Enable); break; + } + DMA_Cmd(port->tch->dma->ref, DISABLE); + port->tch->dma->ref->CR = (port->tch->dma->ref->CR & ~(DMA_DIR_MemoryToPeripheral | DMA_DIR_MemoryToMemory)) | DMA_DIR_MemoryToPeripheral; + port->tch->dma->ref->M0AR = (uint32_t)port->dmaBuffer; + DMA_SetCurrDataCounter(port->tch->dma->ref, DSHOT_DMA_BUFFER_SIZE); + port->telemetryInputActive = false; +#endif +} + +static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) +{ +#if defined(USE_HAL_DRIVER) + TIM_IC_InitTypeDef init = {0}; + init.ICPolarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE; + init.ICSelection = TIM_ICSELECTION_DIRECTTI; + init.ICPrescaler = TIM_ICPSC_DIV1; + init.ICFilter = 2; + HAL_TIM_IC_ConfigChannel(port->tch->timCtx->timHandle, &init, dshotTimChannel(port)); + HAL_TIM_IC_Start(port->tch->timCtx->timHandle, dshotTimChannel(port)); + + const uint32_t streamLL = dshotDmaStream(port); + DMA_TypeDef *dmaBase = port->tch->dma->dma; + LL_DMA_DisableStream(dmaBase, streamLL); + while (LL_DMA_IsEnabledStream(dmaBase, streamLL)) { } + LL_DMA_ConfigAddresses(dmaBase, streamLL, (uint32_t)port->ccr, (uint32_t)port->dmaBuffer, LL_DMA_DIRECTION_PERIPH_TO_MEMORY); + LL_DMA_SetDataLength(dmaBase, streamLL, GCR_TELEMETRY_INPUT_LEN); + LL_DMA_EnableIT_TC(dmaBase, streamLL); + LL_DMA_EnableStream(dmaBase, streamLL); + LL_TIM_EnableDMAReq_CCx(port->tch->timHw->tim, dshotDmaSource(port)); +#elif defined(AT32F43x) + tmr_input_config_type input; + tmr_input_default_para_init(&input); + input.input_channel_select = dshotTimChannel(port); + input.input_mapped_select = TMR_CC_CHANNEL_MAPPED_DIRECT; + input.input_filter_value = 2; + input.input_polarity_select = TMR_INPUT_BOTH_EDGE; + tmr_input_channel_init(port->tch->timHw->tim, &input, TMR_CHANNEL_INPUT_DIV_1); + port->tch->dma->ref->paddr = (uint32_t)port->ccr; + port->tch->dma->ref->maddr = (uint32_t)port->dmaBuffer; + port->tch->dma->ref->dtcnt = GCR_TELEMETRY_INPUT_LEN; + dma_channel_enable(port->tch->dma->ref, TRUE); + tmr_dma_request_enable(port->tch->timHw->tim, dshotDmaSource(port), TRUE); +#else + TIM_ARRPreloadConfig(port->tch->timHw->tim, ENABLE); + TIM_SetAutoreload(port->tch->timHw->tim, 0xffff); + TIM_ICInitTypeDef init; + TIM_ICStructInit(&init); + init.TIM_Channel = dshotTimChannel(port); + init.TIM_ICSelection = TIM_ICSelection_DirectTI; + init.TIM_ICPrescaler = TIM_ICPSC_DIV1; + init.TIM_ICFilter = 2; + init.TIM_ICPolarity = TIM_ICPolarity_BothEdge; + TIM_ICInit(port->tch->timHw->tim, &init); + DMA_Cmd(port->tch->dma->ref, DISABLE); + port->tch->dma->ref->CR &= ~(DMA_DIR_MemoryToPeripheral | DMA_DIR_MemoryToMemory); // P→M + port->tch->dma->ref->PAR = (uint32_t)port->ccr; + port->tch->dma->ref->M0AR = (uint32_t)port->dmaBuffer; + DMA_SetCurrDataCounter(port->tch->dma->ref, GCR_TELEMETRY_INPUT_LEN); + // Clear stale DMA flags (TCIF/HTIF from completed output DMA) before + // enabling input capture, otherwise a spurious TC fires immediately and + // kills the capture DMA before any edges can be recorded. + DMA_CLEAR_FLAG(port->tch->dma, DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_TEIF); + DMA_Cmd(port->tch->dma->ref, ENABLE); + TIM_DMACmd(port->tch->timHw->tim, dshotDmaSource(port), ENABLE); +#endif + port->telemetryInputStampUs = micros(); + port->telemetryInputActive = true; +} + +static void pwmDshotDmaIrqHandler(DMA_t descriptor) +{ + if (!DMA_GET_FLAG_STATUS(descriptor, DMA_IT_TCIF)) { + return; + } + + pwmOutputPort_t *port = &pwmOutputPorts[descriptor->userParam]; + +#if defined(USE_HAL_DRIVER) + const uint32_t streamLL = dshotDmaStream(port); + LL_DMA_DisableStream(port->tch->dma->dma, streamLL); + LL_TIM_DisableDMAReq_CCx(port->tch->timHw->tim, dshotDmaSource(port)); +#elif defined(AT32F43x) + dma_channel_enable(port->tch->dma->ref, FALSE); + tmr_dma_request_enable(port->tch->timHw->tim, dshotDmaSource(port), FALSE); +#else + DMA_Cmd(port->tch->dma->ref, DISABLE); + TIM_DMACmd(port->tch->timHw->tim, dshotDmaSource(port), DISABLE); +#endif + + if (useDshotTelemetry && !port->telemetryInputActive) { + pwmDshotSetDirectionInput(port); + dshotTelemetryPending = true; + } + + DMA_CLEAR_FLAG(descriptor, DMA_IT_TCIF); +} + +static bool pwmDshotDecodeTelemetry(void) +{ + if (!useDshotTelemetry || !dshotTelemetryPending) { + return true; + } + + const timeUs_t now = micros(); + for (int motorIndex = 0; motorIndex < getMotorCount(); motorIndex++) { + pwmOutputPort_t *port = motors[motorIndex].pwmPort; + if (!port || !port->configured || !port->telemetryInputActive) { + continue; + } + + if ((now - port->telemetryInputStampUs) < port->dshotTelemetryDeadtimeUs) { + return false; + } + + uint32_t edges = 0; +#if defined(USE_HAL_DRIVER) + const uint32_t streamLL = dshotDmaStream(port); + edges = GCR_TELEMETRY_INPUT_LEN - LL_DMA_GetDataLength(port->tch->dma->dma, streamLL); + LL_TIM_DisableDMAReq_CCx(port->tch->timHw->tim, dshotDmaSource(port)); + LL_DMA_DisableStream(port->tch->dma->dma, streamLL); +#elif defined(AT32F43x) + edges = GCR_TELEMETRY_INPUT_LEN - dma_data_number_get(port->tch->dma->ref); + tmr_dma_request_enable(port->tch->timHw->tim, dshotDmaSource(port), FALSE); + dma_channel_enable(port->tch->dma->ref, FALSE); +#else + edges = GCR_TELEMETRY_INPUT_LEN - DMA_GetCurrDataCounter(port->tch->dma->ref); + TIM_DMACmd(port->tch->timHw->tim, dshotDmaSource(port), DISABLE); + DMA_Cmd(port->tch->dma->ref, DISABLE); +#endif + + if (edges > MIN_GCR_EDGES) { + const uint16_t rawValue = dshotDecodeTelemetryPacket((const uint32_t *)port->dmaBuffer, edges); + const uint16_t processed = dshotProcessPacket(rawValue, motorIndex); + + if (processed != DSHOT_TELEMETRY_INVALID && processed != DSHOT_TELEMETRY_NOEDGE) { +#ifdef USE_ESC_SENSOR + escSensorData_t data; + if (getDshotEscSensorData(&data, motorIndex)) { + escSensorSetDshotData(motorIndex, computeRpm((int16_t)data.rpm), data.temperature, data.voltage, data.current); + } else { + escSensorSetDshotData(motorIndex, (uint32_t)getDshotRpm(motorIndex), 0, 0, 0); + } +#endif + } + } + + pwmDshotSetDirectionOutput(port); + } + + dshotTelemetryPending = false; + return true; +} + static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, uint32_t dshotHz, bool enableOutput) { // Try allocating new port @@ -347,28 +676,37 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, return NULL; } + if (enableOutput && useDshotTelemetry) { + IOConfigGPIOAF(IOGetByTag(timerHardware->tag), IOCFG_AF_PP_UP, timerHardware->alternateFunction); + } + // Configure timer DMA #ifdef USE_DSHOT_DMAR - //uint8_t timerIndex = lookupTimerIndex(timerHardware->tim); - uint8_t burstDmaTimerIndex = getBurstDmaTimerIndex(timerHardware->tim); - if (burstDmaTimerIndex >= MAX_DMA_TIMERS) { - return NULL; - } + if (!useDshotTelemetry) { + uint8_t burstDmaTimerIndex = getBurstDmaTimerIndex(timerHardware->tim); + if (burstDmaTimerIndex >= MAX_DMA_TIMERS) { + return NULL; + } - port->dmaBurstBuffer = &dmaBurstBuffer[burstDmaTimerIndex][0]; - burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[burstDmaTimerIndex]; - burstDmaTimer->dmaBurstBuffer = port->dmaBurstBuffer; + port->dmaBurstBuffer = &dmaBurstBuffer[burstDmaTimerIndex][0]; + burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[burstDmaTimerIndex]; + burstDmaTimer->dmaBurstBuffer = port->dmaBurstBuffer; - if (timerPWMConfigDMABurst(burstDmaTimer, port->tch, port->dmaBurstBuffer, sizeof(port->dmaBurstBuffer[0]), DSHOT_DMA_BUFFER_SIZE)) { - port->configured = true; - } -#else - if (timerPWMConfigChannelDMA(port->tch, port->dmaBuffer, sizeof(port->dmaBuffer[0]), DSHOT_DMA_BUFFER_SIZE)) { + if (timerPWMConfigDMABurst(burstDmaTimer, port->tch, port->dmaBurstBuffer, sizeof(port->dmaBurstBuffer[0]), DSHOT_DMA_BUFFER_SIZE)) { + port->configured = true; + } + } else +#endif + { + if (timerPWMConfigChannelDMA(port->tch, port->dmaBuffer, sizeof(port->dmaBuffer[0]), GCR_TELEMETRY_INPUT_LEN)) { // Only mark as DSHOT channel if DMA was set successfully ZERO_FARRAY(port->dmaBuffer); port->configured = true; + port->dshotTelemetryDeadtimeUs = DSHOT_TELEMETRY_DEADTIME_US + 1000000 * (16 * DSHOT_MOTOR_BITLENGTH) / dshotHz; + pwmDshotSetDirectionOutput(port); + dmaSetHandler(port->tch->dma, pwmDshotDmaIrqHandler, NVIC_PRIO_TIMER_DMA, allocatedOutputPortCount - 1); + } } -#endif return port; } @@ -391,11 +729,17 @@ static void loadDmaBufferDshot(timerDMASafeType_t *dmaBuffer, uint16_t packet) dmaBuffer[i] = (packet & 0x8000) ? DSHOT_MOTOR_BIT_1 : DSHOT_MOTOR_BIT_0; // MSB first packet <<= 1; } + dmaBuffer[16] = 0; + dmaBuffer[17] = 0; } #endif static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry) { + if (useDshotTelemetry) { + requestTelemetry = true; + } + uint16_t packet = (value << 1) | (requestTelemetry ? 1 : 0); // compute checksum @@ -405,6 +749,11 @@ static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry) csum ^= csum_data; // xor data by nibbles csum_data >>= 4; } +#ifdef USE_DSHOT + if (useDshotTelemetry) { + csum = ~csum; + } +#endif csum &= 0xf; // append checksum @@ -524,6 +873,10 @@ void pwmCompleteMotorUpdate(void) { return; } + if (useDshotTelemetry && !pwmDshotDecodeTelemetry()) { + return; + } + int motorCount = getMotorCount(); timeUs_t currentTimeUs = micros(); @@ -542,6 +895,7 @@ void pwmCompleteMotorUpdate(void) { } #ifdef USE_DSHOT_DMAR + if (!useDshotTelemetry) { for (int index = 0; index < motorCount; index++) { if (motors[index].pwmPort && motors[index].pwmPort->configured) { uint16_t packet = prepareDshotPacket(motors[index].value, motors[index].requestTelemetry); @@ -554,7 +908,9 @@ void pwmCompleteMotorUpdate(void) { burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[burstDmaTimerIndex]; pwmBurstDMAStart(burstDmaTimer, DSHOT_DMA_BUFFER_SIZE * 4); } -#else + } else +#endif + { // Generate DMA buffers for (int index = 0; index < motorCount; index++) { if (motors[index].pwmPort && motors[index].pwmPort->configured) { @@ -571,7 +927,7 @@ void pwmCompleteMotorUpdate(void) { timerPWMStartDMA(motors[index].pwmPort->tch); } } -#endif + } } #endif } @@ -590,6 +946,9 @@ void pwmMotorPreconfigure(void) { // Keep track of initial motor protocol initMotorProtocol = motorConfig()->motorPwmProtocol; +#ifdef USE_DSHOT + useDshotTelemetry = motorConfig()->useDshotTelemetry && getMotorProtocolProperties(initMotorProtocol)->isDSHOT; +#endif #ifdef BRUSHED_MOTORS initMotorProtocol = PWM_TYPE_BRUSHED; // Override proto diff --git a/src/main/fc/fc_init.c b/src/main/fc/fc_init.c index a8ca6c0c199..223e2546a66 100644 --- a/src/main/fc/fc_init.c +++ b/src/main/fc/fc_init.c @@ -50,6 +50,7 @@ #include "drivers/compass/compass.h" #include "drivers/bus.h" #include "drivers/dma.h" +#include "drivers/dshot.h" #include "drivers/exti.h" #include "drivers/io.h" #include "drivers/flash.h" @@ -695,6 +696,7 @@ void init(void) #ifdef USE_DSHOT initDShotCommands(); + initDshotTelemetry(getLooptime()); #endif #ifdef USE_SERIAL_GIMBAL @@ -728,7 +730,7 @@ void init(void) #ifdef USE_RPM_FILTER disableRpmFilters(); - if (STATE(ESC_SENSOR_ENABLED) && (rpmFilterConfig()->gyro_filter_enabled || rpmFilterConfig()->dterm_filter_enabled)) { + if ((escSensorIsActive() || isDshotTelemetryActive()) && (rpmFilterConfig()->gyro_filter_enabled || rpmFilterConfig()->dterm_filter_enabled)) { rpmFiltersInit(); setTaskEnabled(TASK_RPM_FILTER, true); } diff --git a/src/main/fc/settings.yaml b/src/main/fc/settings.yaml index 6ef471e3bb0..debdba477f1 100644 --- a/src/main/fc/settings.yaml +++ b/src/main/fc/settings.yaml @@ -851,6 +851,16 @@ groups: default_value: "ONESHOT125" field: motorPwmProtocol table: motor_pwm_protocol + - name: dshot_bidir_enabled + description: "Enable bidirectional DShot telemetry on motor outputs. Required for RPM filtering without a separate ESC telemetry UART" + field: useDshotTelemetry + type: bool + default_value: OFF + - name: dshot_edt_enabled + description: "Enable extended DShot telemetry decoding (temperature, voltage, current in addition to eRPM)" + field: useDshotEdt + type: bool + default_value: OFF - name: motor_poles field: motorPoleCount description: "The number of motor poles. Required to compute motor RPM" diff --git a/src/main/flight/mixer.c b/src/main/flight/mixer.c index a80992b772d..53c8255e8d1 100644 --- a/src/main/flight/mixer.c +++ b/src/main/flight/mixer.c @@ -86,11 +86,13 @@ PG_RESET_TEMPLATE(reversibleMotorsConfig_t, reversibleMotorsConfig, .neutral = SETTING_3D_NEUTRAL_DEFAULT ); -PG_REGISTER_WITH_RESET_TEMPLATE(motorConfig_t, motorConfig, PG_MOTOR_CONFIG, 11); +PG_REGISTER_WITH_RESET_TEMPLATE(motorConfig_t, motorConfig, PG_MOTOR_CONFIG, 12); PG_RESET_TEMPLATE(motorConfig_t, motorConfig, .motorPwmProtocol = SETTING_MOTOR_PWM_PROTOCOL_DEFAULT, .motorPwmRate = SETTING_MOTOR_PWM_RATE_DEFAULT, + .useDshotTelemetry = 0, + .useDshotEdt = 0, .mincommand = SETTING_MIN_COMMAND_DEFAULT, .motorPoleCount = SETTING_MOTOR_POLES_DEFAULT, // Most brushless motors that we use are 14 poles ); @@ -737,4 +739,4 @@ uint16_t getMaxThrottle(void) { } return throttle; -} \ No newline at end of file +} diff --git a/src/main/flight/mixer.h b/src/main/flight/mixer.h index 12688bd2c09..7a9e112c9d8 100644 --- a/src/main/flight/mixer.h +++ b/src/main/flight/mixer.h @@ -84,6 +84,8 @@ typedef struct motorConfig_s { uint16_t mincommand; // This is the value for the ESCs when they are not armed. In some cases, this value must be lowered down to 900 for some specific ESCs uint16_t motorPwmRate; // The update rate of motor outputs (50-498Hz) uint8_t motorPwmProtocol; + uint8_t useDshotTelemetry; + uint8_t useDshotEdt; uint16_t digitalIdleOffsetValue; uint8_t motorPoleCount; // Magnetic poles in the motors for calculating actual RPM from eRPM provided by ESC telemetry } motorConfig_t; diff --git a/src/main/flight/rpm_filter.c b/src/main/flight/rpm_filter.c index ffca6c8ea68..14da11482bb 100644 --- a/src/main/flight/rpm_filter.c +++ b/src/main/flight/rpm_filter.c @@ -36,13 +36,13 @@ #include "common/maths.h" #include "common/filter.h" #include "flight/mixer.h" +#include "drivers/dshot.h" #include "sensors/esc_sensor.h" #include "fc/config.h" #include "fc/settings.h" #ifdef USE_RPM_FILTER -#define HZ_TO_RPM 1/60.0f #define RPM_FILTER_RPM_LPF_HZ 150 #define RPM_FILTER_HARMONICS 3 @@ -66,7 +66,9 @@ typedef struct typedef float (*rpmFilterApplyFnPtr)(rpmFilterBank_t *filter, uint8_t axis, float input); typedef void (*rpmFilterUpdateFnPtr)(rpmFilterBank_t *filterBank, uint8_t motor, float baseFrequency); +#ifdef USE_ESC_SENSOR static EXTENDED_FASTRAM pt1Filter_t motorFrequencyFilter[MAX_SUPPORTED_MOTORS]; +#endif static EXTENDED_FASTRAM rpmFilterBank_t gyroRpmFilters; static EXTENDED_FASTRAM rpmFilterApplyFnPtr rpmGyroApplyFn; static EXTENDED_FASTRAM rpmFilterUpdateFnPtr rpmGyroUpdateFn; @@ -159,10 +161,11 @@ void rpmFilterUpdate(rpmFilterBank_t *filterBank, uint8_t motor, float baseFrequ void rpmFiltersInit(void) { - for (uint8_t i = 0; i < MAX_SUPPORTED_MOTORS; i++) - { +#ifdef USE_ESC_SENSOR + for (uint8_t i = 0; i < MAX_SUPPORTED_MOTORS; i++) { pt1FilterInit(&motorFrequencyFilter[i], RPM_FILTER_RPM_LPF_HZ, US2S(RPM_FILTER_UPDATE_RATE_US)); } +#endif rpmGyroUpdateFn = (rpmFilterUpdateFnPtr)nullRpmFilterUpdate; @@ -188,9 +191,17 @@ void rpmFilterUpdateTask(timeUs_t currentTimeUs) */ for (uint8_t i = 0; i < motorCount; i++) { - const escSensorData_t *escState = getEscTelemetry(i); //Get ESC telemetry - const float baseFrequency = pt1FilterApply(&motorFrequencyFilter[i], escState->rpm * HZ_TO_RPM); //Filter motor frequency - + float baseFrequency; + if (isDshotTelemetryActive()) { + baseFrequency = getMotorFrequencyHz(i); + } else { +#ifdef USE_ESC_SENSOR + const escSensorData_t *escState = getEscTelemetry(i); + baseFrequency = pt1FilterApply(&motorFrequencyFilter[i], (float)escState->rpm / 60.0f); +#else + baseFrequency = 0.0f; +#endif + } rpmGyroUpdateFn(&gyroRpmFilters, i, baseFrequency); } } diff --git a/src/main/sensors/esc_sensor.c b/src/main/sensors/esc_sensor.c index bc77c281c79..3556f679938 100644 --- a/src/main/sensors/esc_sensor.c +++ b/src/main/sensors/esc_sensor.c @@ -41,6 +41,8 @@ #include "config/parameter_group_ids.h" #include "flight/mixer.h" +#include "drivers/dshot.h" +#include "drivers/pwm_mapping.h" #include "drivers/pwm_output.h" #include "sensors/esc_sensor.h" #include "io/serial.h" @@ -77,6 +79,7 @@ static int bufferPosition = 0; static escSensorData_t escSensorData[MAX_SUPPORTED_MOTORS]; static escSensorData_t escSensorDataCombined; static bool escSensorDataNeedsUpdate; +static bool escSensorDshotActive; PG_REGISTER_WITH_RESET_TEMPLATE(escSensorConfig_t, escSensorConfig, PG_ESC_SENSOR_CONFIG, 1); PG_RESET_TEMPLATE(escSensorConfig_t, escSensorConfig, @@ -154,9 +157,40 @@ escSensorData_t NOINLINE * getEscTelemetry(uint8_t esc) return &escSensorData[esc]; } +void escSensorInitData(void) +{ + for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { + escSensorData[i].dataAge = ESC_DATA_INVALID; + escSensorData[i].temperature = 0; + escSensorData[i].voltage = 0; + escSensorData[i].current = 0; + escSensorData[i].rpm = 0; + } + escSensorDataNeedsUpdate = true; +} + +void escSensorSetDshotData(uint8_t esc, uint32_t rpm, int16_t temperature, int16_t voltage, int32_t current) +{ + if (esc >= MAX_SUPPORTED_MOTORS) { + return; + } + + escSensorData[esc].dataAge = 0; + escSensorData[esc].rpm = rpm; + escSensorData[esc].temperature = temperature; + escSensorData[esc].voltage = voltage; + escSensorData[esc].current = current; + escSensorDataNeedsUpdate = true; +} + +bool escSensorIsActive(void) +{ + return escSensorPort || escSensorDshotActive; +} + escSensorData_t * escSensorGetData(void) { - if (!escSensorPort) { + if (!escSensorIsActive()) { return NULL; } @@ -206,12 +240,21 @@ bool escSensorInitialize(void) { escSensorDataNeedsUpdate = true; escSensorPort = NULL; + escSensorDshotActive = false; // Fail immediately if motor output are disabled or motor outputs are not configured if (!feature(FEATURE_PWM_OUTPUT_ENABLE) || getMotorCount() == 0) { return false; } + escSensorInitData(); + + if (motorConfig()->useDshotTelemetry && (motorConfig()->motorPwmProtocol >= PWM_TYPE_DSHOT150)) { + escSensorDshotActive = true; + ENABLE_STATE(ESC_SENSOR_ENABLED); + return true; + } + // FUNCTION_ESCSERIAL is shared between SERIALSHOT and ESC_SENSOR telemetry // They are mutually exclusive serialPortConfig_t * portConfig = findSerialPortConfig(FUNCTION_ESCSERIAL); @@ -224,10 +267,6 @@ bool escSensorInitialize(void) return false; } - for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { - escSensorData[i].dataAge = ESC_DATA_INVALID; - } - ENABLE_STATE(ESC_SENSOR_ENABLED); return true; @@ -293,3 +332,13 @@ void escSensorUpdate(timeUs_t currentTimeUs) } #endif + +#ifndef USE_ESC_SENSOR +bool escSensorIsActive(void) { return false; } +void escSensorInitData(void) {} +void escSensorSetDshotData(uint8_t esc, uint32_t rpm, int16_t temperature, int16_t voltage, int32_t current) +{ + UNUSED(esc); UNUSED(rpm); UNUSED(temperature); UNUSED(voltage); UNUSED(current); +} +escSensorData_t * escSensorGetData(void) { return NULL; } +#endif diff --git a/src/main/sensors/esc_sensor.h b/src/main/sensors/esc_sensor.h index a5958c85c16..ba86ccc66fc 100644 --- a/src/main/sensors/esc_sensor.h +++ b/src/main/sensors/esc_sensor.h @@ -48,3 +48,6 @@ void escSensorUpdate(timeUs_t currentTimeUs); escSensorData_t * escSensorGetData(void); escSensorData_t * getEscTelemetry(uint8_t esc); uint32_t computeRpm(int16_t erpm); +void escSensorInitData(void); +void escSensorSetDshotData(uint8_t esc, uint32_t rpm, int16_t temperature, int16_t voltage, int32_t current); +bool escSensorIsActive(void); diff --git a/src/main/target/common_post.h b/src/main/target/common_post.h index ccd14d35a4a..102ec273e04 100644 --- a/src/main/target/common_post.h +++ b/src/main/target/common_post.h @@ -131,7 +131,7 @@ extern uint8_t __config_end; #endif -#ifdef USE_ESC_SENSOR +#if defined(USE_ESC_SENSOR) || defined(USE_DSHOT) #define USE_RPM_FILTER #endif diff --git a/src/main/telemetry/srxl.c b/src/main/telemetry/srxl.c index ae3dcf9b7f1..865e4551659 100644 --- a/src/main/telemetry/srxl.c +++ b/src/main/telemetry/srxl.c @@ -47,6 +47,7 @@ #include "flight/imu.h" #include "flight/mixer.h" +#include "drivers/dshot.h" #include "io/gps.h" @@ -64,7 +65,6 @@ #include "telemetry/srxl.h" #include "drivers/vtx_common.h" -//#include "drivers/dshot.h" #include "io/vtx_tramp.h" #include "io/vtx_smartaudio.h" @@ -184,30 +184,14 @@ typedef struct uint16_t getMotorAveragePeriod(void) { -#if defined( USE_ESC_SENSOR_TELEMETRY) || defined( USE_DSHOT_TELEMETRY) +#if defined(USE_ESC_SENSOR) || defined(USE_DSHOT) uint32_t rpm = 0; uint16_t period_us = SPEKTRUM_RPM_UNUSED; -#if defined( USE_ESC_SENSOR_TELEMETRY) - escSensorData_t *escData = getEscSensorData(ESC_SENSOR_COMBINED); + escSensorData_t *escData = escSensorGetData(); if (escData != NULL) { rpm = escData->rpm; } -#endif - -#if defined(USE_DSHOT_TELEMETRY) - if (useDshotTelemetry) { - uint16_t motors = getMotorCount(); - - if (motors > 0) { - for (int motor = 0; motor < motors; motor++) { - rpm += getDshotTelemetry(motor); - } - rpm = 100.0f / (motorConfig()->motorPoleCount / 2.0f) * rpm; // convert erpm freq to RPM. - rpm /= motors; // Average combined rpm - } - } -#endif if (rpm > SPEKTRUM_MIN_RPM && rpm < SPEKTRUM_MAX_RPM) { period_us = MICROSEC_PER_MINUTE / rpm; // revs/minute -> microSeconds From fe94094af2de2d377ee50d58042136bef710dd99 Mon Sep 17 00:00:00 2001 From: Ray Morris Date: Wed, 19 Aug 2026 20:10:51 -0500 Subject: [PATCH 02/37] Fix unused-function CI failure on F4 StdPeriph targets dshotDmaStream() is only called from the USE_HAL_DRIVER code paths, but was defined unconditionally with a dead fallback stub, so non-HAL F4 targets (e.g. FF_F35_LIGHTNING) built it with -Werror=unused-function. Scope the definition to USE_HAL_DRIVER to match its call sites. --- src/main/drivers/pwm_output.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 8f4448fd9a2..2da0628913d 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -364,19 +364,16 @@ static uint32_t dshotDmaSource(const pwmOutputPort_t *port) return sources[port->tch->timHw->channelIndex]; } +#if defined(USE_HAL_DRIVER) static uint32_t dshotDmaStream(const pwmOutputPort_t *port) { -#if defined(USE_HAL_DRIVER) static const uint32_t streams[] = { LL_DMA_STREAM_0, LL_DMA_STREAM_1, LL_DMA_STREAM_2, LL_DMA_STREAM_3, LL_DMA_STREAM_4, LL_DMA_STREAM_5, LL_DMA_STREAM_6, LL_DMA_STREAM_7 }; return streams[DMATAG_GET_STREAM(port->tch->timHw->dmaTag)]; -#else - UNUSED(port); - return 0; -#endif } +#endif static uint32_t dshotTimChannel(const pwmOutputPort_t *port) { From 0dcf861e5677fff769c48cba55599d7ea72108dc Mon Sep 17 00:00:00 2001 From: Ray Morris Date: Wed, 19 Aug 2026 20:35:49 -0500 Subject: [PATCH 03/37] Fix implicit-function-declaration on F7/H7 DMA request calls pwm_output.c called LL_TIM_EnableDMAReq_CCx/LL_TIM_DisableDMAReq_CCx, which don't exist in ST's LL timer driver (only per-channel CC1..CC4 variants are provided). Add local static inline wrappers that set/clear the DIER CCxDE bits directly by mask, matching the equivalent helpers already used internally by timer_impl_hal.c. --- src/main/drivers/pwm_output.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 2da0628913d..d9417c2a4e9 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -373,6 +373,18 @@ static uint32_t dshotDmaStream(const pwmOutputPort_t *port) }; return streams[DMATAG_GET_STREAM(port->tch->timHw->dmaTag)]; } + +// The LL driver only exposes per-channel LL_TIM_{En,Dis}ableDMAReq_CC1..CC4; +// there is no runtime-channel variant, so set/clear the DIER bit directly. +static inline void LL_TIM_EnableDMAReq_CCx(TIM_TypeDef *TIMx, uint16_t dmaSources) +{ + SET_BIT(TIMx->DIER, dmaSources & (TIM_DMA_CC1 | TIM_DMA_CC2 | TIM_DMA_CC3 | TIM_DMA_CC4)); +} + +static inline void LL_TIM_DisableDMAReq_CCx(TIM_TypeDef *TIMx, uint16_t dmaSources) +{ + CLEAR_BIT(TIMx->DIER, dmaSources & (TIM_DMA_CC1 | TIM_DMA_CC2 | TIM_DMA_CC3 | TIM_DMA_CC4)); +} #endif static uint32_t dshotTimChannel(const pwmOutputPort_t *port) From 61fcc05f74274f7b590fdcc7a3becbd2f39441c2 Mon Sep 17 00:00:00 2001 From: Ray Morris Date: Wed, 19 Aug 2026 23:38:00 -0500 Subject: [PATCH 04/37] docs: regenerate Settings.md for PR #11605's new DShot telemetry settings dshot_bidir_enabled and dshot_edt_enabled were added to settings.yaml but docs/Settings.md was never regenerated, failing CI's update_cli_docs.py check. Ran the generator; purely additive diff, no other drift. --- docs/Settings.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/Settings.md b/docs/Settings.md index c8eb8bb0716..6402f11ba02 100644 --- a/docs/Settings.md +++ b/docs/Settings.md @@ -925,6 +925,26 @@ Sets the DShot beeper tone --- +### dshot_bidir_enabled + +Enable bidirectional DShot telemetry on motor outputs. Required for RPM filtering without a separate ESC telemetry UART + +| Default | Min | Max | +| --- | --- | --- | +| OFF | OFF | ON | + +--- + +### dshot_edt_enabled + +Enable extended DShot telemetry decoding (temperature, voltage, current in addition to eRPM) + +| Default | Min | Max | +| --- | --- | --- | +| OFF | OFF | ON | + +--- + ### dterm_lpf2_hz Dterm pre-differentiation LPF cutoff (Hz). Filters gyro before differentiation to reduce noise amplification. Higher = less delay, more noise. 0 = disabled. Values around 200-250Hz can add smoothing with small delay. From 6d26d2a9e150f21565957f4605beaeaf011debce Mon Sep 17 00:00:00 2001 From: Ray Morris Date: Thu, 20 Aug 2026 00:00:53 -0500 Subject: [PATCH 05/37] Fix implicit-function-declaration for loadDmaBufferDshot on DMAR targets loadDmaBufferDshot() was only defined when USE_DSHOT_DMAR was unset, but pwmCompleteMotorUpdate() also calls it as the per-channel DMA fallback on DMAR targets whenever bidir telemetry is enabled (burst DMA can't drive per-channel direction switching). Define it unconditionally; keep loadDmaBufferDshotStride() gated behind USE_DSHOT_DMAR since it's only used by the DMAR-specific burst path. --- src/main/drivers/pwm_output.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index d9417c2a4e9..5bac17c2e9e 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -135,9 +135,8 @@ static uint8_t commandsBuff[DHSOT_COMMAND_QUEUE_SIZE]; static currentExecutingCommand_t currentExecutingCommand; static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry); -#ifndef USE_DSHOT_DMAR static void loadDmaBufferDshot(timerDMASafeType_t *dmaBuffer, uint16_t packet); -#else +#ifdef USE_DSHOT_DMAR static void loadDmaBufferDshotStride(timerDMASafeType_t *dmaBuffer, int stride, uint16_t packet); #endif @@ -731,7 +730,11 @@ static void loadDmaBufferDshotStride(timerDMASafeType_t *dmaBuffer, int stride, dmaBuffer[i++ * stride] = 0; dmaBuffer[i++ * stride] = 0; } -#else +#endif + +// Needed on every target, DMAR or not: DMAR targets fall back to this +// per-channel loader whenever bidir telemetry is enabled, since burst DMA +// can't drive per-channel direction switching. static void loadDmaBufferDshot(timerDMASafeType_t *dmaBuffer, uint16_t packet) { for (int i = 0; i < 16; i++) { @@ -741,7 +744,6 @@ static void loadDmaBufferDshot(timerDMASafeType_t *dmaBuffer, uint16_t packet) dmaBuffer[16] = 0; dmaBuffer[17] = 0; } -#endif static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry) { From 3b2a74dec7bed6db2d347df3de2fb35e1475a221 Mon Sep 17 00:00:00 2001 From: Martin Petrov Date: Thu, 20 Aug 2026 17:48:31 +0300 Subject: [PATCH 06/37] fix: keep DShot telemetry decode out of ITCM --- src/main/drivers/pwm_output.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 5bac17c2e9e..ac4eed2c26c 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -619,7 +619,9 @@ static void pwmDshotDmaIrqHandler(DMA_t descriptor) DMA_CLEAR_FLAG(descriptor, DMA_IT_TCIF); } -static bool pwmDshotDecodeTelemetry(void) +// DMA has already captured the telemetry waveform before this runs. Keep the +// decode path out of the fast motor-update caller on constrained F7 targets. +static bool NOINLINE pwmDshotDecodeTelemetry(void) { if (!useDshotTelemetry || !dshotTelemetryPending) { return true; From ac6c735edf20f6e4f6041e20de0fbe975960c21a Mon Sep 17 00:00:00 2001 From: Error414 Date: Sat, 29 Aug 2026 20:52:09 +0200 Subject: [PATCH 07/37] BidirDshot - fix for H7, invertion of timer, reset DMA for reading telemetry, magic H7 workdown from betaflight --- src/main/drivers/pwm_output.c | 124 ++++++++++++++++++++++++++++++---- 1 file changed, 109 insertions(+), 15 deletions(-) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index ac4eed2c26c..3afdce20079 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -449,15 +449,64 @@ static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t cou return decodedValue >> 4; } +#if defined(USE_HAL_DRIVER) +// Betaflight-style direction switching: instead of poking DIR/addresses into a live +// stream, every switch does a full LL_DMA_DeInit (which also clears all five stream +// event flags - EN=1 is ignored while any of them is set, RM0433) followed by a +// complete LL_DMA_Init built from scratch for the requested direction. +static void dshotDmaInit(const pwmOutputPort_t *port, LL_DMA_InitTypeDef *init, uint32_t direction) +{ + LL_DMA_StructInit(init); +#if defined(STM32H7) || defined(STM32G4) + init->PeriphRequest = DMATAG_GET_CHANNEL(port->tch->timHw->dmaTag); +#else + static const uint32_t channels[] = { + LL_DMA_CHANNEL_0, LL_DMA_CHANNEL_1, LL_DMA_CHANNEL_2, LL_DMA_CHANNEL_3, + LL_DMA_CHANNEL_4, LL_DMA_CHANNEL_5, LL_DMA_CHANNEL_6, LL_DMA_CHANNEL_7 + }; + init->Channel = channels[DMATAG_GET_CHANNEL(port->tch->timHw->dmaTag)]; +#endif + init->PeriphOrM2MSrcAddress = (uint32_t)port->ccr; + init->MemoryOrM2MDstAddress = (uint32_t)port->dmaBuffer; + init->Direction = direction; + init->NbData = (direction == LL_DMA_DIRECTION_MEMORY_TO_PERIPH) ? DSHOT_DMA_BUFFER_SIZE : GCR_TELEMETRY_INPUT_LEN; + init->PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; + init->MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; + init->PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; + init->MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; + init->Mode = LL_DMA_MODE_NORMAL; + init->Priority = LL_DMA_PRIORITY_HIGH; + init->FIFOMode = LL_DMA_FIFOMODE_ENABLE; + // 1/4 threshold like Betaflight: each captured word is pushed to memory promptly + // instead of waiting for four, so a partial GCR frame isn't stuck in the FIFO. + init->FIFOThreshold = LL_DMA_FIFOTHRESHOLD_1_4; + init->MemBurst = LL_DMA_MBURST_SINGLE; + init->PeriphBurst = LL_DMA_PBURST_SINGLE; +} +#endif + static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) { + // Bidirectional DSHOT is carried on inverted (idle-high) signalling - flip the + // channel's normal polarity whenever telemetry is active, matching Betaflight. + const bool inverted = ((port->tch->timHw->output & TIMER_OUTPUT_INVERTED) != 0) ^ useDshotTelemetry; + #if defined(USE_HAL_DRIVER) + // Telemetry input capture widens ARR to 0xffff (see pwmDshotSetDirectionInput); + // restore the DSHOT bit period now, bypassing the ARR preload shadow so it + // takes effect immediately instead of after the next update event. + TIM_TypeDef *tim = port->tch->timHw->tim; + CLEAR_BIT(tim->CR1, TIM_CR1_ARPE); + tim->ARR = DSHOT_MOTOR_BITLENGTH - 1; + SET_BIT(tim->CR1, TIM_CR1_ARPE); + tim->CNT = 0; + TIM_OC_InitTypeDef init = {0}; init.OCMode = TIM_OCMODE_PWM1; init.OCIdleState = TIM_OCIDLESTATE_SET; - init.OCPolarity = TIM_OCPOLARITY_LOW; + init.OCPolarity = inverted ? TIM_OCPOLARITY_LOW : TIM_OCPOLARITY_HIGH; init.OCNIdleState = TIM_OCNIDLESTATE_SET; - init.OCNPolarity = TIM_OCNPOLARITY_LOW; + init.OCNPolarity = inverted ? TIM_OCNPOLARITY_LOW : TIM_OCNPOLARITY_HIGH; init.Pulse = 0; init.OCFastMode = TIM_OCFAST_DISABLE; HAL_TIM_PWM_ConfigChannel(port->tch->timCtx->timHandle, &init, dshotTimChannel(port)); @@ -471,8 +520,10 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) DMA_TypeDef *dmaBase = port->tch->dma->dma; LL_DMA_DisableStream(dmaBase, streamLL); while (LL_DMA_IsEnabledStream(dmaBase, streamLL)) { } - LL_DMA_ConfigAddresses(dmaBase, streamLL, (uint32_t)port->dmaBuffer, (uint32_t)port->ccr, LL_DMA_DIRECTION_MEMORY_TO_PERIPH); - LL_DMA_SetDataLength(dmaBase, streamLL, DSHOT_DMA_BUFFER_SIZE); + LL_DMA_DeInit(dmaBase, streamLL); + LL_DMA_InitTypeDef dmaInit; + dshotDmaInit(port, &dmaInit, LL_DMA_DIRECTION_MEMORY_TO_PERIPH); + LL_DMA_Init(dmaBase, streamLL, &dmaInit); LL_DMA_EnableIT_TC(dmaBase, streamLL); port->telemetryInputActive = false; #elif defined(AT32F43x) @@ -482,12 +533,12 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) if (port->tch->timHw->output & TIMER_OUTPUT_N_CHANNEL) { output.oc_output_state = FALSE; output.occ_output_state = TRUE; - output.occ_polarity = TMR_OUTPUT_ACTIVE_LOW; + output.occ_polarity = inverted ? TMR_OUTPUT_ACTIVE_LOW : TMR_OUTPUT_ACTIVE_HIGH; output.occ_idle_state = FALSE; } else { output.oc_output_state = TRUE; output.occ_output_state = FALSE; - output.oc_polarity = TMR_OUTPUT_ACTIVE_LOW; + output.oc_polarity = inverted ? TMR_OUTPUT_ACTIVE_LOW : TMR_OUTPUT_ACTIVE_HIGH; output.oc_idle_state = TRUE; } tmr_output_channel_config(port->tch->timHw->tim, dshotTimChannel(port), &output); @@ -509,12 +560,12 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) if (port->tch->timHw->output & TIMER_OUTPUT_N_CHANNEL) { init.TIM_OutputState = TIM_OutputState_Disable; init.TIM_OutputNState = TIM_OutputNState_Enable; - init.TIM_OCNPolarity = TIM_OCPolarity_Low; + init.TIM_OCNPolarity = inverted ? TIM_OCPolarity_Low : TIM_OCPolarity_High; init.TIM_OCNIdleState = TIM_OCIdleState_Reset; } else { init.TIM_OutputState = TIM_OutputState_Enable; init.TIM_OutputNState = TIM_OutputNState_Disable; - init.TIM_OCPolarity = TIM_OCPolarity_Low; + init.TIM_OCPolarity = inverted ? TIM_OCPolarity_Low : TIM_OCPolarity_High; init.TIM_OCIdleState = TIM_OCIdleState_Set; } switch (port->tch->timHw->channelIndex) { @@ -534,6 +585,29 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) { #if defined(USE_HAL_DRIVER) + // Betaflight ordering: reset the stream first (DeInit also clears all five event + // flags), then reconfigure the timer channel for capture, then rebuild the stream + // for the capture direction and arm it. + const uint32_t streamLL = dshotDmaStream(port); + DMA_TypeDef *dmaBase = port->tch->dma->dma; + LL_DMA_DisableStream(dmaBase, streamLL); + while (LL_DMA_IsEnabledStream(dmaBase, streamLL)) { } + LL_DMA_DeInit(dmaBase, streamLL); + + // Widen ARR so the free-running counter doesn't wrap every DSHOT bit period + // (20 ticks) while timing GCR edges, which span ~21 bits per telemetry frame. + SET_BIT(port->tch->timHw->tim->CR1, TIM_CR1_ARPE); + port->tch->timHw->tim->ARR = 0xffff; + +#if defined(STM32H7) + // H7 errata workaround (matches Betaflight): reconfiguring the channel from output + // compare to input capture can glitch the pin for a cycle while CCMR/CCER are mid-update. + // Disconnect the pin from the timer first so the ESC never sees the glitch, then + // reconnect it once the IC channel is safely configured. + const IO_t io = IOGetByTag(port->tch->timHw->tag); + IOConfigGPIO(io, IOCFG_OUT_PP); +#endif + TIM_IC_InitTypeDef init = {0}; init.ICPolarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE; init.ICSelection = TIM_ICSELECTION_DIRECTTI; @@ -542,12 +616,14 @@ static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) HAL_TIM_IC_ConfigChannel(port->tch->timCtx->timHandle, &init, dshotTimChannel(port)); HAL_TIM_IC_Start(port->tch->timCtx->timHandle, dshotTimChannel(port)); - const uint32_t streamLL = dshotDmaStream(port); - DMA_TypeDef *dmaBase = port->tch->dma->dma; - LL_DMA_DisableStream(dmaBase, streamLL); - while (LL_DMA_IsEnabledStream(dmaBase, streamLL)) { } - LL_DMA_ConfigAddresses(dmaBase, streamLL, (uint32_t)port->ccr, (uint32_t)port->dmaBuffer, LL_DMA_DIRECTION_PERIPH_TO_MEMORY); - LL_DMA_SetDataLength(dmaBase, streamLL, GCR_TELEMETRY_INPUT_LEN); +#if defined(STM32H7) + const bool baseInverted = port->tch->timHw->output & TIMER_OUTPUT_INVERTED; + IOConfigGPIOAF(io, baseInverted ? IOCFG_AF_PP_PD : IOCFG_AF_PP_UP, port->tch->timHw->alternateFunction); +#endif + + LL_DMA_InitTypeDef dmaInit; + dshotDmaInit(port, &dmaInit, LL_DMA_DIRECTION_PERIPH_TO_MEMORY); + LL_DMA_Init(dmaBase, streamLL, &dmaInit); LL_DMA_EnableIT_TC(dmaBase, streamLL); LL_DMA_EnableStream(dmaBase, streamLL); LL_TIM_EnableDMAReq_CCx(port->tch->timHw->tim, dshotDmaSource(port)); @@ -655,6 +731,13 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) #endif if (edges > MIN_GCR_EDGES) { +#if defined(STM32H7) + // port->dmaBuffer lives in the cacheable DMA_RAM region (write-through on the + // write side, but reads still need an explicit invalidate) - without this the + // CPU can read stale data instead of what the capture DMA just wrote. + uint32_t alignedAddr = (uint32_t)port->dmaBuffer & ~0x1F; + SCB_InvalidateDCache_by_Addr((uint32_t *)alignedAddr, edges * sizeof(port->dmaBuffer[0]) + ((uint32_t)port->dmaBuffer - alignedAddr)); +#endif const uint16_t rawValue = dshotDecodeTelemetryPacket((const uint32_t *)port->dmaBuffer, edges); const uint16_t processed = dshotProcessPacket(rawValue, motorIndex); @@ -687,7 +770,18 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, } if (enableOutput && useDshotTelemetry) { - IOConfigGPIOAF(IOGetByTag(timerHardware->tag), IOCFG_AF_PP_UP, timerHardware->alternateFunction); + // The idle/listen level always needs a pull matching this channel's *un-flipped* + // polarity (pwmDshotSetDirectionOutput flips OCPolarity for bidir, but the GCR + // listen phase still idles toward the same physical level either way). + const IO_t io = IOGetByTag(timerHardware->tag); + const bool baseInverted = timerHardware->output & TIMER_OUTPUT_INVERTED; +#if defined(STM32H7) + // Preset ODR to the bidir idle level once - the H7 OC->IC erratum workaround + // in pwmDshotSetDirectionInput() disconnects the pin from the timer and relies + // on this cached ODR bit (matches Betaflight) instead of redriving the level. + baseInverted ? IOLo(io) : IOHi(io); +#endif + IOConfigGPIOAF(io, baseInverted ? IOCFG_AF_PP_PD : IOCFG_AF_PP_UP, timerHardware->alternateFunction); } // Configure timer DMA From abc7374b1aa2933451b3b2281e8fe3b682ed2709 Mon Sep 17 00:00:00 2001 From: Error414 Date: Sat, 5 Sep 2026 12:27:33 +0200 Subject: [PATCH 08/37] BidirDshot - hold the line to avoid double beeping durring FC bootup --- src/main/drivers/pwm_output.c | 56 ++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 11 deletions(-) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 3afdce20079..37a90d757f5 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -667,6 +667,34 @@ static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) port->telemetryInputActive = true; } +// Set when bidir pins are held low as plain GPIO until the first frame +static bool dshotPinsParkedLow = false; + +// Connect bidir DSHOT pins to their timer AF (idle-high). Called on the first +// real motor update so the line only goes high microseconds before frames start, +// keeping it low through the ESC's boot-time bootloader-entry window. +static void dshotConnectOutputs(void) +{ + for (int index = 0; index < getMotorCount(); index++) { + pwmOutputPort_t *port = motors[index].pwmPort; + if (port && port->configured) { + const timerHardware_t *timHw = port->tch->timHw; + const IO_t io = IOGetByTag(timHw->tag); + // The pull must match this channel's *un-flipped* polarity + // (pwmDshotSetDirectionOutput flips OCPolarity for bidir, but the GCR + // listen phase still idles toward the same physical level either way). + const bool baseInverted = timHw->output & TIMER_OUTPUT_INVERTED; +#if defined(STM32H7) + // Preset ODR to the bidir idle level once - the H7 OC->IC erratum workaround + // in pwmDshotSetDirectionInput() disconnects the pin from the timer and relies + // on this cached ODR bit (matches Betaflight) instead of redriving the level. + baseInverted ? IOLo(io) : IOHi(io); +#endif + IOConfigGPIOAF(io, baseInverted ? IOCFG_AF_PP_PD : IOCFG_AF_PP_UP, timHw->alternateFunction); + } + } +} + static void pwmDshotDmaIrqHandler(DMA_t descriptor) { if (!DMA_GET_FLAG_STATUS(descriptor, DMA_IT_TCIF)) { @@ -770,18 +798,19 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, } if (enableOutput && useDshotTelemetry) { - // The idle/listen level always needs a pull matching this channel's *un-flipped* - // polarity (pwmDshotSetDirectionOutput flips OCPolarity for bidir, but the GCR - // listen phase still idles toward the same physical level either way). + // Bidir signalling idles high, but holding the line high with no edges + // during ESC boot triggers the BLHeli/Bluejay bootloader-entry check + // (~150ms of continuous high right after the ESC's startup melody). The + // first INAV frame goes out seconds after this pin is configured, so the + // ESC would enter its bootloader, time out and reset - replaying the + // startup melody. Park the pin so the ESC sees low, like normal DSHOT + // idle, and defer the AF connect until the first frame goes out + // (dshotConnectOutputs()). On TIMER_OUTPUT_INVERTED hardware the pin + // level is re-inverted downstream, so park high there. const IO_t io = IOGetByTag(timerHardware->tag); - const bool baseInverted = timerHardware->output & TIMER_OUTPUT_INVERTED; -#if defined(STM32H7) - // Preset ODR to the bidir idle level once - the H7 OC->IC erratum workaround - // in pwmDshotSetDirectionInput() disconnects the pin from the timer and relies - // on this cached ODR bit (matches Betaflight) instead of redriving the level. - baseInverted ? IOLo(io) : IOHi(io); -#endif - IOConfigGPIOAF(io, baseInverted ? IOCFG_AF_PP_PD : IOCFG_AF_PP_UP, timerHardware->alternateFunction); + IOConfigGPIO(io, IOCFG_OUT_PP); + (timerHardware->output & TIMER_OUTPUT_INVERTED) ? IOHi(io) : IOLo(io); + dshotPinsParkedLow = true; } // Configure timer DMA @@ -997,6 +1026,11 @@ void pwmCompleteMotorUpdate(void) { #ifdef USE_DSHOT if (isMotorProtocolDshot()) { + if (dshotPinsParkedLow) { + dshotConnectOutputs(); + dshotPinsParkedLow = false; + } + if (!executeDShotCommands()) { return; } From 449945555ee1390d4482bcf4c9740634c4f50abd Mon Sep 17 00:00:00 2001 From: Error414 Date: Tue, 8 Sep 2026 21:14:39 +0200 Subject: [PATCH 09/37] BidirDshot - skip circular DMA keepalive during EEPROM writes pwmSetMotorDMACircular() predates bidirectional DSHOT and corrupts its per-channel direction-switching state machine when a config save runs (e.g. servo autotrim saving on disarm): - On USE_DSHOT_DMAR targets the burst path is never armed with bidir, so dmaBurstBuffer stays NULL and loadDmaBufferDshotStride() writes the zero-throttle frame through the NULL pointer into 0x00000000 - which is ITCM RAM holding .tcm_code (FAST_CODE), corrupting the firmware. - On per-channel targets impl_timerPWMSetDMACircular() re-enables the stream without regard to the current transfer direction, and on exit disables the TIM DMA request before the stream: a FIFO-enabled mem-to-periph stream then cannot drain, EN sticks at 1 and every later reconfiguration is silently ignored - the output is dead until reboot. - Circular output also repeats frames back-to-back, colliding with the GCR reply the ESC drives onto the same line after every frame. Match Betaflight instead: with bidir telemetry active, leave motor DMA alone during the flash write and accept the frame gap. Saves only happen disarmed, the ESC holds zero throttle, and the existing decode path rebuilds the streams (full DeInit/Init) on the first update afterwards. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01BB55zdRNZq3Q6hZYsDYwTc --- src/main/drivers/pwm_output.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 37a90d757f5..c7d19f2c1dd 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -260,6 +260,15 @@ void pwmSetMotorDMACircular(bool circular) return; } + // Bidirectional DSHOT uses per-channel DMA with output/input direction + // switching: the burst path is never armed (dmaBurstBuffer stays NULL on + // USE_DSHOT_DMAR targets) and a port may currently be in the input-capture + // direction. Skip the circular keepalive and accept the frame gap during + // the flash write, matching Betaflight behaviour. + if (useDshotTelemetry) { + return; + } + int motorCount = getMotorCount(); if (circular) { From 57434f33c86bb12d6488e64344a51ef3385dde91 Mon Sep 17 00:00:00 2001 From: Error414 Date: Mon, 21 Sep 2026 22:50:17 +0200 Subject: [PATCH 10/37] Bidir DSHOT - USE_DSHOT_BIDIR (H7), bidir_dshot.c, review fixes Structure: - dshot.c/h -> bidir_dshot.c/h, compiled only with USE_DSHOT_BIDIR. The define comes from common_post.h: USE_DSHOT && STM32H7 && !USE_DSHOT_DMAR (direction switching is verified on H7; DMAR has no per-channel stream). dshot_bidir_enabled / dshot_edt_enabled are hidden elsewhere. - Every bidir path in pwm_output.c sits under USE_DSHOT_BIDIR and, at run time, under useDshotTelemetry: with the setting off, plain DSHOT keeps the timer driver's DMA handler, FIFO setup and channel config from maintenance-10.x. The DMAR fallback to per-channel DMA is gone (excluded by the define instead). - USE_RPM_FILTER follows USE_ESC_SENSOR || USE_DSHOT_BIDIR instead of USE_DSHOT, so targets without ESC sensor do not grow. - No circular keep-alive for bidir: the line idles high for the flash write, as in Betaflight. Fixes: - EDT voltage/current were 10x off (0.25 V and 1 A steps into 0.01 V / 0.01 A fields): x25 / x100 instead of x250 / x1000. - ESC sensor RPM taken from the already computed mechanical RPM instead of computeRpm((int16_t)eRPM/100); an EDT-only first frame no longer publishes rpm = 0. - GCR decoder: guard against len < 1 (shift by -1) on glitch edges and on an exactly filled frame, and against len > 21. - Bidir ESC sensor data is aged at the serial poll rate, so a silent ESC drops out of the combined values like a serial one. - useDshotTelemetry is set once, by pwmMotorPreconfigure(); the ESC sensor asks isDshotTelemetryActive() instead of re-deriving it. - pwmDshotDmaIrqHandler keeps tch->dmaState in step with the timer driver's handler (timerPWMDMAInProgress()). - srxl.c: RPM comes through escSensorGetData(), no dshot include needed; duplicate includes removed. Co-Authored-By: Claude Fable 5.1 --- src/main/CMakeLists.txt | 4 +- src/main/drivers/{dshot.c => bidir_dshot.c} | 36 +++--- src/main/drivers/{dshot.h => bidir_dshot.h} | 2 + src/main/drivers/pwm_output.c | 124 +++++++++++++------- src/main/fc/fc_init.c | 10 +- src/main/fc/settings.yaml | 2 + src/main/flight/rpm_filter.c | 7 +- src/main/sensors/esc_sensor.c | 27 ++++- src/main/target/common_post.h | 19 ++- src/main/telemetry/srxl.c | 3 +- 10 files changed, 156 insertions(+), 78 deletions(-) rename src/main/drivers/{dshot.c => bidir_dshot.c} (85%) rename src/main/drivers/{dshot.h => bidir_dshot.h} (98%) diff --git a/src/main/CMakeLists.txt b/src/main/CMakeLists.txt index 53ea5485d6b..23a9388999e 100755 --- a/src/main/CMakeLists.txt +++ b/src/main/CMakeLists.txt @@ -252,8 +252,8 @@ main_sources(COMMON_SRC drivers/pwm_esc_detect.h drivers/pwm_mapping.c drivers/pwm_mapping.h - drivers/dshot.c - drivers/dshot.h + drivers/bidir_dshot.c + drivers/bidir_dshot.h drivers/pwm_output.c drivers/pwm_output.h drivers/pinio.c diff --git a/src/main/drivers/dshot.c b/src/main/drivers/bidir_dshot.c similarity index 85% rename from src/main/drivers/dshot.c rename to src/main/drivers/bidir_dshot.c index c23b560c8a6..7de3b94c56f 100644 --- a/src/main/drivers/dshot.c +++ b/src/main/drivers/bidir_dshot.c @@ -20,13 +20,18 @@ */ #include +#include #include #include "platform.h" #include "common/utils.h" -#include "drivers/dshot.h" +#include "drivers/bidir_dshot.h" -#ifdef USE_DSHOT +// Bidirectional DSHOT telemetry only: eRPM / EDT decoding, RPM state for the RPM filter and +// the ESC sensor. Frame generation, DMA and DSHOT commands for plain DSHOT live in +// pwm_output.c under USE_DSHOT. Every user of this API is guarded by USE_DSHOT_BIDIR. + +#ifdef USE_DSHOT_BIDIR #include "common/filter.h" #include "common/maths.h" @@ -111,9 +116,10 @@ bool isDshotTelemetryActive(void) return useDshotTelemetry; } +// useDshotTelemetry itself is set by the motor driver (pwmMotorPreconfigure()), which +// knows whether the outputs were configured for DSHOT at all void initDshotTelemetry(timeUs_t looptimeUs) { - useDshotTelemetry = motorConfig()->useDshotTelemetry && (motorConfig()->motorPwmProtocol >= PWM_TYPE_DSHOT150); edtAlwaysDecode = motorConfig()->useDshotEdt != 0; dshotResetTelemetry(); @@ -210,28 +216,14 @@ bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex) return false; } - data->rpm = state->telemetryData[DSHOT_TELEMETRY_TYPE_ERPM]; + // escSensorData_t units: rpm (mechanical), degrees C, 0.01 V, 0.01 A. EDT reports + // the temperature in degrees C, the voltage in 0.25 V and the current in 1 A steps. + data->rpm = lrintf(dshotRpm[motorIndex]); data->temperature = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_TEMPERATURE)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_TEMPERATURE] : 0; - data->voltage = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_VOLTAGE)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_VOLTAGE] * 250 : 0; - data->current = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_CURRENT)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_CURRENT] * 1000 : 0; + data->voltage = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_VOLTAGE)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_VOLTAGE] * 25 : 0; + data->current = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_CURRENT)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_CURRENT] * 100 : 0; return true; } #endif - -#ifndef USE_DSHOT -bool useDshotTelemetry = false; -dshotTelemetryState_t dshotTelemetryState; - -void initDshotTelemetry(timeUs_t looptimeUs) { UNUSED(looptimeUs); } -void dshotResetTelemetry(void) {} -bool isDshotTelemetryConfigured(void) { return false; } -bool isDshotTelemetryActive(void) { return false; } -uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) { UNUSED(motorIndex); return rawValue; } -float getDshotRpm(uint8_t motorIndex) { UNUSED(motorIndex); return 0.0f; } -uint16_t getDshotErpm(uint8_t motorIndex) { UNUSED(motorIndex); return 0; } -float getDshotRpmAverage(void) { return 0.0f; } -float getMotorFrequencyHz(uint8_t motorIndex) { UNUSED(motorIndex); return 0.0f; } -bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex) { UNUSED(data); UNUSED(motorIndex); return false; } -#endif diff --git a/src/main/drivers/dshot.h b/src/main/drivers/bidir_dshot.h similarity index 98% rename from src/main/drivers/dshot.h rename to src/main/drivers/bidir_dshot.h index 31061c76300..5eeeee6aac9 100644 --- a/src/main/drivers/dshot.h +++ b/src/main/drivers/bidir_dshot.h @@ -72,6 +72,7 @@ typedef struct { dshotRawValueState_e rawValueState; } dshotTelemetryState_t; +#ifdef USE_DSHOT_BIDIR extern bool useDshotTelemetry; extern dshotTelemetryState_t dshotTelemetryState; @@ -85,3 +86,4 @@ uint16_t getDshotErpm(uint8_t motorIndex); float getDshotRpmAverage(void); float getMotorFrequencyHz(uint8_t motorIndex); bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex); +#endif diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index e07b273e648..6569628b99d 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -34,9 +34,8 @@ #include "drivers/io.h" #include "drivers/nvic.h" +#include "drivers/bidir_dshot.h" #include "drivers/time.h" -#include "drivers/dshot.h" -#include "drivers/nvic.h" #include "drivers/timer.h" #include "drivers/pwm_mapping.h" #include "drivers/pwm_output.h" @@ -71,9 +70,17 @@ #define DSHOT_MOTOR_BITLENGTH 20 #define DSHOT_DMA_BUFFER_SIZE 18 /* resolution + frame reset (2us) */ +#define MAX_DMA_TIMERS 8 + +#ifdef USE_DSHOT_BIDIR #define DSHOT_TELEMETRY_DEADTIME_US 35 #define GCR_TELEMETRY_INPUT_LEN MAX_GCR_EDGES -#define MAX_DMA_TIMERS 8 +/* A bidir port captures the GCR edges of the ESC reply into the same buffer it sends the + * frame from, so the buffer is sized for the larger of the two */ +#define DSHOT_PORT_DMA_BUFFER_SIZE GCR_TELEMETRY_INPUT_LEN +#else +#define DSHOT_PORT_DMA_BUFFER_SIZE DSHOT_DMA_BUFFER_SIZE +#endif /* Keep-alive frame replayed by circular DMA while the CPU is stalled by a flash write: * 16 data bits followed by an idle (line low) gap of DSHOT_KEEPALIVE_GAP_US. @@ -120,14 +127,16 @@ typedef struct { #ifdef USE_DSHOT // DSHOT parameters - timerDMASafeType_t dmaBuffer[GCR_TELEMETRY_INPUT_LEN]; + timerDMASafeType_t dmaBuffer[DSHOT_PORT_DMA_BUFFER_SIZE]; #ifdef USE_DSHOT_DMAR timerDMASafeType_t *dmaBurstBuffer; #endif +#ifdef USE_DSHOT_BIDIR bool telemetryInputActive; timeUs_t telemetryInputStampUs; timeUs_t dshotTelemetryDeadtimeUs; #endif +#endif } pwmOutputPort_t; typedef struct { @@ -158,7 +167,9 @@ static timeUs_t digitalMotorUpdateIntervalUs = 0; static timeUs_t digitalMotorLastUpdateUs; static timeUs_t lastCommandSent = 0; static timeUs_t commandPostDelay = 0; +#ifdef USE_DSHOT_BIDIR static bool dshotTelemetryPending = false; +#endif static circularBuffer_t commandsCircularBuffer; static uint8_t commandsBuff[DHSOT_COMMAND_QUEUE_SIZE]; @@ -168,6 +179,7 @@ static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry); uint32_t getDshotHz(motorPwmProtocolTypes_e pwmProtocolType); #ifndef USE_DSHOT_DMAR static void loadDmaBufferDshot(timerDMASafeType_t *dmaBuffer, uint16_t packet); +#else static void loadDmaBufferDshotStride(timerDMASafeType_t *dmaBuffer, int stride, uint16_t packet); #endif @@ -176,6 +188,7 @@ burstDmaTimer_t burstDmaTimers[MAX_DMA_TIMERS]; uint8_t burstDmaTimersCount = 0; #endif +#ifdef USE_DSHOT_BIDIR // GCR decode algorithm ported from Betaflight (GPLv3) static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count); static bool pwmDshotDecodeTelemetry(void); @@ -183,6 +196,7 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port); static void pwmDshotSetDirectionInput(pwmOutputPort_t *port); static void pwmDshotDmaIrqHandler(DMA_t descriptor); #endif +#endif static void pwmOutConfigTimer(pwmOutputPort_t * p, TCH_t * tch, uint32_t hz, uint16_t period, uint16_t value) { @@ -307,14 +321,14 @@ void pwmSetMotorDMACircular(bool circular) return; } - // Bidirectional DSHOT uses per-channel DMA with output/input direction - // switching: the burst path is never armed (dmaBurstBuffer stays NULL on - // USE_DSHOT_DMAR targets) and a port may currently be in the input-capture - // direction. Skip the circular keepalive and accept the frame gap during - // the flash write, matching Betaflight behaviour. +#ifdef USE_DSHOT_BIDIR + // No replay for bidir: the ports switch direction per frame and one may sit in input + // capture, so the circular replay below does not apply. The ESC sees a frame gap (line + // idle-high) for the flash write, as in Betaflight. if (useDshotTelemetry) { return; } +#endif int motorCount = getMotorCount(); const uint32_t dshotHz = getDshotHz(initMotorProtocol); @@ -444,6 +458,7 @@ static uint8_t getBurstDmaTimerIndex(TIM_TypeDef *timer) } #endif +#ifdef USE_DSHOT_BIDIR static uint32_t dshotDmaSource(const pwmOutputPort_t *port) { #if defined(USE_HAL_DRIVER) || !defined(AT32F43x) @@ -503,8 +518,16 @@ static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t cou break; } len = (diff + 8) / 16; + if (len < 1 || len > 21) { + // Edges closer than half a GCR bit or further apart than a whole frame + return DSHOT_TELEMETRY_INVALID; + } } else { len = 21 - bits; + if (len < 1) { + // All bits accounted for, no trailing run left to infer + break; + } } value <<= len; @@ -786,6 +809,9 @@ static void dshotConnectOutputs(void) } } +// Takes over the stream's completion interrupt from the timer driver on bidir ports: once +// the frame is out the port is turned round to capture the ESC reply, and +// pwmDshotDecodeTelemetry() turns it back before the next frame static void pwmDshotDmaIrqHandler(DMA_t descriptor) { if (!DMA_GET_FLAG_STATUS(descriptor, DMA_IT_TCIF)) { @@ -806,7 +832,12 @@ static void pwmDshotDmaIrqHandler(DMA_t descriptor) TIM_DMACmd(port->tch->timHw->tim, dshotDmaSource(port), DISABLE); #endif - if (useDshotTelemetry && !port->telemetryInputActive) { + // Same bookkeeping as the timer driver's handler (timerPWMDMAInProgress()) + if (port->tch->dmaState == TCH_DMA_ACTIVE) { + port->tch->dmaState = TCH_DMA_IDLE; + } + + if (!port->telemetryInputActive) { pwmDshotSetDirectionInput(port); dshotTelemetryPending = true; } @@ -818,7 +849,7 @@ static void pwmDshotDmaIrqHandler(DMA_t descriptor) // decode path out of the fast motor-update caller on constrained F7 targets. static bool NOINLINE pwmDshotDecodeTelemetry(void) { - if (!useDshotTelemetry || !dshotTelemetryPending) { + if (!dshotTelemetryPending) { return true; } @@ -851,9 +882,8 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) if (edges > MIN_GCR_EDGES) { #if defined(STM32H7) - // port->dmaBuffer lives in the cacheable DMA_RAM region (write-through on the - // write side, but reads still need an explicit invalidate) - without this the - // CPU can read stale data instead of what the capture DMA just wrote. + // Defensive: DMA_RAM is mapped non-cacheable by the MPU, so this is a no-op as + // long as the port buffers stay there uint32_t alignedAddr = (uint32_t)port->dmaBuffer & ~0x1F; SCB_InvalidateDCache_by_Addr((uint32_t *)alignedAddr, edges * sizeof(port->dmaBuffer[0]) + ((uint32_t)port->dmaBuffer - alignedAddr)); #endif @@ -862,11 +892,10 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) if (processed != DSHOT_TELEMETRY_INVALID && processed != DSHOT_TELEMETRY_NOEDGE) { #ifdef USE_ESC_SENSOR + // Nothing to publish before the first eRPM value (an EDT frame may come first) escSensorData_t data; if (getDshotEscSensorData(&data, motorIndex)) { - escSensorSetDshotData(motorIndex, computeRpm((int16_t)data.rpm), data.temperature, data.voltage, data.current); - } else { - escSensorSetDshotData(motorIndex, (uint32_t)getDshotRpm(motorIndex), 0, 0, 0); + escSensorSetDshotData(motorIndex, data.rpm, data.temperature, data.voltage, data.current); } #endif } @@ -878,6 +907,7 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) dshotTelemetryPending = false; return true; } +#endif // USE_DSHOT_BIDIR static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, uint32_t dshotHz, bool enableOutput) { @@ -888,6 +918,7 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, return NULL; } +#ifdef USE_DSHOT_BIDIR if (enableOutput && useDshotTelemetry) { // Bidir signalling idles high, but holding the line high with no edges // during ESC boot triggers the BLHeli/Bluejay bootloader-entry check @@ -903,34 +934,38 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, (timerHardware->output & TIMER_OUTPUT_INVERTED) ? IOHi(io) : IOLo(io); dshotPinsParkedLow = true; } +#endif // Configure timer DMA #ifdef USE_DSHOT_DMAR - if (!useDshotTelemetry) { - uint8_t burstDmaTimerIndex = getBurstDmaTimerIndex(timerHardware->tim); - if (burstDmaTimerIndex >= MAX_DMA_TIMERS) { - return NULL; - } + uint8_t burstDmaTimerIndex = getBurstDmaTimerIndex(timerHardware->tim); + if (burstDmaTimerIndex >= MAX_DMA_TIMERS) { + return NULL; + } - port->dmaBurstBuffer = &dmaBurstBuffer[burstDmaTimerIndex][0]; - burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[burstDmaTimerIndex]; - burstDmaTimer->dmaBurstBuffer = port->dmaBurstBuffer; + port->dmaBurstBuffer = &dmaBurstBuffer[burstDmaTimerIndex][0]; + burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[burstDmaTimerIndex]; + burstDmaTimer->dmaBurstBuffer = port->dmaBurstBuffer; - if (timerPWMConfigDMABurst(burstDmaTimer, port->tch, port->dmaBurstBuffer, sizeof(port->dmaBurstBuffer[0]), DSHOT_DMA_BUFFER_SIZE)) { - port->configured = true; - } - } else -#endif - { - if (timerPWMConfigChannelDMA(port->tch, port->dmaBuffer, sizeof(port->dmaBuffer[0]), GCR_TELEMETRY_INPUT_LEN)) { + if (timerPWMConfigDMABurst(burstDmaTimer, port->tch, port->dmaBurstBuffer, sizeof(port->dmaBurstBuffer[0]), DSHOT_DMA_BUFFER_SIZE)) { + port->configured = true; + } +#else + if (timerPWMConfigChannelDMA(port->tch, port->dmaBuffer, sizeof(port->dmaBuffer[0]), DSHOT_DMA_BUFFER_SIZE)) { // Only mark as DSHOT channel if DMA was set successfully ZERO_FARRAY(port->dmaBuffer); port->configured = true; +#ifdef USE_DSHOT_BIDIR + if (useDshotTelemetry) { + // Inverted signalling and per-frame direction switching; the port takes the + // stream's completion interrupt over from the timer driver port->dshotTelemetryDeadtimeUs = DSHOT_TELEMETRY_DEADTIME_US + 1000000 * (16 * DSHOT_MOTOR_BITLENGTH) / dshotHz; pwmDshotSetDirectionOutput(port); dmaSetHandler(port->tch->dma, pwmDshotDmaIrqHandler, NVIC_PRIO_TIMER_DMA, allocatedOutputPortCount - 1); } +#endif } +#endif return port; } @@ -946,26 +981,26 @@ static void loadDmaBufferDshotStride(timerDMASafeType_t *dmaBuffer, int stride, dmaBuffer[i++ * stride] = 0; dmaBuffer[i++ * stride] = 0; } -#endif - -// Needed on every target, DMAR or not: DMAR targets fall back to this -// per-channel loader whenever bidir telemetry is enabled, since burst DMA -// can't drive per-channel direction switching. +#else static void loadDmaBufferDshot(timerDMASafeType_t *dmaBuffer, uint16_t packet) { for (int i = 0; i < 16; i++) { dmaBuffer[i] = (packet & 0x8000) ? DSHOT_MOTOR_BIT_1 : DSHOT_MOTOR_BIT_0; // MSB first packet <<= 1; } + // Frame reset slots: rewritten every time, a bidir port captures edges into this buffer dmaBuffer[16] = 0; dmaBuffer[17] = 0; } +#endif static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry) { +#ifdef USE_DSHOT_BIDIR if (useDshotTelemetry) { requestTelemetry = true; } +#endif uint16_t packet = (value << 1) | (requestTelemetry ? 1 : 0); @@ -976,7 +1011,7 @@ static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry) csum ^= csum_data; // xor data by nibbles csum_data >>= 4; } -#ifdef USE_DSHOT +#ifdef USE_DSHOT_BIDIR if (useDshotTelemetry) { csum = ~csum; } @@ -1100,9 +1135,11 @@ void pwmCompleteMotorUpdate(void) { return; } +#ifdef USE_DSHOT_BIDIR if (useDshotTelemetry && !pwmDshotDecodeTelemetry()) { return; } +#endif int motorCount = getMotorCount(); timeUs_t currentTimeUs = micros(); @@ -1117,17 +1154,18 @@ void pwmCompleteMotorUpdate(void) { #ifdef USE_DSHOT if (isMotorProtocolDshot()) { +#ifdef USE_DSHOT_BIDIR if (dshotPinsParkedLow) { dshotConnectOutputs(); dshotPinsParkedLow = false; } +#endif if (!executeDShotCommands()) { return; } #ifdef USE_DSHOT_DMAR - if (!useDshotTelemetry) { for (int index = 0; index < motorCount; index++) { if (motors[index].pwmPort && motors[index].pwmPort->configured) { uint16_t packet = prepareDshotPacket(motors[index].value, motors[index].requestTelemetry); @@ -1140,9 +1178,7 @@ void pwmCompleteMotorUpdate(void) { burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[burstDmaTimerIndex]; pwmBurstDMAStart(burstDmaTimer, DSHOT_DMA_BUFFER_SIZE * 4); } - } else -#endif - { +#else // Generate DMA buffers for (int index = 0; index < motorCount; index++) { if (motors[index].pwmPort && motors[index].pwmPort->configured) { @@ -1159,7 +1195,7 @@ void pwmCompleteMotorUpdate(void) { timerPWMStartDMA(motors[index].pwmPort->tch); } } - } +#endif } #endif } @@ -1178,7 +1214,7 @@ void pwmMotorPreconfigure(void) { // Keep track of initial motor protocol initMotorProtocol = motorConfig()->motorPwmProtocol; -#ifdef USE_DSHOT +#ifdef USE_DSHOT_BIDIR useDshotTelemetry = motorConfig()->useDshotTelemetry && getMotorProtocolProperties(initMotorProtocol)->isDSHOT; #endif diff --git a/src/main/fc/fc_init.c b/src/main/fc/fc_init.c index ccf2db750ff..4ce76d8cb5b 100644 --- a/src/main/fc/fc_init.c +++ b/src/main/fc/fc_init.c @@ -50,7 +50,7 @@ #include "drivers/compass/compass.h" #include "drivers/bus.h" #include "drivers/dma.h" -#include "drivers/dshot.h" +#include "drivers/bidir_dshot.h" #include "drivers/exti.h" #include "drivers/io.h" #include "drivers/flash.h" @@ -765,6 +765,8 @@ void init(void) #ifdef USE_DSHOT initDShotCommands(); +#endif +#ifdef USE_DSHOT_BIDIR initDshotTelemetry(getLooptime()); #endif @@ -799,7 +801,11 @@ void init(void) #ifdef USE_RPM_FILTER disableRpmFilters(); - if ((escSensorIsActive() || isDshotTelemetryActive()) && (rpmFilterConfig()->gyro_filter_enabled || rpmFilterConfig()->dterm_filter_enabled)) { + bool rpmSourceActive = escSensorIsActive(); +#ifdef USE_DSHOT_BIDIR + rpmSourceActive = rpmSourceActive || isDshotTelemetryActive(); +#endif + if (rpmSourceActive && (rpmFilterConfig()->gyro_filter_enabled || rpmFilterConfig()->dterm_filter_enabled)) { rpmFiltersInit(); setTaskEnabled(TASK_RPM_FILTER, true); } diff --git a/src/main/fc/settings.yaml b/src/main/fc/settings.yaml index a4a529e13aa..b0e5b1c63b2 100644 --- a/src/main/fc/settings.yaml +++ b/src/main/fc/settings.yaml @@ -898,11 +898,13 @@ groups: - name: dshot_bidir_enabled description: "Enable bidirectional DShot telemetry on motor outputs. Required for RPM filtering without a separate ESC telemetry UART" field: useDshotTelemetry + condition: USE_DSHOT_BIDIR type: bool default_value: OFF - name: dshot_edt_enabled description: "Enable extended DShot telemetry decoding (temperature, voltage, current in addition to eRPM)" field: useDshotEdt + condition: USE_DSHOT_BIDIR type: bool default_value: OFF - name: motor_poles diff --git a/src/main/flight/rpm_filter.c b/src/main/flight/rpm_filter.c index 14da11482bb..155efab45a0 100644 --- a/src/main/flight/rpm_filter.c +++ b/src/main/flight/rpm_filter.c @@ -36,7 +36,7 @@ #include "common/maths.h" #include "common/filter.h" #include "flight/mixer.h" -#include "drivers/dshot.h" +#include "drivers/bidir_dshot.h" #include "sensors/esc_sensor.h" #include "fc/config.h" #include "fc/settings.h" @@ -192,9 +192,12 @@ void rpmFilterUpdateTask(timeUs_t currentTimeUs) for (uint8_t i = 0; i < motorCount; i++) { float baseFrequency; +#ifdef USE_DSHOT_BIDIR if (isDshotTelemetryActive()) { baseFrequency = getMotorFrequencyHz(i); - } else { + } else +#endif + { #ifdef USE_ESC_SENSOR const escSensorData_t *escState = getEscTelemetry(i); baseFrequency = pt1FilterApply(&motorFrequencyFilter[i], (float)escState->rpm / 60.0f); diff --git a/src/main/sensors/esc_sensor.c b/src/main/sensors/esc_sensor.c index 20fcf261b44..81e37b00c04 100644 --- a/src/main/sensors/esc_sensor.c +++ b/src/main/sensors/esc_sensor.c @@ -41,8 +41,7 @@ #include "config/parameter_group_ids.h" #include "flight/mixer.h" -#include "drivers/dshot.h" -#include "drivers/pwm_mapping.h" +#include "drivers/bidir_dshot.h" #include "drivers/pwm_output.h" #include "sensors/esc_sensor.h" #include "drivers/pwm_mapping.h" @@ -290,11 +289,14 @@ bool escSensorInitialize(void) escSensorInitData(); - if (motorConfig()->useDshotTelemetry && (motorConfig()->motorPwmProtocol >= PWM_TYPE_DSHOT150)) { +#ifdef USE_DSHOT_BIDIR + // Telemetry on the motor line: fed by the motor driver, no port to open + if (isDshotTelemetryActive()) { escSensorDshotActive = true; ENABLE_STATE(ESC_SENSOR_ENABLED); return true; } +#endif // FUNCTION_ESCSERIAL is shared between SERIALSHOT and ESC_SENSOR telemetry // They are mutually exclusive @@ -315,6 +317,25 @@ bool escSensorInitialize(void) void escSensorUpdate(timeUs_t currentTimeUs) { +#ifdef USE_DSHOT_BIDIR + if (escSensorDshotActive) { + // The motor driver refreshes the data with every decoded frame. Age it at the serial + // poll rate, so a silent ESC drops out of the combined values the same way (the serial + // poll timer doubles as the aging clock, nothing polls here) + const timeMs_t currentTimeMs = currentTimeUs / 1000; + if (currentTimeMs - escTriggerTimeMs >= ESC_REQUEST_TIMEOUT_MS) { + escTriggerTimeMs = currentTimeMs; + for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { + if (escSensorData[i].dataAge < ESC_DATA_INVALID) { + escSensorData[i].dataAge++; + escSensorDataNeedsUpdate = true; + } + } + } + return; + } +#endif + #ifdef USE_MOTOR_SRXL2 if (motorConfig()->motorPwmProtocol == PWM_TYPE_SRXL2) { /* One ESC per port, so escSensorData[i] belongs to the i-th assigned diff --git a/src/main/target/common_post.h b/src/main/target/common_post.h index 5ea03c4fc8d..fb68ba72832 100644 --- a/src/main/target/common_post.h +++ b/src/main/target/common_post.h @@ -185,7 +185,24 @@ extern uint8_t __config_end; #endif #endif -#if defined(USE_ESC_SENSOR) || defined(USE_DSHOT) +// DSHOT variants, all on top of USE_DSHOT: +// - USE_DSHOT_DMAR: one burst DMA stream per timer (target choice) +// - USE_DSHOT_BIDIR: bidirectional DSHOT (eRPM telemetry on the motor line, +// dshot_bidir_enabled). Needs a DMA stream per motor channel for the direction +// switching, so it excludes USE_DSHOT_DMAR. H7 only: the direction switching is +// verified there. Elsewhere the setting is hidden and stays off. +#if defined(USE_DSHOT_DMAR) && !defined(USE_DSHOT) +#error "USE_DSHOT_DMAR requires USE_DSHOT" +#endif +#if defined(USE_DSHOT) && defined(STM32H7) && !defined(USE_DSHOT_DMAR) +#define USE_DSHOT_BIDIR +#endif +#if defined(USE_DSHOT_BIDIR) && (!defined(USE_DSHOT) || defined(USE_DSHOT_DMAR)) +#error "USE_DSHOT_BIDIR requires USE_DSHOT and excludes USE_DSHOT_DMAR" +#endif + +// RPM filter sources: serial ESC telemetry or bidirectional DSHOT +#if defined(USE_ESC_SENSOR) || defined(USE_DSHOT_BIDIR) #define USE_RPM_FILTER #endif diff --git a/src/main/telemetry/srxl.c b/src/main/telemetry/srxl.c index 865e4551659..cb6e5c750d8 100644 --- a/src/main/telemetry/srxl.c +++ b/src/main/telemetry/srxl.c @@ -47,7 +47,6 @@ #include "flight/imu.h" #include "flight/mixer.h" -#include "drivers/dshot.h" #include "io/gps.h" @@ -184,7 +183,7 @@ typedef struct uint16_t getMotorAveragePeriod(void) { -#if defined(USE_ESC_SENSOR) || defined(USE_DSHOT) +#if defined(USE_ESC_SENSOR) uint32_t rpm = 0; uint16_t period_us = SPEKTRUM_RPM_UNUSED; From 59a71614361fb822cda54721d76d632e67f54dd2 Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 24 Sep 2026 19:30:47 +0200 Subject: [PATCH 11/37] DSHOT BIDIR - keep pin hight --- src/main/drivers/pwm_output.c | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 6569628b99d..fe0b175190b 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -321,23 +321,34 @@ void pwmSetMotorDMACircular(bool circular) return; } + int motorCount = getMotorCount(); + const uint32_t dshotHz = getDshotHz(initMotorProtocol); + const uint32_t keepaliveSlots = DSHOT_KEEPALIVE_SLOTS(dshotHz); + // A frame started by pwmCompleteMotorUpdate() may still be in flight for this long + const uint32_t frameUs = DSHOT_DMA_BUFFER_SIZE * DSHOT_MOTOR_BITLENGTH * 1000000UL / dshotHz; + #ifdef USE_DSHOT_BIDIR - // No replay for bidir: the ports switch direction per frame and one may sit in input - // capture, so the circular replay below does not apply. The ESC sees a frame gap (line - // idle-high) for the flash write, as in Betaflight. + // No keep-alive frames for bidir: the ESC sees a frame gap for the flash write, as in + // Betaflight. Between frames a bidir port waits in input capture with the line held + // high only by its pull-up, so on entry complete the turnaround the normal way (frame + // in flight, its reply, every port back to output): in output CCR is 0, which with + // the bidir polarity drives the line at its idle-high level for the whole write. + // Nothing to undo on exit, the next frame starts from that same output state. if (useDshotTelemetry) { + if (circular) { + // Let a frame in flight finish, with the deadtime as margin for its completion + // IRQ, then wait out the reply and turn the ports round as before any frame + delayMicroseconds(frameUs + DSHOT_TELEMETRY_DEADTIME_US); + while (!pwmDshotDecodeTelemetry()) { } + } return; } #endif - int motorCount = getMotorCount(); - const uint32_t dshotHz = getDshotHz(initMotorProtocol); - const uint32_t keepaliveSlots = DSHOT_KEEPALIVE_SLOTS(dshotHz); - if (circular) { // A frame started by pwmCompleteMotorUpdate() may still be in flight: let it finish // and keep the line low for one full gap before the keep-alive stream starts - delayMicroseconds(DSHOT_DMA_BUFFER_SIZE * DSHOT_MOTOR_BITLENGTH * 1000000UL / dshotHz + DSHOT_KEEPALIVE_GAP_US); + delayMicroseconds(frameUs + DSHOT_KEEPALIVE_GAP_US); // Load a zero-throttle packet into the shared keep-alive buffer. The padding slots // must be zero (line low between frames); DMA_RAM is NOLOAD and not cleared at From 1385fdd3c79f639860ad7cafd678a3c5f908031c Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 24 Sep 2026 19:35:31 +0200 Subject: [PATCH 12/37] DSHOT BIDIR - allow for all target without DMAR --- src/main/target/common_post.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/target/common_post.h b/src/main/target/common_post.h index fb68ba72832..a43e6c247de 100644 --- a/src/main/target/common_post.h +++ b/src/main/target/common_post.h @@ -194,7 +194,7 @@ extern uint8_t __config_end; #if defined(USE_DSHOT_DMAR) && !defined(USE_DSHOT) #error "USE_DSHOT_DMAR requires USE_DSHOT" #endif -#if defined(USE_DSHOT) && defined(STM32H7) && !defined(USE_DSHOT_DMAR) +#if defined(USE_DSHOT) && !defined(USE_DSHOT_DMAR) #define USE_DSHOT_BIDIR #endif #if defined(USE_DSHOT_BIDIR) && (!defined(USE_DSHOT) || defined(USE_DSHOT_DMAR)) From d94f0fcaebebc8bc0a016823b55bb14d677322d2 Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 24 Sep 2026 20:42:34 +0200 Subject: [PATCH 13/37] DSHOT BIDIR - fix 1. SRXL2 telemetry disappears from consumers --- src/main/fc/fc_init.c | 2 +- src/main/sensors/esc_sensor.c | 10 ---------- src/main/sensors/esc_sensor.h | 1 - 3 files changed, 1 insertion(+), 12 deletions(-) diff --git a/src/main/fc/fc_init.c b/src/main/fc/fc_init.c index 4ce76d8cb5b..7a501dbfbf4 100644 --- a/src/main/fc/fc_init.c +++ b/src/main/fc/fc_init.c @@ -801,7 +801,7 @@ void init(void) #ifdef USE_RPM_FILTER disableRpmFilters(); - bool rpmSourceActive = escSensorIsActive(); + bool rpmSourceActive = STATE(ESC_SENSOR_ENABLED); #ifdef USE_DSHOT_BIDIR rpmSourceActive = rpmSourceActive || isDshotTelemetryActive(); #endif diff --git a/src/main/sensors/esc_sensor.c b/src/main/sensors/esc_sensor.c index 81e37b00c04..c1fe8cd62b8 100644 --- a/src/main/sensors/esc_sensor.c +++ b/src/main/sensors/esc_sensor.c @@ -185,11 +185,6 @@ void escSensorSetDshotData(uint8_t esc, uint32_t rpm, int16_t temperature, int16 escSensorDataNeedsUpdate = true; } -bool escSensorIsActive(void) -{ - return escSensorPort || escSensorDshotActive; -} - escSensorData_t * escSensorGetData(void) { /* @@ -206,10 +201,6 @@ escSensorData_t * escSensorGetData(void) return NULL; } - if (!escSensorIsActive()) { - return NULL; - } - if (escSensorDataNeedsUpdate) { escSensorDataCombined.dataAge = 0; escSensorDataCombined.temperature = 0; @@ -444,7 +435,6 @@ void escSensorUpdate(timeUs_t currentTimeUs) #endif #ifndef USE_ESC_SENSOR -bool escSensorIsActive(void) { return false; } void escSensorInitData(void) {} void escSensorSetDshotData(uint8_t esc, uint32_t rpm, int16_t temperature, int16_t voltage, int32_t current) { diff --git a/src/main/sensors/esc_sensor.h b/src/main/sensors/esc_sensor.h index 0a8aa1f7f04..a9b0662a1b0 100644 --- a/src/main/sensors/esc_sensor.h +++ b/src/main/sensors/esc_sensor.h @@ -50,5 +50,4 @@ escSensorData_t * getEscTelemetry(uint8_t esc); uint32_t computeRpm(int16_t erpm); void escSensorInitData(void); void escSensorSetDshotData(uint8_t esc, uint32_t rpm, int16_t temperature, int16_t voltage, int32_t current); -bool escSensorIsActive(void); int getTelemetryMotorCount(void); From d9df0b4794ad729d066d784eafcb426916412092 Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 24 Sep 2026 20:48:10 +0200 Subject: [PATCH 14/37] DSHOT BIDIR - 2. AT32 motors never receive usable telemetry --- src/main/drivers/pwm_output.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index fe0b175190b..8a9eab2a45c 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -652,6 +652,15 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) LL_DMA_EnableIT_TC(dmaBase, streamLL); port->telemetryInputActive = false; #elif defined(AT32F43x) + // Telemetry input capture widens the period to 0xffff (see pwmDshotSetDirectionInput); + // restore the DSHOT bit period now, bypassing the period buffer so it takes effect + // immediately, and reset the counter so a stale count above the new period doesn't + // have to run all the way round (TMR2/TMR5 are 32-bit) before the first compare. + tmr_period_buffer_enable(port->tch->timHw->tim, FALSE); + tmr_period_value_set(port->tch->timHw->tim, DSHOT_MOTOR_BITLENGTH - 1); + tmr_period_buffer_enable(port->tch->timHw->tim, TRUE); + tmr_counter_value_set(port->tch->timHw->tim, 0); + tmr_output_config_type output = {0}; tmr_output_default_para_init(&output); output.oc_mode = TMR_OUTPUT_CONTROL_PWM_MODE_A; @@ -753,6 +762,11 @@ static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) LL_DMA_EnableStream(dmaBase, streamLL); LL_TIM_EnableDMAReq_CCx(port->tch->timHw->tim, dshotDmaSource(port)); #elif defined(AT32F43x) + // Widen the period so the free-running counter doesn't wrap every DSHOT bit period + // (20 ticks) while timing GCR edges, which span ~21 bits per telemetry frame. + tmr_period_buffer_enable(port->tch->timHw->tim, TRUE); + tmr_period_value_set(port->tch->timHw->tim, 0xffff); + tmr_input_config_type input; tmr_input_default_para_init(&input); input.input_channel_select = dshotTimChannel(port); From cb545947c6b8c705704248c39e5a90bf68a9161d Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 24 Sep 2026 21:11:02 +0200 Subject: [PATCH 15/37] DSHOT BIDIR - 5. Rp2350 accepts telemetry it cannot use - disable bidirdshot for rpi2350 --- src/main/target/common_post.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/target/common_post.h b/src/main/target/common_post.h index a43e6c247de..b596b95435e 100644 --- a/src/main/target/common_post.h +++ b/src/main/target/common_post.h @@ -189,12 +189,13 @@ extern uint8_t __config_end; // - USE_DSHOT_DMAR: one burst DMA stream per timer (target choice) // - USE_DSHOT_BIDIR: bidirectional DSHOT (eRPM telemetry on the motor line, // dshot_bidir_enabled). Needs a DMA stream per motor channel for the direction -// switching, so it excludes USE_DSHOT_DMAR. H7 only: the direction switching is -// verified there. Elsewhere the setting is hidden and stays off. +// switching, so it excludes USE_DSHOT_DMAR. Implemented by the timer/DMA motor +// driver (pwm_output.c); RP2350 drives its motors from a PIO program that only +// transmits, so the setting is hidden there and stays off. #if defined(USE_DSHOT_DMAR) && !defined(USE_DSHOT) #error "USE_DSHOT_DMAR requires USE_DSHOT" #endif -#if defined(USE_DSHOT) && !defined(USE_DSHOT_DMAR) +#if defined(USE_DSHOT) && !defined(USE_DSHOT_DMAR) && !defined(RP2350) #define USE_DSHOT_BIDIR #endif #if defined(USE_DSHOT_BIDIR) && (!defined(USE_DSHOT) || defined(USE_DSHOT_DMAR)) From 4ec7ad616f889685ab837e315542267a09818be3 Mon Sep 17 00:00:00 2001 From: Error414 Date: Sat, 26 Sep 2026 19:35:09 +0200 Subject: [PATCH 16/37] DSHOT BIDIR - small fixes for RPM filters --- src/main/drivers/bidir_dshot.c | 16 ++++++---------- src/main/drivers/bidir_dshot.h | 5 +++-- src/main/drivers/pwm_output.c | 33 ++++++++++++++++++++++----------- src/main/fc/fc_init.c | 2 +- src/main/flight/rpm_filter.c | 18 ++++++++---------- 5 files changed, 40 insertions(+), 34 deletions(-) diff --git a/src/main/drivers/bidir_dshot.c b/src/main/drivers/bidir_dshot.c index 7de3b94c56f..df624e49c7c 100644 --- a/src/main/drivers/bidir_dshot.c +++ b/src/main/drivers/bidir_dshot.c @@ -30,21 +30,21 @@ // Bidirectional DSHOT telemetry only: eRPM / EDT decoding, RPM state for the RPM filter and // the ESC sensor. Frame generation, DMA and DSHOT commands for plain DSHOT live in // pwm_output.c under USE_DSHOT. Every user of this API is guarded by USE_DSHOT_BIDIR. +// +// Values are published as decoded, unfiltered: frames arrive at the DSHOT frame rate, which +// follows the scheduler's idle time rather than any fixed period, so smoothing belongs to the +// consumer that samples them at a known rate (rpmFilterUpdateTask()). #ifdef USE_DSHOT_BIDIR -#include "common/filter.h" #include "common/maths.h" #include "flight/mixer.h" #include "drivers/pwm_mapping.h" -#define DSHOT_RPM_LPF_HZ 150 - bool useDshotTelemetry = false; dshotTelemetryState_t dshotTelemetryState; -static pt1Filter_t motorFreqLpf[MAX_SUPPORTED_MOTORS]; static float motorFrequencyHz[MAX_SUPPORTED_MOTORS]; static float dshotRpm[MAX_SUPPORTED_MOTORS]; static float dshotRpmAverage; @@ -118,7 +118,7 @@ bool isDshotTelemetryActive(void) // useDshotTelemetry itself is set by the motor driver (pwmMotorPreconfigure()), which // knows whether the outputs were configured for DSHOT at all -void initDshotTelemetry(timeUs_t looptimeUs) +void initDshotTelemetry(void) { edtAlwaysDecode = motorConfig()->useDshotEdt != 0; @@ -129,10 +129,6 @@ void initDshotTelemetry(timeUs_t looptimeUs) } erpmToHz = ERPM_PER_LSB / 60.0f / (motorConfig()->motorPoleCount / 2.0f); - - for (unsigned i = 0; i < MAX_SUPPORTED_MOTORS; i++) { - pt1FilterInit(&motorFreqLpf[i], DSHOT_RPM_LPF_HZ, looptimeUs * 1e-6f); - } } uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) @@ -168,7 +164,7 @@ uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) if (type == DSHOT_TELEMETRY_TYPE_ERPM) { dshotRpm[motorIndex] = erpmToRpm(decoded); - motorFrequencyHz[motorIndex] = pt1FilterApply(&motorFreqLpf[motorIndex], erpmToHz * decoded); + motorFrequencyHz[motorIndex] = erpmToHz * decoded; } float rpmTotal = 0.0f; diff --git a/src/main/drivers/bidir_dshot.h b/src/main/drivers/bidir_dshot.h index 5eeeee6aac9..1c8eb96d60f 100644 --- a/src/main/drivers/bidir_dshot.h +++ b/src/main/drivers/bidir_dshot.h @@ -26,7 +26,7 @@ #include "platform.h" -#include "drivers/time.h" +#include "drivers/time.h" // timeUs_t for sensors/esc_sensor.h, which has no includes of its own #include "flight/mixer.h" #include "sensors/esc_sensor.h" @@ -76,7 +76,7 @@ typedef struct { extern bool useDshotTelemetry; extern dshotTelemetryState_t dshotTelemetryState; -void initDshotTelemetry(timeUs_t looptimeUs); +void initDshotTelemetry(void); void dshotResetTelemetry(void); bool isDshotTelemetryConfigured(void); bool isDshotTelemetryActive(void); @@ -84,6 +84,7 @@ uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex); float getDshotRpm(uint8_t motorIndex); uint16_t getDshotErpm(uint8_t motorIndex); float getDshotRpmAverage(void); +// Mechanical frequency from the last decoded eRPM frame, unfiltered (see bidir_dshot.c) float getMotorFrequencyHz(uint8_t motorIndex); bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex); #endif diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 8a9eab2a45c..a798357eb32 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -133,8 +133,6 @@ typedef struct { #endif #ifdef USE_DSHOT_BIDIR bool telemetryInputActive; - timeUs_t telemetryInputStampUs; - timeUs_t dshotTelemetryDeadtimeUs; #endif #endif } pwmOutputPort_t; @@ -169,6 +167,13 @@ static timeUs_t lastCommandSent = 0; static timeUs_t commandPostDelay = 0; #ifdef USE_DSHOT_BIDIR static bool dshotTelemetryPending = false; +/* One stamp for the whole frame, taken from the last port turned round for the reply + * (all ports switch within microseconds of each other). Turning a port back to output + * resets the counter and period of its timer, which every other port on that timer + * shares, so no port may switch back while a sibling could still be capturing: the + * deadtime is therefore waited out once, for all ports, before any of them is touched */ +static timeUs_t dshotTelemetryInputStampUs = 0; +static timeUs_t dshotTelemetryDeadtimeUs = 0; #endif static circularBuffer_t commandsCircularBuffer; @@ -802,7 +807,6 @@ static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) DMA_Cmd(port->tch->dma->ref, ENABLE); TIM_DMACmd(port->tch->timHw->tim, dshotDmaSource(port), ENABLE); #endif - port->telemetryInputStampUs = micros(); port->telemetryInputActive = true; } @@ -864,6 +868,7 @@ static void pwmDshotDmaIrqHandler(DMA_t descriptor) if (!port->telemetryInputActive) { pwmDshotSetDirectionInput(port); + dshotTelemetryInputStampUs = micros(); dshotTelemetryPending = true; } @@ -878,17 +883,23 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) return true; } - const timeUs_t now = micros(); + // Wait for the last reply of the frame before switching any port back (see + // dshotTelemetryInputStampUs) + if ((micros() - dshotTelemetryInputStampUs) < dshotTelemetryDeadtimeUs) { + return false; + } + + // Cleared before the loop: a completion IRQ landing while the loop runs re-arms it, so a + // port the loop has already passed is picked up by the next call instead of being left + // in input for the following frame + dshotTelemetryPending = false; + for (int motorIndex = 0; motorIndex < getMotorCount(); motorIndex++) { pwmOutputPort_t *port = motors[motorIndex].pwmPort; if (!port || !port->configured || !port->telemetryInputActive) { continue; } - if ((now - port->telemetryInputStampUs) < port->dshotTelemetryDeadtimeUs) { - return false; - } - uint32_t edges = 0; #if defined(USE_HAL_DRIVER) const uint32_t streamLL = dshotDmaStream(port); @@ -929,8 +940,8 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) pwmDshotSetDirectionOutput(port); } - dshotTelemetryPending = false; - return true; + // Re-armed during the loop: some port is in input again, hold the frame until it is back + return !dshotTelemetryPending; } #endif // USE_DSHOT_BIDIR @@ -984,7 +995,7 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, if (useDshotTelemetry) { // Inverted signalling and per-frame direction switching; the port takes the // stream's completion interrupt over from the timer driver - port->dshotTelemetryDeadtimeUs = DSHOT_TELEMETRY_DEADTIME_US + 1000000 * (16 * DSHOT_MOTOR_BITLENGTH) / dshotHz; + dshotTelemetryDeadtimeUs = DSHOT_TELEMETRY_DEADTIME_US + 1000000 * (16 * DSHOT_MOTOR_BITLENGTH) / dshotHz; pwmDshotSetDirectionOutput(port); dmaSetHandler(port->tch->dma, pwmDshotDmaIrqHandler, NVIC_PRIO_TIMER_DMA, allocatedOutputPortCount - 1); } diff --git a/src/main/fc/fc_init.c b/src/main/fc/fc_init.c index 7a501dbfbf4..b83297e9744 100644 --- a/src/main/fc/fc_init.c +++ b/src/main/fc/fc_init.c @@ -767,7 +767,7 @@ void init(void) initDShotCommands(); #endif #ifdef USE_DSHOT_BIDIR - initDshotTelemetry(getLooptime()); + initDshotTelemetry(); #endif #ifdef USE_SERIAL_GIMBAL diff --git a/src/main/flight/rpm_filter.c b/src/main/flight/rpm_filter.c index 155efab45a0..52586280e36 100644 --- a/src/main/flight/rpm_filter.c +++ b/src/main/flight/rpm_filter.c @@ -66,9 +66,7 @@ typedef struct typedef float (*rpmFilterApplyFnPtr)(rpmFilterBank_t *filter, uint8_t axis, float input); typedef void (*rpmFilterUpdateFnPtr)(rpmFilterBank_t *filterBank, uint8_t motor, float baseFrequency); -#ifdef USE_ESC_SENSOR static EXTENDED_FASTRAM pt1Filter_t motorFrequencyFilter[MAX_SUPPORTED_MOTORS]; -#endif static EXTENDED_FASTRAM rpmFilterBank_t gyroRpmFilters; static EXTENDED_FASTRAM rpmFilterApplyFnPtr rpmGyroApplyFn; static EXTENDED_FASTRAM rpmFilterUpdateFnPtr rpmGyroUpdateFn; @@ -161,11 +159,9 @@ void rpmFilterUpdate(rpmFilterBank_t *filterBank, uint8_t motor, float baseFrequ void rpmFiltersInit(void) { -#ifdef USE_ESC_SENSOR for (uint8_t i = 0; i < MAX_SUPPORTED_MOTORS; i++) { pt1FilterInit(&motorFrequencyFilter[i], RPM_FILTER_RPM_LPF_HZ, US2S(RPM_FILTER_UPDATE_RATE_US)); } -#endif rpmGyroUpdateFn = (rpmFilterUpdateFnPtr)nullRpmFilterUpdate; @@ -187,24 +183,26 @@ void rpmFilterUpdateTask(timeUs_t currentTimeUs) uint8_t motorCount = getMotorCount(); /* - * For each motor, read ERPM, filter it and update motor frequency + * For each motor, read its frequency, filter it and update the notches. Both sources + * hand over their latest raw value; the LPF runs here, at this task's fixed rate, so its + * cutoff does not depend on how often new frames happened to arrive */ for (uint8_t i = 0; i < motorCount; i++) { - float baseFrequency; + float motorFrequency; #ifdef USE_DSHOT_BIDIR if (isDshotTelemetryActive()) { - baseFrequency = getMotorFrequencyHz(i); + motorFrequency = getMotorFrequencyHz(i); } else #endif { #ifdef USE_ESC_SENSOR - const escSensorData_t *escState = getEscTelemetry(i); - baseFrequency = pt1FilterApply(&motorFrequencyFilter[i], (float)escState->rpm / 60.0f); + motorFrequency = (float)getEscTelemetry(i)->rpm / 60.0f; #else - baseFrequency = 0.0f; + motorFrequency = 0.0f; #endif } + const float baseFrequency = pt1FilterApply(&motorFrequencyFilter[i], motorFrequency); rpmGyroUpdateFn(&gyroRpmFilters, i, baseFrequency); } } From fdd4052b2bc074c5f252b2e4c10f20d3fe5c229f Mon Sep 17 00:00:00 2001 From: Error414 Date: Mon, 28 Sep 2026 11:12:14 +0200 Subject: [PATCH 17/37] DSHOT BIDIR - add bidir dshot rpm to MSP --- docs/Blackbox.md | 1 + docs/Settings.md | 1 + src/main/build/debug.h | 1 + src/main/fc/cli.c | 3 ++- src/main/fc/fc_msp.c | 23 ++++++++++++++++++++--- src/main/fc/settings.yaml | 2 +- src/main/flight/rpm_filter.c | 5 +++++ 7 files changed, 31 insertions(+), 5 deletions(-) diff --git a/docs/Blackbox.md b/docs/Blackbox.md index 55b0f19c103..91b6934c1ee 100644 --- a/docs/Blackbox.md +++ b/docs/Blackbox.md @@ -194,6 +194,7 @@ Available debug modes include: - `GPS` - GPS debugging - `ALTITUDE` - Altitude estimation debugging - `MAG` - Raw, uncalibrated magnetometer samples (useful for external compass calibration) +- `RPM_FILTER` - Per-motor RPM as seen by the RPM filter, motors 1-8 in `debug[0]`-`debug[7]` (needs the RPM filter enabled, so bidirectional DShot or ESC telemetry) - And 20+ other modes for specific subsystems To use debug mode logging: diff --git a/docs/Settings.md b/docs/Settings.md index 807e8612643..d4628807791 100644 --- a/docs/Settings.md +++ b/docs/Settings.md @@ -803,6 +803,7 @@ Defines debug values exposed in debug variables (developer / debugging setting) | ESC | | | FW_TURN | | | MAG | | +| RPM_FILTER | | --- diff --git a/src/main/build/debug.h b/src/main/build/debug.h index 23caa6b6fa7..6adfd58cf72 100644 --- a/src/main/build/debug.h +++ b/src/main/build/debug.h @@ -87,6 +87,7 @@ typedef enum { DEBUG_ESC, DEBUG_FW_TURN, DEBUG_MAG, + DEBUG_RPM_FILTER, DEBUG_COUNT // also update debugModeNames in cli.c } debugType_e; diff --git a/src/main/fc/cli.c b/src/main/fc/cli.c index 73c65919b09..d602e069b77 100644 --- a/src/main/fc/cli.c +++ b/src/main/fc/cli.c @@ -238,7 +238,8 @@ static const char *debugModeNames[DEBUG_COUNT] = { "TERRAIN_NAV", "ESC", "FW_TURN", - "MAG" + "MAG", + "RPM_FILTER" }; /* Sensor names (used in lookup tables for *_hardware settings and in status diff --git a/src/main/fc/fc_msp.c b/src/main/fc/fc_msp.c index d00984f2d85..42fb6bd8a3f 100644 --- a/src/main/fc/fc_msp.c +++ b/src/main/fc/fc_msp.c @@ -47,6 +47,7 @@ #include "drivers/compass/compass.h" #include "drivers/compass/compass_msp.h" #include "drivers/barometer/barometer_msp.h" +#include "drivers/bidir_dshot.h" #include "drivers/pitotmeter/pitotmeter_msp.h" #include "sensors/battery_sensor_fake.h" #include "drivers/bus_i2c.h" @@ -1939,18 +1940,34 @@ static bool mspFcProcessOutCommand(uint16_t cmdMSP, sbuf_t *dst, mspPostProcessF break; #endif -#ifdef USE_ESC_SENSOR +#if defined(USE_ESC_SENSOR) || defined(USE_DSHOT_BIDIR) case MSP2_INAV_ESC_RPM: { uint8_t motorCount = getMotorCount(); + // Same source selection as rpmFilterUpdateTask(): bidirectional DSHOT keeps its + // own per-motor RPM, so it works on targets without USE_ESC_SENSOR too for (uint8_t i = 0; i < motorCount; i++){ - const escSensorData_t *escState = getEscTelemetry(i); //Get ESC telemetry - sbufWriteU32(dst, escState->rpm); + uint32_t rpm; +#ifdef USE_DSHOT_BIDIR + if (isDshotTelemetryActive()) { + rpm = lrintf(getDshotRpm(i)); + } else +#endif + { +#ifdef USE_ESC_SENSOR + rpm = getEscTelemetry(i)->rpm; +#else + rpm = 0; +#endif + } + sbufWriteU32(dst, rpm); } } break; +#endif +#ifdef USE_ESC_SENSOR case MSP2_INAV_ESC_TELEM: { uint8_t motorCount = getMotorCount(); diff --git a/src/main/fc/settings.yaml b/src/main/fc/settings.yaml index c0ca1657145..6c0d770f4c1 100644 --- a/src/main/fc/settings.yaml +++ b/src/main/fc/settings.yaml @@ -93,7 +93,7 @@ tables: "AUTOTRIM", "AUTOTUNE", "RATE_DYNAMICS", "LANDING", "POS_EST", "ADAPTIVE_FILTER", "HEADTRACKER", "GPS", "LULU", "SBUS2", "OSD_REFRESH", "MAG_CALIB", "VTOL_TRANSITION", "VTOL_MC_PROTECT", "TERRAIN_NAV", "ESC", - "FW_TURN", "MAG"] + "FW_TURN", "MAG", "RPM_FILTER"] - name: vtol_mc_protection_mode values: ["OFF", "NAV", "NAV_AND_STABILIZED"] - name: aux_operator diff --git a/src/main/flight/rpm_filter.c b/src/main/flight/rpm_filter.c index 52586280e36..0e2970abab0 100644 --- a/src/main/flight/rpm_filter.c +++ b/src/main/flight/rpm_filter.c @@ -204,6 +204,11 @@ void rpmFilterUpdateTask(timeUs_t currentTimeUs) } const float baseFrequency = pt1FilterApply(&motorFrequencyFilter[i], motorFrequency); rpmGyroUpdateFn(&gyroRpmFilters, i, baseFrequency); + + // Per-motor RPM as the notch sees it (after the LPF); blackbox has no per-motor field + if (i < DEBUG32_VALUE_COUNT) { + DEBUG_SET(DEBUG_RPM_FILTER, i, lrintf(baseFrequency * 60.0f)); + } } } From 61637a556788346eb08ed6dd8f060240ce01c03a Mon Sep 17 00:00:00 2001 From: Error414 Date: Mon, 28 Sep 2026 17:53:32 +0200 Subject: [PATCH 18/37] DSHOT BIDIR - fix DMA library clearing flag --- src/main/drivers/dma.h | 8 ++++---- src/main/drivers/pwm_output.c | 9 +++------ src/main/flight/rpm_filter.c | 2 ++ 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/main/drivers/dma.h b/src/main/drivers/dma.h index 10ece999253..3a866f6eae8 100644 --- a/src/main/drivers/dma.h +++ b/src/main/drivers/dma.h @@ -100,8 +100,8 @@ typedef void (*dmaCallbackHandlerFuncPtr)(DMA_t channelDescriptor); dmaDescriptors[i].irqHandlerCallback(&dmaDescriptors[i]);\ } -#define DMA_CLEAR_FLAG(d, flag) if (d->flagsShift > 31) d->dma->HIFCR = (flag << (d->flagsShift - 32)); else d->dma->LIFCR = (flag << d->flagsShift) -#define DMA_GET_FLAG_STATUS(d, flag) (d->flagsShift > 31 ? d->dma->HISR & (flag << (d->flagsShift - 32)): d->dma->LISR & (flag << d->flagsShift)) +#define DMA_CLEAR_FLAG(d, flag) if (d->flagsShift > 31) d->dma->HIFCR = ((flag) << (d->flagsShift - 32)); else d->dma->LIFCR = ((flag) << d->flagsShift) +#define DMA_GET_FLAG_STATUS(d, flag) (d->flagsShift > 31 ? d->dma->HISR & ((flag) << (d->flagsShift - 32)): d->dma->LISR & ((flag) << d->flagsShift)) @@ -129,8 +129,8 @@ DMA_t dmaGetByRef(const DMA_Stream_TypeDef * ref); } //Same as dma_flag_clear/dma_flag_get -#define DMA_CLEAR_FLAG(d, flag) d->dma->clr = (flag << d->flagsShift) -#define DMA_GET_FLAG_STATUS(d, flag) (d->dma->sts & (flag << d->flagsShift)) +#define DMA_CLEAR_FLAG(d, flag) d->dma->clr = ((flag) << d->flagsShift) +#define DMA_GET_FLAG_STATUS(d, flag) (d->dma->sts & ((flag) << d->flagsShift)) DMA_t dmaGetByRef(const dma_channel_type * ref); diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index e95c47a3958..0beae79075d 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -1032,12 +1032,9 @@ static void loadDmaBufferDshot(timerDMASafeType_t *dmaBuffer, uint16_t packet) static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry) { -#ifdef USE_DSHOT_BIDIR - if (useDshotTelemetry) { - requestTelemetry = true; - } -#endif - + // The telemetry bit asks for a serial telemetry packet on the ESC's telemetry wire; + // the eRPM reply on the motor line is triggered by the inverted checksum alone, so + // bidir leaves the bit to the serial ESC sensor's round-robin requests uint16_t packet = (value << 1) | (requestTelemetry ? 1 : 0); // compute checksum diff --git a/src/main/flight/rpm_filter.c b/src/main/flight/rpm_filter.c index 0e2970abab0..1cbdb6d6923 100644 --- a/src/main/flight/rpm_filter.c +++ b/src/main/flight/rpm_filter.c @@ -22,6 +22,8 @@ * along with this program. If not, see http://www.gnu.org/licenses/. */ +#include + #include "platform.h" #include "flight/rpm_filter.h" From 20b0c5445e7ca6eb1861e45852e0e94fbc59acf2 Mon Sep 17 00:00:00 2001 From: Error414 Date: Tue, 29 Sep 2026 16:38:05 +0200 Subject: [PATCH 19/37] DSHOT BIDIR - add counters of frames for bidir and for aurt telemetry --- src/main/drivers/bidir_dshot.c | 24 ++++++++++++++++++------ src/main/drivers/bidir_dshot.h | 11 ++--------- src/main/drivers/pwm_output.c | 26 +++++++++++++++++--------- src/main/sensors/esc_sensor.c | 18 ++++++++++++++++++ src/main/sensors/esc_sensor.h | 22 ++++++++++++++++++++++ 5 files changed, 77 insertions(+), 24 deletions(-) diff --git a/src/main/drivers/bidir_dshot.c b/src/main/drivers/bidir_dshot.c index df624e49c7c..bc53b07281f 100644 --- a/src/main/drivers/bidir_dshot.c +++ b/src/main/drivers/bidir_dshot.c @@ -50,6 +50,7 @@ static float dshotRpm[MAX_SUPPORTED_MOTORS]; static float dshotRpmAverage; static float erpmToHz; static bool edtAlwaysDecode; +static timeUs_t frameWindowStartUs; static const dshotTelemetryType_e extendedTelemetryLookup[8] = { DSHOT_TELEMETRY_TYPE_ERPM, @@ -137,24 +138,24 @@ uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) return rawValue; } + // Called once per reply window, NOEDGE included, so total covers a silent ESC too + dshotTelemetryState.motorState[motorIndex].frames.total++; + if (rawValue == DSHOT_TELEMETRY_INVALID || rawValue == DSHOT_TELEMETRY_NOEDGE) { - if (rawValue == DSHOT_TELEMETRY_INVALID) { - dshotTelemetryState.invalidPacketCount++; - } return rawValue; } - dshotTelemetryState.readCount++; dshotTelemetryState.motorState[motorIndex].rawValue = rawValue; dshotTelemetryType_e type; uint32_t decoded; dshotDecodeTelemetryValue(motorIndex, &decoded, &type); if (decoded == DSHOT_TELEMETRY_INVALID) { - dshotTelemetryState.invalidPacketCount++; return DSHOT_TELEMETRY_INVALID; } + dshotTelemetryState.motorState[motorIndex].frames.valid++; + dshotTelemetryState.motorState[motorIndex].telemetryData[type] = decoded; dshotTelemetryState.motorState[motorIndex].telemetryTypes |= (1 << type); @@ -176,11 +177,22 @@ uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) } } dshotRpmAverage = rpmCount ? rpmTotal / rpmCount : 0.0f; - dshotTelemetryState.rawValueState = DSHOT_RAW_VALUE_STATE_PROCESSED; return rawValue; } +void dshotFrameWindowUpdate(timeUs_t currentTimeUs) +{ + if (currentTimeUs - frameWindowStartUs < ESC_FRAME_WINDOW_MS * 1000) { + return; + } + + frameWindowStartUs = currentTimeUs; + for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { + escFrameCounterCloseWindow(&dshotTelemetryState.motorState[i].frames); + } +} + uint16_t getDshotErpm(uint8_t motorIndex) { return dshotTelemetryState.motorState[motorIndex].telemetryData[DSHOT_TELEMETRY_TYPE_ERPM]; diff --git a/src/main/drivers/bidir_dshot.h b/src/main/drivers/bidir_dshot.h index 1c8eb96d60f..0dca223e4ea 100644 --- a/src/main/drivers/bidir_dshot.h +++ b/src/main/drivers/bidir_dshot.h @@ -52,24 +52,16 @@ typedef enum { #define DSHOT_NORMAL_TELEMETRY_MASK (1 << DSHOT_TELEMETRY_TYPE_ERPM) #define DSHOT_EXTENDED_TELEMETRY_MASK (~DSHOT_NORMAL_TELEMETRY_MASK) -typedef enum { - DSHOT_RAW_VALUE_STATE_INVALID = 0, - DSHOT_RAW_VALUE_STATE_NOT_PROCESSED, - DSHOT_RAW_VALUE_STATE_PROCESSED, -} dshotRawValueState_e; - typedef struct { uint16_t rawValue; uint16_t telemetryData[DSHOT_TELEMETRY_TYPE_COUNT]; uint8_t telemetryTypes; uint8_t maxTemp; + escFrameCounter_t frames; } dshotTelemetryMotorState_t; typedef struct { - uint32_t invalidPacketCount; - uint32_t readCount; dshotTelemetryMotorState_t motorState[MAX_SUPPORTED_MOTORS]; - dshotRawValueState_e rawValueState; } dshotTelemetryState_t; #ifdef USE_DSHOT_BIDIR @@ -81,6 +73,7 @@ void dshotResetTelemetry(void); bool isDshotTelemetryConfigured(void); bool isDshotTelemetryActive(void); uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex); +void dshotFrameWindowUpdate(timeUs_t currentTimeUs); float getDshotRpm(uint8_t motorIndex); uint16_t getDshotErpm(uint8_t motorIndex); float getDshotRpmAverage(void); diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 0beae79075d..0c2f5edf711 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -916,6 +916,8 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) DMA_Cmd(port->tch->dma->ref, DISABLE); #endif + // Too few edges is no reply at all; still handed on so the frame counter sees it + uint16_t rawValue = DSHOT_TELEMETRY_NOEDGE; if (edges > MIN_GCR_EDGES) { #if defined(STM32H7) // Defensive: DMA_RAM is mapped non-cacheable by the MPU, so this is a no-op as @@ -923,18 +925,18 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) uint32_t alignedAddr = (uint32_t)port->dmaBuffer & ~0x1F; SCB_InvalidateDCache_by_Addr((uint32_t *)alignedAddr, edges * sizeof(port->dmaBuffer[0]) + ((uint32_t)port->dmaBuffer - alignedAddr)); #endif - const uint16_t rawValue = dshotDecodeTelemetryPacket((const uint32_t *)port->dmaBuffer, edges); - const uint16_t processed = dshotProcessPacket(rawValue, motorIndex); + rawValue = dshotDecodeTelemetryPacket((const uint32_t *)port->dmaBuffer, edges); + } - if (processed != DSHOT_TELEMETRY_INVALID && processed != DSHOT_TELEMETRY_NOEDGE) { + const uint16_t processed = dshotProcessPacket(rawValue, motorIndex); + if (processed != DSHOT_TELEMETRY_INVALID && processed != DSHOT_TELEMETRY_NOEDGE) { #ifdef USE_ESC_SENSOR - // Nothing to publish before the first eRPM value (an EDT frame may come first) - escSensorData_t data; - if (getDshotEscSensorData(&data, motorIndex)) { - escSensorSetDshotData(motorIndex, data.rpm, data.temperature, data.voltage, data.current); - } -#endif + // Nothing to publish before the first eRPM value (an EDT frame may come first) + escSensorData_t data; + if (getDshotEscSensorData(&data, motorIndex)) { + escSensorSetDshotData(motorIndex, data.rpm, data.temperature, data.voltage, data.current); } +#endif } pwmDshotSetDirectionOutput(port); @@ -1177,6 +1179,12 @@ void pwmCompleteMotorUpdate(void) { int motorCount = getMotorCount(); timeUs_t currentTimeUs = micros(); +#ifdef USE_DSHOT_BIDIR + if (useDshotTelemetry) { + dshotFrameWindowUpdate(currentTimeUs); + } +#endif + // Enforce motor update rate if ((digitalMotorUpdateIntervalUs == 0) || ((currentTimeUs - digitalMotorLastUpdateUs) <= digitalMotorUpdateIntervalUs)) { return; diff --git a/src/main/sensors/esc_sensor.c b/src/main/sensors/esc_sensor.c index c1fe8cd62b8..b925bb426a2 100644 --- a/src/main/sensors/esc_sensor.c +++ b/src/main/sensors/esc_sensor.c @@ -79,6 +79,8 @@ static int escSensorMotor; static uint8_t telemetryBuffer[TELEMETRY_FRAME_SIZE]; static int bufferPosition = 0; static escSensorData_t escSensorData[MAX_SUPPORTED_MOTORS]; +static escFrameCounter_t escSensorFrames[MAX_SUPPORTED_MOTORS]; +static timeMs_t escFrameWindowStartMs; static escSensorData_t escSensorDataCombined; static bool escSensorDataNeedsUpdate; static bool escSensorDshotActive; @@ -132,6 +134,7 @@ static bool escSensorDecodeFrame(void) if (bufferPosition >= TELEMETRY_FRAME_SIZE) { uint8_t checksum = crc8_update(0, telemetryBuffer, TELEMETRY_FRAME_SIZE - 1); if (checksum == telemetryBuffer[TELEMETRY_FRAME_SIZE - 1]) { + escSensorFrames[escSensorMotor].valid++; escSensorData[escSensorMotor].dataAge = 0; escSensorData[escSensorMotor].temperature = telemetryBuffer[0]; escSensorData[escSensorMotor].voltage = ((uint16_t)telemetryBuffer[1]) << 8 | telemetryBuffer[2]; @@ -159,6 +162,11 @@ escSensorData_t NOINLINE * getEscTelemetry(uint8_t esc) return &escSensorData[esc]; } +const escFrameCounter_t * escSensorGetFrameCounter(uint8_t esc) +{ + return &escSensorFrames[esc]; +} + void escSensorInitData(void) { for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { @@ -381,6 +389,13 @@ void escSensorUpdate(timeUs_t currentTimeUs) const timeMs_t currentTimeMs = currentTimeUs / 1000; + if (currentTimeMs - escFrameWindowStartMs >= ESC_FRAME_WINDOW_MS) { + escFrameWindowStartMs = currentTimeMs; + for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { + escFrameCounterCloseWindow(&escSensorFrames[i]); + } + } + switch (escSensorState) { case ESC_SENSOR_WAIT_STARTUP: if (currentTimeMs > ESC_BOOTTIME_MS) { @@ -393,6 +408,9 @@ void escSensorUpdate(timeUs_t currentTimeUs) if (!escSensorConfig()->listenOnly) { pwmRequestMotorTelemetry(escSensorMotor); } + // One reply expected per request (per listen window with listenOnly); a timeout + // or a CRC error just never makes it to valid + escSensorFrames[escSensorMotor].total++; bufferPosition = 0; escTriggerTimeMs = currentTimeMs; escSensorState = ESC_SENSOR_WAITING; diff --git a/src/main/sensors/esc_sensor.h b/src/main/sensors/esc_sensor.h index a9b0662a1b0..4021cd1d992 100644 --- a/src/main/sensors/esc_sensor.h +++ b/src/main/sensors/esc_sensor.h @@ -32,6 +32,27 @@ typedef struct { uint32_t rpm; } escSensorData_t; +#define ESC_FRAME_WINDOW_MS 1000 + +// Telemetry link quality of one ESC over fixed back-to-back windows. total counts every reply +// expected, a missing one too, valid those that decoded. The last closed window is kept, so +// the reported value moves once per window; lastWindowTotal == 0 means nothing was expected +// (boot, other telemetry source) and lastWindowSuccess is meaningless then +typedef struct { + uint16_t total; + uint16_t valid; + uint16_t lastWindowTotal; + uint8_t lastWindowSuccess; // percent +} escFrameCounter_t; + +static inline void escFrameCounterCloseWindow(escFrameCounter_t *counter) +{ + counter->lastWindowTotal = counter->total; + counter->lastWindowSuccess = counter->total ? (uint32_t)counter->valid * 100 / counter->total : 0; + counter->total = 0; + counter->valid = 0; +} + typedef struct escSensorConfig_s { uint16_t currentOffset; // offset consumed by the flight controller / VTX / cam / ... in mA uint8_t listenOnly; @@ -47,6 +68,7 @@ bool escSensorInitialize(void); void escSensorUpdate(timeUs_t currentTimeUs); escSensorData_t * escSensorGetData(void); escSensorData_t * getEscTelemetry(uint8_t esc); +const escFrameCounter_t * escSensorGetFrameCounter(uint8_t esc); uint32_t computeRpm(int16_t erpm); void escSensorInitData(void); void escSensorSetDshotData(uint8_t esc, uint32_t rpm, int16_t temperature, int16_t voltage, int32_t current); From 020f8f90fede4d5137a3519e42b68a40d51e8417 Mon Sep 17 00:00:00 2001 From: Error414 Date: Tue, 29 Sep 2026 16:44:20 +0200 Subject: [PATCH 20/37] DSHOT BIDIR - add counters to MSP for configurator --- docs/development/msp/README.md | 6 ++++-- docs/development/msp/msp_messages.json | 18 +++++++++++++++--- src/main/fc/fc_msp.c | 8 ++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/docs/development/msp/README.md b/docs/development/msp/README.md index e5f33283da5..750da8cb9dd 100644 --- a/docs/development/msp/README.md +++ b/docs/development/msp/README.md @@ -4180,7 +4180,7 @@ When the MSP JSON specification changes, bump `msp_messages.json` version: **Notes:** Requires `USE_PROGRAMMING_FRAMEWORK`. Fixed 8-byte reply carrying one 64-bit mask as two `uint32_t` halves, low half first. Only the first `MIN(MAX_LOGIC_CONDITIONS, 64)` bits are evaluated. A condition counts as configured when any of `enabled`, `activatorId` (default -1), `operation`, `operandA.type`, `operandA.value`, `operandB.type`, `operandB.value` or `flags` differs from its default. ## `MSP2_INAV_ESC_RPM (8256 / 0x2040)` -**Description:** Retrieves the RPM reported by each ESC via telemetry. +**Description:** Retrieves the RPM and telemetry link quality reported by each ESC. **Request Payload:** **None** @@ -4188,8 +4188,10 @@ When the MSP JSON specification changes, bump `msp_messages.json` version: |Field|C Type|Size (Bytes)|Units|Description| |---|---|---|---|---| | `escRpm` | `uint32_t` | 4 | RPM | RPM reported by the ESC | +| `frameSuccess` | `uint8_t` | 1 | % | Share of telemetry replies decoded in the last closed window. 255 when no reply was expected in that window | +| `frameTotal` | `uint16_t` | 2 | frames | Telemetry replies expected in the last closed window, missing ones included | -**Notes:** Requires `USE_ESC_SENSOR`. Payload size depends on the number of detected motors with telemetry. +**Notes:** Requires `USE_ESC_SENSOR` or `USE_DSHOT_BIDIR`. 7 bytes per motor, `getMotorCount()` entries. Source follows the RPM filter: bidirectional DSHOT when `isDshotTelemetryActive()`, serial ESC telemetry otherwise. The frame statistics come from fixed back-to-back windows of `ESC_FRAME_WINDOW_MS` (1 s), so they change once per window. A reply counts as missing when the ESC stays silent, fails CRC/GCR decoding or (serial) times out. Sources without frame counting (SRXL2) always report 255 / 0. ## `MSP2_INAV_ESC_TELEM (8257 / 0x2041)` **Description:** Retrieves the full telemetry data structure reported by each ESC. diff --git a/docs/development/msp/msp_messages.json b/docs/development/msp/msp_messages.json index 41169c0dead..79a87a24e22 100644 --- a/docs/development/msp/msp_messages.json +++ b/docs/development/msp/msp_messages.json @@ -2,7 +2,7 @@ "version": { "major": 2, "minor": 1, - "patch": 1 + "patch": 2 }, "messages": { "MSP_API_VERSION": { @@ -9847,13 +9847,25 @@ "ctype": "uint32_t", "desc": "RPM reported by the ESC", "units": "RPM" + }, + { + "name": "frameSuccess", + "ctype": "uint8_t", + "desc": "Share of telemetry replies decoded in the last closed window. 255 when no reply was expected in that window", + "units": "%" + }, + { + "name": "frameTotal", + "ctype": "uint16_t", + "desc": "Telemetry replies expected in the last closed window, missing ones included", + "units": "frames" } ], "repeating": "getMotorCount()" }, "variable_len": "getMotorCount()", - "notes": "Requires `USE_ESC_SENSOR`. Payload size depends on the number of detected motors with telemetry.", - "description": "Retrieves the RPM reported by each ESC via telemetry." + "notes": "Requires `USE_ESC_SENSOR` or `USE_DSHOT_BIDIR`. 7 bytes per motor, `getMotorCount()` entries. Source follows the RPM filter: bidirectional DSHOT when `isDshotTelemetryActive()`, serial ESC telemetry otherwise. The frame statistics come from fixed back-to-back windows of `ESC_FRAME_WINDOW_MS` (1 s), so they change once per window. A reply counts as missing when the ESC stays silent, fails CRC/GCR decoding or (serial) times out. Sources without frame counting (SRXL2) always report 255 / 0.", + "description": "Retrieves the RPM and telemetry link quality reported by each ESC." }, "MSP2_INAV_ESC_TELEM": { "code": 8257, diff --git a/src/main/fc/fc_msp.c b/src/main/fc/fc_msp.c index e1fcc3b4404..c8197c2d802 100644 --- a/src/main/fc/fc_msp.c +++ b/src/main/fc/fc_msp.c @@ -1967,19 +1967,27 @@ static bool mspFcProcessOutCommand(uint16_t cmdMSP, sbuf_t *dst, mspPostProcessF // own per-motor RPM, so it works on targets without USE_ESC_SENSOR too for (uint8_t i = 0; i < motorCount; i++){ uint32_t rpm; + const escFrameCounter_t *frames = NULL; #ifdef USE_DSHOT_BIDIR if (isDshotTelemetryActive()) { rpm = lrintf(getDshotRpm(i)); + frames = &dshotTelemetryState.motorState[i].frames; } else #endif { #ifdef USE_ESC_SENSOR rpm = getEscTelemetry(i)->rpm; + frames = escSensorGetFrameCounter(i); #else rpm = 0; #endif } sbufWriteU32(dst, rpm); + // Link quality of the last closed window; 255 when no reply was expected in it + // (boot, no telemetry source, a source without frame counting such as SRXL2) + const bool framesKnown = frames && frames->lastWindowTotal > 0; + sbufWriteU8(dst, framesKnown ? frames->lastWindowSuccess : 255); + sbufWriteU16(dst, framesKnown ? frames->lastWindowTotal : 0); } } break; From 535673d48a48017d3264eb65302ba47bd3f841e2 Mon Sep 17 00:00:00 2001 From: Error414 Date: Wed, 30 Sep 2026 18:57:25 +0200 Subject: [PATCH 21/37] DSHOT BIDIR - adjust error counter --- src/main/drivers/bidir_dshot.c | 9 +++++++-- src/main/drivers/pwm_output.c | 2 +- src/main/sensors/esc_sensor.h | 3 ++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/drivers/bidir_dshot.c b/src/main/drivers/bidir_dshot.c index bc53b07281f..f75a4737d5e 100644 --- a/src/main/drivers/bidir_dshot.c +++ b/src/main/drivers/bidir_dshot.c @@ -138,10 +138,15 @@ uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) return rawValue; } - // Called once per reply window, NOEDGE included, so total covers a silent ESC too + // As in Betaflight, a window without a reply is not counted: an ESC may skip replies + // when busy, so only replies that were at least partly captured count + if (rawValue == DSHOT_TELEMETRY_NOEDGE) { + return rawValue; + } + dshotTelemetryState.motorState[motorIndex].frames.total++; - if (rawValue == DSHOT_TELEMETRY_INVALID || rawValue == DSHOT_TELEMETRY_NOEDGE) { + if (rawValue == DSHOT_TELEMETRY_INVALID) { return rawValue; } diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 0c2f5edf711..97c018e5e4d 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -916,7 +916,7 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) DMA_Cmd(port->tch->dma->ref, DISABLE); #endif - // Too few edges is no reply at all; still handed on so the frame counter sees it + // Too few edges is no reply at all uint16_t rawValue = DSHOT_TELEMETRY_NOEDGE; if (edges > MIN_GCR_EDGES) { #if defined(STM32H7) diff --git a/src/main/sensors/esc_sensor.h b/src/main/sensors/esc_sensor.h index 4021cd1d992..a75d7364efd 100644 --- a/src/main/sensors/esc_sensor.h +++ b/src/main/sensors/esc_sensor.h @@ -35,7 +35,8 @@ typedef struct { #define ESC_FRAME_WINDOW_MS 1000 // Telemetry link quality of one ESC over fixed back-to-back windows. total counts every reply -// expected, a missing one too, valid those that decoded. The last closed window is kept, so +// expected (serial: a missing one too; bidir DSHOT: only replies with edges, as in Betaflight), +// valid those that decoded. The last closed window is kept, so // the reported value moves once per window; lastWindowTotal == 0 means nothing was expected // (boot, other telemetry source) and lastWindowSuccess is meaningless then typedef struct { From 5ef40b9c3853c003c8b751de447dc423f34d0da4 Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 1 Oct 2026 08:20:53 +0200 Subject: [PATCH 22/37] DSHOT BIDIR - pull up durring eeprom saving instead of dire driving pin --- src/main/drivers/pwm_output.c | 37 ++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 97c018e5e4d..3d56d57d51b 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -200,6 +200,10 @@ static bool pwmDshotDecodeTelemetry(void); static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port); static void pwmDshotSetDirectionInput(pwmOutputPort_t *port); static void pwmDshotDmaIrqHandler(DMA_t descriptor); +// Set while bidir pins are plain GPIO, disconnected from their timer: parked low until +// the first frame, or held by the pull only during a flash write. The next frame +// reconnects them (dshotConnectOutputs()). +static bool dshotPinsDisconnected = false; #endif #endif @@ -334,17 +338,25 @@ void pwmSetMotorDMACircular(bool circular) #ifdef USE_DSHOT_BIDIR // No keep-alive frames for bidir: the ESC sees a frame gap for the flash write, as in - // Betaflight. Between frames a bidir port waits in input capture with the line held - // high only by its pull-up, so on entry complete the turnaround the normal way (frame - // in flight, its reply, every port back to output): in output CCR is 0, which with - // the bidir polarity drives the line at its idle-high level for the whole write. - // Nothing to undo on exit, the next frame starts from that same output state. + // Betaflight, with the line held at its idle level only by the pull. if (useDshotTelemetry) { - if (circular) { - // Let a frame in flight finish, with the deadtime as margin for its completion - // IRQ, then wait out the reply and turn the ports round as before any frame + if (circular && !dshotPinsDisconnected) { + // Complete the DSHOT exchange before the write: let a frame in flight finish, + // with the deadtime as margin for its completion IRQ, then wait out and decode + // the reply, which turns every port back to output delayMicroseconds(frameUs + DSHOT_TELEMETRY_DEADTIME_US); while (!pwmDshotDecodeTelemetry()) { } + + // Disconnect the pins from the timers so nothing drives the line during the + // write; the next frame after it reconnects them + for (int i = 0; i < motorCount; i++) { + const pwmOutputPort_t *port = motors[i].pwmPort; + if (port && port->configured) { + const bool baseInverted = port->tch->timHw->output & TIMER_OUTPUT_INVERTED; + IOConfigGPIO(IOGetByTag(port->tch->timHw->tag), baseInverted ? IOCFG_IPD : IOCFG_IPU); + } + } + dshotPinsDisconnected = true; } return; } @@ -810,9 +822,6 @@ static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) port->telemetryInputActive = true; } -// Set when bidir pins are held low as plain GPIO until the first frame -static bool dshotPinsParkedLow = false; - // Connect bidir DSHOT pins to their timer AF (idle-high). Called on the first // real motor update so the line only goes high microseconds before frames start, // keeping it low through the ESC's boot-time bootloader-entry window. @@ -970,7 +979,7 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, const IO_t io = IOGetByTag(timerHardware->tag); IOConfigGPIO(io, IOCFG_OUT_PP); (timerHardware->output & TIMER_OUTPUT_INVERTED) ? IOHi(io) : IOLo(io); - dshotPinsParkedLow = true; + dshotPinsDisconnected = true; } #endif @@ -1196,9 +1205,9 @@ void pwmCompleteMotorUpdate(void) { if (isMotorProtocolDshot()) { #ifdef USE_DSHOT_BIDIR - if (dshotPinsParkedLow) { + if (dshotPinsDisconnected) { dshotConnectOutputs(); - dshotPinsParkedLow = false; + dshotPinsDisconnected = false; } #endif From 7e2742d554feaf73e24020cac33e003eff893552 Mon Sep 17 00:00:00 2001 From: Error414 Date: Fri, 2 Oct 2026 15:30:41 +0200 Subject: [PATCH 23/37] DSHOT BIDIR - disable bidir for F7, not enought memory so far --- src/main/target/common_post.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/target/common_post.h b/src/main/target/common_post.h index b596b95435e..80629eb05c6 100644 --- a/src/main/target/common_post.h +++ b/src/main/target/common_post.h @@ -191,11 +191,12 @@ extern uint8_t __config_end; // dshot_bidir_enabled). Needs a DMA stream per motor channel for the direction // switching, so it excludes USE_DSHOT_DMAR. Implemented by the timer/DMA motor // driver (pwm_output.c); RP2350 drives its motors from a PIO program that only -// transmits, so the setting is hidden there and stays off. +// transmits, so the setting is hidden there and stays off. STM32F7 is excluded +// as well: bidirectional DSHOT is only supported on STM32H7 and AT32. #if defined(USE_DSHOT_DMAR) && !defined(USE_DSHOT) #error "USE_DSHOT_DMAR requires USE_DSHOT" #endif -#if defined(USE_DSHOT) && !defined(USE_DSHOT_DMAR) && !defined(RP2350) +#if defined(USE_DSHOT) && !defined(USE_DSHOT_DMAR) && !defined(RP2350) && !defined(STM32F7) #define USE_DSHOT_BIDIR #endif #if defined(USE_DSHOT_BIDIR) && (!defined(USE_DSHOT) || defined(USE_DSHOT_DMAR)) From fc84c1152630d5f6877d9b1d207d11e29cadc93a Mon Sep 17 00:00:00 2001 From: Error414 Date: Fri, 2 Oct 2026 17:18:50 +0200 Subject: [PATCH 24/37] DSHOT BIDIR - optimize memory --- src/main/drivers/bidir_dshot.c | 128 +++++++-------------------------- src/main/drivers/bidir_dshot.h | 18 ----- src/main/drivers/pwm_output.c | 35 +++++---- src/main/fc/fc_msp.c | 6 +- src/main/sensors/esc_sensor.c | 42 ++++++----- src/main/sensors/esc_sensor.h | 24 +++---- 6 files changed, 79 insertions(+), 174 deletions(-) diff --git a/src/main/drivers/bidir_dshot.c b/src/main/drivers/bidir_dshot.c index f75a4737d5e..ac0d982bccd 100644 --- a/src/main/drivers/bidir_dshot.c +++ b/src/main/drivers/bidir_dshot.c @@ -19,12 +19,9 @@ * If not, see . */ -#include #include -#include #include "platform.h" -#include "common/utils.h" #include "drivers/bidir_dshot.h" // Bidirectional DSHOT telemetry only: eRPM / EDT decoding, RPM state for the RPM filter and @@ -37,36 +34,21 @@ #ifdef USE_DSHOT_BIDIR -#include "common/maths.h" - #include "flight/mixer.h" -#include "drivers/pwm_mapping.h" + +// Only eRPM, temperature, voltage and current are kept; the EDT debug and status frames +// have no consumer and just mark their type as seen +#define DSHOT_TELEMETRY_STORED_TYPE_COUNT (DSHOT_TELEMETRY_TYPE_CURRENT + 1) + +typedef struct { + uint16_t telemetryData[DSHOT_TELEMETRY_STORED_TYPE_COUNT]; + uint8_t telemetryTypes; // bit per dshotTelemetryType_e seen since boot +} dshotTelemetryMotorState_t; bool useDshotTelemetry = false; -dshotTelemetryState_t dshotTelemetryState; -static float motorFrequencyHz[MAX_SUPPORTED_MOTORS]; -static float dshotRpm[MAX_SUPPORTED_MOTORS]; -static float dshotRpmAverage; +static dshotTelemetryMotorState_t motorTelemetry[MAX_SUPPORTED_MOTORS]; static float erpmToHz; -static bool edtAlwaysDecode; -static timeUs_t frameWindowStartUs; - -static const dshotTelemetryType_e extendedTelemetryLookup[8] = { - DSHOT_TELEMETRY_TYPE_ERPM, - DSHOT_TELEMETRY_TYPE_TEMPERATURE, - DSHOT_TELEMETRY_TYPE_VOLTAGE, - DSHOT_TELEMETRY_TYPE_CURRENT, - DSHOT_TELEMETRY_TYPE_DEBUG1, - DSHOT_TELEMETRY_TYPE_DEBUG2, - DSHOT_TELEMETRY_TYPE_DEBUG3, - DSHOT_TELEMETRY_TYPE_STATE_EVENTS, -}; - -static float erpmToRpm(uint32_t erpm) -{ - return erpm * erpmToHz * 60.0f; -} static uint32_t dshotDecodeErpmTelemetryValue(uint16_t value) { @@ -82,10 +64,9 @@ static uint32_t dshotDecodeErpmTelemetryValue(uint16_t value) return (1000000 * 60 / 100 + value / 2) / value; } -static void dshotDecodeTelemetryValue(uint8_t motorIndex, uint32_t *decoded, dshotTelemetryType_e *type) +static void dshotDecodeTelemetryValue(uint16_t value, uint8_t motorIndex, uint32_t *decoded, dshotTelemetryType_e *type) { - const uint16_t value = dshotTelemetryState.motorState[motorIndex].rawValue; - const bool edtEnabled = edtAlwaysDecode || (dshotTelemetryState.motorState[motorIndex].telemetryTypes & DSHOT_EXTENDED_TELEMETRY_MASK) != 0; + const bool edtEnabled = motorConfig()->useDshotEdt || (motorTelemetry[motorIndex].telemetryTypes & DSHOT_EXTENDED_TELEMETRY_MASK) != 0; const unsigned telemetryType = (value & 0x0f00) >> 8; const bool isErpm = !edtEnabled || (telemetryType & 0x01) || (telemetryType == 0); @@ -93,25 +74,12 @@ static void dshotDecodeTelemetryValue(uint8_t motorIndex, uint32_t *decoded, dsh *decoded = dshotDecodeErpmTelemetryValue(value); *type = DSHOT_TELEMETRY_TYPE_ERPM; } else { - const unsigned typeIndex = telemetryType >> 1; - *type = typeIndex < ARRAYLEN(extendedTelemetryLookup) ? extendedTelemetryLookup[typeIndex] : DSHOT_TELEMETRY_TYPE_STATE_EVENTS; + // EDT frame types 2, 4, ... 14 are the enum values 1..7 in order + *type = telemetryType >> 1; *decoded = value & 0x00ff; } } -void dshotResetTelemetry(void) -{ - memset(&dshotTelemetryState, 0, sizeof(dshotTelemetryState)); - memset(dshotRpm, 0, sizeof(dshotRpm)); - memset(motorFrequencyHz, 0, sizeof(motorFrequencyHz)); - dshotRpmAverage = 0.0f; -} - -bool isDshotTelemetryConfigured(void) -{ - return useDshotTelemetry; -} - bool isDshotTelemetryActive(void) { return useDshotTelemetry; @@ -121,10 +89,6 @@ bool isDshotTelemetryActive(void) // knows whether the outputs were configured for DSHOT at all void initDshotTelemetry(void) { - edtAlwaysDecode = motorConfig()->useDshotEdt != 0; - - dshotResetTelemetry(); - if (!useDshotTelemetry) { return; } @@ -144,78 +108,38 @@ uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) return rawValue; } - dshotTelemetryState.motorState[motorIndex].frames.total++; + escFrameCounter_t *frames = escSensorFrameCounter(motorIndex); + frames->total++; if (rawValue == DSHOT_TELEMETRY_INVALID) { return rawValue; } - dshotTelemetryState.motorState[motorIndex].rawValue = rawValue; - dshotTelemetryType_e type; uint32_t decoded; - dshotDecodeTelemetryValue(motorIndex, &decoded, &type); + dshotDecodeTelemetryValue(rawValue, motorIndex, &decoded, &type); if (decoded == DSHOT_TELEMETRY_INVALID) { return DSHOT_TELEMETRY_INVALID; } - dshotTelemetryState.motorState[motorIndex].frames.valid++; - - dshotTelemetryState.motorState[motorIndex].telemetryData[type] = decoded; - dshotTelemetryState.motorState[motorIndex].telemetryTypes |= (1 << type); - - if (type == DSHOT_TELEMETRY_TYPE_TEMPERATURE && decoded > dshotTelemetryState.motorState[motorIndex].maxTemp) { - dshotTelemetryState.motorState[motorIndex].maxTemp = decoded; - } + frames->valid++; - if (type == DSHOT_TELEMETRY_TYPE_ERPM) { - dshotRpm[motorIndex] = erpmToRpm(decoded); - motorFrequencyHz[motorIndex] = erpmToHz * decoded; + motorTelemetry[motorIndex].telemetryTypes |= (1 << type); + if (type < DSHOT_TELEMETRY_STORED_TYPE_COUNT) { + motorTelemetry[motorIndex].telemetryData[type] = decoded; } - float rpmTotal = 0.0f; - int rpmCount = 0; - for (unsigned i = 0; i < getMotorCount(); i++) { - if (dshotTelemetryState.motorState[i].telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_ERPM)) { - rpmTotal += dshotRpm[i]; - rpmCount++; - } - } - dshotRpmAverage = rpmCount ? rpmTotal / rpmCount : 0.0f; - return rawValue; } -void dshotFrameWindowUpdate(timeUs_t currentTimeUs) -{ - if (currentTimeUs - frameWindowStartUs < ESC_FRAME_WINDOW_MS * 1000) { - return; - } - - frameWindowStartUs = currentTimeUs; - for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { - escFrameCounterCloseWindow(&dshotTelemetryState.motorState[i].frames); - } -} - -uint16_t getDshotErpm(uint8_t motorIndex) +float getMotorFrequencyHz(uint8_t motorIndex) { - return dshotTelemetryState.motorState[motorIndex].telemetryData[DSHOT_TELEMETRY_TYPE_ERPM]; + return motorTelemetry[motorIndex].telemetryData[DSHOT_TELEMETRY_TYPE_ERPM] * erpmToHz; } float getDshotRpm(uint8_t motorIndex) { - return dshotRpm[motorIndex]; -} - -float getDshotRpmAverage(void) -{ - return dshotRpmAverage; -} - -float getMotorFrequencyHz(uint8_t motorIndex) -{ - return motorFrequencyHz[motorIndex]; + return getMotorFrequencyHz(motorIndex) * 60.0f; } bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex) @@ -224,14 +148,14 @@ bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex) return false; } - const dshotTelemetryMotorState_t *state = &dshotTelemetryState.motorState[motorIndex]; + const dshotTelemetryMotorState_t *state = &motorTelemetry[motorIndex]; if ((state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_ERPM)) == 0) { return false; } // escSensorData_t units: rpm (mechanical), degrees C, 0.01 V, 0.01 A. EDT reports // the temperature in degrees C, the voltage in 0.25 V and the current in 1 A steps. - data->rpm = lrintf(dshotRpm[motorIndex]); + data->rpm = lrintf(getDshotRpm(motorIndex)); data->temperature = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_TEMPERATURE)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_TEMPERATURE] : 0; data->voltage = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_VOLTAGE)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_VOLTAGE] * 25 : 0; data->current = (state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_CURRENT)) ? state->telemetryData[DSHOT_TELEMETRY_TYPE_CURRENT] * 100 : 0; diff --git a/src/main/drivers/bidir_dshot.h b/src/main/drivers/bidir_dshot.h index 0dca223e4ea..ac37fde5cf5 100644 --- a/src/main/drivers/bidir_dshot.h +++ b/src/main/drivers/bidir_dshot.h @@ -52,31 +52,13 @@ typedef enum { #define DSHOT_NORMAL_TELEMETRY_MASK (1 << DSHOT_TELEMETRY_TYPE_ERPM) #define DSHOT_EXTENDED_TELEMETRY_MASK (~DSHOT_NORMAL_TELEMETRY_MASK) -typedef struct { - uint16_t rawValue; - uint16_t telemetryData[DSHOT_TELEMETRY_TYPE_COUNT]; - uint8_t telemetryTypes; - uint8_t maxTemp; - escFrameCounter_t frames; -} dshotTelemetryMotorState_t; - -typedef struct { - dshotTelemetryMotorState_t motorState[MAX_SUPPORTED_MOTORS]; -} dshotTelemetryState_t; - #ifdef USE_DSHOT_BIDIR extern bool useDshotTelemetry; -extern dshotTelemetryState_t dshotTelemetryState; void initDshotTelemetry(void); -void dshotResetTelemetry(void); -bool isDshotTelemetryConfigured(void); bool isDshotTelemetryActive(void); uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex); -void dshotFrameWindowUpdate(timeUs_t currentTimeUs); float getDshotRpm(uint8_t motorIndex); -uint16_t getDshotErpm(uint8_t motorIndex); -float getDshotRpmAverage(void); // Mechanical frequency from the last decoded eRPM frame, unfiltered (see bidir_dshot.c) float getMotorFrequencyHz(uint8_t motorIndex); bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex); diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 3d56d57d51b..22ab5c06eb4 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -487,24 +487,23 @@ static uint8_t getBurstDmaTimerIndex(TIM_TypeDef *timer) #endif #ifdef USE_DSHOT_BIDIR +// The CC1..CC4 DMA request bits sit next to each other in DIER on every supported MCU static uint32_t dshotDmaSource(const pwmOutputPort_t *port) { #if defined(USE_HAL_DRIVER) || !defined(AT32F43x) - static const uint32_t sources[] = { TIM_DMA_CC1, TIM_DMA_CC2, TIM_DMA_CC3, TIM_DMA_CC4 }; + STATIC_ASSERT(TIM_DMA_CC2 == TIM_DMA_CC1 << 1 && TIM_DMA_CC4 == TIM_DMA_CC1 << 3, tim_dma_cc_bits_adjacent); + return TIM_DMA_CC1 << port->tch->timHw->channelIndex; #else - static const uint32_t sources[] = { TMR_C1_DMA_REQUEST, TMR_C2_DMA_REQUEST, TMR_C3_DMA_REQUEST, TMR_C4_DMA_REQUEST }; + STATIC_ASSERT(TMR_C2_DMA_REQUEST == TMR_C1_DMA_REQUEST << 1 && TMR_C4_DMA_REQUEST == TMR_C1_DMA_REQUEST << 3, tmr_dma_request_bits_adjacent); + return TMR_C1_DMA_REQUEST << port->tch->timHw->channelIndex; #endif - return sources[port->tch->timHw->channelIndex]; } #if defined(USE_HAL_DRIVER) static uint32_t dshotDmaStream(const pwmOutputPort_t *port) { - static const uint32_t streams[] = { - LL_DMA_STREAM_0, LL_DMA_STREAM_1, LL_DMA_STREAM_2, LL_DMA_STREAM_3, - LL_DMA_STREAM_4, LL_DMA_STREAM_5, LL_DMA_STREAM_6, LL_DMA_STREAM_7 - }; - return streams[DMATAG_GET_STREAM(port->tch->timHw->dmaTag)]; + STATIC_ASSERT(LL_DMA_STREAM_0 == 0 && LL_DMA_STREAM_7 == 7, ll_dma_stream_is_index); + return DMATAG_GET_STREAM(port->tch->timHw->dmaTag); } // The LL driver only exposes per-channel LL_TIM_{En,Dis}ableDMAReq_CC1..CC4; @@ -520,16 +519,19 @@ static inline void LL_TIM_DisableDMAReq_CCx(TIM_TypeDef *TIMx, uint16_t dmaSourc } #endif +// The channel identifiers are evenly spaced, so channelIndex maps onto them linearly static uint32_t dshotTimChannel(const pwmOutputPort_t *port) { #if defined(USE_HAL_DRIVER) - static const uint32_t channels[] = { TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3, TIM_CHANNEL_4 }; + STATIC_ASSERT(TIM_CHANNEL_4 == TIM_CHANNEL_1 + 3 * (TIM_CHANNEL_2 - TIM_CHANNEL_1), tim_channel_ids_linear); + return TIM_CHANNEL_1 + port->tch->timHw->channelIndex * (TIM_CHANNEL_2 - TIM_CHANNEL_1); #elif defined(AT32F43x) - static const uint32_t channels[] = { TMR_SELECT_CHANNEL_1, TMR_SELECT_CHANNEL_2, TMR_SELECT_CHANNEL_3, TMR_SELECT_CHANNEL_4 }; + STATIC_ASSERT(TMR_SELECT_CHANNEL_4 == TMR_SELECT_CHANNEL_1 + 3 * (TMR_SELECT_CHANNEL_2 - TMR_SELECT_CHANNEL_1), tmr_channel_ids_linear); + return TMR_SELECT_CHANNEL_1 + port->tch->timHw->channelIndex * (TMR_SELECT_CHANNEL_2 - TMR_SELECT_CHANNEL_1); #else - static const uint32_t channels[] = { TIM_Channel_1, TIM_Channel_2, TIM_Channel_3, TIM_Channel_4 }; + STATIC_ASSERT(TIM_Channel_4 == TIM_Channel_1 + 3 * (TIM_Channel_2 - TIM_Channel_1), tim_channel_ids_linear); + return TIM_Channel_1 + port->tch->timHw->channelIndex * (TIM_Channel_2 - TIM_Channel_1); #endif - return channels[port->tch->timHw->channelIndex]; } static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count) @@ -928,12 +930,7 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) // Too few edges is no reply at all uint16_t rawValue = DSHOT_TELEMETRY_NOEDGE; if (edges > MIN_GCR_EDGES) { -#if defined(STM32H7) - // Defensive: DMA_RAM is mapped non-cacheable by the MPU, so this is a no-op as - // long as the port buffers stay there - uint32_t alignedAddr = (uint32_t)port->dmaBuffer & ~0x1F; - SCB_InvalidateDCache_by_Addr((uint32_t *)alignedAddr, edges * sizeof(port->dmaBuffer[0]) + ((uint32_t)port->dmaBuffer - alignedAddr)); -#endif + // No cache maintenance: pwmOutputPorts is DMA_RAM, which the H7 MPU maps non-cacheable rawValue = dshotDecodeTelemetryPacket((const uint32_t *)port->dmaBuffer, edges); } @@ -1190,7 +1187,7 @@ void pwmCompleteMotorUpdate(void) { #ifdef USE_DSHOT_BIDIR if (useDshotTelemetry) { - dshotFrameWindowUpdate(currentTimeUs); + escSensorFrameWindowUpdate(currentTimeUs / 1000); } #endif diff --git a/src/main/fc/fc_msp.c b/src/main/fc/fc_msp.c index c8197c2d802..8e8f143b953 100644 --- a/src/main/fc/fc_msp.c +++ b/src/main/fc/fc_msp.c @@ -1967,17 +1967,14 @@ static bool mspFcProcessOutCommand(uint16_t cmdMSP, sbuf_t *dst, mspPostProcessF // own per-motor RPM, so it works on targets without USE_ESC_SENSOR too for (uint8_t i = 0; i < motorCount; i++){ uint32_t rpm; - const escFrameCounter_t *frames = NULL; #ifdef USE_DSHOT_BIDIR if (isDshotTelemetryActive()) { rpm = lrintf(getDshotRpm(i)); - frames = &dshotTelemetryState.motorState[i].frames; } else #endif { #ifdef USE_ESC_SENSOR rpm = getEscTelemetry(i)->rpm; - frames = escSensorGetFrameCounter(i); #else rpm = 0; #endif @@ -1985,7 +1982,8 @@ static bool mspFcProcessOutCommand(uint16_t cmdMSP, sbuf_t *dst, mspPostProcessF sbufWriteU32(dst, rpm); // Link quality of the last closed window; 255 when no reply was expected in it // (boot, no telemetry source, a source without frame counting such as SRXL2) - const bool framesKnown = frames && frames->lastWindowTotal > 0; + const escFrameCounter_t *frames = escSensorFrameCounter(i); + const bool framesKnown = frames->lastWindowTotal > 0; sbufWriteU8(dst, framesKnown ? frames->lastWindowSuccess : 255); sbufWriteU16(dst, framesKnown ? frames->lastWindowTotal : 0); } diff --git a/src/main/sensors/esc_sensor.c b/src/main/sensors/esc_sensor.c index b925bb426a2..eb3d61e0faf 100644 --- a/src/main/sensors/esc_sensor.c +++ b/src/main/sensors/esc_sensor.c @@ -52,6 +52,29 @@ #include "fc/runtime_config.h" #include "fc/settings.h" +static escFrameCounter_t escSensorFrames[MAX_SUPPORTED_MOTORS]; +static timeMs_t escFrameWindowStartMs; + +escFrameCounter_t * escSensorFrameCounter(uint8_t esc) +{ + return &escSensorFrames[esc]; +} + +void escSensorFrameWindowUpdate(timeMs_t currentTimeMs) +{ + if (currentTimeMs - escFrameWindowStartMs < ESC_FRAME_WINDOW_MS) { + return; + } + + escFrameWindowStartMs = currentTimeMs; + for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { + escFrameCounter_t *counter = &escSensorFrames[i]; + counter->lastWindowTotal = counter->total; + counter->lastWindowSuccess = counter->total ? (uint32_t)counter->valid * 100 / counter->total : 0; + counter->total = 0; + counter->valid = 0; + } +} #if defined(USE_ESC_SENSOR) @@ -79,11 +102,8 @@ static int escSensorMotor; static uint8_t telemetryBuffer[TELEMETRY_FRAME_SIZE]; static int bufferPosition = 0; static escSensorData_t escSensorData[MAX_SUPPORTED_MOTORS]; -static escFrameCounter_t escSensorFrames[MAX_SUPPORTED_MOTORS]; -static timeMs_t escFrameWindowStartMs; static escSensorData_t escSensorDataCombined; static bool escSensorDataNeedsUpdate; -static bool escSensorDshotActive; PG_REGISTER_WITH_RESET_TEMPLATE(escSensorConfig_t, escSensorConfig, PG_ESC_SENSOR_CONFIG, 1); PG_RESET_TEMPLATE(escSensorConfig_t, escSensorConfig, @@ -162,11 +182,6 @@ escSensorData_t NOINLINE * getEscTelemetry(uint8_t esc) return &escSensorData[esc]; } -const escFrameCounter_t * escSensorGetFrameCounter(uint8_t esc) -{ - return &escSensorFrames[esc]; -} - void escSensorInitData(void) { for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { @@ -255,7 +270,6 @@ bool escSensorInitialize(void) { escSensorDataNeedsUpdate = true; escSensorPort = NULL; - escSensorDshotActive = false; // Fail immediately if motor output are disabled or motor outputs are not configured if (!feature(FEATURE_PWM_OUTPUT_ENABLE) || getMotorCount() == 0) { @@ -291,7 +305,6 @@ bool escSensorInitialize(void) #ifdef USE_DSHOT_BIDIR // Telemetry on the motor line: fed by the motor driver, no port to open if (isDshotTelemetryActive()) { - escSensorDshotActive = true; ENABLE_STATE(ESC_SENSOR_ENABLED); return true; } @@ -317,7 +330,7 @@ bool escSensorInitialize(void) void escSensorUpdate(timeUs_t currentTimeUs) { #ifdef USE_DSHOT_BIDIR - if (escSensorDshotActive) { + if (isDshotTelemetryActive()) { // The motor driver refreshes the data with every decoded frame. Age it at the serial // poll rate, so a silent ESC drops out of the combined values the same way (the serial // poll timer doubles as the aging clock, nothing polls here) @@ -389,12 +402,7 @@ void escSensorUpdate(timeUs_t currentTimeUs) const timeMs_t currentTimeMs = currentTimeUs / 1000; - if (currentTimeMs - escFrameWindowStartMs >= ESC_FRAME_WINDOW_MS) { - escFrameWindowStartMs = currentTimeMs; - for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { - escFrameCounterCloseWindow(&escSensorFrames[i]); - } - } + escSensorFrameWindowUpdate(currentTimeMs); switch (escSensorState) { case ESC_SENSOR_WAIT_STARTUP: diff --git a/src/main/sensors/esc_sensor.h b/src/main/sensors/esc_sensor.h index a75d7364efd..702f68938d5 100644 --- a/src/main/sensors/esc_sensor.h +++ b/src/main/sensors/esc_sensor.h @@ -34,11 +34,12 @@ typedef struct { #define ESC_FRAME_WINDOW_MS 1000 -// Telemetry link quality of one ESC over fixed back-to-back windows. total counts every reply -// expected (serial: a missing one too; bidir DSHOT: only replies with edges, as in Betaflight), -// valid those that decoded. The last closed window is kept, so -// the reported value moves once per window; lastWindowTotal == 0 means nothing was expected -// (boot, other telemetry source) and lastWindowSuccess is meaningless then +// Telemetry link quality of one ESC over fixed back-to-back windows, shared by the serial +// ESC sensor and bidirectional DSHOT (only one source is ever active). total counts every +// reply expected (serial: a missing one too; bidir DSHOT: only replies with edges, as in +// Betaflight), valid those that decoded. The last closed window is kept, so the reported +// value moves once per window; lastWindowTotal == 0 means nothing was expected (boot, a +// source without frame counting such as SRXL2) and lastWindowSuccess is meaningless then typedef struct { uint16_t total; uint16_t valid; @@ -46,14 +47,6 @@ typedef struct { uint8_t lastWindowSuccess; // percent } escFrameCounter_t; -static inline void escFrameCounterCloseWindow(escFrameCounter_t *counter) -{ - counter->lastWindowTotal = counter->total; - counter->lastWindowSuccess = counter->total ? (uint32_t)counter->valid * 100 / counter->total : 0; - counter->total = 0; - counter->valid = 0; -} - typedef struct escSensorConfig_s { uint16_t currentOffset; // offset consumed by the flight controller / VTX / cam / ... in mA uint8_t listenOnly; @@ -69,7 +62,10 @@ bool escSensorInitialize(void); void escSensorUpdate(timeUs_t currentTimeUs); escSensorData_t * escSensorGetData(void); escSensorData_t * getEscTelemetry(uint8_t esc); -const escFrameCounter_t * escSensorGetFrameCounter(uint8_t esc); +escFrameCounter_t * escSensorFrameCounter(uint8_t esc); +// Closes the counting window of every ESC once ESC_FRAME_WINDOW_MS have passed; the active +// source calls it from wherever it runs regularly +void escSensorFrameWindowUpdate(timeMs_t currentTimeMs); uint32_t computeRpm(int16_t erpm); void escSensorInitData(void); void escSensorSetDshotData(uint8_t esc, uint32_t rpm, int16_t temperature, int16_t voltage, int32_t current); From d6ed72230ea26881991c60921b5b63e0ef120ebc Mon Sep 17 00:00:00 2001 From: Error414 Date: Tue, 6 Oct 2026 20:57:27 +0200 Subject: [PATCH 25/37] DSHOT BIDIR - fix EDT, send EDT ON after arm --- docs/Settings.md | 2 +- src/main/drivers/pwm_output.c | 1 + src/main/drivers/pwm_output.h | 1 + src/main/fc/fc_core.c | 18 ++++++++++++++++++ src/main/fc/settings.yaml | 2 +- 5 files changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/Settings.md b/docs/Settings.md index eae8e696a65..b0f66f277aa 100644 --- a/docs/Settings.md +++ b/docs/Settings.md @@ -957,7 +957,7 @@ Enable bidirectional DShot telemetry on motor outputs. Required for RPM filterin ### dshot_edt_enabled -Enable extended DShot telemetry decoding (temperature, voltage, current in addition to eRPM) +Enable extended DShot telemetry (temperature, voltage, current in addition to eRPM). The ESC is asked for it on every arm, so the values appear after the first arm | Default | Min | Max | | --- | --- | --- | diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 22ab5c06eb4..53d131f8c92 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -1121,6 +1121,7 @@ static int getDShotCommandRepeats(dshotCommands_e cmd) { int repeats = 1; switch (cmd) { + case DSHOT_CMD_EXTENDED_TELEMETRY_ENABLE: case DSHOT_CMD_SPIN_DIRECTION_NORMAL: case DSHOT_CMD_SPIN_DIRECTION_REVERSED: repeats = 10; diff --git a/src/main/drivers/pwm_output.h b/src/main/drivers/pwm_output.h index afe1a1916e3..fec7d8cd0d0 100644 --- a/src/main/drivers/pwm_output.h +++ b/src/main/drivers/pwm_output.h @@ -27,6 +27,7 @@ #define MAX_PWM_OUTPUTS (MAX_PWM_OUTPUT_PORTS) #endif typedef enum { + DSHOT_CMD_EXTENDED_TELEMETRY_ENABLE = 13, DSHOT_CMD_SPIN_DIRECTION_NORMAL = 20, DSHOT_CMD_SPIN_DIRECTION_REVERSED = 21, } dshotCommands_e; diff --git a/src/main/fc/fc_core.c b/src/main/fc/fc_core.c index 778dce2e511..a79c29b5555 100644 --- a/src/main/fc/fc_core.c +++ b/src/main/fc/fc_core.c @@ -37,6 +37,7 @@ #include "drivers/time.h" #include "drivers/system.h" #include "drivers/pwm_output.h" +#include "drivers/bidir_dshot.h" #include "drivers/pwm_mapping.h" #include "sensors/sensors.h" @@ -593,6 +594,17 @@ bool emergInflightRearmEnabled(void) return false; // craft doesn't appear to be flying, don't allow emergency rearm } +#ifdef USE_DSHOT_BIDIR +// As in Betaflight: the ESC sends EDT frames only after being asked and forgets it on power-up, +// so ask on every arm, while the motors are still stopped and the ESC accepts commands +static void requestDshotExtendedTelemetry(void) +{ + if (isDshotTelemetryActive() && motorConfig()->useDshotEdt) { + sendDShotCommand(DSHOT_CMD_EXTENDED_TELEMETRY_ENABLE); + } +} +#endif + void tryArm(void) { updateArmingStatus(); @@ -608,6 +620,9 @@ void tryArm(void) const bool turtleIsActive = IS_RC_MODE_ACTIVE(BOXTURTLE); #endif if (STATE(MULTIROTOR) && turtleIsActive && !FLIGHT_MODE(TURTLE_MODE) && emergencyArmingCanOverrideArmingDisabled() && isMotorProtocolDshot()) { +#ifdef USE_DSHOT_BIDIR + requestDshotExtendedTelemetry(); +#endif sendDShotCommand(DSHOT_CMD_SPIN_DIRECTION_REVERSED); ENABLE_ARMING_FLAG(ARMED); ENABLE_FLIGHT_MODE(TURTLE_MODE); @@ -633,6 +648,9 @@ void tryArm(void) lastDisarmReason = DISARM_NONE; +#ifdef USE_DSHOT_BIDIR + requestDshotExtendedTelemetry(); +#endif ENABLE_ARMING_FLAG(ARMED); ENABLE_ARMING_FLAG(WAS_EVER_ARMED); //It is required to inform the mixer that arming was executed and it has to switch to the FORWARD direction diff --git a/src/main/fc/settings.yaml b/src/main/fc/settings.yaml index 221188fc69b..400bbeca6d6 100644 --- a/src/main/fc/settings.yaml +++ b/src/main/fc/settings.yaml @@ -903,7 +903,7 @@ groups: type: bool default_value: OFF - name: dshot_edt_enabled - description: "Enable extended DShot telemetry decoding (temperature, voltage, current in addition to eRPM)" + description: "Enable extended DShot telemetry (temperature, voltage, current in addition to eRPM). The ESC is asked for it on every arm, so the values appear after the first arm" field: useDshotEdt condition: USE_DSHOT_BIDIR type: bool From 4a7d4e2d45d84834d99653edde40a103000171b7 Mon Sep 17 00:00:00 2001 From: Error414 Date: Tue, 6 Oct 2026 21:51:13 +0200 Subject: [PATCH 26/37] DSHOT BIDIR - try to make space for F722 --- src/main/drivers/pwm_output.c | 3 ++- src/main/sensors/esc_sensor.c | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 53d131f8c92..3ffc8f45a1d 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -1133,7 +1133,8 @@ static int getDShotCommandRepeats(dshotCommands_e cmd) { return repeats; } -static bool executeDShotCommands(void){ +// NOINLINE: pwmCompleteMotorUpdate() is inlined into the ITCM scheduler; commands are rare +static bool NOINLINE executeDShotCommands(void){ timeUs_t tNow = micros(); diff --git a/src/main/sensors/esc_sensor.c b/src/main/sensors/esc_sensor.c index eb3d61e0faf..88c60921e61 100644 --- a/src/main/sensors/esc_sensor.c +++ b/src/main/sensors/esc_sensor.c @@ -60,7 +60,8 @@ escFrameCounter_t * escSensorFrameCounter(uint8_t esc) return &escSensorFrames[esc]; } -void escSensorFrameWindowUpdate(timeMs_t currentTimeMs) +// NOINLINE: escSensorUpdate() is inlined into the ITCM scheduler; this runs once per window +void NOINLINE escSensorFrameWindowUpdate(timeMs_t currentTimeMs) { if (currentTimeMs - escFrameWindowStartMs < ESC_FRAME_WINDOW_MS) { return; From e88caefda420bdfb367496d2eb2e47b28d802d87 Mon Sep 17 00:00:00 2001 From: Error414 Date: Fri, 9 Oct 2026 19:48:08 +0200 Subject: [PATCH 27/37] DSHOT BIDIR - use direct writing to registers for F7/H7 --- src/main/drivers/pwm_output.c | 250 +++++++++++++++++++--------------- 1 file changed, 139 insertions(+), 111 deletions(-) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 3ffc8f45a1d..47727b0ea18 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -33,6 +33,7 @@ #include "common/circular_queue.h" #include "drivers/io.h" +#include "drivers/io_impl.h" #include "drivers/nvic.h" #include "drivers/bidir_dshot.h" #include "drivers/time.h" @@ -73,7 +74,11 @@ #define MAX_DMA_TIMERS 8 #ifdef USE_DSHOT_BIDIR -#define DSHOT_TELEMETRY_DEADTIME_US 35 +/* Telemetry reply window, measured from the frame start: the 18-slot frame, then the ESC's + * ~30 us turnaround and its 21-bit GCR reply at 5/4 of the DSHOT bit rate (17 slots). + * DSHOT_TELEMETRY_DEADTIME_US covers the turnaround plus margin for ESC timing variation. */ +#define DSHOT_TELEMETRY_DEADTIME_US 45 +#define DSHOT_TELEMETRY_WINDOW_SLOTS (DSHOT_DMA_BUFFER_SIZE + 17) #define GCR_TELEMETRY_INPUT_LEN MAX_GCR_EDGES /* A bidir port captures the GCR edges of the ESC reply into the same buffer it sends the * frame from, so the buffer is sized for the larger of the two */ @@ -167,13 +172,15 @@ static timeUs_t lastCommandSent = 0; static timeUs_t commandPostDelay = 0; #ifdef USE_DSHOT_BIDIR static bool dshotTelemetryPending = false; -/* One stamp for the whole frame, taken from the last port turned round for the reply - * (all ports switch within microseconds of each other). Turning a port back to output - * resets the counter and period of its timer, which every other port on that timer - * shares, so no port may switch back while a sibling could still be capturing: the - * deadtime is therefore waited out once, for all ports, before any of them is touched */ -static timeUs_t dshotTelemetryInputStampUs = 0; +/* One stamp for the whole frame, taken in the main loop just before the frames start, so + * the completion ISR has no clock to read. Turning a port back to output resets the + * counter and period of its timer, which every other port on that timer shares, so no + * port may switch back while a sibling could still be capturing: the reply window is + * therefore waited out once, for all ports, before any of them is touched */ +static timeUs_t dshotTelemetryFrameStampUs = 0; static timeUs_t dshotTelemetryDeadtimeUs = 0; +// DEBUG_ESC: cycle counter at the frame start, debug[motor] = cycles until its capture is armed +static uint32_t dshotFrameStartCycles = 0; #endif static circularBuffer_t commandsCircularBuffer; @@ -519,13 +526,41 @@ static inline void LL_TIM_DisableDMAReq_CCx(TIM_TypeDef *TIMx, uint16_t dmaSourc } #endif +#if defined(USE_HAL_DRIVER) +// Register slices of this port's timer channel for the direction switch: the channel's +// byte in CCMR1/CCMR2 and its nibble in CCER. Derived on the fly, the shifts cost a few cycles. +typedef struct { + volatile uint32_t *ccmr; + uint32_t ccmrShift; + uint32_t ccmrMask; // the channel's byte plus its OCxM[3] bit + uint32_t ccerShift; + uint32_t ccerMask; +} dshotChannelRegs_t; + +static dshotChannelRegs_t dshotChannelRegs(const pwmOutputPort_t *port) +{ + const uint32_t channelIndex = port->tch->timHw->channelIndex; + TIM_TypeDef *tim = port->tch->timHw->tim; + dshotChannelRegs_t regs; + regs.ccmr = (channelIndex < 2) ? &tim->CCMR1 : &tim->CCMR2; + regs.ccmrShift = 8 * (channelIndex & 1); + regs.ccmrMask = (0xFF | TIM_CCMR1_OC1M_3) << regs.ccmrShift; + regs.ccerShift = 4 * channelIndex; + regs.ccerMask = 0xF << regs.ccerShift; + return regs; +} + +// CCMRx channel byte for capture: CCxS=01 (TI direct), ICxPSC=0, ICxF=0010 (fDTS, N=4) +#define DSHOT_CCMR_INPUT (TIM_CCMR1_CC1S_0 | TIM_CCMR1_IC1F_1) +// CCMRx channel byte for output: CCxS=00, OCxM=110 (PWM1); preload is added once CCR is zeroed +#define DSHOT_CCMR_OUTPUT (TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1) +// CCER channel nibble for capture: both edges, channel on +#define DSHOT_CCER_INPUT (TIM_CCER_CC1E | TIM_CCER_CC1P | TIM_CCER_CC1NP) +#else // The channel identifiers are evenly spaced, so channelIndex maps onto them linearly static uint32_t dshotTimChannel(const pwmOutputPort_t *port) { -#if defined(USE_HAL_DRIVER) - STATIC_ASSERT(TIM_CHANNEL_4 == TIM_CHANNEL_1 + 3 * (TIM_CHANNEL_2 - TIM_CHANNEL_1), tim_channel_ids_linear); - return TIM_CHANNEL_1 + port->tch->timHw->channelIndex * (TIM_CHANNEL_2 - TIM_CHANNEL_1); -#elif defined(AT32F43x) +#if defined(AT32F43x) STATIC_ASSERT(TMR_SELECT_CHANNEL_4 == TMR_SELECT_CHANNEL_1 + 3 * (TMR_SELECT_CHANNEL_2 - TMR_SELECT_CHANNEL_1), tmr_channel_ids_linear); return TMR_SELECT_CHANNEL_1 + port->tch->timHw->channelIndex * (TMR_SELECT_CHANNEL_2 - TMR_SELECT_CHANNEL_1); #else @@ -533,6 +568,7 @@ static uint32_t dshotTimChannel(const pwmOutputPort_t *port) return TIM_Channel_1 + port->tch->timHw->channelIndex * (TIM_Channel_2 - TIM_Channel_1); #endif } +#endif static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count) { @@ -593,42 +629,6 @@ static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t cou return decodedValue >> 4; } -#if defined(USE_HAL_DRIVER) -// Betaflight-style direction switching: instead of poking DIR/addresses into a live -// stream, every switch does a full LL_DMA_DeInit (which also clears all five stream -// event flags - EN=1 is ignored while any of them is set, RM0433) followed by a -// complete LL_DMA_Init built from scratch for the requested direction. -static void dshotDmaInit(const pwmOutputPort_t *port, LL_DMA_InitTypeDef *init, uint32_t direction) -{ - LL_DMA_StructInit(init); -#if defined(STM32H7) || defined(STM32G4) - init->PeriphRequest = DMATAG_GET_CHANNEL(port->tch->timHw->dmaTag); -#else - static const uint32_t channels[] = { - LL_DMA_CHANNEL_0, LL_DMA_CHANNEL_1, LL_DMA_CHANNEL_2, LL_DMA_CHANNEL_3, - LL_DMA_CHANNEL_4, LL_DMA_CHANNEL_5, LL_DMA_CHANNEL_6, LL_DMA_CHANNEL_7 - }; - init->Channel = channels[DMATAG_GET_CHANNEL(port->tch->timHw->dmaTag)]; -#endif - init->PeriphOrM2MSrcAddress = (uint32_t)port->ccr; - init->MemoryOrM2MDstAddress = (uint32_t)port->dmaBuffer; - init->Direction = direction; - init->NbData = (direction == LL_DMA_DIRECTION_MEMORY_TO_PERIPH) ? DSHOT_DMA_BUFFER_SIZE : GCR_TELEMETRY_INPUT_LEN; - init->PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; - init->MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; - init->PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; - init->MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; - init->Mode = LL_DMA_MODE_NORMAL; - init->Priority = LL_DMA_PRIORITY_HIGH; - init->FIFOMode = LL_DMA_FIFOMODE_ENABLE; - // 1/4 threshold like Betaflight: each captured word is pushed to memory promptly - // instead of waiting for four, so a partial GCR frame isn't stuck in the FIFO. - init->FIFOThreshold = LL_DMA_FIFOTHRESHOLD_1_4; - init->MemBurst = LL_DMA_MBURST_SINGLE; - init->PeriphBurst = LL_DMA_PBURST_SINGLE; -} -#endif - static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) { // Bidirectional DSHOT is carried on inverted (idle-high) signalling - flip the @@ -645,30 +645,30 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) SET_BIT(tim->CR1, TIM_CR1_ARPE); tim->CNT = 0; - TIM_OC_InitTypeDef init = {0}; - init.OCMode = TIM_OCMODE_PWM1; - init.OCIdleState = TIM_OCIDLESTATE_SET; - init.OCPolarity = inverted ? TIM_OCPOLARITY_LOW : TIM_OCPOLARITY_HIGH; - init.OCNIdleState = TIM_OCNIDLESTATE_SET; - init.OCNPolarity = inverted ? TIM_OCNPOLARITY_LOW : TIM_OCNPOLARITY_HIGH; - init.Pulse = 0; - init.OCFastMode = TIM_OCFAST_DISABLE; - HAL_TIM_PWM_ConfigChannel(port->tch->timCtx->timHandle, &init, dshotTimChannel(port)); + // Channel back to PWM1 output. CCxS is only writable with the channel off, and CCR is + // zeroed before OCxPE goes back on so the stale capture value can't give one bit period + // of output before the first update event. Idle state (CR2 OISx) is untouched. + const dshotChannelRegs_t regs = dshotChannelRegs(port); + CLEAR_BIT(tim->CCER, regs.ccerMask); + MODIFY_REG(*regs.ccmr, regs.ccmrMask, DSHOT_CCMR_OUTPUT << regs.ccmrShift); + *port->ccr = 0; + SET_BIT(*regs.ccmr, TIM_CCMR1_OC1PE << regs.ccmrShift); + uint32_t ccer; if (port->tch->timHw->output & TIMER_OUTPUT_N_CHANNEL) { - HAL_TIMEx_PWMN_Start(port->tch->timCtx->timHandle, dshotTimChannel(port)); + ccer = TIM_CCER_CC1NE | (inverted ? TIM_CCER_CC1NP : 0); } else { - HAL_TIM_PWM_Start(port->tch->timCtx->timHandle, dshotTimChannel(port)); + ccer = TIM_CCER_CC1E | (inverted ? TIM_CCER_CC1P : 0); } - - const uint32_t streamLL = dshotDmaStream(port); - DMA_TypeDef *dmaBase = port->tch->dma->dma; - LL_DMA_DisableStream(dmaBase, streamLL); - while (LL_DMA_IsEnabledStream(dmaBase, streamLL)) { } - LL_DMA_DeInit(dmaBase, streamLL); - LL_DMA_InitTypeDef dmaInit; - dshotDmaInit(port, &dmaInit, LL_DMA_DIRECTION_MEMORY_TO_PERIPH); - LL_DMA_Init(dmaBase, streamLL, &dmaInit); - LL_DMA_EnableIT_TC(dmaBase, streamLL); + MODIFY_REG(tim->CCER, regs.ccerMask, ccer << regs.ccerShift); + + // Stream back to memory-to-peripheral; timerPWMPrepareDMA() sets count and addresses and + // enables it for the next frame. The capture may still be draining (the decode loop only + // cleared EN), so wait for EN to read 0 before touching CR, then clear all five event + // flags: EN=1 is ignored while any of them is set (RM0433). + DMA_Stream_TypeDef *stream = port->tch->dma->ref; + for (uint32_t timeout = 10000; timeout && (stream->CR & DMA_SxCR_EN); timeout--) { } + DMA_CLEAR_FLAG(port->tch->dma, DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_TEIF | DMA_IT_DMEIF | DMA_IT_FEIF); + stream->CR = (stream->CR & ~(DMA_SxCR_DIR | DMA_SxCR_EN)) | DMA_SxCR_DIR_0; port->telemetryInputActive = false; #elif defined(AT32F43x) // Telemetry input capture widens the period to 0xffff (see pwmDshotSetDirectionInput); @@ -735,51 +735,52 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) #endif } -static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) +FAST_CODE static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) { #if defined(USE_HAL_DRIVER) - // Betaflight ordering: reset the stream first (DeInit also clears all five event - // flags), then reconfigure the timer channel for capture, then rebuild the stream - // for the capture direction and arm it. - const uint32_t streamLL = dshotDmaStream(port); - DMA_TypeDef *dmaBase = port->tch->dma->dma; - LL_DMA_DisableStream(dmaBase, streamLL); - while (LL_DMA_IsEnabledStream(dmaBase, streamLL)) { } - LL_DMA_DeInit(dmaBase, streamLL); + // Runs in the DMA completion ISR for every motor in turn, so it only writes registers: + // no HAL/LL init calls, and the stream is reconfigured in place (hardware clears its EN + // bit at end of transfer, the wait below only covers the flag/EN ordering). + // pwmOutputPorts lives in non-cacheable DMA_RAM, so read tch once. + TCH_t *tch = port->tch; + TIM_TypeDef *tim = tch->timHw->tim; + const dshotChannelRegs_t regs = dshotChannelRegs(port); // Widen ARR so the free-running counter doesn't wrap every DSHOT bit period // (20 ticks) while timing GCR edges, which span ~21 bits per telemetry frame. - SET_BIT(port->tch->timHw->tim->CR1, TIM_CR1_ARPE); - port->tch->timHw->tim->ARR = 0xffff; + // ARPE is set, so this lands at the next update event, within one bit period. + tim->ARR = 0xffff; #if defined(STM32H7) // H7 errata workaround (matches Betaflight): reconfiguring the channel from output // compare to input capture can glitch the pin for a cycle while CCMR/CCER are mid-update. - // Disconnect the pin from the timer first so the ESC never sees the glitch, then - // reconnect it once the IC channel is safely configured. - const IO_t io = IOGetByTag(port->tch->timHw->tag); - IOConfigGPIO(io, IOCFG_OUT_PP); + // Drive it as a plain GPIO output at the preset ODR level meanwhile. Only MODER changes; + // pull, speed and AF stay as dshotConnectOutputs() set them. + const IO_t io = IOGetByTag(tch->timHw->tag); + GPIO_TypeDef *gpio = IO_GPIO(io); + const uint32_t moderShift = 2 * IO_GPIOPinIdx(io); + MODIFY_REG(gpio->MODER, GPIO_MODER_MODE0_Msk << moderShift, GPIO_MODER_MODE0_0 << moderShift); #endif - TIM_IC_InitTypeDef init = {0}; - init.ICPolarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE; - init.ICSelection = TIM_ICSELECTION_DIRECTTI; - init.ICPrescaler = TIM_ICPSC_DIV1; - init.ICFilter = 2; - HAL_TIM_IC_ConfigChannel(port->tch->timCtx->timHandle, &init, dshotTimChannel(port)); - HAL_TIM_IC_Start(port->tch->timCtx->timHandle, dshotTimChannel(port)); + // Channel to input capture, both edges, filter N=4. CCxS is only writable with the channel off. + CLEAR_BIT(tim->CCER, regs.ccerMask); + MODIFY_REG(*regs.ccmr, regs.ccmrMask, DSHOT_CCMR_INPUT << regs.ccmrShift); + MODIFY_REG(tim->CCER, regs.ccerMask, DSHOT_CCER_INPUT << regs.ccerShift); #if defined(STM32H7) - const bool baseInverted = port->tch->timHw->output & TIMER_OUTPUT_INVERTED; - IOConfigGPIOAF(io, baseInverted ? IOCFG_AF_PP_PD : IOCFG_AF_PP_UP, port->tch->timHw->alternateFunction); + MODIFY_REG(gpio->MODER, GPIO_MODER_MODE0_Msk << moderShift, GPIO_MODER_MODE0_1 << moderShift); #endif - LL_DMA_InitTypeDef dmaInit; - dshotDmaInit(port, &dmaInit, LL_DMA_DIRECTION_PERIPH_TO_MEMORY); - LL_DMA_Init(dmaBase, streamLL, &dmaInit); - LL_DMA_EnableIT_TC(dmaBase, streamLL); - LL_DMA_EnableStream(dmaBase, streamLL); - LL_TIM_EnableDMAReq_CCx(port->tch->timHw->tim, dshotDmaSource(port)); + // Stream to peripheral-to-memory: addresses, FIFO and request stay from the output frame. + // Clear all five event flags first, EN=1 is ignored while any of them is set (RM0433). + DMA_Stream_TypeDef *stream = tch->dma->ref; + for (uint32_t timeout = 1000; timeout && (stream->CR & DMA_SxCR_EN); timeout--) { } + DMA_CLEAR_FLAG(tch->dma, DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_TEIF | DMA_IT_DMEIF | DMA_IT_FEIF); + const uint32_t cr = (stream->CR & ~(DMA_SxCR_DIR | DMA_SxCR_EN)) | DMA_SxCR_TCIE; + stream->CR = cr; + stream->NDTR = GCR_TELEMETRY_INPUT_LEN; + stream->CR = cr | DMA_SxCR_EN; + LL_TIM_EnableDMAReq_CCx(tim, TIM_DMA_CC1 << tch->timHw->channelIndex); #elif defined(AT32F43x) // Widen the period so the free-running counter doesn't wrap every DSHOT bit period // (20 ticks) while timing GCR edges, which span ~21 bits per telemetry frame. @@ -851,18 +852,21 @@ static void dshotConnectOutputs(void) // Takes over the stream's completion interrupt from the timer driver on bidir ports: once // the frame is out the port is turned round to capture the ESC reply, and -// pwmDshotDecodeTelemetry() turns it back before the next frame -static void pwmDshotDmaIrqHandler(DMA_t descriptor) +// pwmDshotDecodeTelemetry() turns it back before the next frame. Runs once per motor per +// frame, back to back, so it lives in ITCM where available. +FAST_CODE static void pwmDshotDmaIrqHandler(DMA_t descriptor) { if (!DMA_GET_FLAG_STATUS(descriptor, DMA_IT_TCIF)) { return; } - pwmOutputPort_t *port = &pwmOutputPorts[descriptor->userParam]; + // userParam is the motor index (see motorConfigDshot()) + pwmOutputPort_t *port = motors[descriptor->userParam].pwmPort; #if defined(USE_HAL_DRIVER) - const uint32_t streamLL = dshotDmaStream(port); - LL_DMA_DisableStream(port->tch->dma->dma, streamLL); + // The stream disabled itself at end of transfer (normal mode). The DMA request must go + // too: CCR is 0 after the frame, so compare matches keep a request pending and the stream + // would serve it as a bogus first capture the moment it is re-enabled for input. LL_TIM_DisableDMAReq_CCx(port->tch->timHw->tim, dshotDmaSource(port)); #elif defined(AT32F43x) dma_channel_enable(port->tch->dma->ref, FALSE); @@ -879,8 +883,13 @@ static void pwmDshotDmaIrqHandler(DMA_t descriptor) if (!port->telemetryInputActive) { pwmDshotSetDirectionInput(port); - dshotTelemetryInputStampUs = micros(); dshotTelemetryPending = true; + + // DEBUG_ESC: debug[motor] = cycles from the frame start to this capture being armed + // (H7: /480 = us, F7: /216) + if (debugMode == DEBUG_ESC && descriptor->userParam < DEBUG32_VALUE_COUNT) { + debug[descriptor->userParam] = ticks() - dshotFrameStartCycles; + } } DMA_CLEAR_FLAG(descriptor, DMA_IT_TCIF); @@ -894,9 +903,9 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) return true; } - // Wait for the last reply of the frame before switching any port back (see - // dshotTelemetryInputStampUs) - if ((micros() - dshotTelemetryInputStampUs) < dshotTelemetryDeadtimeUs) { + // Wait out the reply window of the frame before switching any port back (see + // dshotTelemetryFrameStampUs) + if ((micros() - dshotTelemetryFrameStampUs) < dshotTelemetryDeadtimeUs) { return false; } @@ -953,8 +962,9 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) } #endif // USE_DSHOT_BIDIR -static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, uint32_t dshotHz, bool enableOutput) +static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, uint32_t dshotHz, bool enableOutput, uint8_t motorIndex) { + UNUSED(motorIndex); // Try allocating new port pwmOutputPort_t * port = pwmOutConfig(timerHardware, OWNER_MOTOR, dshotHz, DSHOT_MOTOR_BITLENGTH, 0, enableOutput); @@ -1003,9 +1013,17 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, if (useDshotTelemetry) { // Inverted signalling and per-frame direction switching; the port takes the // stream's completion interrupt over from the timer driver - dshotTelemetryDeadtimeUs = DSHOT_TELEMETRY_DEADTIME_US + 1000000 * (16 * DSHOT_MOTOR_BITLENGTH) / dshotHz; + dshotTelemetryDeadtimeUs = DSHOT_TELEMETRY_DEADTIME_US + 1000000 * (DSHOT_TELEMETRY_WINDOW_SLOTS * DSHOT_MOTOR_BITLENGTH) / dshotHz; +#if defined(USE_HAL_DRIVER) + // FIFO threshold 1/4 for both directions (the timer driver set FULL), so captured + // edges reach memory one word at a time and the decode never finds a partial reply + // still sitting in the FIFO. Set once here; the direction switch leaves FCR alone. + port->tch->dma->ref->FCR = DMA_SxFCR_DMDIS; +#endif pwmDshotSetDirectionOutput(port); - dmaSetHandler(port->tch->dma, pwmDshotDmaIrqHandler, NVIC_PRIO_TIMER_DMA, allocatedOutputPortCount - 1); + // The handler gets the motor index: it reaches the port through motors[] and uses + // the index straight as the debug slot + dmaSetHandler(port->tch->dma, pwmDshotDmaIrqHandler, NVIC_PRIO_TIMER_DMA, motorIndex); } #endif } @@ -1238,6 +1256,16 @@ void pwmCompleteMotorUpdate(void) { } } +#ifdef USE_DSHOT_BIDIR + if (useDshotTelemetry) { + // Reference for the reply window; the completion ISRs don't read the clock + dshotTelemetryFrameStampUs = micros(); + if (debugMode == DEBUG_ESC) { + dshotFrameStartCycles = ticks(); + } + } +#endif + // Start DMA on all timers for (int index = 0; index < motorCount; index++) { if (motors[index].pwmPort && motors[index].pwmPort->configured) { @@ -1358,7 +1386,7 @@ bool pwmMotorConfig(const timerHardware_t *timerHardware, uint8_t motorIndex, bo case PWM_TYPE_DSHOT600: case PWM_TYPE_DSHOT300: case PWM_TYPE_DSHOT150: - motors[motorIndex].pwmPort = motorConfigDshot(timerHardware, getDshotHz(initMotorProtocol), enableOutput); + motors[motorIndex].pwmPort = motorConfigDshot(timerHardware, getDshotHz(initMotorProtocol), enableOutput, motorIndex); break; #endif From 776761bb5e2e530ba002139fce066fd25ab84295 Mon Sep 17 00:00:00 2001 From: Error414 Date: Fri, 9 Oct 2026 20:02:00 +0200 Subject: [PATCH 28/37] DSHOT BIDIR - make F4 IRQ faster --- src/main/drivers/pwm_output.c | 133 ++++++++-------------------------- 1 file changed, 32 insertions(+), 101 deletions(-) diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 47727b0ea18..303f090881d 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -497,7 +497,7 @@ static uint8_t getBurstDmaTimerIndex(TIM_TypeDef *timer) // The CC1..CC4 DMA request bits sit next to each other in DIER on every supported MCU static uint32_t dshotDmaSource(const pwmOutputPort_t *port) { -#if defined(USE_HAL_DRIVER) || !defined(AT32F43x) +#if !defined(AT32F43x) STATIC_ASSERT(TIM_DMA_CC2 == TIM_DMA_CC1 << 1 && TIM_DMA_CC4 == TIM_DMA_CC1 << 3, tim_dma_cc_bits_adjacent); return TIM_DMA_CC1 << port->tch->timHw->channelIndex; #else @@ -506,31 +506,22 @@ static uint32_t dshotDmaSource(const pwmOutputPort_t *port) #endif } -#if defined(USE_HAL_DRIVER) -static uint32_t dshotDmaStream(const pwmOutputPort_t *port) -{ - STATIC_ASSERT(LL_DMA_STREAM_0 == 0 && LL_DMA_STREAM_7 == 7, ll_dma_stream_is_index); - return DMATAG_GET_STREAM(port->tch->timHw->dmaTag); -} - -// The LL driver only exposes per-channel LL_TIM_{En,Dis}ableDMAReq_CC1..CC4; -// there is no runtime-channel variant, so set/clear the DIER bit directly. -static inline void LL_TIM_EnableDMAReq_CCx(TIM_TypeDef *TIMx, uint16_t dmaSources) +#if !defined(AT32F43x) +// Per-channel DMA request bit in DIER; the LL and SPL drivers only offer fixed-channel variants +static inline void dshotDmaReqEnable(TIM_TypeDef *tim, uint32_t dmaSource) { - SET_BIT(TIMx->DIER, dmaSources & (TIM_DMA_CC1 | TIM_DMA_CC2 | TIM_DMA_CC3 | TIM_DMA_CC4)); + SET_BIT(tim->DIER, dmaSource); } -static inline void LL_TIM_DisableDMAReq_CCx(TIM_TypeDef *TIMx, uint16_t dmaSources) +static inline void dshotDmaReqDisable(TIM_TypeDef *tim, uint32_t dmaSource) { - CLEAR_BIT(TIMx->DIER, dmaSources & (TIM_DMA_CC1 | TIM_DMA_CC2 | TIM_DMA_CC3 | TIM_DMA_CC4)); + CLEAR_BIT(tim->DIER, dmaSource); } -#endif -#if defined(USE_HAL_DRIVER) // Register slices of this port's timer channel for the direction switch: the channel's // byte in CCMR1/CCMR2 and its nibble in CCER. Derived on the fly, the shifts cost a few cycles. typedef struct { - volatile uint32_t *ccmr; + __typeof__(((TIM_TypeDef *)0)->CCMR1) *ccmr; // CCMRx is 16 bits wide on F4, 32 on F7/H7 uint32_t ccmrShift; uint32_t ccmrMask; // the channel's byte plus its OCxM[3] bit uint32_t ccerShift; @@ -544,7 +535,11 @@ static dshotChannelRegs_t dshotChannelRegs(const pwmOutputPort_t *port) dshotChannelRegs_t regs; regs.ccmr = (channelIndex < 2) ? &tim->CCMR1 : &tim->CCMR2; regs.ccmrShift = 8 * (channelIndex & 1); - regs.ccmrMask = (0xFF | TIM_CCMR1_OC1M_3) << regs.ccmrShift; + regs.ccmrMask = 0xFF << regs.ccmrShift; +#ifdef TIM_CCMR1_OC1M_3 + // F7/H7 keep a fourth OCxM bit outside the channel byte; F4 has none + regs.ccmrMask |= TIM_CCMR1_OC1M_3 << regs.ccmrShift; +#endif regs.ccerShift = 4 * channelIndex; regs.ccerMask = 0xF << regs.ccerShift; return regs; @@ -560,13 +555,8 @@ static dshotChannelRegs_t dshotChannelRegs(const pwmOutputPort_t *port) // The channel identifiers are evenly spaced, so channelIndex maps onto them linearly static uint32_t dshotTimChannel(const pwmOutputPort_t *port) { -#if defined(AT32F43x) STATIC_ASSERT(TMR_SELECT_CHANNEL_4 == TMR_SELECT_CHANNEL_1 + 3 * (TMR_SELECT_CHANNEL_2 - TMR_SELECT_CHANNEL_1), tmr_channel_ids_linear); return TMR_SELECT_CHANNEL_1 + port->tch->timHw->channelIndex * (TMR_SELECT_CHANNEL_2 - TMR_SELECT_CHANNEL_1); -#else - STATIC_ASSERT(TIM_Channel_4 == TIM_Channel_1 + 3 * (TIM_Channel_2 - TIM_Channel_1), tim_channel_ids_linear); - return TIM_Channel_1 + port->tch->timHw->channelIndex * (TIM_Channel_2 - TIM_Channel_1); -#endif } #endif @@ -635,7 +625,7 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) // channel's normal polarity whenever telemetry is active, matching Betaflight. const bool inverted = ((port->tch->timHw->output & TIMER_OUTPUT_INVERTED) != 0) ^ useDshotTelemetry; -#if defined(USE_HAL_DRIVER) +#if !defined(AT32F43x) // Telemetry input capture widens ARR to 0xffff (see pwmDshotSetDirectionInput); // restore the DSHOT bit period now, bypassing the ARR preload shadow so it // takes effect immediately instead of after the next update event. @@ -670,7 +660,7 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) DMA_CLEAR_FLAG(port->tch->dma, DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_TEIF | DMA_IT_DMEIF | DMA_IT_FEIF); stream->CR = (stream->CR & ~(DMA_SxCR_DIR | DMA_SxCR_EN)) | DMA_SxCR_DIR_0; port->telemetryInputActive = false; -#elif defined(AT32F43x) +#else // Telemetry input capture widens the period to 0xffff (see pwmDshotSetDirectionInput); // restore the DSHOT bit period now, bypassing the period buffer so it takes effect // immediately, and reset the counter so a stale count above the new period doesn't @@ -701,43 +691,12 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) port->tch->dma->ref->maddr = (uint32_t)port->dmaBuffer; port->tch->dma->ref->dtcnt = DSHOT_DMA_BUFFER_SIZE; port->telemetryInputActive = false; -#else - TIM_ARRPreloadConfig(port->tch->timHw->tim, DISABLE); - TIM_SetAutoreload(port->tch->timHw->tim, DSHOT_MOTOR_BITLENGTH - 1); - TIM_ARRPreloadConfig(port->tch->timHw->tim, ENABLE); - TIM_SetCounter(port->tch->timHw->tim, 0); - TIM_OCInitTypeDef init; - TIM_OCStructInit(&init); - init.TIM_OCMode = TIM_OCMode_PWM1; - init.TIM_Pulse = 0; - if (port->tch->timHw->output & TIMER_OUTPUT_N_CHANNEL) { - init.TIM_OutputState = TIM_OutputState_Disable; - init.TIM_OutputNState = TIM_OutputNState_Enable; - init.TIM_OCNPolarity = inverted ? TIM_OCPolarity_Low : TIM_OCPolarity_High; - init.TIM_OCNIdleState = TIM_OCIdleState_Reset; - } else { - init.TIM_OutputState = TIM_OutputState_Enable; - init.TIM_OutputNState = TIM_OutputNState_Disable; - init.TIM_OCPolarity = inverted ? TIM_OCPolarity_Low : TIM_OCPolarity_High; - init.TIM_OCIdleState = TIM_OCIdleState_Set; - } - switch (port->tch->timHw->channelIndex) { - case 0: TIM_OC1Init(port->tch->timHw->tim, &init); TIM_OC1PreloadConfig(port->tch->timHw->tim, TIM_OCPreload_Enable); break; - case 1: TIM_OC2Init(port->tch->timHw->tim, &init); TIM_OC2PreloadConfig(port->tch->timHw->tim, TIM_OCPreload_Enable); break; - case 2: TIM_OC3Init(port->tch->timHw->tim, &init); TIM_OC3PreloadConfig(port->tch->timHw->tim, TIM_OCPreload_Enable); break; - default: TIM_OC4Init(port->tch->timHw->tim, &init); TIM_OC4PreloadConfig(port->tch->timHw->tim, TIM_OCPreload_Enable); break; - } - DMA_Cmd(port->tch->dma->ref, DISABLE); - port->tch->dma->ref->CR = (port->tch->dma->ref->CR & ~(DMA_DIR_MemoryToPeripheral | DMA_DIR_MemoryToMemory)) | DMA_DIR_MemoryToPeripheral; - port->tch->dma->ref->M0AR = (uint32_t)port->dmaBuffer; - DMA_SetCurrDataCounter(port->tch->dma->ref, DSHOT_DMA_BUFFER_SIZE); - port->telemetryInputActive = false; #endif } FAST_CODE static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) { -#if defined(USE_HAL_DRIVER) +#if !defined(AT32F43x) // Runs in the DMA completion ISR for every motor in turn, so it only writes registers: // no HAL/LL init calls, and the stream is reconfigured in place (hardware clears its EN // bit at end of transfer, the wait below only covers the flag/EN ordering). @@ -780,8 +739,8 @@ FAST_CODE static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) stream->CR = cr; stream->NDTR = GCR_TELEMETRY_INPUT_LEN; stream->CR = cr | DMA_SxCR_EN; - LL_TIM_EnableDMAReq_CCx(tim, TIM_DMA_CC1 << tch->timHw->channelIndex); -#elif defined(AT32F43x) + dshotDmaReqEnable(tim, dshotDmaSource(port)); +#else // Widen the period so the free-running counter doesn't wrap every DSHOT bit period // (20 ticks) while timing GCR edges, which span ~21 bits per telemetry frame. tmr_period_buffer_enable(port->tch->timHw->tim, TRUE); @@ -799,28 +758,6 @@ FAST_CODE static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) port->tch->dma->ref->dtcnt = GCR_TELEMETRY_INPUT_LEN; dma_channel_enable(port->tch->dma->ref, TRUE); tmr_dma_request_enable(port->tch->timHw->tim, dshotDmaSource(port), TRUE); -#else - TIM_ARRPreloadConfig(port->tch->timHw->tim, ENABLE); - TIM_SetAutoreload(port->tch->timHw->tim, 0xffff); - TIM_ICInitTypeDef init; - TIM_ICStructInit(&init); - init.TIM_Channel = dshotTimChannel(port); - init.TIM_ICSelection = TIM_ICSelection_DirectTI; - init.TIM_ICPrescaler = TIM_ICPSC_DIV1; - init.TIM_ICFilter = 2; - init.TIM_ICPolarity = TIM_ICPolarity_BothEdge; - TIM_ICInit(port->tch->timHw->tim, &init); - DMA_Cmd(port->tch->dma->ref, DISABLE); - port->tch->dma->ref->CR &= ~(DMA_DIR_MemoryToPeripheral | DMA_DIR_MemoryToMemory); // P→M - port->tch->dma->ref->PAR = (uint32_t)port->ccr; - port->tch->dma->ref->M0AR = (uint32_t)port->dmaBuffer; - DMA_SetCurrDataCounter(port->tch->dma->ref, GCR_TELEMETRY_INPUT_LEN); - // Clear stale DMA flags (TCIF/HTIF from completed output DMA) before - // enabling input capture, otherwise a spurious TC fires immediately and - // kills the capture DMA before any edges can be recorded. - DMA_CLEAR_FLAG(port->tch->dma, DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_TEIF); - DMA_Cmd(port->tch->dma->ref, ENABLE); - TIM_DMACmd(port->tch->timHw->tim, dshotDmaSource(port), ENABLE); #endif port->telemetryInputActive = true; } @@ -863,17 +800,14 @@ FAST_CODE static void pwmDshotDmaIrqHandler(DMA_t descriptor) // userParam is the motor index (see motorConfigDshot()) pwmOutputPort_t *port = motors[descriptor->userParam].pwmPort; -#if defined(USE_HAL_DRIVER) - // The stream disabled itself at end of transfer (normal mode). The DMA request must go - // too: CCR is 0 after the frame, so compare matches keep a request pending and the stream - // would serve it as a bogus first capture the moment it is re-enabled for input. - LL_TIM_DisableDMAReq_CCx(port->tch->timHw->tim, dshotDmaSource(port)); -#elif defined(AT32F43x) +#if defined(AT32F43x) dma_channel_enable(port->tch->dma->ref, FALSE); tmr_dma_request_enable(port->tch->timHw->tim, dshotDmaSource(port), FALSE); #else - DMA_Cmd(port->tch->dma->ref, DISABLE); - TIM_DMACmd(port->tch->timHw->tim, dshotDmaSource(port), DISABLE); + // The stream disabled itself at end of transfer (normal mode). The DMA request must go + // too: CCR is 0 after the frame, so compare matches keep a request pending and the stream + // would serve it as a bogus first capture the moment it is re-enabled for input. + dshotDmaReqDisable(port->tch->timHw->tim, dshotDmaSource(port)); #endif // Same bookkeeping as the timer driver's handler (timerPWMDMAInProgress()) @@ -921,19 +855,14 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) } uint32_t edges = 0; -#if defined(USE_HAL_DRIVER) - const uint32_t streamLL = dshotDmaStream(port); - edges = GCR_TELEMETRY_INPUT_LEN - LL_DMA_GetDataLength(port->tch->dma->dma, streamLL); - LL_TIM_DisableDMAReq_CCx(port->tch->timHw->tim, dshotDmaSource(port)); - LL_DMA_DisableStream(port->tch->dma->dma, streamLL); -#elif defined(AT32F43x) +#if defined(AT32F43x) edges = GCR_TELEMETRY_INPUT_LEN - dma_data_number_get(port->tch->dma->ref); tmr_dma_request_enable(port->tch->timHw->tim, dshotDmaSource(port), FALSE); dma_channel_enable(port->tch->dma->ref, FALSE); #else - edges = GCR_TELEMETRY_INPUT_LEN - DMA_GetCurrDataCounter(port->tch->dma->ref); - TIM_DMACmd(port->tch->timHw->tim, dshotDmaSource(port), DISABLE); - DMA_Cmd(port->tch->dma->ref, DISABLE); + edges = GCR_TELEMETRY_INPUT_LEN - port->tch->dma->ref->NDTR; + dshotDmaReqDisable(port->tch->timHw->tim, dshotDmaSource(port)); + CLEAR_BIT(port->tch->dma->ref->CR, DMA_SxCR_EN); #endif // Too few edges is no reply at all @@ -1015,9 +944,11 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, // stream's completion interrupt over from the timer driver dshotTelemetryDeadtimeUs = DSHOT_TELEMETRY_DEADTIME_US + 1000000 * (DSHOT_TELEMETRY_WINDOW_SLOTS * DSHOT_MOTOR_BITLENGTH) / dshotHz; #if defined(USE_HAL_DRIVER) - // FIFO threshold 1/4 for both directions (the timer driver set FULL), so captured - // edges reach memory one word at a time and the decode never finds a partial reply - // still sitting in the FIFO. Set once here; the direction switch leaves FCR alone. + // FIFO threshold 1/4 for both directions (the F7/H7 timer driver set FULL), so + // captured edges reach memory one word at a time and the decode never finds a + // partial reply still sitting in the FIFO. Set once here; the direction switch + // leaves FCR alone. The F4 driver runs the stream in direct mode, which already + // writes every word straight away. port->tch->dma->ref->FCR = DMA_SxFCR_DMDIS; #endif pwmDshotSetDirectionOutput(port); From 21fc86c18eda838269c584e138c349954121040e Mon Sep 17 00:00:00 2001 From: Error414 Date: Mon, 12 Oct 2026 11:20:25 +0200 Subject: [PATCH 29/37] DSHOT BIDIR - add checking for getting RPM error --- src/main/drivers/bidir_dshot.c | 15 ++++++++++++++- src/main/drivers/bidir_dshot.h | 2 +- src/main/flight/rpm_filter.c | 6 +++++- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/main/drivers/bidir_dshot.c b/src/main/drivers/bidir_dshot.c index ac0d982bccd..d99a2ed87f9 100644 --- a/src/main/drivers/bidir_dshot.c +++ b/src/main/drivers/bidir_dshot.c @@ -40,9 +40,14 @@ // have no consumer and just mark their type as seen #define DSHOT_TELEMETRY_STORED_TYPE_COUNT (DSHOT_TELEMETRY_TYPE_CURRENT + 1) +// A silent ESC (reset, brownout, desync) must not leave the RPM notches on its last speed. +// Replies come with every frame, so this is far longer than any regular gap, EDT included +#define DSHOT_ERPM_TIMEOUT_MS 100 + typedef struct { uint16_t telemetryData[DSHOT_TELEMETRY_STORED_TYPE_COUNT]; uint8_t telemetryTypes; // bit per dshotTelemetryType_e seen since boot + timeMs_t lastErpmMs; // millis(), not micros(): a dead ESC must not turn fresh on wrap } dshotTelemetryMotorState_t; bool useDshotTelemetry = false; @@ -128,13 +133,21 @@ uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) if (type < DSHOT_TELEMETRY_STORED_TYPE_COUNT) { motorTelemetry[motorIndex].telemetryData[type] = decoded; } + if (type == DSHOT_TELEMETRY_TYPE_ERPM) { + motorTelemetry[motorIndex].lastErpmMs = millis(); + } return rawValue; } float getMotorFrequencyHz(uint8_t motorIndex) { - return motorTelemetry[motorIndex].telemetryData[DSHOT_TELEMETRY_TYPE_ERPM] * erpmToHz; + const dshotTelemetryMotorState_t *state = &motorTelemetry[motorIndex]; + if (millis() - state->lastErpmMs > DSHOT_ERPM_TIMEOUT_MS) { + return 0.0f; + } + + return state->telemetryData[DSHOT_TELEMETRY_TYPE_ERPM] * erpmToHz; } float getDshotRpm(uint8_t motorIndex) diff --git a/src/main/drivers/bidir_dshot.h b/src/main/drivers/bidir_dshot.h index ac37fde5cf5..4ecdd37115e 100644 --- a/src/main/drivers/bidir_dshot.h +++ b/src/main/drivers/bidir_dshot.h @@ -59,7 +59,7 @@ void initDshotTelemetry(void); bool isDshotTelemetryActive(void); uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex); float getDshotRpm(uint8_t motorIndex); -// Mechanical frequency from the last decoded eRPM frame, unfiltered (see bidir_dshot.c) +// Mechanical frequency from the last decoded eRPM frame, unfiltered (see bidir_dshot.c); 0 once it is stale float getMotorFrequencyHz(uint8_t motorIndex); bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex); #endif diff --git a/src/main/flight/rpm_filter.c b/src/main/flight/rpm_filter.c index 1cbdb6d6923..951fbec8770 100644 --- a/src/main/flight/rpm_filter.c +++ b/src/main/flight/rpm_filter.c @@ -46,6 +46,9 @@ #ifdef USE_RPM_FILTER #define RPM_FILTER_RPM_LPF_HZ 150 +// Serial ESC telemetry ages by one per missed reply of that motor (SRXL2 only once its own +// stale timeout passed): a single CRC error keeps the value, a silent ESC drops to 0 +#define RPM_FILTER_MAX_ESC_DATA_AGE 2 #define RPM_FILTER_HARMONICS 3 PG_REGISTER_WITH_RESET_TEMPLATE(rpmFilterConfig_t, rpmFilterConfig, PG_RPM_FILTER_CONFIG, 1); @@ -199,7 +202,8 @@ void rpmFilterUpdateTask(timeUs_t currentTimeUs) #endif { #ifdef USE_ESC_SENSOR - motorFrequency = (float)getEscTelemetry(i)->rpm / 60.0f; + const escSensorData_t *escData = getEscTelemetry(i); + motorFrequency = escData->dataAge <= RPM_FILTER_MAX_ESC_DATA_AGE ? (float)escData->rpm / 60.0f : 0.0f; #else motorFrequency = 0.0f; #endif From 2fffdeffe268aefe7e143a5e9af82bf7844ff862 Mon Sep 17 00:00:00 2001 From: Error414 Date: Sat, 17 Oct 2026 13:00:33 +0200 Subject: [PATCH 30/37] DSHOT BIDIR - add motor_poles to BB header and to debug insert RPM instead of frequency --- docs/Blackbox.md | 2 +- src/main/blackbox/blackbox.c | 1 + src/main/flight/rpm_filter.c | 12 +++++++----- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/Blackbox.md b/docs/Blackbox.md index 91b6934c1ee..732428e1b97 100644 --- a/docs/Blackbox.md +++ b/docs/Blackbox.md @@ -194,7 +194,7 @@ Available debug modes include: - `GPS` - GPS debugging - `ALTITUDE` - Altitude estimation debugging - `MAG` - Raw, uncalibrated magnetometer samples (useful for external compass calibration) -- `RPM_FILTER` - Per-motor RPM as seen by the RPM filter, motors 1-8 in `debug[0]`-`debug[7]` (needs the RPM filter enabled, so bidirectional DShot or ESC telemetry) +- `RPM_FILTER` - Raw per-motor eRPM/100 (same unit as Betaflight's `eRPM[]` blackbox field, before the RPM filter's smoothing), motors 1-8 in `debug[0]`-`debug[7]`; RPM = value * 100 / (`motor_poles` / 2). Needs the RPM filter enabled, so bidirectional DShot or ESC telemetry. `src/utils/blackbox_rpm_to_erpm.py` renames the fields to `eRPM[]` for PIDtoolbox - And 20+ other modes for specific subsystems To use debug mode logging: diff --git a/src/main/blackbox/blackbox.c b/src/main/blackbox/blackbox.c index d6a05751965..0975b163f85 100644 --- a/src/main/blackbox/blackbox.c +++ b/src/main/blackbox/blackbox.c @@ -2154,6 +2154,7 @@ static bool blackboxWriteSysinfo(void) #endif BLACKBOX_PRINT_HEADER_LINE("serialrx_provider", "%d", rxConfig()->serialrx_provider); BLACKBOX_PRINT_HEADER_LINE("motor_pwm_protocol", "%d", motorConfig()->motorPwmProtocol); + BLACKBOX_PRINT_HEADER_LINE("motor_poles", "%d", motorConfig()->motorPoleCount); BLACKBOX_PRINT_HEADER_LINE("motor_pwm_rate", "%d", getEscUpdateFrequency()); BLACKBOX_PRINT_HEADER_LINE("debug_mode", "%d", systemConfig()->debug_mode); BLACKBOX_PRINT_HEADER_LINE("features", "%d", featureConfig()->enabledFeatures); diff --git a/src/main/flight/rpm_filter.c b/src/main/flight/rpm_filter.c index 951fbec8770..7e3c98e7d75 100644 --- a/src/main/flight/rpm_filter.c +++ b/src/main/flight/rpm_filter.c @@ -187,6 +187,8 @@ void rpmFilterUpdateTask(timeUs_t currentTimeUs) UNUSED(currentTimeUs); uint8_t motorCount = getMotorCount(); + // Debug holds eRPM/100 like Betaflight's eRPM[] blackbox field, so log tools can reuse it + const float hzToErpm100 = 60.0f * (motorConfig()->motorPoleCount / 2.0f) / ERPM_PER_LSB; /* * For each motor, read its frequency, filter it and update the notches. Both sources * hand over their latest raw value; the LPF runs here, at this task's fixed rate, so its @@ -208,13 +210,13 @@ void rpmFilterUpdateTask(timeUs_t currentTimeUs) motorFrequency = 0.0f; #endif } - const float baseFrequency = pt1FilterApply(&motorFrequencyFilter[i], motorFrequency); - rpmGyroUpdateFn(&gyroRpmFilters, i, baseFrequency); - - // Per-motor RPM as the notch sees it (after the LPF); blackbox has no per-motor field + // Raw telemetry before the LPF; blackbox has no per-motor field if (i < DEBUG32_VALUE_COUNT) { - DEBUG_SET(DEBUG_RPM_FILTER, i, lrintf(baseFrequency * 60.0f)); + DEBUG_SET(DEBUG_RPM_FILTER, i, lrintf(motorFrequency * hzToErpm100)); } + + const float baseFrequency = pt1FilterApply(&motorFrequencyFilter[i], motorFrequency); + rpmGyroUpdateFn(&gyroRpmFilters, i, baseFrequency); } } From abeae364973d79f07b6b1aad87aee7945085e6d2 Mon Sep 17 00:00:00 2001 From: Error414 Date: Tue, 3 Nov 2026 21:38:04 +0100 Subject: [PATCH 31/37] DSHOT BIDIR - AT32 bitbang --- docs/ESC and servo outputs.md | 17 + src/main/CMakeLists.txt | 4 + src/main/drivers/dma.h | 3 + src/main/drivers/dma_at32f43x.c | 5 + src/main/drivers/dshot_bitbang.c | 899 ++++++++++++++++++++++++ src/main/drivers/dshot_bitbang.h | 70 ++ src/main/drivers/dshot_bitbang_decode.c | 186 +++++ src/main/drivers/dshot_bitbang_decode.h | 39 + src/main/drivers/pwm_output.c | 209 +++--- src/main/drivers/pwm_output.h | 1 + src/main/drivers/resource.c | 2 +- src/main/drivers/resource.h | 1 + src/main/fc/fc_init.c | 16 + src/main/target/common_post.h | 23 +- 14 files changed, 1378 insertions(+), 97 deletions(-) create mode 100644 src/main/drivers/dshot_bitbang.c create mode 100644 src/main/drivers/dshot_bitbang.h create mode 100644 src/main/drivers/dshot_bitbang_decode.c create mode 100644 src/main/drivers/dshot_bitbang_decode.h diff --git a/docs/ESC and servo outputs.md b/docs/ESC and servo outputs.md index a3c4a39d199..47813d328f8 100644 --- a/docs/ESC and servo outputs.md +++ b/docs/ESC and servo outputs.md @@ -15,6 +15,23 @@ ESC protocol can be selected in Configurator. No special configuration is requir Check the ESC documentation for the list of protocols that are supported. +### Bidirectional DSHOT + +With `dshot_bidir_enabled = ON` the ESC answers every DSHOT frame with its eRPM on the motor +wire (and, with `dshot_edt_enabled`, temperature, voltage and current), which feeds the RPM +filter and the ESC telemetry without a separate ESC telemetry UART. Set `motor_poles` to the +pole count of the motors so the eRPM is converted to RPM. The ESC firmware must support +bidirectional DSHOT (BLHeli_32, Bluejay, AM32). + +On STM32 the reply is captured by the motor's own timer channel, so every motor output needs +its timer channel's DMA stream. On AT32 the motor pins are "bitbanged" instead, as in +Betaflight: a spare channel of TMR8 or TMR1 paces DMA transfers that drive and read the +whole GPIO port, one per port with motors on it. That timer must be unused by anything else +(LED strip, servos, beeper). If neither TMR8 nor TMR1 is free, bidirectional DSHOT is switched +off for that boot: the motors run plain DSHOT on their timers, there is no eRPM telemetry or +RPM filter, and the boot log reports "Bitbang DSHOT unavailable". Without +`dshot_bidir_enabled` DSHOT on AT32 stays on the timers as before. + ## Servo outputs By default, INAV uses 50Hz servo update rate. If you want to increase it, make sure that servos support diff --git a/src/main/CMakeLists.txt b/src/main/CMakeLists.txt index d637af2d53f..9f4536c9ebf 100755 --- a/src/main/CMakeLists.txt +++ b/src/main/CMakeLists.txt @@ -254,6 +254,10 @@ main_sources(COMMON_SRC drivers/pwm_mapping.h drivers/bidir_dshot.c drivers/bidir_dshot.h + drivers/dshot_bitbang.c + drivers/dshot_bitbang.h + drivers/dshot_bitbang_decode.c + drivers/dshot_bitbang_decode.h drivers/pwm_output.c drivers/pwm_output.h drivers/pinio.c diff --git a/src/main/drivers/dma.h b/src/main/drivers/dma.h index 3a866f6eae8..fab3edb6686 100644 --- a/src/main/drivers/dma.h +++ b/src/main/drivers/dma.h @@ -135,6 +135,9 @@ DMA_t dmaGetByRef(const DMA_Stream_TypeDef * ref); DMA_t dmaGetByRef(const dma_channel_type * ref); void dmaMuxEnable(DMA_t dma, uint32_t dmaMuxid); +// Walks the channel table; NULL past its end. Any channel serves any peripheral through +// the DMAMUX, so a user without a fixed assignment can take whichever is still free. +DMA_t dmaGetByIndex(unsigned index); #endif diff --git a/src/main/drivers/dma_at32f43x.c b/src/main/drivers/dma_at32f43x.c index 7f48af509e9..5ef15b1d5b3 100644 --- a/src/main/drivers/dma_at32f43x.c +++ b/src/main/drivers/dma_at32f43x.c @@ -103,6 +103,11 @@ DMA_t dmaGetByTag(dmaTag_t tag) return (DMA_t) NULL; } +DMA_t dmaGetByIndex(unsigned index) +{ + return index < ARRAYLEN(dmaDescriptors) ? &dmaDescriptors[index] : NULL; +} + void dmaEnableClock(DMA_t dma) { if (dma->dma == DMA1) { diff --git a/src/main/drivers/dshot_bitbang.c b/src/main/drivers/dshot_bitbang.c new file mode 100644 index 00000000000..5d2bd2babac --- /dev/null +++ b/src/main/drivers/dshot_bitbang.c @@ -0,0 +1,899 @@ +/* + * This file is part of INAV. + * + * INAV is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * INAV is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with INAV. If not, see . + * + * Ported from Betaflight's dshot_bitbang.c and dshot_bitbang_stdperiph.c (AT32), GPLv3. + */ + +/* + * Bitbanged bidirectional DSHOT. + * + * The motor pins are plain GPIO outputs. For every GPIO port that carries motors there is + * one DMA channel writing 32-bit words into the port's set/clear register (scr), one word + * per third of a DSHOT bit: all pins to the active level, the pins sending a 0 back to idle, + * every pin back to idle. The words are paced by the compare event of a spare TMR1/TMR8 + * channel, so one timer channel and one DMA channel serve every motor on the port and the + * motor outputs' own timer channels are not used at all. + * + * After the frame the port's pins are switched to inputs and the same DMA channel reads the + * port's input register, three samples per GCR bit of the ESC reply, into a buffer that + * dshotBitbangDecode() walks per motor pin once the window has closed. + * + * This is the only bidirectional DSHOT on AT32F43x: timer channel 4 cannot capture both + * edges there (see AT32_BIDIR_DSHOT.md in the repository root). Plain DSHOT keeps using the + * timer driver in pwm_output.c, which also owns the frame contents, the DSHOT commands and + * the update rate; this module only drives the pins and reads the replies. + * + * DEBUG_ESC: debug[0] replies decoded, debug[1] windows without a reply, debug[2] replies + * that failed to decode, debug[3] windows cut short, debug[4] port groups, debug[5] status + * (dshotBitbangStatus_e). + */ + +#include +#include +#include + +#include "platform.h" + +#ifdef USE_DSHOT_BITBANG + +#include "build/atomic.h" +#include "build/build_config.h" +#include "build/debug.h" + +#include "common/log.h" +#include "common/maths.h" +#include "common/utils.h" + +#include "drivers/bidir_dshot.h" +#include "drivers/dma.h" +#include "drivers/dshot_bitbang.h" +#include "drivers/dshot_bitbang_decode.h" +#include "drivers/io.h" +#include "drivers/io_impl.h" +#include "drivers/nvic.h" +#include "drivers/pwm_mapping.h" +#include "drivers/rcc.h" +#include "drivers/time.h" +#include "drivers/timer.h" +#include "drivers/timer_impl.h" + +#include "flight/mixer.h" + +// Pin groups: one per GPIO port that carries motors. Each needs a pacer channel, so the +// limit is the eight channels of TMR8 and TMR1; four cover PA, PB, PC and one more. +#define BB_MAX_PORTS 4 +// Pacer timers: TMR8 and TMR1, the advanced timers with four channels each +#define BB_MAX_PACERS 2 + +#define BB_FRAME_BITS 16 +#define BB_STATES_PER_BIT 3 // all pins active, the 0-bit pins back to idle, all pins back to idle +// One more bit period at idle after the frame, so the ESC samples the last bit before the +// pins turn into inputs (the level on a floating line is undefined) +#define BB_HOLD_STATES 3 +#define BB_OUTPUT_BUFFER_LENGTH (BB_FRAME_BITS * BB_STATES_PER_BIT + BB_HOLD_STATES) // 51 words + +// Input window in samples, one sample per pacer period at DSHOT_BITBANG_TELEMETRY_OVERSAMPLE +// times the GCR bit rate: the ESC's ~30 us turnaround, the 21-bit reply and slack. +// Betaflight's figure, sized for DSHOT600 (134 samples) plus six spare. +#define BB_INPUT_BUFFER_LENGTH 140 + +// Compare value of the pacer channel: the DMA request fires this many counts into each period +#define BB_PACER_COMPARE 10 + +// Bound on waiting for the DMA channel enable bit to drop after clearing it: the hardware +// only clears it once the transfer in flight is done, a handful of bus cycles +#define BB_DMA_STOP_SPIN_LIMIT 100 + +// Every status flag of a channel: global, full transfer, half transfer, transfer error. +// Writing the global flag clears the other three with it, the rest are named for clarity. +#define BB_DMA_FLAGS (0x1 | DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_DMEIF) + +// The AT32 headers have no MODIFY_REG +#define BB_MODIFY_REG(reg, mask, value) ((reg) = ((reg) & ~(mask)) | (value)) + +typedef enum { + BB_DIRECTION_OUTPUT = 0, + BB_DIRECTION_INPUT +} bbDirection_e; + +// A compare channel that can pace a port group +typedef struct { + tmr_type *tim; + uint8_t channelIndex; // 0..3 + uint32_t dmaMuxId; // DMAMUX request of this channel's compare event +} bbPacerChannel_t; + +// A timer used as pacer; its period is shared by every port group on it +typedef struct { + tmr_type *tim; + uint16_t dmaSources; // TMR_Cx_DMA_REQUEST bits of the port groups on this timer +} bbPacer_t; + +// One GPIO port with motors on it +typedef struct { + int portIndex; + gpio_type *gpio; + const bbPacerChannel_t *pacerChannel; + bbPacer_t *pacer; + uint16_t dmaSource; // TMR_Cx_DMA_REQUEST of the pacer channel + DMA_t dma; + + // cfgr (mode) bits of the motor pins on this port: the mask, and their input and + // output settings + uint32_t gpioModeMask; + uint32_t gpioModeInput; + uint32_t gpioModeOutput; + // scr word that puts every motor pin of the port at its idle level + uint32_t gpioIdleScr; + + // DMA channel control register for either direction, enable bit clear: the direction + // switch rewrites the channel from these instead of running the SDK init + uint32_t dmaCtrlOutput; + uint32_t dmaCtrlInput; + // Pacer period for sending and for sampling + uint16_t outputPeriod; + uint16_t inputPeriod; + + uint32_t *outputBuffer; + uint16_t *inputBuffer; + + volatile uint8_t direction; // bbDirection_e, where the pins and the DMA point + volatile bool telemetryPending; // reply window of the last frame still open + bool telemetryAborted; // the window was cut short, the samples are not a whole reply +} bbPort_t; + +typedef struct { + IO_t io; // set once the motor has been handed to this driver + const timerHardware_t *timHw; // the output as the target defines it, for the fallback to the timers + ioTag_t tag; + uint8_t pinIndex; + bool enabled; // outputs enabled at all (FEATURE_PWM_OUTPUT_ENABLE) + bool inverted; // the line idles high (bidirectional signalling on non-inverting hardware) + ioConfig_t iocfg; + bbPort_t *port; + bool configured; // in a port group, frames go out on it +} bbMotor_t; + +// TMR8 first: on the AT32 targets TMR1 CH1 is often the LED strip +static const bbPacerChannel_t bbPacerChannels[] = { + { TMR8, 0, DMAMUX_DMAREQ_ID_TMR8_CH1 }, + { TMR8, 1, DMAMUX_DMAREQ_ID_TMR8_CH2 }, + { TMR8, 2, DMAMUX_DMAREQ_ID_TMR8_CH3 }, + { TMR8, 3, DMAMUX_DMAREQ_ID_TMR8_CH4 }, + { TMR1, 0, DMAMUX_DMAREQ_ID_TMR1_CH1 }, + { TMR1, 1, DMAMUX_DMAREQ_ID_TMR1_CH2 }, + { TMR1, 2, DMAMUX_DMAREQ_ID_TMR1_CH3 }, + { TMR1, 3, DMAMUX_DMAREQ_ID_TMR1_CH4 }, +}; + +static bbPacer_t bbPacers[BB_MAX_PACERS]; +static int bbPacerCount = 0; +static bbPort_t bbPorts[BB_MAX_PORTS]; +static int bbPortCount = 0; +static bbMotor_t bbMotors[MAX_MOTORS]; + +// Plain RAM: the ADC's DMA buffer lives there too, and the CPU has no cache to keep coherent +static uint32_t bbOutputBuffers[BB_MAX_PORTS][BB_OUTPUT_BUFFER_LENGTH]; +static uint16_t bbInputBuffers[BB_MAX_PORTS][BB_INPUT_BUFFER_LENGTH]; + +static bool bbActive = false; // selected for this boot +static bool bbReady = false; // port groups set up, frames may go out +static dshotBitbangStatus_e bbStatus = DSHOT_BITBANG_STATUS_OK; +static uint32_t bbOutputStateHz; // pacer rate while sending: three states per bit +static uint32_t bbInputSampleHz; // pacer rate while sampling +static bool bbFrameInFlight = false; +static timeUs_t bbFrameStartUs = 0; +// Backstop for a reply window that never closes: frame plus window plus a quarter +static timeUs_t bbTelemetryTimeoutUs = 0; + +// DEBUG_ESC counters +static uint32_t bbStatDecoded = 0; +static uint32_t bbStatNoEdge = 0; +static uint32_t bbStatInvalid = 0; +static uint32_t bbStatAborted = 0; + +// The channel identifiers are evenly spaced, so channelIndex maps onto them linearly +static tmr_channel_select_type bbTimChannel(uint8_t channelIndex) +{ + STATIC_ASSERT(TMR_SELECT_CHANNEL_4 == TMR_SELECT_CHANNEL_1 + 3 * (TMR_SELECT_CHANNEL_2 - TMR_SELECT_CHANNEL_1), tmr_channel_ids_linear); + return (tmr_channel_select_type)(TMR_SELECT_CHANNEL_1 + channelIndex * (TMR_SELECT_CHANNEL_2 - TMR_SELECT_CHANNEL_1)); +} + +// The CC1..CC4 DMA request bits sit next to each other in IDEN +static uint16_t bbDmaSource(uint8_t channelIndex) +{ + STATIC_ASSERT(TMR_C2_DMA_REQUEST == TMR_C1_DMA_REQUEST << 1 && TMR_C4_DMA_REQUEST == TMR_C1_DMA_REQUEST << 3, tmr_dma_request_bits_adjacent); + return TMR_C1_DMA_REQUEST << channelIndex; +} + +// A pacer takes the whole timer (period and prescaler), so no channel of it may belong to +// anyone else. Every timer user allocates through timerGetTCH(), which records the channel +// in timerCtx; this driver does not, so its own pacers do not show up here. +static bool bbTimerIsFree(tmr_type *tim) +{ + return false; // TEMPORARY: forces the fallback to plain timer DSHOT for testing, remove before commit + const uint8_t timerIndex = lookupTimerIndex(tim); + if (timerIndex >= HARDWARE_TIMER_DEFINITION_COUNT) { + return false; + } + + const timHardwareContext_t *timCtx = timerCtx[timerIndex]; + if (timCtx == NULL) { + return true; + } + + for (int channel = 0; channel < CC_CHANNELS_PER_TIMER; channel++) { + if (timCtx->ch[channel].timHw != NULL) { + return false; + } + } + + return true; +} + +static bbPacer_t *bbPacerGet(tmr_type *tim, uint16_t outputPeriod) +{ + for (int i = 0; i < bbPacerCount; i++) { + if (bbPacers[i].tim == tim) { + return &bbPacers[i]; + } + } + + if (bbPacerCount >= BB_MAX_PACERS) { + return NULL; + } + + const uint8_t timerIndex = lookupTimerIndex(tim); + if (timerIndex >= HARDWARE_TIMER_DEFINITION_COUNT) { + return NULL; + } + + bbPacer_t *pacer = &bbPacers[bbPacerCount++]; + pacer->tim = tim; + pacer->dmaSources = 0; + + // timerInit() only clocks the timers in the target's timer table; the pacer may not be one + RCC_ClockCmd(timerDefinitions[timerIndex].rcc, ENABLE); + + // Free running from here on; the port groups gate its DMA requests. The period is + // buffered, so the direction switches below change it at the next overflow instead of + // mid-period (Betaflight does the same). + tmr_counter_enable(tim, FALSE); + tmr_base_init(tim, outputPeriod, 0); + tmr_clock_source_div_set(tim, TMR_CLOCK_DIV1); + tmr_cnt_dir_set(tim, TMR_COUNT_UP); + tmr_period_buffer_enable(tim, TRUE); + tmr_counter_enable(tim, TRUE); + + return pacer; +} + +// The pacer channel is output compare with nothing muxed to it: only its compare event is +// used, as the DMA request +static void bbPacerChannelInit(const bbPacerChannel_t *pacerChannel) +{ + tmr_type *tim = pacerChannel->tim; + const tmr_channel_select_type channel = bbTimChannel(pacerChannel->channelIndex); + + tmr_output_config_type output; + tmr_output_default_para_init(&output); + output.oc_mode = TMR_OUTPUT_CONTROL_PWM_MODE_A; + output.oc_idle_state = TRUE; + output.oc_output_state = TRUE; + output.oc_polarity = TMR_OUTPUT_ACTIVE_LOW; + tmr_output_channel_config(tim, channel, &output); + + tmr_channel_value_set(tim, channel, BB_PACER_COMPARE); + tmr_output_channel_buffer_enable(tim, channel, TRUE); + tmr_channel_enable(tim, channel, TRUE); +} + +static DMA_t bbFindFreeDma(void) +{ + for (unsigned index = 0; ; index++) { + DMA_t dma = dmaGetByIndex(index); + if (dma == NULL) { + return NULL; + } + if (dmaGetOwner(dma) == OWNER_FREE) { + return dma; + } + } +} + +static void bbDmaIrqHandler(DMA_t descriptor); + +static void bbDmaSetup(bbPort_t *port) +{ + dmaInit(port->dma, OWNER_DSHOT_BITBANG, RESOURCE_INDEX(port - bbPorts)); + dmaSetHandler(port->dma, bbDmaIrqHandler, NVIC_PRIO_TIMER_DMA, (uint32_t)port); + + dma_channel_type *channel = port->dma->ref; + dma_reset(channel); + + // Run the SDK init once per direction only to learn the control register value for it; + // the direction switch then rewrites the channel from that value + dma_init_type init; + dma_default_para_init(&init); + init.peripheral_inc_enable = FALSE; + init.memory_inc_enable = TRUE; + init.loop_mode_enable = FALSE; + init.priority = DMA_PRIORITY_VERY_HIGH; + + // Sampling: the port's input register, one halfword per pacer period + init.direction = DMA_DIR_PERIPHERAL_TO_MEMORY; + init.buffer_size = BB_INPUT_BUFFER_LENGTH; + init.peripheral_base_addr = (uint32_t)&port->gpio->idt; + init.peripheral_data_width = DMA_PERIPHERAL_DATA_WIDTH_HALFWORD; + init.memory_base_addr = (uint32_t)port->inputBuffer; + init.memory_data_width = DMA_MEMORY_DATA_WIDTH_HALFWORD; + dma_init(channel, &init); + port->dmaCtrlInput = channel->ctrl | DMA_FDT_INT; + + // Sending: one set/clear word per pacer period + init.direction = DMA_DIR_MEMORY_TO_PERIPHERAL; + init.buffer_size = BB_OUTPUT_BUFFER_LENGTH; + init.peripheral_base_addr = (uint32_t)&port->gpio->scr; + init.peripheral_data_width = DMA_PERIPHERAL_DATA_WIDTH_WORD; + init.memory_base_addr = (uint32_t)port->outputBuffer; + init.memory_data_width = DMA_MEMORY_DATA_WIDTH_WORD; + dma_init(channel, &init); + port->dmaCtrlOutput = channel->ctrl | DMA_FDT_INT; + + // dma_reset() does not touch the mux, but keep the request routing after the inits anyway + dmaMuxEnable(port->dma, port->pacerChannel->dmaMuxId); +} + +// Channel registers for one direction; the channel must be disabled +static void bbDmaLoad(bbPort_t *port, bbDirection_e direction) +{ + dma_channel_type *channel = port->dma->ref; + + if (direction == BB_DIRECTION_INPUT) { + channel->ctrl = port->dmaCtrlInput; + channel->dtcnt = BB_INPUT_BUFFER_LENGTH; + channel->paddr = (uint32_t)&port->gpio->idt; + channel->maddr = (uint32_t)port->inputBuffer; + } else { + channel->ctrl = port->dmaCtrlOutput; + channel->dtcnt = BB_OUTPUT_BUFFER_LENGTH; + channel->paddr = (uint32_t)&port->gpio->scr; + channel->maddr = (uint32_t)port->outputBuffer; + } +} + +// Clearing the enable bit is a request; the hardware drops it once the transfer in flight +// is done, and the channel registers may not be written before that +static bool bbDmaStop(bbPort_t *port) +{ + dma_channel_type *channel = port->dma->ref; + + dma_channel_enable(channel, FALSE); + for (unsigned spin = 0; spin < BB_DMA_STOP_SPIN_LIMIT; spin++) { + if (!channel->ctrl_bit.chen) { + return true; + } + } + + return false; +} + +// Pins back to outputs at their idle level and the channel reloaded for a frame, not yet +// enabled. false if the channel would not stop: its registers were left alone and the +// pins stay inputs, off a line something is evidently still driving. +static bool bbSwitchToOutput(bbPort_t *port) +{ + if (!bbDmaStop(port)) { + return false; + } + DMA_CLEAR_FLAG(port->dma, BB_DMA_FLAGS); + + // Idle level first, so that is what the pins drive the moment they become outputs + port->gpio->scr = port->gpioIdleScr; + ATOMIC_BLOCK(NVIC_PRIO_MAX) { + BB_MODIFY_REG(port->gpio->cfgr, port->gpioModeMask, port->gpioModeOutput); + } + + bbDmaLoad(port, BB_DIRECTION_OUTPUT); + port->pacer->tim->pr = port->outputPeriod; + port->direction = BB_DIRECTION_OUTPUT; + + return true; +} + +// Pins to inputs and the channel sampling them; runs in the completion interrupt of the frame +static void bbSwitchToInput(bbPort_t *port) +{ + ATOMIC_BLOCK(NVIC_PRIO_MAX) { + BB_MODIFY_REG(port->gpio->cfgr, port->gpioModeMask, port->gpioModeInput); + } + + bbDmaLoad(port, BB_DIRECTION_INPUT); + + // Restart the period for sampling. Every port group on this timer finished its frame on + // the same compare event, so none of them is still sending. The counter is zeroed first: + // the new period is shorter, and a count above it would run to the 16-bit wrap. + tmr_type *tim = port->pacer->tim; + tim->cval = 0; + tim->pr = port->inputPeriod; + + port->direction = BB_DIRECTION_INPUT; + dma_channel_enable(port->dma->ref, TRUE); +} + +static void bbDmaIrqHandler(DMA_t descriptor) +{ + bbPort_t *port = (bbPort_t *)descriptor->userParam; + tmr_type *tim = port->pacer->tim; + + // The request goes first: a request the timer has already raised is not withdrawn by + // IDEN (AT32 errata 1.10.1), so stop raising new ones before the channel stops serving them + tmr_dma_request_enable(tim, port->dmaSource, FALSE); + dma_channel_enable(port->dma->ref, FALSE); + + const bool transferError = DMA_GET_FLAG_STATUS(descriptor, DMA_IT_DMEIF) != 0; + DMA_CLEAR_FLAG(descriptor, BB_DMA_FLAGS); + + if (port->direction == BB_DIRECTION_INPUT || transferError) { + // The reply window has been sampled, or the transfer died and nothing more comes + // this frame: either way the buffer is not touched again until the next frame + if (transferError) { + port->telemetryAborted = true; + } + port->telemetryPending = false; + return; + } + + // Frame out: turn the port round and have the pacer clock the samples in + bbSwitchToInput(port); + tmr_dma_request_enable(tim, port->dmaSource, TRUE); +} + +static bool bbTelemetryPending(void) +{ + bool pending = false; + for (int i = 0; i < bbPortCount; i++) { + pending |= bbPorts[i].telemetryPending; + } + return pending; +} + +// Find or set up the group of the GPIO port this pin belongs to +static bbPort_t *bbPortGet(IO_t io) +{ + const int portIndex = IO_GPIOPortIdx(io); + + for (int i = 0; i < bbPortCount; i++) { + if (bbPorts[i].portIndex == portIndex) { + return &bbPorts[i]; + } + } + + if (bbPortCount >= BB_MAX_PORTS) { + bbStatus = DSHOT_BITBANG_STATUS_TOO_MANY_PORTS; + return NULL; + } + + // First unused channel of a timer nobody else has a channel on + const bbPacerChannel_t *pacerChannel = NULL; + for (unsigned i = 0; i < ARRAYLEN(bbPacerChannels) && pacerChannel == NULL; i++) { + const bbPacerChannel_t *candidate = &bbPacerChannels[i]; + if (!bbTimerIsFree(candidate->tim)) { + continue; + } + bool taken = false; + for (int p = 0; p < bbPortCount; p++) { + taken |= bbPorts[p].pacerChannel == candidate; + } + if (!taken) { + pacerChannel = candidate; + } + } + if (pacerChannel == NULL) { + bbStatus = DSHOT_BITBANG_STATUS_NO_PACER; + return NULL; + } + + DMA_t dma = bbFindFreeDma(); + if (dma == NULL) { + bbStatus = DSHOT_BITBANG_STATUS_NO_DMA; + return NULL; + } + + bbPort_t *port = &bbPorts[bbPortCount]; + memset(port, 0, sizeof(*port)); + port->portIndex = portIndex; + port->gpio = IO_GPIO(io); + port->pacerChannel = pacerChannel; + port->dmaSource = bbDmaSource(pacerChannel->channelIndex); + port->dma = dma; + port->outputBuffer = bbOutputBuffers[bbPortCount]; + port->inputBuffer = bbInputBuffers[bbPortCount]; + + const uint32_t timerClockHz = timerClock(pacerChannel->tim); + port->outputPeriod = timerClockHz / bbOutputStateHz - 1; + port->inputPeriod = timerClockHz / bbInputSampleHz - 1; + + port->pacer = bbPacerGet(pacerChannel->tim, port->outputPeriod); + if (port->pacer == NULL) { + bbStatus = DSHOT_BITBANG_STATUS_NO_PACER; + return NULL; + } + port->pacer->dmaSources |= port->dmaSource; + bbPacerChannelInit(pacerChannel); + + bbDmaSetup(port); + port->direction = BB_DIRECTION_OUTPUT; + + bbPortCount++; + return port; +} + +// The fixed part of the motor's bits in the port's output buffer: every bit starts with the +// pin going active and ends with it back at idle; the middle word is written per frame +static void bbPortAddMotor(bbPort_t *port, const bbMotor_t *motor) +{ + const uint32_t pinMask = 1u << motor->pinIndex; + // scr: low half sets the pin, high half clears it + const uint32_t toHigh = pinMask; + const uint32_t toLow = pinMask << 16; + const uint32_t toIdle = motor->inverted ? toHigh : toLow; + const uint32_t toActive = motor->inverted ? toLow : toHigh; + + port->gpioModeMask |= 0x3u << (motor->pinIndex * 2); + port->gpioModeInput |= (uint32_t)GPIO_MODE_INPUT << (motor->pinIndex * 2); + port->gpioModeOutput |= (uint32_t)GPIO_MODE_OUTPUT << (motor->pinIndex * 2); + port->gpioIdleScr |= toIdle; + + uint32_t *buffer = port->outputBuffer; + for (int bit = 0; bit < BB_FRAME_BITS; bit++) { + buffer[bit * BB_STATES_PER_BIT + 0] |= toActive; + buffer[bit * BB_STATES_PER_BIT + 2] |= toIdle; + } + // Hold: idle again for the extra bit period, then no change + buffer[BB_FRAME_BITS * BB_STATES_PER_BIT] |= toIdle; +} + +void dshotBitbangInit(uint32_t bitRateHz) +{ + bbActive = true; + bbStatus = DSHOT_BITBANG_STATUS_OK; + + bbOutputStateHz = bitRateHz * BB_STATES_PER_BIT; + // GCR replies run at 5/4 of the DSHOT bit rate + bbInputSampleHz = bitRateHz * 5 / 4 * DSHOT_BITBANG_TELEMETRY_OVERSAMPLE; + + const uint32_t frameUs = BB_OUTPUT_BUFFER_LENGTH * 1000000UL / bbOutputStateHz; + const uint32_t windowUs = BB_INPUT_BUFFER_LENGTH * 1000000UL / bbInputSampleHz; + bbTelemetryTimeoutUs = (frameUs + windowUs) * 5 / 4; +} + +bool dshotBitbangIsActive(void) +{ + return bbActive; +} + +dshotBitbangStatus_e dshotBitbangGetStatus(void) +{ + return bbStatus; +} + +bool dshotBitbangMotorConfig(const timerHardware_t *timHw, uint8_t motorIndex, bool enableOutput) +{ + if (!bbActive || motorIndex >= MAX_MOTORS) { + return false; + } + + const IO_t io = IOGetByTag(timHw->tag); + if (io == NULL) { + return false; + } + + bbMotor_t *motor = &bbMotors[motorIndex]; + motor->io = io; + motor->timHw = timHw; + motor->tag = timHw->tag; + motor->pinIndex = IO_GPIOPinIdx(io); + motor->enabled = enableOutput; + IOInit(io, OWNER_MOTOR, RESOURCE_OUTPUT, RESOURCE_INDEX(motorIndex)); + + if (!enableOutput) { + // Outputs disabled: plain GPIO driven low, as the timer driver does + IOConfigGPIO(io, IOCFG_OUT_OD); + IOLo(io); + return true; + } + + // Bidirectional signalling idles high; hardware with an inverter on the output flips it + const bool hardwareInverted = (timHw->output & TIMER_OUTPUT_INVERTED) != 0; + motor->inverted = hardwareInverted != useDshotTelemetry; + // The pull holds the line at idle while the port listens for the reply + motor->iocfg = IO_CONFIG(GPIO_MODE_OUTPUT, GPIO_DRIVE_STRENGTH_STRONGER, GPIO_OUTPUT_PUSH_PULL, motor->inverted ? GPIO_PULL_UP : GPIO_PULL_DOWN); + + // Holding the line at its idle-high level with no edges during ESC boot triggers the + // BLHeli/Bluejay bootloader-entry check (~150 ms of continuous high right after the + // startup melody), and the first frame goes out seconds after this. Park the pin so the + // ESC sees low, like plain DSHOT idle; the first frame drives the idle level + // (bbSwitchToOutput()) microseconds before it starts. On inverting hardware the level + // is re-inverted downstream, so park high there. + IOWrite(io, hardwareInverted); + IOConfigGPIO(io, motor->iocfg); + + return true; +} + +bool dshotBitbangMotorIsConfigured(uint8_t motorIndex) +{ + return motorIndex < MAX_MOTORS && bbMotors[motorIndex].configured; +} + +bool dshotBitbangGetMotorOutput(uint8_t motorIndex, const timerHardware_t **timHw, bool *enableOutput) +{ + if (motorIndex >= MAX_MOTORS || bbMotors[motorIndex].io == NULL) { + return false; + } + + *timHw = bbMotors[motorIndex].timHw; + *enableOutput = bbMotors[motorIndex].enabled; + return true; +} + +void dshotBitbangRelease(void) +{ + // Port groups that were set up before the failure: hand their DMA channels back and + // leave the channels silent. The pin stays a parked GPIO output; the timer driver + // reconfigures it as its alternate function. + for (int i = 0; i < bbPortCount; i++) { + bbPort_t *port = &bbPorts[i]; + tmr_dma_request_enable(port->pacer->tim, port->dmaSource, FALSE); + dma_channel_enable(port->dma->ref, FALSE); + dma_reset(port->dma->ref); + tmr_channel_enable(port->pacerChannel->tim, bbTimChannel(port->pacerChannel->channelIndex), FALSE); + port->dma->irqHandlerCallback = NULL; + port->dma->owner = OWNER_FREE; + port->dma->resourceIndex = 0; + } + // The pacer timers were free, nothing else expects them running + for (int i = 0; i < bbPacerCount; i++) { + tmr_counter_enable(bbPacers[i].tim, FALSE); + } + for (int motorIndex = 0; motorIndex < MAX_MOTORS; motorIndex++) { + bbMotors[motorIndex].configured = false; + bbMotors[motorIndex].port = NULL; + } + + bbPortCount = 0; + bbPacerCount = 0; + bbFrameInFlight = false; + bbReady = false; + bbActive = false; +} + +bool dshotBitbangPostInit(void) +{ + if (!bbActive) { + return true; + } + + memset(bbOutputBuffers, 0, sizeof(bbOutputBuffers)); + memset(bbInputBuffers, 0, sizeof(bbInputBuffers)); + + for (int motorIndex = 0; motorIndex < MAX_MOTORS; motorIndex++) { + bbMotor_t *motor = &bbMotors[motorIndex]; + if (motor->io == NULL || !motor->enabled) { + continue; + } + + bbPort_t *port = bbPortGet(motor->io); + if (port == NULL) { + LOG_ERROR(PWM, "Bitbang DSHOT: no pacer or DMA for motor %d (status %d)", motorIndex, bbStatus); + return false; + } + + motor->port = port; + bbPortAddMotor(port, motor); + motor->configured = true; + } + + // The pins stay parked until the first frame + bbReady = true; + return true; +} + +void dshotBitbangWrite(uint8_t motorIndex, uint16_t packet) +{ + if (motorIndex >= MAX_MOTORS || !bbMotors[motorIndex].configured) { + return; + } + + const bbMotor_t *motor = &bbMotors[motorIndex]; + uint32_t *buffer = motor->port->outputBuffer; + // The middle state of a bit: the pin back to idle for a 0, no change for a 1 + const uint32_t toIdle = motor->inverted ? (1u << motor->pinIndex) : (1u << (motor->pinIndex + 16)); + + for (int bit = 0; bit < BB_FRAME_BITS; bit++, packet <<= 1) { + uint32_t *middle = &buffer[bit * BB_STATES_PER_BIT + 1]; + if (packet & 0x8000) { + *middle &= ~toIdle; + } else { + *middle |= toIdle; + } + } +} + +void dshotBitbangUpdateComplete(void) +{ + if (!bbReady) { + return; + } + + for (int i = 0; i < bbPortCount; i++) { + bbPort_t *port = &bbPorts[i]; + port->telemetryAborted = false; + if (!bbSwitchToOutput(port)) { + // Nothing goes out on a port whose channel would not stop + port->telemetryAborted = true; + port->telemetryPending = false; + continue; + } + // The window is pending from the frame start: the decode must not read the buffer + // before the completion interrupt of the frame has even turned the port round + port->telemetryPending = true; + dma_channel_enable(port->dma->ref, TRUE); + } + + bbFrameStartUs = micros(); + bbFrameInFlight = true; + + // Every port group on a timer starts on its next compare event + for (int i = 0; i < bbPacerCount; i++) { + tmr_dma_request_enable(bbPacers[i].tim, bbPacers[i].dmaSources, TRUE); + } +} + +bool dshotBitbangDecodeTelemetry(void) +{ + if (!bbReady || !bbFrameInFlight) { + return true; + } + + if (bbTelemetryPending()) { + if ((micros() - bbFrameStartUs) < bbTelemetryTimeoutUs) { + return false; + } + + // A window that never closed: stop sampling and skip those buffers, they may hold + // part of a reply that would still decode to a wrong but valid value. Atomic so the + // completion interrupt can't turn the port round between these steps. + for (int i = 0; i < bbPortCount; i++) { + bbPort_t *port = &bbPorts[i]; + ATOMIC_BLOCK(NVIC_PRIO_MAX) { + if (port->telemetryPending) { + tmr_dma_request_enable(port->pacer->tim, port->dmaSource, FALSE); + dma_channel_enable(port->dma->ref, FALSE); + port->telemetryAborted = true; + port->telemetryPending = false; + bbStatAborted++; + } + } + } + } + bbFrameInFlight = false; + + for (int motorIndex = 0; motorIndex < getMotorCount(); motorIndex++) { + const bbMotor_t *motor = &bbMotors[motorIndex]; + if (!motor->configured || motor->port->telemetryAborted) { + continue; + } + + const uint16_t rawValue = dshotBitbangDecode(motor->port->inputBuffer, BB_INPUT_BUFFER_LENGTH, motor->pinIndex, motor->inverted); + if (rawValue == DSHOT_TELEMETRY_NOEDGE) { + bbStatNoEdge++; + } else if (rawValue == DSHOT_TELEMETRY_INVALID) { + bbStatInvalid++; + } else { + bbStatDecoded++; + } + + const uint16_t processed = dshotProcessPacket(rawValue, motorIndex); + if (processed != DSHOT_TELEMETRY_INVALID && processed != DSHOT_TELEMETRY_NOEDGE) { +#ifdef USE_ESC_SENSOR + // Nothing to publish before the first eRPM value (an EDT frame may come first) + escSensorData_t data; + if (getDshotEscSensorData(&data, motorIndex)) { + escSensorSetDshotData(motorIndex, data.rpm, data.temperature, data.voltage, data.current); + } +#endif + } + } + + if (debugMode == DEBUG_ESC) { + debug[0] = bbStatDecoded; + debug[1] = bbStatNoEdge; + debug[2] = bbStatInvalid; + debug[3] = bbStatAborted; + debug[4] = bbPortCount; + debug[5] = bbStatus; + } + + return true; +} + +void dshotBitbangStop(void) +{ + if (!bbReady) { + return; + } + + // Let the reply windows of the frame in flight close; the backstop bounds the wait + const timeUs_t startUs = micros(); + while (bbFrameInFlight && bbTelemetryPending() && (micros() - startUs) < bbTelemetryTimeoutUs) { } + + // Atomic per port: a completion interrupt landing in between would turn the port + // round again and re-enable its pacer request + for (int i = 0; i < bbPortCount; i++) { + bbPort_t *port = &bbPorts[i]; + ATOMIC_BLOCK(NVIC_PRIO_MAX) { + tmr_dma_request_enable(port->pacer->tim, port->dmaSource, FALSE); + port->telemetryPending = false; + port->telemetryAborted = true; + bbSwitchToOutput(port); + } + } + bbFrameInFlight = false; +} + +void dshotBitbangDisconnect(void) +{ + dshotBitbangStop(); + + // Inputs: the pull of each pin keeps its line at idle, nothing drives it. The next + // frame turns the ports back to outputs as it does after every reply window. + for (int i = 0; i < bbPortCount; i++) { + bbPort_t *port = &bbPorts[i]; + ATOMIC_BLOCK(NVIC_PRIO_MAX) { + BB_MODIFY_REG(port->gpio->cfgr, port->gpioModeMask, port->gpioModeInput); + } + } +} + +ioTag_t dshotBitbangGetMotorPinTag(uint8_t motorIndex) +{ + if (motorIndex >= MAX_MOTORS || bbMotors[motorIndex].io == NULL) { + return IOTAG_NONE; + } + return bbMotors[motorIndex].tag; +} + +void dshotBitbangRestoreMotorPin(uint8_t motorIndex) +{ + if (motorIndex >= MAX_MOTORS || bbMotors[motorIndex].io == NULL) { + return; + } + + const bbMotor_t *motor = &bbMotors[motorIndex]; + if (!motor->enabled) { + IOConfigGPIO(motor->io, IOCFG_OUT_OD); + IOLo(motor->io); + return; + } + + // Back to an output at idle; frames resume with pwmEnableMotors() + IOWrite(motor->io, motor->inverted); + IOConfigGPIO(motor->io, motor->iocfg); +} + +#endif // USE_DSHOT_BITBANG diff --git a/src/main/drivers/dshot_bitbang.h b/src/main/drivers/dshot_bitbang.h new file mode 100644 index 00000000000..c1c646d31a2 --- /dev/null +++ b/src/main/drivers/dshot_bitbang.h @@ -0,0 +1,70 @@ +/* + * This file is part of INAV. + * + * INAV is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * INAV is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with INAV. If not, see . + */ + +#pragma once + +#include +#include + +#include "drivers/io_types.h" + +struct timerHardware_s; + +#ifdef USE_DSHOT_BITBANG + +typedef enum { + DSHOT_BITBANG_STATUS_OK = 0, + DSHOT_BITBANG_STATUS_NO_PACER, // no TMR1/TMR8 channel left on a timer nothing else uses + DSHOT_BITBANG_STATUS_NO_DMA, // no free DMA channel + DSHOT_BITBANG_STATUS_TOO_MANY_PORTS, // motors spread over more GPIO ports than there are groups +} dshotBitbangStatus_e; + +// Selected for this boot by the motor driver (pwmMotorPreconfigure()); bitRateHz is the +// DSHOT bit rate, 150000 / 300000 / 600000 +void dshotBitbangInit(uint32_t bitRateHz); +bool dshotBitbangIsActive(void); +dshotBitbangStatus_e dshotBitbangGetStatus(void); + +// Per motor at output init: only the pin is taken, the timer channel of the output stays free +bool dshotBitbangMotorConfig(const struct timerHardware_s *timHw, uint8_t motorIndex, bool enableOutput); +bool dshotBitbangMotorIsConfigured(uint8_t motorIndex); +// After every other user of timers and DMA has had its pick: groups the motor pins by GPIO +// port and gives each group a pacer channel and a DMA channel. On false nothing sends; +// the motor driver then releases this driver and falls back to its timers. +bool dshotBitbangPostInit(void); +// The output a motor was handed over with, for that fallback; false if it never was +bool dshotBitbangGetMotorOutput(uint8_t motorIndex, const struct timerHardware_s **timHw, bool *enableOutput); +// Give back every timer and DMA channel taken and go inactive +void dshotBitbangRelease(void); + +// One motor update: the packets of every motor (checksum included, MSB first), then the frame +void dshotBitbangWrite(uint8_t motorIndex, uint16_t packet); +void dshotBitbangUpdateComplete(void); +// Decodes the replies to the last frame and publishes them; false while the reply window +// of that frame is still open, so the caller skips this update +bool dshotBitbangDecodeTelemetry(void); + +// Finish the exchange in flight and leave the lines at idle, driven (Stop) or held only by +// their pulls (Disconnect). The next frame takes the pins back either way. +void dshotBitbangStop(void); +void dshotBitbangDisconnect(void); + +// ESC passthrough: the 4-way interface drives the pin itself in between +ioTag_t dshotBitbangGetMotorPinTag(uint8_t motorIndex); +void dshotBitbangRestoreMotorPin(uint8_t motorIndex); + +#endif diff --git a/src/main/drivers/dshot_bitbang_decode.c b/src/main/drivers/dshot_bitbang_decode.c new file mode 100644 index 00000000000..9036e942c2f --- /dev/null +++ b/src/main/drivers/dshot_bitbang_decode.c @@ -0,0 +1,186 @@ +/* + * This file is part of INAV. + * + * INAV is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * INAV is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with INAV. If not, see . + * + * Ported from Betaflight's dshot_bitbang_decode.c (decode_bb, GPLv3). + */ + +#include +#include + +#include "platform.h" + +#ifdef USE_DSHOT_BITBANG + +#include "common/maths.h" +#include "common/utils.h" + +#include "drivers/bidir_dshot.h" +#include "drivers/dshot_bitbang_decode.h" +#include "drivers/time.h" + +// A reply is 21 GCR bits; allow two bits of timing slack either way +#define MIN_VALID_BBSAMPLES ((21 - 2) * DSHOT_BITBANG_TELEMETRY_OVERSAMPLE) +#define MAX_VALID_BBSAMPLES ((21 + 2) * DSHOT_BITBANG_TELEMETRY_OVERSAMPLE) + +// How often the leading idle run is re-measured to update preambleSkip +#define MARGIN_CHECK_INTERVAL_US 500000 + +// Samples of idle to keep ahead of the first edge when skipping the preamble +#define DSHOT_TELEMETRY_START_MARGIN 5 + +/* + * The ESC answers about 30 us after the frame, so the capture starts with a run of idle + * samples. Their count is measured over MARGIN_CHECK_INTERVAL_US and the decoder then + * jumps most of that run on later replies instead of scanning it. Shared by every motor: + * all ESCs on a board answer with about the same delay. + */ +static uint32_t minMargin = UINT32_MAX; +static timeUs_t nextMarginCheckUs = 0; +static uint32_t preambleSkip = 0; + +// The GCR run lengths were packed MSB first into value as 1000... groups; strip the start +// bit, map the four GCR quintets to nibbles and verify the checksum +static uint32_t decodeGcrValue(uint32_t value) +{ +#define iv 0xffffffff + value &= 0xfffff; + static const uint32_t decode[32] = { + iv, iv, iv, iv, iv, iv, iv, iv, iv, 9, 10, 11, iv, 13, 14, 15, + iv, iv, 2, 3, iv, 5, 6, 7, iv, 0, 8, 1, iv, 4, 12, iv }; +#undef iv + + uint32_t decodedValue = decode[value & 0x1f]; + decodedValue |= decode[(value >> 5) & 0x1f] << 4; + decodedValue |= decode[(value >> 10) & 0x1f] << 8; + decodedValue |= decode[(value >> 15) & 0x1f] << 12; + + uint32_t csum = decodedValue; + csum = csum ^ (csum >> 8); // xor bytes + csum = csum ^ (csum >> 4); // xor nibbles + + if ((csum & 0xf) != 0xf || decodedValue > 0xffff) { + return DSHOT_TELEMETRY_INVALID; + } + + return decodedValue >> 4; +} + +uint32_t dshotBitbangDecode(const uint16_t *buffer, uint32_t count, uint32_t bit, bool idleHigh) +{ + const timeUs_t now = micros(); + const uint16_t mask = 1 << bit; + // The loops below are written for idle-high lines: a reply starts with the first low + // sample. Flipping the pin's sample makes an idle-low line look the same to them. + const uint16_t flip = idleHigh ? 0 : mask; + + uint16_t lastValue = 0; + uint32_t value = 0; + + const uint16_t *p = buffer; + const uint16_t *endP = p + count - MIN_VALID_BBSAMPLES; + + // Jump forward in the buffer to just before where the first low sample is expected + p += preambleSkip; + + // Eliminate the leading idle level by looking for the first low sample. + // Manual loop unrolling and branch hinting to produce faster code. + while (p < endP) { + if (__builtin_expect(!((*p++ ^ flip) & mask), 0) || + __builtin_expect(!((*p++ ^ flip) & mask), 0) || + __builtin_expect(!((*p++ ^ flip) & mask), 0) || + __builtin_expect(!((*p++ ^ flip) & mask), 0)) { + break; + } + } + + const uint32_t startMargin = p - buffer; + + if (p >= endP) { + // No reply is fine: a busy ESC may skip one. Caller sees DSHOT_TELEMETRY_NOEDGE. + // Widen the start margin in case the preamble skip went past a late reply. + if (preambleSkip > 0) { + preambleSkip--; + } + return DSHOT_TELEMETRY_NOEDGE; + } + + const int remaining = MIN((int)(count - startMargin), MAX_VALID_BBSAMPLES); + const uint16_t *oldP = p; + uint32_t bits = 0; + endP = p + remaining; + + while (endP > p) { + // Look for the next edge. Manual loop unrolling and branch hinting to produce faster code. + if (__builtin_expect(((*p++ ^ flip) & mask) != lastValue, 0) || + __builtin_expect(((*p++ ^ flip) & mask) != lastValue, 0) || + __builtin_expect(((*p++ ^ flip) & mask) != lastValue, 0) || + __builtin_expect(((*p++ ^ flip) & mask) != lastValue, 0)) { + if (endP > p) { + // A level of length n gets decoded to a sequence of bits of + // the form 1000 with a length of (n+1) / 3 to account for 3x + // oversampling. + const int len = MAX((int)(p - oldP + 1) / DSHOT_BITBANG_TELEMETRY_OVERSAMPLE, 1); + bits += len; + value <<= len; + value |= 1 << (len - 1); + oldP = p; + lastValue = (*(p - 1) ^ flip) & mask; + } + } + } + + // The last run has no closing edge, the line just stays at its final level: its length + // is whatever is left of the 21 bits + if (bits < 18) { + return DSHOT_TELEMETRY_NOEDGE; + } + + const int nlen = 21 - bits; + if (nlen < 0) { + return DSHOT_TELEMETRY_NOEDGE; + } + + // Data appears valid: track how early the reply came + if (startMargin < minMargin) { + minMargin = startMargin; + } + + if (cmpTimeUs(now, nextMarginCheckUs) >= 0) { + nextMarginCheckUs += MARGIN_CHECK_INTERVAL_US; + + // Handle a skipped check + if (nextMarginCheckUs < now) { + nextMarginCheckUs = now + DSHOT_TELEMETRY_START_MARGIN; + } + + if (minMargin > DSHOT_TELEMETRY_START_MARGIN) { + preambleSkip = minMargin - DSHOT_TELEMETRY_START_MARGIN; + } else { + preambleSkip = 0; + } + + minMargin = UINT32_MAX; + } + + if (nlen > 0) { + value <<= nlen; + value |= 1 << (nlen - 1); + } + + return decodeGcrValue(value); +} + +#endif // USE_DSHOT_BITBANG diff --git a/src/main/drivers/dshot_bitbang_decode.h b/src/main/drivers/dshot_bitbang_decode.h new file mode 100644 index 00000000000..9ebbe5b89b0 --- /dev/null +++ b/src/main/drivers/dshot_bitbang_decode.h @@ -0,0 +1,39 @@ +/* + * This file is part of INAV. + * + * INAV is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * INAV is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with INAV. If not, see . + */ + +#pragma once + +#include +#include + +// Number of samples taken of every GCR bit of the ESC reply; the decoder's bit timing +// assumes this rate +#define DSHOT_BITBANG_TELEMETRY_OVERSAMPLE 3 + +/* + * Decode one ESC reply out of a sampled GPIO port. + * + * buffer holds count consecutive reads of the port's input data register, one per + * DSHOT_BITBANG_TELEMETRY_OVERSAMPLE-th of a GCR bit, and bit is the pin to look at. + * idleHigh says which level the line rests at between frames (true for the inverted + * signalling bidirectional DSHOT normally uses). + * + * Returns the 16-bit telemetry value with its checksum removed, DSHOT_TELEMETRY_INVALID + * for a reply that did not decode or failed its checksum, or DSHOT_TELEMETRY_NOEDGE when + * the line never left idle (the ESC did not reply). + */ +uint32_t dshotBitbangDecode(const uint16_t *buffer, uint32_t count, uint32_t bit, bool idleHigh); diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 303f090881d..90f5028dca0 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -36,6 +36,7 @@ #include "drivers/io_impl.h" #include "drivers/nvic.h" #include "drivers/bidir_dshot.h" +#include "drivers/dshot_bitbang.h" #include "drivers/time.h" #include "drivers/timer.h" #include "drivers/pwm_mapping.h" @@ -73,7 +74,7 @@ #define DSHOT_DMA_BUFFER_SIZE 18 /* resolution + frame reset (2us) */ #define MAX_DMA_TIMERS 8 -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BIDIR_TIMER /* Telemetry reply window, measured from the frame start: the 18-slot frame, then the ESC's * ~30 us turnaround and its 21-bit GCR reply at 5/4 of the DSHOT bit rate (17 slots). * DSHOT_TELEMETRY_DEADTIME_US covers the turnaround plus margin for ESC timing variation. */ @@ -136,7 +137,7 @@ typedef struct { #ifdef USE_DSHOT_DMAR timerDMASafeType_t *dmaBurstBuffer; #endif -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BIDIR_TIMER bool telemetryInputActive; #endif #endif @@ -170,7 +171,7 @@ static timeUs_t digitalMotorUpdateIntervalUs = 0; static timeUs_t digitalMotorLastUpdateUs; static timeUs_t lastCommandSent = 0; static timeUs_t commandPostDelay = 0; -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BIDIR_TIMER static bool dshotTelemetryPending = false; /* One stamp for the whole frame, taken in the main loop just before the frames start, so * the completion ISR has no clock to read. Turning a port back to output resets the @@ -200,7 +201,7 @@ burstDmaTimer_t burstDmaTimers[MAX_DMA_TIMERS]; uint8_t burstDmaTimersCount = 0; #endif -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BIDIR_TIMER // GCR decode algorithm ported from Betaflight (GPLv3) static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count); static bool pwmDshotDecodeTelemetry(void); @@ -307,6 +308,12 @@ void pwmShutdownPulsesForAllMotors(uint8_t motorCount) void pwmDisableMotors(void) { pwmMotorsEnabled = false; +#ifdef USE_DSHOT_BITBANG + // The 4-way interface takes the pins next: finish the frame and reply in flight first + if (dshotBitbangIsActive()) { + dshotBitbangStop(); + } +#endif } void pwmEnableMotors(void) @@ -343,7 +350,18 @@ void pwmSetMotorDMACircular(bool circular) // A frame started by pwmCompleteMotorUpdate() may still be in flight for this long const uint32_t frameUs = DSHOT_DMA_BUFFER_SIZE * DSHOT_MOTOR_BITLENGTH * 1000000UL / dshotHz; -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + // Bitbang ports idle as plain GPIO: before the write finish the exchange in flight + // and leave the lines to their pulls; the next frame takes the pins back + if (circular) { + dshotBitbangDisconnect(); + } + return; + } +#endif + +#ifdef USE_DSHOT_BIDIR_TIMER // No keep-alive frames for bidir: the ESC sees a frame gap for the flash write, as in // Betaflight, with the line held at its idle level only by the pull. if (useDshotTelemetry) { @@ -493,20 +511,14 @@ static uint8_t getBurstDmaTimerIndex(TIM_TypeDef *timer) } #endif -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BIDIR_TIMER // The CC1..CC4 DMA request bits sit next to each other in DIER on every supported MCU static uint32_t dshotDmaSource(const pwmOutputPort_t *port) { -#if !defined(AT32F43x) STATIC_ASSERT(TIM_DMA_CC2 == TIM_DMA_CC1 << 1 && TIM_DMA_CC4 == TIM_DMA_CC1 << 3, tim_dma_cc_bits_adjacent); return TIM_DMA_CC1 << port->tch->timHw->channelIndex; -#else - STATIC_ASSERT(TMR_C2_DMA_REQUEST == TMR_C1_DMA_REQUEST << 1 && TMR_C4_DMA_REQUEST == TMR_C1_DMA_REQUEST << 3, tmr_dma_request_bits_adjacent); - return TMR_C1_DMA_REQUEST << port->tch->timHw->channelIndex; -#endif } -#if !defined(AT32F43x) // Per-channel DMA request bit in DIER; the LL and SPL drivers only offer fixed-channel variants static inline void dshotDmaReqEnable(TIM_TypeDef *tim, uint32_t dmaSource) { @@ -551,14 +563,6 @@ static dshotChannelRegs_t dshotChannelRegs(const pwmOutputPort_t *port) #define DSHOT_CCMR_OUTPUT (TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1) // CCER channel nibble for capture: both edges, channel on #define DSHOT_CCER_INPUT (TIM_CCER_CC1E | TIM_CCER_CC1P | TIM_CCER_CC1NP) -#else -// The channel identifiers are evenly spaced, so channelIndex maps onto them linearly -static uint32_t dshotTimChannel(const pwmOutputPort_t *port) -{ - STATIC_ASSERT(TMR_SELECT_CHANNEL_4 == TMR_SELECT_CHANNEL_1 + 3 * (TMR_SELECT_CHANNEL_2 - TMR_SELECT_CHANNEL_1), tmr_channel_ids_linear); - return TMR_SELECT_CHANNEL_1 + port->tch->timHw->channelIndex * (TMR_SELECT_CHANNEL_2 - TMR_SELECT_CHANNEL_1); -} -#endif static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count) { @@ -625,7 +629,6 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) // channel's normal polarity whenever telemetry is active, matching Betaflight. const bool inverted = ((port->tch->timHw->output & TIMER_OUTPUT_INVERTED) != 0) ^ useDshotTelemetry; -#if !defined(AT32F43x) // Telemetry input capture widens ARR to 0xffff (see pwmDshotSetDirectionInput); // restore the DSHOT bit period now, bypassing the ARR preload shadow so it // takes effect immediately instead of after the next update event. @@ -660,43 +663,10 @@ static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) DMA_CLEAR_FLAG(port->tch->dma, DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_TEIF | DMA_IT_DMEIF | DMA_IT_FEIF); stream->CR = (stream->CR & ~(DMA_SxCR_DIR | DMA_SxCR_EN)) | DMA_SxCR_DIR_0; port->telemetryInputActive = false; -#else - // Telemetry input capture widens the period to 0xffff (see pwmDshotSetDirectionInput); - // restore the DSHOT bit period now, bypassing the period buffer so it takes effect - // immediately, and reset the counter so a stale count above the new period doesn't - // have to run all the way round (TMR2/TMR5 are 32-bit) before the first compare. - tmr_period_buffer_enable(port->tch->timHw->tim, FALSE); - tmr_period_value_set(port->tch->timHw->tim, DSHOT_MOTOR_BITLENGTH - 1); - tmr_period_buffer_enable(port->tch->timHw->tim, TRUE); - tmr_counter_value_set(port->tch->timHw->tim, 0); - - tmr_output_config_type output = {0}; - tmr_output_default_para_init(&output); - output.oc_mode = TMR_OUTPUT_CONTROL_PWM_MODE_A; - if (port->tch->timHw->output & TIMER_OUTPUT_N_CHANNEL) { - output.oc_output_state = FALSE; - output.occ_output_state = TRUE; - output.occ_polarity = inverted ? TMR_OUTPUT_ACTIVE_LOW : TMR_OUTPUT_ACTIVE_HIGH; - output.occ_idle_state = FALSE; - } else { - output.oc_output_state = TRUE; - output.occ_output_state = FALSE; - output.oc_polarity = inverted ? TMR_OUTPUT_ACTIVE_LOW : TMR_OUTPUT_ACTIVE_HIGH; - output.oc_idle_state = TRUE; - } - tmr_output_channel_config(port->tch->timHw->tim, dshotTimChannel(port), &output); - tmr_channel_value_set(port->tch->timHw->tim, dshotTimChannel(port), 0); - tmr_output_channel_buffer_enable(port->tch->timHw->tim, dshotTimChannel(port), TRUE); - dma_channel_enable(port->tch->dma->ref, FALSE); - port->tch->dma->ref->maddr = (uint32_t)port->dmaBuffer; - port->tch->dma->ref->dtcnt = DSHOT_DMA_BUFFER_SIZE; - port->telemetryInputActive = false; -#endif } FAST_CODE static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) { -#if !defined(AT32F43x) // Runs in the DMA completion ISR for every motor in turn, so it only writes registers: // no HAL/LL init calls, and the stream is reconfigured in place (hardware clears its EN // bit at end of transfer, the wait below only covers the flag/EN ordering). @@ -740,25 +710,6 @@ FAST_CODE static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) stream->NDTR = GCR_TELEMETRY_INPUT_LEN; stream->CR = cr | DMA_SxCR_EN; dshotDmaReqEnable(tim, dshotDmaSource(port)); -#else - // Widen the period so the free-running counter doesn't wrap every DSHOT bit period - // (20 ticks) while timing GCR edges, which span ~21 bits per telemetry frame. - tmr_period_buffer_enable(port->tch->timHw->tim, TRUE); - tmr_period_value_set(port->tch->timHw->tim, 0xffff); - - tmr_input_config_type input; - tmr_input_default_para_init(&input); - input.input_channel_select = dshotTimChannel(port); - input.input_mapped_select = TMR_CC_CHANNEL_MAPPED_DIRECT; - input.input_filter_value = 2; - input.input_polarity_select = TMR_INPUT_BOTH_EDGE; - tmr_input_channel_init(port->tch->timHw->tim, &input, TMR_CHANNEL_INPUT_DIV_1); - port->tch->dma->ref->paddr = (uint32_t)port->ccr; - port->tch->dma->ref->maddr = (uint32_t)port->dmaBuffer; - port->tch->dma->ref->dtcnt = GCR_TELEMETRY_INPUT_LEN; - dma_channel_enable(port->tch->dma->ref, TRUE); - tmr_dma_request_enable(port->tch->timHw->tim, dshotDmaSource(port), TRUE); -#endif port->telemetryInputActive = true; } @@ -800,15 +751,10 @@ FAST_CODE static void pwmDshotDmaIrqHandler(DMA_t descriptor) // userParam is the motor index (see motorConfigDshot()) pwmOutputPort_t *port = motors[descriptor->userParam].pwmPort; -#if defined(AT32F43x) - dma_channel_enable(port->tch->dma->ref, FALSE); - tmr_dma_request_enable(port->tch->timHw->tim, dshotDmaSource(port), FALSE); -#else // The stream disabled itself at end of transfer (normal mode). The DMA request must go // too: CCR is 0 after the frame, so compare matches keep a request pending and the stream // would serve it as a bogus first capture the moment it is re-enabled for input. dshotDmaReqDisable(port->tch->timHw->tim, dshotDmaSource(port)); -#endif // Same bookkeeping as the timer driver's handler (timerPWMDMAInProgress()) if (port->tch->dmaState == TCH_DMA_ACTIVE) { @@ -855,15 +801,9 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) } uint32_t edges = 0; -#if defined(AT32F43x) - edges = GCR_TELEMETRY_INPUT_LEN - dma_data_number_get(port->tch->dma->ref); - tmr_dma_request_enable(port->tch->timHw->tim, dshotDmaSource(port), FALSE); - dma_channel_enable(port->tch->dma->ref, FALSE); -#else edges = GCR_TELEMETRY_INPUT_LEN - port->tch->dma->ref->NDTR; dshotDmaReqDisable(port->tch->timHw->tim, dshotDmaSource(port)); CLEAR_BIT(port->tch->dma->ref->CR, DMA_SxCR_EN); -#endif // Too few edges is no reply at all uint16_t rawValue = DSHOT_TELEMETRY_NOEDGE; @@ -889,7 +829,7 @@ static bool NOINLINE pwmDshotDecodeTelemetry(void) // Re-armed during the loop: some port is in input again, hold the frame until it is back return !dshotTelemetryPending; } -#endif // USE_DSHOT_BIDIR +#endif // USE_DSHOT_BIDIR_TIMER static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, uint32_t dshotHz, bool enableOutput, uint8_t motorIndex) { @@ -901,7 +841,7 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, return NULL; } -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BIDIR_TIMER if (enableOutput && useDshotTelemetry) { // Bidir signalling idles high, but holding the line high with no edges // during ESC boot triggers the BLHeli/Bluejay bootloader-entry check @@ -938,7 +878,7 @@ static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, // Only mark as DSHOT channel if DMA was set successfully ZERO_FARRAY(port->dmaBuffer); port->configured = true; -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BIDIR_TIMER if (useDshotTelemetry) { // Inverted signalling and per-frame direction switching; the port takes the // stream's completion interrupt over from the timer driver @@ -1041,6 +981,17 @@ bool isMotorProtocolDigital(void) return isMotorProtocolDshot(); } +// A motor with an output behind it: a timer port, or a bitbanged pin +static bool isMotorOutputConfigured(int index) +{ +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + return dshotBitbangMotorIsConfigured(index); + } +#endif + return motors[index].pwmPort && motors[index].pwmPort->configured; +} + void pwmRequestMotorTelemetry(int motorIndex) { if (!isMotorProtocolDigital()) { @@ -1049,7 +1000,7 @@ void pwmRequestMotorTelemetry(int motorIndex) const int motorCount = getMotorCount(); for (int index = 0; index < motorCount; index++) { - if (motors[index].pwmPort && motors[index].pwmPort->configured && index == motorIndex) { + if (isMotorOutputConfigured(index) && index == motorIndex) { motors[index].requestTelemetry = true; } } @@ -1127,11 +1078,16 @@ void pwmCompleteMotorUpdate(void) { return; } -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BIDIR_TIMER if (useDshotTelemetry && !pwmDshotDecodeTelemetry()) { return; } #endif +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive() && !dshotBitbangDecodeTelemetry()) { + return; + } +#endif int motorCount = getMotorCount(); timeUs_t currentTimeUs = micros(); @@ -1152,7 +1108,24 @@ void pwmCompleteMotorUpdate(void) { #ifdef USE_DSHOT if (isMotorProtocolDshot()) { -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + // No frames while the motors are disabled: the 4-way interface owns the pins then + if (!pwmMotorsEnabled || !executeDShotCommands()) { + return; + } + for (int index = 0; index < motorCount; index++) { + if (dshotBitbangMotorIsConfigured(index)) { + dshotBitbangWrite(index, prepareDshotPacket(motors[index].value, motors[index].requestTelemetry)); + motors[index].requestTelemetry = false; + } + } + dshotBitbangUpdateComplete(); + return; + } +#endif + +#ifdef USE_DSHOT_BIDIR_TIMER if (dshotPinsDisconnected) { dshotConnectOutputs(); dshotPinsDisconnected = false; @@ -1187,7 +1160,7 @@ void pwmCompleteMotorUpdate(void) { } } -#ifdef USE_DSHOT_BIDIR +#ifdef USE_DSHOT_BIDIR_TIMER if (useDshotTelemetry) { // Reference for the reply window; the completion ISRs don't read the clock dshotTelemetryFrameStampUs = micros(); @@ -1247,6 +1220,13 @@ void pwmMotorPreconfigure(void) case PWM_TYPE_DSHOT600: case PWM_TYPE_DSHOT300: case PWM_TYPE_DSHOT150: +#ifdef USE_DSHOT_BITBANG + // Bidirectional DSHOT is bitbanged on this MCU (dshot_bitbang.c); plain DSHOT + // stays on the timers + if (useDshotTelemetry) { + dshotBitbangInit(getDshotHz(initMotorProtocol) / DSHOT_MOTOR_BITLENGTH); + } +#endif motorConfigDigitalUpdateInterval(getEscUpdateFrequency()); motorWritePtr = pwmWriteDigital; break; @@ -1317,6 +1297,13 @@ bool pwmMotorConfig(const timerHardware_t *timerHardware, uint8_t motorIndex, bo case PWM_TYPE_DSHOT600: case PWM_TYPE_DSHOT300: case PWM_TYPE_DSHOT150: +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + // Only the pin is taken, its timer channel stays free; the pin joins its GPIO + // port's group in dshotBitbangPostInit(), once every other timer user has chosen + return dshotBitbangMotorConfig(timerHardware, motorIndex, enableOutput); + } +#endif motors[motorIndex].pwmPort = motorConfigDshot(timerHardware, getDshotHz(initMotorProtocol), enableOutput, motorIndex); break; #endif @@ -1333,9 +1320,43 @@ bool pwmMotorConfig(const timerHardware_t *timerHardware, uint8_t motorIndex, bo return (motors[motorIndex].pwmPort != NULL); } +// After every other timer and DMA user has had its pick (fc_init). Bitbang DSHOT needs a +// whole spare timer: without one the motors go back to plain DSHOT on their own timer +// channels and bidirectional telemetry stays off for this boot, rather than blocking arming +// over a feature the airframe can fly without. +bool pwmMotorPostInit(void) +{ +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive() && !dshotBitbangPostInit()) { + LOG_ERROR(PWM, "Bitbang DSHOT unavailable (status %d), bidirectional DSHOT off", dshotBitbangGetStatus()); + dshotBitbangRelease(); + useDshotTelemetry = false; + + const uint32_t dshotHz = getDshotHz(initMotorProtocol); + for (int index = 0; index < getMotorCount(); index++) { + const timerHardware_t *timHw; + bool enableOutput; + if (!dshotBitbangGetMotorOutput(index, &timHw, &enableOutput)) { + continue; + } + motors[index].pwmPort = motorConfigDshot(timHw, dshotHz, enableOutput, index); + if (motors[index].pwmPort == NULL) { + return false; + } + } + } +#endif + return true; +} + // Helper function for ESC passthrough ioTag_t pwmGetMotorPinTag(int motorIndex) { +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + return dshotBitbangGetMotorPinTag(motorIndex); + } +#endif if (motors[motorIndex].pwmPort) { return motors[motorIndex].pwmPort->tch->timHw->tag; } @@ -1349,6 +1370,12 @@ ioTag_t pwmGetMotorPinTag(int motorIndex) // on HAL targets a bare IOConfigGPIO(IOCFG_AF_PP) programs AF0 and the timer loses the pin. void pwmRestoreMotorPin(int motorIndex) { +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + dshotBitbangRestoreMotorPin(motorIndex); + return; + } +#endif if (motors[motorIndex].pwmPort) { const timerHardware_t *timHw = motors[motorIndex].pwmPort->tch->timHw; IOConfigGPIOAF(IOGetByTag(timHw->tag), IOCFG_AF_PP, timHw->alternateFunction); diff --git a/src/main/drivers/pwm_output.h b/src/main/drivers/pwm_output.h index fec7d8cd0d0..622713432ea 100644 --- a/src/main/drivers/pwm_output.h +++ b/src/main/drivers/pwm_output.h @@ -57,6 +57,7 @@ struct timerHardware_s; void pwmMotorPreconfigure(void); bool pwmMotorConfig(const struct timerHardware_s *timerHardware, uint8_t motorIndex, bool enableOutput); +bool pwmMotorPostInit(void); void pwmServoPreconfigure(void); bool pwmServoConfig(const struct timerHardware_s *timerHardware, uint8_t servoIndex, uint16_t servoPwmRate, uint16_t servoCenterPulse, bool enableOutput); diff --git a/src/main/drivers/resource.c b/src/main/drivers/resource.c index d3d3aea8773..ad2e9a2479b 100644 --- a/src/main/drivers/resource.c +++ b/src/main/drivers/resource.c @@ -22,7 +22,7 @@ const char * const ownerNames[OWNER_TOTAL_COUNT] = { "RANGEFINDER", "SYSTEM", "SPI", "QUADSPI", "I2C", "SDCARD", "FLASH", "USB", "BEEPER", "OSD", "BARO", "MPU", "INVERTER", "LED STRIP", "LED", "RECEIVER", "TRANSMITTER", "VTX", "SPI_PREINIT", "COMPASS", "TEMPERATURE", "1-WIRE", "AIRSPEED", "OLED DISPLAY", - "PINIO", "IRLOCK", "DRONECAN", "CURRENT METER" + "PINIO", "IRLOCK", "DRONECAN", "CURRENT METER", "DSHOT BITBANG" }; const char * const resourceNames[RESOURCE_TOTAL_COUNT] = { diff --git a/src/main/drivers/resource.h b/src/main/drivers/resource.h index 56276a3c9f2..95795a19a06 100644 --- a/src/main/drivers/resource.h +++ b/src/main/drivers/resource.h @@ -56,6 +56,7 @@ typedef enum { OWNER_IRLOCK, OWNER_DRONECAN, OWNER_CURRENT_METER, + OWNER_DSHOT_BITBANG, OWNER_TOTAL_COUNT } resourceOwner_e; diff --git a/src/main/fc/fc_init.c b/src/main/fc/fc_init.c index b83297e9744..7dfcda4c3db 100644 --- a/src/main/fc/fc_init.c +++ b/src/main/fc/fc_init.c @@ -51,6 +51,7 @@ #include "drivers/bus.h" #include "drivers/dma.h" #include "drivers/bidir_dshot.h" +#include "drivers/dshot_bitbang.h" #include "drivers/exti.h" #include "drivers/io.h" #include "drivers/flash.h" @@ -769,6 +770,21 @@ void init(void) #ifdef USE_DSHOT_BIDIR initDshotTelemetry(); #endif +#ifdef USE_DSHOT_BITBANG + // After every other timer and DMA user: the bitbang pacers take what is left. Without + // a spare timer the motors fall back to plain DSHOT, and the ESC sensor, which signed + // up for the motor-line telemetry above, is set up again for its serial source, if any + const bool dshotTelemetryWasActive = isDshotTelemetryActive(); + if (!pwmMotorPostInit()) { + ENABLE_ARMING_FLAG(ARMING_DISABLED_PWM_OUTPUT_ERROR); + } + if (dshotTelemetryWasActive && !isDshotTelemetryActive()) { + DISABLE_STATE(ESC_SENSOR_ENABLED); +#ifdef USE_ESC_SENSOR + escSensorInitialize(); +#endif + } +#endif #ifdef USE_SERIAL_GIMBAL gimbalCommonInit(); diff --git a/src/main/target/common_post.h b/src/main/target/common_post.h index 80629eb05c6..997d6bfce61 100644 --- a/src/main/target/common_post.h +++ b/src/main/target/common_post.h @@ -188,17 +188,30 @@ extern uint8_t __config_end; // DSHOT variants, all on top of USE_DSHOT: // - USE_DSHOT_DMAR: one burst DMA stream per timer (target choice) // - USE_DSHOT_BIDIR: bidirectional DSHOT (eRPM telemetry on the motor line, -// dshot_bidir_enabled). Needs a DMA stream per motor channel for the direction -// switching, so it excludes USE_DSHOT_DMAR. Implemented by the timer/DMA motor -// driver (pwm_output.c); RP2350 drives its motors from a PIO program that only -// transmits, so the setting is hidden there and stays off. STM32F7 is excluded -// as well: bidirectional DSHOT is only supported on STM32H7 and AT32. +// dshot_bidir_enabled), in one of the two forms below. Needs a DMA stream per +// motor channel or port group, so it excludes USE_DSHOT_DMAR. RP2350 drives its +// motors from a PIO program that only transmits, so the setting is hidden there +// and stays off. STM32F7 is excluded as well for now, F7 targets lack the flash. +// - USE_DSHOT_BIDIR_TIMER: the motor timer channels send the frame and are turned +// round to capture the reply (pwm_output.c). STM32F4 and STM32H7. +// - USE_DSHOT_BITBANG: the motor pins are driven as plain GPIO by DMA, paced by a +// spare TMR1/TMR8 channel, and sampled the same way for the reply +// (dshot_bitbang.c). AT32F43x, where timer channel 4 cannot capture both edges +// (see AT32_BIDIR_DSHOT.md in the repository root). Used whenever +// dshot_bidir_enabled is on and a whole TMR8 or TMR1 is free, otherwise the motors +// fall back to plain DSHOT on their timers (pwmMotorPostInit()). #if defined(USE_DSHOT_DMAR) && !defined(USE_DSHOT) #error "USE_DSHOT_DMAR requires USE_DSHOT" #endif #if defined(USE_DSHOT) && !defined(USE_DSHOT_DMAR) && !defined(RP2350) && !defined(STM32F7) #define USE_DSHOT_BIDIR #endif +#if defined(USE_DSHOT_BIDIR) && defined(AT32F43x) +#define USE_DSHOT_BITBANG +#endif +#if defined(USE_DSHOT_BIDIR) && !defined(USE_DSHOT_BITBANG) +#define USE_DSHOT_BIDIR_TIMER +#endif #if defined(USE_DSHOT_BIDIR) && (!defined(USE_DSHOT) || defined(USE_DSHOT_DMAR)) #error "USE_DSHOT_BIDIR requires USE_DSHOT and excludes USE_DSHOT_DMAR" #endif From 5fae2af8d9d2323d096d04630c25d42b1710d0bc Mon Sep 17 00:00:00 2001 From: Error414 Date: Tue, 3 Nov 2026 22:09:44 +0100 Subject: [PATCH 32/37] DSHOT BIDIR - refactor dshot --- src/main/CMakeLists.txt | 14 +- src/main/drivers/{ => dshot}/bidir_dshot.c | 6 +- src/main/drivers/{ => dshot}/bidir_dshot.h | 0 src/main/drivers/dshot/dshot.c | 1096 +++++++++++++++++ src/main/drivers/dshot/dshot.h | 65 + src/main/drivers/{ => dshot}/dshot_bitbang.c | 8 +- src/main/drivers/{ => dshot}/dshot_bitbang.h | 2 +- .../{ => dshot}/dshot_bitbang_decode.c | 4 +- .../{ => dshot}/dshot_bitbang_decode.h | 0 src/main/drivers/pwm_output.c | 1083 +--------------- src/main/drivers/pwm_output.h | 6 +- src/main/fc/fc_core.c | 2 +- src/main/fc/fc_init.c | 4 +- src/main/fc/fc_msp.c | 2 +- src/main/flight/rpm_filter.c | 2 +- src/main/sensors/esc_sensor.c | 2 +- src/main/target/common_post.h | 4 +- 17 files changed, 1237 insertions(+), 1063 deletions(-) rename src/main/drivers/{ => dshot}/bidir_dshot.c (96%) rename src/main/drivers/{ => dshot}/bidir_dshot.h (100%) create mode 100644 src/main/drivers/dshot/dshot.c create mode 100644 src/main/drivers/dshot/dshot.h rename src/main/drivers/{ => dshot}/dshot_bitbang.c (99%) rename src/main/drivers/{ => dshot}/dshot_bitbang.h (97%) rename src/main/drivers/{ => dshot}/dshot_bitbang_decode.c (98%) rename src/main/drivers/{ => dshot}/dshot_bitbang_decode.h (100%) diff --git a/src/main/CMakeLists.txt b/src/main/CMakeLists.txt index 9f4536c9ebf..cbe240da989 100755 --- a/src/main/CMakeLists.txt +++ b/src/main/CMakeLists.txt @@ -252,12 +252,14 @@ main_sources(COMMON_SRC drivers/pwm_esc_detect.h drivers/pwm_mapping.c drivers/pwm_mapping.h - drivers/bidir_dshot.c - drivers/bidir_dshot.h - drivers/dshot_bitbang.c - drivers/dshot_bitbang.h - drivers/dshot_bitbang_decode.c - drivers/dshot_bitbang_decode.h + drivers/dshot/bidir_dshot.c + drivers/dshot/bidir_dshot.h + drivers/dshot/dshot.c + drivers/dshot/dshot.h + drivers/dshot/dshot_bitbang.c + drivers/dshot/dshot_bitbang.h + drivers/dshot/dshot_bitbang_decode.c + drivers/dshot/dshot_bitbang_decode.h drivers/pwm_output.c drivers/pwm_output.h drivers/pinio.c diff --git a/src/main/drivers/bidir_dshot.c b/src/main/drivers/dshot/bidir_dshot.c similarity index 96% rename from src/main/drivers/bidir_dshot.c rename to src/main/drivers/dshot/bidir_dshot.c index d99a2ed87f9..b511263ac4c 100644 --- a/src/main/drivers/bidir_dshot.c +++ b/src/main/drivers/dshot/bidir_dshot.c @@ -22,11 +22,11 @@ #include #include "platform.h" -#include "drivers/bidir_dshot.h" +#include "drivers/dshot/bidir_dshot.h" // Bidirectional DSHOT telemetry only: eRPM / EDT decoding, RPM state for the RPM filter and // the ESC sensor. Frame generation, DMA and DSHOT commands for plain DSHOT live in -// pwm_output.c under USE_DSHOT. Every user of this API is guarded by USE_DSHOT_BIDIR. +// dshot.c under USE_DSHOT. Every user of this API is guarded by USE_DSHOT_BIDIR. // // Values are published as decoded, unfiltered: frames arrive at the DSHOT frame rate, which // follows the scheduler's idle time rather than any fixed period, so smoothing belongs to the @@ -90,7 +90,7 @@ bool isDshotTelemetryActive(void) return useDshotTelemetry; } -// useDshotTelemetry itself is set by the motor driver (pwmMotorPreconfigure()), which +// useDshotTelemetry itself is set by the DSHOT driver (dshotInit()), which // knows whether the outputs were configured for DSHOT at all void initDshotTelemetry(void) { diff --git a/src/main/drivers/bidir_dshot.h b/src/main/drivers/dshot/bidir_dshot.h similarity index 100% rename from src/main/drivers/bidir_dshot.h rename to src/main/drivers/dshot/bidir_dshot.h diff --git a/src/main/drivers/dshot/dshot.c b/src/main/drivers/dshot/dshot.c new file mode 100644 index 00000000000..2f8d84c1e16 --- /dev/null +++ b/src/main/drivers/dshot/dshot.c @@ -0,0 +1,1096 @@ +/* + * This file is part of INAV. + * + * INAV is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * INAV is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with INAV. If not, see . + */ + +/* + * DSHOT: the protocol layer for every DSHOT output (throttle and telemetry request per motor, + * packet checksum, DSHOT commands, frame rate) and the output driver for the motor timer + * channels. Each channel sends its frame by DMA into its CCR, one slot per bit; with + * USE_DSHOT_DMAR one burst stream per timer feeds all of its channels. For bidirectional + * DSHOT (USE_DSHOT_BIDIR_TIMER) the channel is turned round to input capture after the frame + * to time the edges of the ESC's GCR reply and back to output before the next frame; the + * decoded values go to bidir_dshot.c. On AT32 bidirectional DSHOT is bitbanged instead + * (dshot_bitbang.c), this module then only prepares the packets. + * + * The motor driver (pwm_output.c) hands the DSHOT protocols to this module: dshotInit() once, + * dshotMotorConfig() per motor, dshotCompleteMotorUpdate() every loop, and the ESC passthrough + * and flash-write hooks. + */ + +#include +#include +#include + +#include "platform.h" + +#if defined(USE_DSHOT) && !defined(SITL_BUILD) && !defined(RP2350) + +#include "build/atomic.h" +#include "build/build_config.h" +#include "build/debug.h" + +#include "common/circular_queue.h" +#include "common/log.h" +#include "common/maths.h" +#include "common/utils.h" + +#include "drivers/dma.h" +#include "drivers/dshot/bidir_dshot.h" +#include "drivers/dshot/dshot.h" +#include "drivers/dshot/dshot_bitbang.h" +#include "drivers/io.h" +#include "drivers/io_impl.h" +#include "drivers/nvic.h" +#include "drivers/pwm_mapping.h" +#include "drivers/pwm_output.h" +#include "drivers/resource.h" +#include "drivers/time.h" +#include "drivers/timer.h" +#include "drivers/timer_impl.h" + +#include "flight/mixer.h" + +#include "sensors/esc_sensor.h" + +/* Timer clock per DSHOT rate: DSHOT_MOTOR_BITLENGTH (20) ticks make one bit, so + * 12 MHz / 20 = 600 kbit/s. */ +#define MOTOR_DSHOT600_HZ 12000000 +#define MOTOR_DSHOT300_HZ 6000000 +#define MOTOR_DSHOT150_HZ 3000000 +/* Fastest rate INAV supports; static buffers that depend on the bit period (keep-alive + * buffer) are sized from it, so update this when a faster rate is added. */ +#define MOTOR_DSHOT_FASTEST_HZ MOTOR_DSHOT600_HZ + +#define DSHOT_MOTOR_BIT_0 7 +#define DSHOT_MOTOR_BIT_1 14 +#define DSHOT_MOTOR_BITLENGTH 20 + +#define DSHOT_DMA_BUFFER_SIZE 18 /* resolution + frame reset (2us) */ +#define MAX_DMA_TIMERS 8 + +#ifdef USE_DSHOT_BIDIR_TIMER +/* Telemetry reply window, measured from the frame start: the 18-slot frame, then the ESC's + * ~30 us turnaround and its 21-bit GCR reply at 5/4 of the DSHOT bit rate (17 slots). + * DSHOT_TELEMETRY_DEADTIME_US covers the turnaround plus margin for ESC timing variation. */ +#define DSHOT_TELEMETRY_DEADTIME_US 45 +#define DSHOT_TELEMETRY_WINDOW_SLOTS (DSHOT_DMA_BUFFER_SIZE + 17) +#define GCR_TELEMETRY_INPUT_LEN MAX_GCR_EDGES +/* A bidir motor captures the GCR edges of the ESC reply into the same buffer it sends the + * frame from, so the buffer is sized for the larger of the two */ +#define DSHOT_PORT_DMA_BUFFER_SIZE GCR_TELEMETRY_INPUT_LEN +#else +#define DSHOT_PORT_DMA_BUFFER_SIZE DSHOT_DMA_BUFFER_SIZE +#endif + +/* Keep-alive frame replayed by circular DMA while the CPU is stalled by a flash write: + * 16 data bits followed by an idle (line low) gap of DSHOT_KEEPALIVE_GAP_US. + * One DMA slot is one DSHOT bit period, so the gap needs gapUs * dshotHz / bitLength slots. */ +#define DSHOT_KEEPALIVE_GAP_US 40 +#define DSHOT_KEEPALIVE_SLOTS(dshotHz) (16 + (DSHOT_KEEPALIVE_GAP_US * ((dshotHz) / 1000000) + DSHOT_MOTOR_BITLENGTH - 1) / DSHOT_MOTOR_BITLENGTH) +/* The buffer is static, so it is sized for the fastest rate: the shorter the bit period, + * the more slots a 40 us gap needs (40 slots at DSHOT600, 28 at DSHOT300, 22 at DSHOT150). + * Only DSHOT_KEEPALIVE_SLOTS(actual rate) slots are used at run time. */ +#define DSHOT_KEEPALIVE_BUFFER_SIZE DSHOT_KEEPALIVE_SLOTS(MOTOR_DSHOT_FASTEST_HZ) +/* Bound for the waits at the keep-alive transitions: two keep-alive cycles at DSHOT150 */ +#define DSHOT_KEEPALIVE_WAIT_TIMEOUT_US 400 + +#define DSHOT_COMMAND_DELAY_US 1000 +#define DSHOT_COMMAND_INTERVAL_US 10000 +#define DSHOT_COMMAND_QUEUE_LENGTH 8 +#define DSHOT_COMMAND_QUEUE_SIZE (DSHOT_COMMAND_QUEUE_LENGTH * sizeof(dshotCommands_e)) + +typedef struct { + // Set by the mixer, sent with the next frame + uint16_t value; + bool requestTelemetry; + + // Timer output of the motor: tch is NULL while it has none (bitbanged, or the channel + // was taken), configured once its DMA is set up and frames go out on it + TCH_t *tch; + volatile timCCR_t *ccr; // Shortcut for timer CCR register + bool configured; + timerDMASafeType_t dmaBuffer[DSHOT_PORT_DMA_BUFFER_SIZE]; +#ifdef USE_DSHOT_DMAR + timerDMASafeType_t *dmaBurstBuffer; +#endif +#ifdef USE_DSHOT_BIDIR_TIMER + bool telemetryInputActive; +#endif +} dshotMotor_t; + +typedef struct { + dshotCommands_e cmd; + int remainingRepeats; +} currentExecutingCommand_t; + +// The frame (and capture) buffers are DMA targets; DMA_RAM is not cleared at startup, dshotInit() does +static DMA_RAM dshotMotor_t motors[MAX_MOTORS]; + +#ifdef USE_DSHOT_DMAR +static timerDMASafeType_t dmaBurstBuffer[MAX_DMA_TIMERS][DSHOT_DMA_BUFFER_SIZE * 4]; +static burstDmaTimer_t burstDmaTimers[MAX_DMA_TIMERS]; +static uint8_t burstDmaTimersCount = 0; +#endif + +// Every motor replays the same zero-throttle keep-alive frame, so one buffer feeds all DMA streams +#ifdef USE_DSHOT_DMAR +static DMA_RAM timerDMASafeType_t dshotKeepaliveBuffer[DSHOT_KEEPALIVE_BUFFER_SIZE * 4]; +#else +static DMA_RAM timerDMASafeType_t dshotKeepaliveBuffer[DSHOT_KEEPALIVE_BUFFER_SIZE]; +#endif + +static uint32_t dshotHz = 0; // Timer clock of the configured rate, DSHOT_MOTOR_BITLENGTH ticks per bit +static timeUs_t dshotUpdateIntervalUs = 0; +static timeUs_t dshotLastUpdateUs; +static timeUs_t lastCommandSent = 0; +static timeUs_t commandPostDelay = 0; +#ifdef USE_DSHOT_BIDIR_TIMER +static bool dshotTelemetryPending = false; +/* One stamp for the whole frame, taken in the main loop just before the frames start, so + * the completion ISR has no clock to read. Turning a motor back to output resets the + * counter and period of its timer, which every other motor on that timer shares, so no + * motor may switch back while a sibling could still be capturing: the reply window is + * therefore waited out once, for all motors, before any of them is touched */ +static timeUs_t dshotTelemetryFrameStampUs = 0; +static timeUs_t dshotTelemetryDeadtimeUs = 0; +// DEBUG_ESC: cycle counter at the frame start, debug[motor] = cycles until its capture is armed +static uint32_t dshotFrameStartCycles = 0; +// Set while bidir pins are plain GPIO, disconnected from their timer: parked low until +// the first frame, or held by the pull only during a flash write. The next frame +// reconnects them (dshotConnectOutputs()). +static bool dshotPinsDisconnected = false; +#endif + +static circularBuffer_t commandsCircularBuffer; +static uint8_t commandsBuff[DSHOT_COMMAND_QUEUE_SIZE]; +static currentExecutingCommand_t currentExecutingCommand; + +static uint32_t getDshotHz(motorPwmProtocolTypes_e pwmProtocolType) +{ + switch (pwmProtocolType) { + case(PWM_TYPE_DSHOT600): + return MOTOR_DSHOT600_HZ; + case(PWM_TYPE_DSHOT300): + return MOTOR_DSHOT300_HZ; + default: + case(PWM_TYPE_DSHOT150): + return MOTOR_DSHOT150_HZ; + } +} + +static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry) +{ + // The telemetry bit asks for a serial telemetry packet on the ESC's telemetry wire; + // the eRPM reply on the motor line is triggered by the inverted checksum alone, so + // bidir leaves the bit to the serial ESC sensor's round-robin requests + uint16_t packet = (value << 1) | (requestTelemetry ? 1 : 0); + + // compute checksum + int csum = 0; + int csum_data = packet; + for (int i = 0; i < 3; i++) { + csum ^= csum_data; // xor data by nibbles + csum_data >>= 4; + } +#ifdef USE_DSHOT_BIDIR + if (useDshotTelemetry) { + csum = ~csum; + } +#endif + csum &= 0xf; + + // append checksum + packet = (packet << 4) | csum; + + return packet; +} + +#ifdef USE_DSHOT_DMAR +static void loadDmaBufferDshotStride(timerDMASafeType_t *dmaBuffer, int stride, uint16_t packet) +{ + int i; + for (i = 0; i < 16; i++) { + dmaBuffer[i * stride] = (packet & 0x8000) ? DSHOT_MOTOR_BIT_1 : DSHOT_MOTOR_BIT_0; // MSB first + packet <<= 1; + } + dmaBuffer[i++ * stride] = 0; + dmaBuffer[i++ * stride] = 0; +} + +static uint8_t getBurstDmaTimerIndex(TIM_TypeDef *timer) +{ + for (int i = 0; i < burstDmaTimersCount; i++) { + if (burstDmaTimers[i].timer == timer) { + return i; + } + } + burstDmaTimers[burstDmaTimersCount++].timer = timer; + return burstDmaTimersCount - 1; +} +#else +static void loadDmaBufferDshot(timerDMASafeType_t *dmaBuffer, uint16_t packet) +{ + for (int i = 0; i < 16; i++) { + dmaBuffer[i] = (packet & 0x8000) ? DSHOT_MOTOR_BIT_1 : DSHOT_MOTOR_BIT_0; // MSB first + packet <<= 1; + } + // Frame reset slots: rewritten every time, a bidir motor captures edges into this buffer + dmaBuffer[16] = 0; + dmaBuffer[17] = 0; +} +#endif + +#ifdef USE_DSHOT_BIDIR_TIMER +// The CC1..CC4 DMA request bits sit next to each other in DIER on every supported MCU +static uint32_t dshotDmaSource(const dshotMotor_t *motor) +{ + STATIC_ASSERT(TIM_DMA_CC2 == TIM_DMA_CC1 << 1 && TIM_DMA_CC4 == TIM_DMA_CC1 << 3, tim_dma_cc_bits_adjacent); + return TIM_DMA_CC1 << motor->tch->timHw->channelIndex; +} + +// Per-channel DMA request bit in DIER; the LL and SPL drivers only offer fixed-channel variants +static inline void dshotDmaReqEnable(TIM_TypeDef *tim, uint32_t dmaSource) +{ + SET_BIT(tim->DIER, dmaSource); +} + +static inline void dshotDmaReqDisable(TIM_TypeDef *tim, uint32_t dmaSource) +{ + CLEAR_BIT(tim->DIER, dmaSource); +} + +// Register slices of this motor's timer channel for the direction switch: the channel's +// byte in CCMR1/CCMR2 and its nibble in CCER. Derived on the fly, the shifts cost a few cycles. +typedef struct { + __typeof__(((TIM_TypeDef *)0)->CCMR1) *ccmr; // CCMRx is 16 bits wide on F4, 32 on F7/H7 + uint32_t ccmrShift; + uint32_t ccmrMask; // the channel's byte plus its OCxM[3] bit + uint32_t ccerShift; + uint32_t ccerMask; +} dshotChannelRegs_t; + +static dshotChannelRegs_t dshotChannelRegs(const dshotMotor_t *motor) +{ + const uint32_t channelIndex = motor->tch->timHw->channelIndex; + TIM_TypeDef *tim = motor->tch->timHw->tim; + dshotChannelRegs_t regs; + regs.ccmr = (channelIndex < 2) ? &tim->CCMR1 : &tim->CCMR2; + regs.ccmrShift = 8 * (channelIndex & 1); + regs.ccmrMask = 0xFF << regs.ccmrShift; +#ifdef TIM_CCMR1_OC1M_3 + // F7/H7 keep a fourth OCxM bit outside the channel byte; F4 has none + regs.ccmrMask |= TIM_CCMR1_OC1M_3 << regs.ccmrShift; +#endif + regs.ccerShift = 4 * channelIndex; + regs.ccerMask = 0xF << regs.ccerShift; + return regs; +} + +// CCMRx channel byte for capture: CCxS=01 (TI direct), ICxPSC=0, ICxF=0010 (fDTS, N=4) +#define DSHOT_CCMR_INPUT (TIM_CCMR1_CC1S_0 | TIM_CCMR1_IC1F_1) +// CCMRx channel byte for output: CCxS=00, OCxM=110 (PWM1); preload is added once CCR is zeroed +#define DSHOT_CCMR_OUTPUT (TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1) +// CCER channel nibble for capture: both edges, channel on +#define DSHOT_CCER_INPUT (TIM_CCER_CC1E | TIM_CCER_CC1P | TIM_CCER_CC1NP) + +// GCR decode algorithm ported from Betaflight (GPLv3) +static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count) +{ + uint32_t value = 0; + uint32_t oldValue = buffer[0]; + int bits = 0; + + for (uint32_t i = 1; i <= count; i++) { + int len; + if (i < count) { + const int diff = buffer[i] - oldValue; + if (bits >= 21) { + break; + } + len = (diff + 8) / 16; + if (len < 1 || len > 21) { + // Edges closer than half a GCR bit or further apart than a whole frame + return DSHOT_TELEMETRY_INVALID; + } + } else { + len = 21 - bits; + if (len < 1) { + // All bits accounted for, no trailing run left to infer + break; + } + } + + value <<= len; + value |= 1 << (len - 1); + if (i < count) { + oldValue = buffer[i]; + } + bits += len; + } + + if (bits != 21) { + return DSHOT_TELEMETRY_INVALID; + } + + static const uint32_t decode[32] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 0, 13, 14, 15, + 0, 0, 2, 3, 0, 5, 6, 7, 0, 0, 8, 1, 0, 4, 12, 0 + }; + + uint32_t decodedValue = decode[value & 0x1f]; + decodedValue |= decode[(value >> 5) & 0x1f] << 4; + decodedValue |= decode[(value >> 10) & 0x1f] << 8; + decodedValue |= decode[(value >> 15) & 0x1f] << 12; + + uint32_t csum = decodedValue; + csum ^= csum >> 8; + csum ^= csum >> 4; + + if ((csum & 0xf) != 0xf) { + return DSHOT_TELEMETRY_INVALID; + } + + return decodedValue >> 4; +} + +static void dshotSetDirectionOutput(dshotMotor_t *motor) +{ + // Bidirectional DSHOT is carried on inverted (idle-high) signalling - flip the + // channel's normal polarity whenever telemetry is active, matching Betaflight. + const bool inverted = ((motor->tch->timHw->output & TIMER_OUTPUT_INVERTED) != 0) ^ useDshotTelemetry; + + // Telemetry input capture widens ARR to 0xffff (see dshotSetDirectionInput); + // restore the DSHOT bit period now, bypassing the ARR preload shadow so it + // takes effect immediately instead of after the next update event. + TIM_TypeDef *tim = motor->tch->timHw->tim; + CLEAR_BIT(tim->CR1, TIM_CR1_ARPE); + tim->ARR = DSHOT_MOTOR_BITLENGTH - 1; + SET_BIT(tim->CR1, TIM_CR1_ARPE); + tim->CNT = 0; + + // Channel back to PWM1 output. CCxS is only writable with the channel off, and CCR is + // zeroed before OCxPE goes back on so the stale capture value can't give one bit period + // of output before the first update event. Idle state (CR2 OISx) is untouched. + const dshotChannelRegs_t regs = dshotChannelRegs(motor); + CLEAR_BIT(tim->CCER, regs.ccerMask); + MODIFY_REG(*regs.ccmr, regs.ccmrMask, DSHOT_CCMR_OUTPUT << regs.ccmrShift); + *motor->ccr = 0; + SET_BIT(*regs.ccmr, TIM_CCMR1_OC1PE << regs.ccmrShift); + uint32_t ccer; + if (motor->tch->timHw->output & TIMER_OUTPUT_N_CHANNEL) { + ccer = TIM_CCER_CC1NE | (inverted ? TIM_CCER_CC1NP : 0); + } else { + ccer = TIM_CCER_CC1E | (inverted ? TIM_CCER_CC1P : 0); + } + MODIFY_REG(tim->CCER, regs.ccerMask, ccer << regs.ccerShift); + + // Stream back to memory-to-peripheral; timerPWMPrepareDMA() sets count and addresses and + // enables it for the next frame. The capture may still be draining (the decode loop only + // cleared EN), so wait for EN to read 0 before touching CR, then clear all five event + // flags: EN=1 is ignored while any of them is set (RM0433). + DMA_Stream_TypeDef *stream = motor->tch->dma->ref; + for (uint32_t timeout = 10000; timeout && (stream->CR & DMA_SxCR_EN); timeout--) { } + DMA_CLEAR_FLAG(motor->tch->dma, DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_TEIF | DMA_IT_DMEIF | DMA_IT_FEIF); + stream->CR = (stream->CR & ~(DMA_SxCR_DIR | DMA_SxCR_EN)) | DMA_SxCR_DIR_0; + motor->telemetryInputActive = false; +} + +FAST_CODE static void dshotSetDirectionInput(dshotMotor_t *motor) +{ + // Runs in the DMA completion ISR for every motor in turn, so it only writes registers: + // no HAL/LL init calls, and the stream is reconfigured in place (hardware clears its EN + // bit at end of transfer, the wait below only covers the flag/EN ordering). + // motors[] lives in non-cacheable DMA_RAM, so read tch once. + TCH_t *tch = motor->tch; + TIM_TypeDef *tim = tch->timHw->tim; + const dshotChannelRegs_t regs = dshotChannelRegs(motor); + + // Widen ARR so the free-running counter doesn't wrap every DSHOT bit period + // (20 ticks) while timing GCR edges, which span ~21 bits per telemetry frame. + // ARPE is set, so this lands at the next update event, within one bit period. + tim->ARR = 0xffff; + +#if defined(STM32H7) + // H7 errata workaround (matches Betaflight): reconfiguring the channel from output + // compare to input capture can glitch the pin for a cycle while CCMR/CCER are mid-update. + // Drive it as a plain GPIO output at the preset ODR level meanwhile. Only MODER changes; + // pull, speed and AF stay as dshotConnectOutputs() set them. + const IO_t io = IOGetByTag(tch->timHw->tag); + GPIO_TypeDef *gpio = IO_GPIO(io); + const uint32_t moderShift = 2 * IO_GPIOPinIdx(io); + MODIFY_REG(gpio->MODER, GPIO_MODER_MODE0_Msk << moderShift, GPIO_MODER_MODE0_0 << moderShift); +#endif + + // Channel to input capture, both edges, filter N=4. CCxS is only writable with the channel off. + CLEAR_BIT(tim->CCER, regs.ccerMask); + MODIFY_REG(*regs.ccmr, regs.ccmrMask, DSHOT_CCMR_INPUT << regs.ccmrShift); + MODIFY_REG(tim->CCER, regs.ccerMask, DSHOT_CCER_INPUT << regs.ccerShift); + +#if defined(STM32H7) + MODIFY_REG(gpio->MODER, GPIO_MODER_MODE0_Msk << moderShift, GPIO_MODER_MODE0_1 << moderShift); +#endif + + // Stream to peripheral-to-memory: addresses, FIFO and request stay from the output frame. + // Clear all five event flags first, EN=1 is ignored while any of them is set (RM0433). + DMA_Stream_TypeDef *stream = tch->dma->ref; + for (uint32_t timeout = 1000; timeout && (stream->CR & DMA_SxCR_EN); timeout--) { } + DMA_CLEAR_FLAG(tch->dma, DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_TEIF | DMA_IT_DMEIF | DMA_IT_FEIF); + const uint32_t cr = (stream->CR & ~(DMA_SxCR_DIR | DMA_SxCR_EN)) | DMA_SxCR_TCIE; + stream->CR = cr; + stream->NDTR = GCR_TELEMETRY_INPUT_LEN; + stream->CR = cr | DMA_SxCR_EN; + dshotDmaReqEnable(tim, dshotDmaSource(motor)); + motor->telemetryInputActive = true; +} + +// Connect bidir DSHOT pins to their timer AF (idle-high). Called on the first +// real motor update so the line only goes high microseconds before frames start, +// keeping it low through the ESC's boot-time bootloader-entry window. +static void dshotConnectOutputs(void) +{ + for (int index = 0; index < getMotorCount(); index++) { + const dshotMotor_t *motor = &motors[index]; + if (motor->configured) { + const timerHardware_t *timHw = motor->tch->timHw; + const IO_t io = IOGetByTag(timHw->tag); + // The pull must match this channel's *un-flipped* polarity + // (dshotSetDirectionOutput flips OCPolarity for bidir, but the GCR + // listen phase still idles toward the same physical level either way). + const bool baseInverted = timHw->output & TIMER_OUTPUT_INVERTED; +#if defined(STM32H7) + // Preset ODR to the bidir idle level once - the H7 OC->IC erratum workaround + // in dshotSetDirectionInput() disconnects the pin from the timer and relies + // on this cached ODR bit (matches Betaflight) instead of redriving the level. + baseInverted ? IOLo(io) : IOHi(io); +#endif + IOConfigGPIOAF(io, baseInverted ? IOCFG_AF_PP_PD : IOCFG_AF_PP_UP, timHw->alternateFunction); + } + } +} + +// Takes over the stream's completion interrupt from the timer driver on bidir motors: once +// the frame is out the channel is turned round to capture the ESC reply, and +// dshotDecodeTelemetry() turns it back before the next frame. Runs once per motor per +// frame, back to back, so it lives in ITCM where available. +FAST_CODE static void dshotDmaIrqHandler(DMA_t descriptor) +{ + if (!DMA_GET_FLAG_STATUS(descriptor, DMA_IT_TCIF)) { + return; + } + + // userParam is the motor index (see dshotTimerMotorConfig()) + dshotMotor_t *motor = &motors[descriptor->userParam]; + + // The stream disabled itself at end of transfer (normal mode). The DMA request must go + // too: CCR is 0 after the frame, so compare matches keep a request pending and the stream + // would serve it as a bogus first capture the moment it is re-enabled for input. + dshotDmaReqDisable(motor->tch->timHw->tim, dshotDmaSource(motor)); + + // Same bookkeeping as the timer driver's handler (timerPWMDMAInProgress()) + if (motor->tch->dmaState == TCH_DMA_ACTIVE) { + motor->tch->dmaState = TCH_DMA_IDLE; + } + + if (!motor->telemetryInputActive) { + dshotSetDirectionInput(motor); + dshotTelemetryPending = true; + + // DEBUG_ESC: debug[motor] = cycles from the frame start to this capture being armed + // (H7: /480 = us, F7: /216) + if (debugMode == DEBUG_ESC && descriptor->userParam < DEBUG32_VALUE_COUNT) { + debug[descriptor->userParam] = ticks() - dshotFrameStartCycles; + } + } + + DMA_CLEAR_FLAG(descriptor, DMA_IT_TCIF); +} + +// DMA has already captured the telemetry waveform before this runs. Keep the +// decode path out of the fast motor-update caller on constrained F7 targets. +static bool NOINLINE dshotDecodeTelemetry(void) +{ + if (!dshotTelemetryPending) { + return true; + } + + // Wait out the reply window of the frame before switching any motor back (see + // dshotTelemetryFrameStampUs) + if ((micros() - dshotTelemetryFrameStampUs) < dshotTelemetryDeadtimeUs) { + return false; + } + + // Cleared before the loop: a completion IRQ landing while the loop runs re-arms it, so a + // motor the loop has already passed is picked up by the next call instead of being left + // in input for the following frame + dshotTelemetryPending = false; + + for (int motorIndex = 0; motorIndex < getMotorCount(); motorIndex++) { + dshotMotor_t *motor = &motors[motorIndex]; + if (!motor->configured || !motor->telemetryInputActive) { + continue; + } + + uint32_t edges = 0; + edges = GCR_TELEMETRY_INPUT_LEN - motor->tch->dma->ref->NDTR; + dshotDmaReqDisable(motor->tch->timHw->tim, dshotDmaSource(motor)); + CLEAR_BIT(motor->tch->dma->ref->CR, DMA_SxCR_EN); + + // Too few edges is no reply at all + uint16_t rawValue = DSHOT_TELEMETRY_NOEDGE; + if (edges > MIN_GCR_EDGES) { + // No cache maintenance: motors[] is DMA_RAM, which the H7 MPU maps non-cacheable + rawValue = dshotDecodeTelemetryPacket((const uint32_t *)motor->dmaBuffer, edges); + } + + const uint16_t processed = dshotProcessPacket(rawValue, motorIndex); + if (processed != DSHOT_TELEMETRY_INVALID && processed != DSHOT_TELEMETRY_NOEDGE) { +#ifdef USE_ESC_SENSOR + // Nothing to publish before the first eRPM value (an EDT frame may come first) + escSensorData_t data; + if (getDshotEscSensorData(&data, motorIndex)) { + escSensorSetDshotData(motorIndex, data.rpm, data.temperature, data.voltage, data.current); + } +#endif + } + + dshotSetDirectionOutput(motor); + } + + // Re-armed during the loop: some motor is in input again, hold the frame until it is back + return !dshotTelemetryPending; +} +#endif // USE_DSHOT_BIDIR_TIMER + +// Timer output of one motor: claims the output's timer channel and pin, as pwmOutConfig() +// does for the PWM protocols, and sets up the DMA that sends the frames. True once the motor +// has its channel; without DMA it stays unconfigured and sends nothing. +static bool dshotTimerMotorConfig(const timerHardware_t *timerHardware, uint8_t motorIndex, bool enableOutput) +{ + dshotMotor_t *motor = &motors[motorIndex]; + + TCH_t *tch = timerGetTCH(timerHardware); + if (tch == NULL) { + return false; + } + + const IO_t io = IOGetByTag(timerHardware->tag); + IOInit(io, OWNER_MOTOR, RESOURCE_OUTPUT, RESOURCE_INDEX(motorIndex)); + + motor->tch = tch; + motor->configured = false; + timerConfigBase(tch, DSHOT_MOTOR_BITLENGTH, dshotHz); + timerPWMConfigChannel(tch, 0); + timerPWMStart(tch); + timerEnable(tch); + motor->ccr = timerCCR(tch); + *motor->ccr = 0; + + if (enableOutput) { + IOConfigGPIOAF(io, IOCFG_AF_PP, timerHardware->alternateFunction); + } else { + // If PWM outputs are disabled - configure as GPIO and drive low + IOConfigGPIO(io, IOCFG_OUT_OD); + IOLo(io); + } + +#ifdef USE_DSHOT_BIDIR_TIMER + if (enableOutput && useDshotTelemetry) { + // Bidir signalling idles high, but holding the line high with no edges + // during ESC boot triggers the BLHeli/Bluejay bootloader-entry check + // (~150ms of continuous high right after the ESC's startup melody). The + // first INAV frame goes out seconds after this pin is configured, so the + // ESC would enter its bootloader, time out and reset - replaying the + // startup melody. Park the pin so the ESC sees low, like normal DSHOT + // idle, and defer the AF connect until the first frame goes out + // (dshotConnectOutputs()). On TIMER_OUTPUT_INVERTED hardware the pin + // level is re-inverted downstream, so park high there. + IOConfigGPIO(io, IOCFG_OUT_PP); + (timerHardware->output & TIMER_OUTPUT_INVERTED) ? IOHi(io) : IOLo(io); + dshotPinsDisconnected = true; + } +#endif + + // Configure timer DMA +#ifdef USE_DSHOT_DMAR + uint8_t burstDmaTimerIndex = getBurstDmaTimerIndex(timerHardware->tim); + if (burstDmaTimerIndex >= MAX_DMA_TIMERS) { + motor->tch = NULL; + return false; + } + + motor->dmaBurstBuffer = &dmaBurstBuffer[burstDmaTimerIndex][0]; + burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[burstDmaTimerIndex]; + burstDmaTimer->dmaBurstBuffer = motor->dmaBurstBuffer; + + if (timerPWMConfigDMABurst(burstDmaTimer, motor->tch, motor->dmaBurstBuffer, sizeof(motor->dmaBurstBuffer[0]), DSHOT_DMA_BUFFER_SIZE)) { + motor->configured = true; + } +#else + if (timerPWMConfigChannelDMA(motor->tch, motor->dmaBuffer, sizeof(motor->dmaBuffer[0]), DSHOT_DMA_BUFFER_SIZE)) { + // Only mark as DSHOT channel if DMA was set successfully + ZERO_FARRAY(motor->dmaBuffer); + motor->configured = true; +#ifdef USE_DSHOT_BIDIR_TIMER + if (useDshotTelemetry) { + // Inverted signalling and per-frame direction switching; the motor takes the + // stream's completion interrupt over from the timer driver + dshotTelemetryDeadtimeUs = DSHOT_TELEMETRY_DEADTIME_US + 1000000 * (DSHOT_TELEMETRY_WINDOW_SLOTS * DSHOT_MOTOR_BITLENGTH) / dshotHz; +#if defined(USE_HAL_DRIVER) + // FIFO threshold 1/4 for both directions (the F7/H7 timer driver set FULL), so + // captured edges reach memory one word at a time and the decode never finds a + // partial reply still sitting in the FIFO. Set once here; the direction switch + // leaves FCR alone. The F4 driver runs the stream in direct mode, which already + // writes every word straight away. + motor->tch->dma->ref->FCR = DMA_SxFCR_DMDIS; +#endif + dshotSetDirectionOutput(motor); + // The handler gets the motor index: it reaches the motor through motors[] and uses + // the index straight as the debug slot + dmaSetHandler(motor->tch->dma, dshotDmaIrqHandler, NVIC_PRIO_TIMER_DMA, motorIndex); + } +#endif + } +#endif + + return true; +} + +void dshotInit(motorPwmProtocolTypes_e protocol, uint32_t updateRateHz) +{ + ZERO_FARRAY(motors); + + dshotHz = getDshotHz(protocol); + dshotUpdateIntervalUs = 1000000 / updateRateHz; + dshotLastUpdateUs = 0; + +#ifdef USE_DSHOT_BIDIR + useDshotTelemetry = motorConfig()->useDshotTelemetry; +#endif +#ifdef USE_DSHOT_BITBANG + // Bidirectional DSHOT is bitbanged on this MCU (dshot_bitbang.c); plain DSHOT + // stays on the timers + if (useDshotTelemetry) { + dshotBitbangInit(dshotHz / DSHOT_MOTOR_BITLENGTH); + } +#endif +} + +void dshotWriteMotor(uint8_t index, uint16_t value) +{ + // Just keep track of motor value, actual update happens in dshotCompleteMotorUpdate() + // DSHOT and some other digital protocols use 11-bit throttle range [0;2047] + motors[index].value = constrain(value, 0, 2047); +} + +// A motor with an output behind it: a timer channel, or a bitbanged pin +static bool isMotorOutputConfigured(int index) +{ +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + return dshotBitbangMotorIsConfigured(index); + } +#endif + return motors[index].configured; +} + +void dshotRequestTelemetry(uint8_t motorIndex) +{ + const int motorCount = getMotorCount(); + for (int index = 0; index < motorCount; index++) { + if (isMotorOutputConfigured(index) && index == motorIndex) { + motors[index].requestTelemetry = true; + } + } +} + +void sendDShotCommand(dshotCommands_e cmd) +{ + circularBufferPushElement(&commandsCircularBuffer, (uint8_t *) &cmd); +} + +void initDShotCommands(void) +{ + circularBufferInit(&commandsCircularBuffer, commandsBuff, DSHOT_COMMAND_QUEUE_SIZE, sizeof(dshotCommands_e)); + + currentExecutingCommand.remainingRepeats = 0; +} + +static int getDShotCommandRepeats(dshotCommands_e cmd) +{ + int repeats = 1; + + switch (cmd) { + case DSHOT_CMD_EXTENDED_TELEMETRY_ENABLE: + case DSHOT_CMD_SPIN_DIRECTION_NORMAL: + case DSHOT_CMD_SPIN_DIRECTION_REVERSED: + repeats = 10; + break; + default: + break; + } + + return repeats; +} + +// NOINLINE: dshotCompleteMotorUpdate() is inlined into the ITCM scheduler; commands are rare +static bool NOINLINE executeDShotCommands(void) +{ + timeUs_t tNow = micros(); + + if (currentExecutingCommand.remainingRepeats == 0) { + const int isTherePendingCommands = !circularBufferIsEmpty(&commandsCircularBuffer); + if (isTherePendingCommands && (tNow - lastCommandSent > DSHOT_COMMAND_INTERVAL_US)) { + //Load the command + dshotCommands_e cmd; + circularBufferPopHead(&commandsCircularBuffer, (uint8_t *) &cmd); + currentExecutingCommand.cmd = cmd; + currentExecutingCommand.remainingRepeats = getDShotCommandRepeats(cmd); + commandPostDelay = DSHOT_COMMAND_INTERVAL_US; + } else { + if (commandPostDelay) { + if (tNow - lastCommandSent < commandPostDelay) { + return false; + } + commandPostDelay = 0; + } + + return true; + } + } + for (uint8_t i = 0; i < getMotorCount(); i++) { + motors[i].requestTelemetry = true; + motors[i].value = currentExecutingCommand.cmd; + } + if (tNow - lastCommandSent >= DSHOT_COMMAND_DELAY_US) { + currentExecutingCommand.remainingRepeats--; + lastCommandSent = tNow; + return true; + } else { + return false; + } +} + +void dshotCompleteMotorUpdate(bool motorsEnabled) +{ +#ifdef USE_DSHOT_BIDIR_TIMER + if (useDshotTelemetry && !dshotDecodeTelemetry()) { + return; + } +#endif +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive() && !dshotBitbangDecodeTelemetry()) { + return; + } +#endif + + const int motorCount = getMotorCount(); + const timeUs_t currentTimeUs = micros(); + +#ifdef USE_DSHOT_BIDIR + if (useDshotTelemetry) { + escSensorFrameWindowUpdate(currentTimeUs / 1000); + } +#endif + + // Enforce motor update rate + if ((dshotUpdateIntervalUs == 0) || ((currentTimeUs - dshotLastUpdateUs) <= dshotUpdateIntervalUs)) { + return; + } + + dshotLastUpdateUs = currentTimeUs; + +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + // No frames while the motors are disabled: the 4-way interface owns the pins then + if (!motorsEnabled || !executeDShotCommands()) { + return; + } + for (int index = 0; index < motorCount; index++) { + if (dshotBitbangMotorIsConfigured(index)) { + dshotBitbangWrite(index, prepareDshotPacket(motors[index].value, motors[index].requestTelemetry)); + motors[index].requestTelemetry = false; + } + } + dshotBitbangUpdateComplete(); + return; + } +#else + UNUSED(motorsEnabled); +#endif + +#ifdef USE_DSHOT_BIDIR_TIMER + if (dshotPinsDisconnected) { + dshotConnectOutputs(); + dshotPinsDisconnected = false; + } +#endif + + if (!executeDShotCommands()) { + return; + } + +#ifdef USE_DSHOT_DMAR + for (int index = 0; index < motorCount; index++) { + if (motors[index].configured) { + uint16_t packet = prepareDshotPacket(motors[index].value, motors[index].requestTelemetry); + loadDmaBufferDshotStride(&motors[index].dmaBurstBuffer[motors[index].tch->timHw->channelIndex], 4, packet); + motors[index].requestTelemetry = false; + } + } + + for (int burstDmaTimerIndex = 0; burstDmaTimerIndex < burstDmaTimersCount; burstDmaTimerIndex++) { + burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[burstDmaTimerIndex]; + pwmBurstDMAStart(burstDmaTimer, DSHOT_DMA_BUFFER_SIZE * 4); + } +#else + // Generate DMA buffers + for (int index = 0; index < motorCount; index++) { + if (motors[index].configured) { + uint16_t packet = prepareDshotPacket(motors[index].value, motors[index].requestTelemetry); + loadDmaBufferDshot(motors[index].dmaBuffer, packet); + timerPWMPrepareDMA(motors[index].tch, DSHOT_DMA_BUFFER_SIZE); + motors[index].requestTelemetry = false; + } + } + +#ifdef USE_DSHOT_BIDIR_TIMER + if (useDshotTelemetry) { + // Reference for the reply window; the completion ISRs don't read the clock + dshotTelemetryFrameStampUs = micros(); + if (debugMode == DEBUG_ESC) { + dshotFrameStartCycles = ticks(); + } + } +#endif + + // Start DMA on all timers + for (int index = 0; index < motorCount; index++) { + if (motors[index].configured) { + timerPWMStartDMA(motors[index].tch); + } + } +#endif +} + +bool dshotMotorConfig(const timerHardware_t *timerHardware, uint8_t motorIndex, bool enableOutput) +{ +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + // Only the pin is taken, its timer channel stays free; the pin joins its GPIO + // port's group in dshotBitbangPostInit(), once every other timer user has chosen + return dshotBitbangMotorConfig(timerHardware, motorIndex, enableOutput); + } +#endif + return dshotTimerMotorConfig(timerHardware, motorIndex, enableOutput); +} + +// After every other timer and DMA user has had its pick (fc_init). Bitbang DSHOT needs a +// whole spare timer: without one the motors go back to plain DSHOT on their own timer +// channels and bidirectional telemetry stays off for this boot, rather than blocking arming +// over a feature the airframe can fly without. +bool dshotMotorPostInit(void) +{ +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive() && !dshotBitbangPostInit()) { + LOG_ERROR(PWM, "Bitbang DSHOT unavailable (status %d), bidirectional DSHOT off", dshotBitbangGetStatus()); + dshotBitbangRelease(); + useDshotTelemetry = false; + + for (int index = 0; index < getMotorCount(); index++) { + const timerHardware_t *timHw; + bool enableOutput; + if (!dshotBitbangGetMotorOutput(index, &timHw, &enableOutput)) { + continue; + } + if (!dshotTimerMotorConfig(timHw, index, enableOutput)) { + return false; + } + } + } +#endif + return true; +} + +/* + * Wait (bounded) until the keep-alive stream of this motor is sending its idle padding. + * CCR holds the slot last written by DMA: a bit length while a data bit is in flight, + * 0 in the padding. Waiting for the data -> padding transition leaves a full + * DSHOT_KEEPALIVE_GAP_US before the DMA wraps to the next frame, so the stream can be + * stopped with the last frame complete and the line low. + */ +static void dshotWaitForKeepalivePadding(const dshotMotor_t *motor) +{ + const timeUs_t start = micros(); + while (*motor->ccr == 0 && (micros() - start) < DSHOT_KEEPALIVE_WAIT_TIMEOUT_US); + while (*motor->ccr != 0 && (micros() - start) < DSHOT_KEEPALIVE_WAIT_TIMEOUT_US); +} + +void dshotSetDMACircular(bool circular) +{ + const int motorCount = getMotorCount(); + const uint32_t keepaliveSlots = DSHOT_KEEPALIVE_SLOTS(dshotHz); + // A frame started by dshotCompleteMotorUpdate() may still be in flight for this long + const uint32_t frameUs = DSHOT_DMA_BUFFER_SIZE * DSHOT_MOTOR_BITLENGTH * 1000000UL / dshotHz; + +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + // Bitbang pins idle as plain GPIO: before the write finish the exchange in flight + // and leave the lines to their pulls; the next frame takes the pins back + if (circular) { + dshotBitbangDisconnect(); + } + return; + } +#endif + +#ifdef USE_DSHOT_BIDIR_TIMER + // No keep-alive frames for bidir: the ESC sees a frame gap for the flash write, as in + // Betaflight, with the line held at its idle level only by the pull. + if (useDshotTelemetry) { + if (circular && !dshotPinsDisconnected) { + // Complete the DSHOT exchange before the write: let a frame in flight finish, + // with the deadtime as margin for its completion IRQ, then wait out and decode + // the reply, which turns every motor back to output + delayMicroseconds(frameUs + DSHOT_TELEMETRY_DEADTIME_US); + while (!dshotDecodeTelemetry()) { } + + // Disconnect the pins from the timers so nothing drives the line during the + // write; the next frame after it reconnects them + for (int i = 0; i < motorCount; i++) { + const dshotMotor_t *motor = &motors[i]; + if (motor->configured) { + const bool baseInverted = motor->tch->timHw->output & TIMER_OUTPUT_INVERTED; + IOConfigGPIO(IOGetByTag(motor->tch->timHw->tag), baseInverted ? IOCFG_IPD : IOCFG_IPU); + } + } + dshotPinsDisconnected = true; + } + return; + } +#endif + + if (circular) { + // A frame started by dshotCompleteMotorUpdate() may still be in flight: let it finish + // and keep the line low for one full gap before the keep-alive stream starts + delayMicroseconds(frameUs + DSHOT_KEEPALIVE_GAP_US); + + // Load a zero-throttle packet into the shared keep-alive buffer. The padding slots + // must be zero (line low between frames); DMA_RAM is NOLOAD and not cleared at + // startup, so clear it explicitly. + uint16_t packet = prepareDshotPacket(0, false); + ZERO_FARRAY(dshotKeepaliveBuffer); +#ifdef USE_DSHOT_DMAR + for (int i = 0; i < motorCount; i++) { + if (motors[i].configured) { + loadDmaBufferDshotStride(&dshotKeepaliveBuffer[motors[i].tch->timHw->channelIndex], 4, packet); + } + } +#else + loadDmaBufferDshot(dshotKeepaliveBuffer, packet); +#endif + } + +#ifdef USE_DSHOT_DMAR + // Burst DMA: one DMA stream per timer, shared across channels + for (int i = 0; i < burstDmaTimersCount; i++) { + burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[i]; + // Find the first motor using this timer to get the TCH for DMA state + for (int m = 0; m < motorCount; m++) { + if (motors[m].configured && motors[m].tch->timHw->tim == burstDmaTimer->timer) { + if (circular) { + impl_pwmBurstDMASetCircular(burstDmaTimer, motors[m].tch, true, dshotKeepaliveBuffer, keepaliveSlots * 4); + } else { + // Atomic so no ISR can delay the stop past the padding into the next frame + ATOMIC_BLOCK(NVIC_PRIO_MAX) { + dshotWaitForKeepalivePadding(&motors[m]); + impl_pwmBurstDMASetCircular(burstDmaTimer, motors[m].tch, false, burstDmaTimer->dmaBurstBuffer, DSHOT_DMA_BUFFER_SIZE * 4); + } + } + break; + } + } + } +#else + // Per-channel DMA: one DMA stream per motor + for (int i = 0; i < motorCount; i++) { + if (motors[i].configured) { + if (circular) { + impl_timerPWMSetDMACircular(motors[i].tch, true, dshotKeepaliveBuffer, keepaliveSlots); + } else { + // Atomic so no ISR can delay the stop past the padding into the next frame + ATOMIC_BLOCK(NVIC_PRIO_MAX) { + dshotWaitForKeepalivePadding(&motors[i]); + impl_timerPWMSetDMACircular(motors[i].tch, false, motors[i].dmaBuffer, DSHOT_DMA_BUFFER_SIZE); + } + } + } + } +#endif + + if (!circular) { + // The streams were stopped while sending padding, so CCR is already 0 and the lines + // stay low until dshotCompleteMotorUpdate() sends the next frame. Enforce it in case a + // wait above timed out; the timer would otherwise keep repeating the last bit. + for (int i = 0; i < motorCount; i++) { + if (motors[i].configured) { + *motors[i].ccr = 0; + } + } + } +} + +void dshotStop(void) +{ +#ifdef USE_DSHOT_BITBANG + // The 4-way interface takes the pins next: finish the frame and reply in flight first + if (dshotBitbangIsActive()) { + dshotBitbangStop(); + } +#endif +} + +// Helper function for ESC passthrough +ioTag_t dshotGetMotorPinTag(uint8_t motorIndex) +{ +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + return dshotBitbangGetMotorPinTag(motorIndex); + } +#endif + if (motors[motorIndex].tch) { + return motors[motorIndex].tch->timHw->tag; + } + return IOTAG_NONE; +} + +// Helper function for ESC passthrough: hand the pin back to its timer after the 4-way +// interface drove it as plain GPIO. The alternate function has to be given explicitly: +// on HAL targets a bare IOConfigGPIO(IOCFG_AF_PP) programs AF0 and the timer loses the pin. +void dshotRestoreMotorPin(uint8_t motorIndex) +{ +#ifdef USE_DSHOT_BITBANG + if (dshotBitbangIsActive()) { + dshotBitbangRestoreMotorPin(motorIndex); + return; + } +#endif + if (motors[motorIndex].tch) { + const timerHardware_t *timHw = motors[motorIndex].tch->timHw; + IOConfigGPIOAF(IOGetByTag(timHw->tag), IOCFG_AF_PP, timHw->alternateFunction); + } +} + +#endif // USE_DSHOT && !SITL_BUILD && !RP2350 diff --git a/src/main/drivers/dshot/dshot.h b/src/main/drivers/dshot/dshot.h new file mode 100644 index 00000000000..06a8dbd2c47 --- /dev/null +++ b/src/main/drivers/dshot/dshot.h @@ -0,0 +1,65 @@ +/* + * This file is part of INAV. + * + * INAV is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * INAV is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with INAV. If not, see . + */ + +#pragma once + +#include +#include + +#include "drivers/io_types.h" +#include "drivers/pwm_mapping.h" // motorPwmProtocolTypes_e + +struct timerHardware_s; + +// DSHOT output, used by the motor driver (pwm_output.c) for the DSHOT protocols. The DSHOT +// commands (sendDShotCommand(), initDShotCommands()) are declared in pwm_output.h with the +// rest of the motor API and implemented here as well. +#ifdef USE_DSHOT + +// Once, from pwmMotorPreconfigure(): fixes the bit rate and the frame rate, and on AT32 +// hands bidirectional DSHOT to the bitbang driver (dshot_bitbang.c) +void dshotInit(motorPwmProtocolTypes_e protocol, uint32_t updateRateHz); + +// Per motor at output init: the timer channel of the output takes the pin, or the bitbang +// driver does. True when the motor got its output; frames only go out on a timer channel +// once its DMA is set up as well. +bool dshotMotorConfig(const struct timerHardware_s *timHw, uint8_t motorIndex, bool enableOutput); +// After every other timer and DMA user has had its pick (fc_init): the bitbang driver takes +// what is left, or the motors go back to plain DSHOT on their timers. False if that fails too. +bool dshotMotorPostInit(void); + +// Throttle for the next frame, 11-bit range [0;2047]; sent by dshotCompleteMotorUpdate() +void dshotWriteMotor(uint8_t motorIndex, uint16_t value); +// Set the telemetry bit of the motor's next frame (serial ESC telemetry request) +void dshotRequestTelemetry(uint8_t motorIndex); +// One motor update, rate limited to the frame rate: the replies to the last frame are +// decoded first, then a pending DSHOT command or the throttle frame goes out. With +// motorsEnabled false the 4-way interface owns the pins and the bitbang driver sends nothing. +void dshotCompleteMotorUpdate(bool motorsEnabled); + +// Motors disabled (pwmDisableMotors()): finish the bitbang exchange in flight +void dshotStop(void); +// Around a flash write, which stalls the CPU: plain DSHOT replays a zero-throttle frame by +// circular DMA, bidirectional DSHOT finishes the exchange in flight and leaves the pins to +// their pulls until the next frame +void dshotSetDMACircular(bool circular); + +// ESC passthrough: the 4-way interface drives the pin itself in between +ioTag_t dshotGetMotorPinTag(uint8_t motorIndex); +void dshotRestoreMotorPin(uint8_t motorIndex); + +#endif diff --git a/src/main/drivers/dshot_bitbang.c b/src/main/drivers/dshot/dshot_bitbang.c similarity index 99% rename from src/main/drivers/dshot_bitbang.c rename to src/main/drivers/dshot/dshot_bitbang.c index 5d2bd2babac..8d500e6bbdf 100644 --- a/src/main/drivers/dshot_bitbang.c +++ b/src/main/drivers/dshot/dshot_bitbang.c @@ -33,7 +33,7 @@ * * This is the only bidirectional DSHOT on AT32F43x: timer channel 4 cannot capture both * edges there (see AT32_BIDIR_DSHOT.md in the repository root). Plain DSHOT keeps using the - * timer driver in pwm_output.c, which also owns the frame contents, the DSHOT commands and + * timer driver in dshot.c, which also owns the frame contents, the DSHOT commands and * the update rate; this module only drives the pins and reads the replies. * * DEBUG_ESC: debug[0] replies decoded, debug[1] windows without a reply, debug[2] replies @@ -57,10 +57,10 @@ #include "common/maths.h" #include "common/utils.h" -#include "drivers/bidir_dshot.h" +#include "drivers/dshot/bidir_dshot.h" #include "drivers/dma.h" -#include "drivers/dshot_bitbang.h" -#include "drivers/dshot_bitbang_decode.h" +#include "drivers/dshot/dshot_bitbang.h" +#include "drivers/dshot/dshot_bitbang_decode.h" #include "drivers/io.h" #include "drivers/io_impl.h" #include "drivers/nvic.h" diff --git a/src/main/drivers/dshot_bitbang.h b/src/main/drivers/dshot/dshot_bitbang.h similarity index 97% rename from src/main/drivers/dshot_bitbang.h rename to src/main/drivers/dshot/dshot_bitbang.h index c1c646d31a2..d1db0d7108d 100644 --- a/src/main/drivers/dshot_bitbang.h +++ b/src/main/drivers/dshot/dshot_bitbang.h @@ -33,7 +33,7 @@ typedef enum { DSHOT_BITBANG_STATUS_TOO_MANY_PORTS, // motors spread over more GPIO ports than there are groups } dshotBitbangStatus_e; -// Selected for this boot by the motor driver (pwmMotorPreconfigure()); bitRateHz is the +// Selected for this boot by the DSHOT driver (dshotInit()); bitRateHz is the // DSHOT bit rate, 150000 / 300000 / 600000 void dshotBitbangInit(uint32_t bitRateHz); bool dshotBitbangIsActive(void); diff --git a/src/main/drivers/dshot_bitbang_decode.c b/src/main/drivers/dshot/dshot_bitbang_decode.c similarity index 98% rename from src/main/drivers/dshot_bitbang_decode.c rename to src/main/drivers/dshot/dshot_bitbang_decode.c index 9036e942c2f..3ccf102573c 100644 --- a/src/main/drivers/dshot_bitbang_decode.c +++ b/src/main/drivers/dshot/dshot_bitbang_decode.c @@ -27,8 +27,8 @@ #include "common/maths.h" #include "common/utils.h" -#include "drivers/bidir_dshot.h" -#include "drivers/dshot_bitbang_decode.h" +#include "drivers/dshot/bidir_dshot.h" +#include "drivers/dshot/dshot_bitbang_decode.h" #include "drivers/time.h" // A reply is 21 GCR bits; allow two bits of timing slack either way diff --git a/src/main/drivers/dshot_bitbang_decode.h b/src/main/drivers/dshot/dshot_bitbang_decode.h similarity index 100% rename from src/main/drivers/dshot_bitbang_decode.h rename to src/main/drivers/dshot/dshot_bitbang_decode.h diff --git a/src/main/drivers/pwm_output.c b/src/main/drivers/pwm_output.c index 90f5028dca0..1c1ffed7fd5 100644 --- a/src/main/drivers/pwm_output.c +++ b/src/main/drivers/pwm_output.c @@ -18,109 +18,29 @@ #include #include #include -#include #include "platform.h" #if !defined(SITL_BUILD) && !defined(RP2350) -#include "build/atomic.h" -#include "build/debug.h" -#include "build/build_config.h" - #include "common/log.h" #include "common/maths.h" -#include "common/circular_queue.h" +#include "common/utils.h" +#include "drivers/dshot/dshot.h" #include "drivers/io.h" -#include "drivers/io_impl.h" -#include "drivers/nvic.h" -#include "drivers/bidir_dshot.h" -#include "drivers/dshot_bitbang.h" -#include "drivers/time.h" -#include "drivers/timer.h" #include "drivers/pwm_mapping.h" #include "drivers/pwm_output.h" +#include "drivers/timer.h" + #include "io/motor_srxl2.h" #include "io/servo_sbus.h" -#include "sensors/esc_sensor.h" - -#include "config/feature.h" - -#include "fc/config.h" -#include "fc/runtime_config.h" - -#include "drivers/timer_impl.h" -#include "drivers/timer.h" #define MULTISHOT_5US_PW (MULTISHOT_TIMER_HZ * 5 / 1000000.0f) #define MULTISHOT_20US_MULT (MULTISHOT_TIMER_HZ * 20 / 1000000.0f / 1000.0f) -#ifdef USE_DSHOT -/* Timer clock per DSHOT rate: DSHOT_MOTOR_BITLENGTH (20) ticks make one bit, so - * 12 MHz / 20 = 600 kbit/s. */ -#define MOTOR_DSHOT600_HZ 12000000 -#define MOTOR_DSHOT300_HZ 6000000 -#define MOTOR_DSHOT150_HZ 3000000 -/* Fastest rate INAV supports; static buffers that depend on the bit period (keep-alive - * buffer) are sized from it, so update this when a faster rate is added. */ -#define MOTOR_DSHOT_FASTEST_HZ MOTOR_DSHOT600_HZ - - -#define DSHOT_MOTOR_BIT_0 7 -#define DSHOT_MOTOR_BIT_1 14 -#define DSHOT_MOTOR_BITLENGTH 20 - -#define DSHOT_DMA_BUFFER_SIZE 18 /* resolution + frame reset (2us) */ -#define MAX_DMA_TIMERS 8 - -#ifdef USE_DSHOT_BIDIR_TIMER -/* Telemetry reply window, measured from the frame start: the 18-slot frame, then the ESC's - * ~30 us turnaround and its 21-bit GCR reply at 5/4 of the DSHOT bit rate (17 slots). - * DSHOT_TELEMETRY_DEADTIME_US covers the turnaround plus margin for ESC timing variation. */ -#define DSHOT_TELEMETRY_DEADTIME_US 45 -#define DSHOT_TELEMETRY_WINDOW_SLOTS (DSHOT_DMA_BUFFER_SIZE + 17) -#define GCR_TELEMETRY_INPUT_LEN MAX_GCR_EDGES -/* A bidir port captures the GCR edges of the ESC reply into the same buffer it sends the - * frame from, so the buffer is sized for the larger of the two */ -#define DSHOT_PORT_DMA_BUFFER_SIZE GCR_TELEMETRY_INPUT_LEN -#else -#define DSHOT_PORT_DMA_BUFFER_SIZE DSHOT_DMA_BUFFER_SIZE -#endif - -/* Keep-alive frame replayed by circular DMA while the CPU is stalled by a flash write: - * 16 data bits followed by an idle (line low) gap of DSHOT_KEEPALIVE_GAP_US. - * One DMA slot is one DSHOT bit period, so the gap needs gapUs * dshotHz / bitLength slots. */ -#define DSHOT_KEEPALIVE_GAP_US 40 -#define DSHOT_KEEPALIVE_SLOTS(dshotHz) (16 + (DSHOT_KEEPALIVE_GAP_US * ((dshotHz) / 1000000) + DSHOT_MOTOR_BITLENGTH - 1) / DSHOT_MOTOR_BITLENGTH) -/* The buffer is static, so it is sized for the fastest rate: the shorter the bit period, - * the more slots a 40 us gap needs (40 slots at DSHOT600, 28 at DSHOT300, 22 at DSHOT150). - * Only DSHOT_KEEPALIVE_SLOTS(actual rate) slots are used at run time. */ -#define DSHOT_KEEPALIVE_BUFFER_SIZE DSHOT_KEEPALIVE_SLOTS(MOTOR_DSHOT_FASTEST_HZ) -/* Bound for the waits at the keep-alive transitions: two keep-alive cycles at DSHOT150 */ -#define DSHOT_KEEPALIVE_WAIT_TIMEOUT_US 400 - -#define DSHOT_COMMAND_DELAY_US 1000 -#define DSHOT_COMMAND_INTERVAL_US 10000 -#define DSHOT_COMMAND_QUEUE_LENGTH 8 -#define DHSOT_COMMAND_QUEUE_SIZE DSHOT_COMMAND_QUEUE_LENGTH * sizeof(dshotCommands_e) -#endif - typedef void (*pwmWriteFuncPtr)(uint8_t index, uint16_t value); // function pointer used to write motors -#ifdef USE_DSHOT_DMAR - timerDMASafeType_t dmaBurstBuffer[MAX_DMA_TIMERS][DSHOT_DMA_BUFFER_SIZE * 4]; -#endif - -#ifdef USE_DSHOT -// Every motor replays the same zero-throttle keep-alive frame, so one buffer feeds all DMA streams -#ifdef USE_DSHOT_DMAR -static DMA_RAM timerDMASafeType_t dshotKeepaliveBuffer[DSHOT_KEEPALIVE_BUFFER_SIZE * 4]; -#else -static DMA_RAM timerDMASafeType_t dshotKeepaliveBuffer[DSHOT_KEEPALIVE_BUFFER_SIZE]; -#endif -#endif - typedef struct { TCH_t * tch; bool configured; @@ -130,28 +50,12 @@ typedef struct { volatile timCCR_t *ccr; // Shortcut for timer CCR register float pulseOffset; float pulseScale; - -#ifdef USE_DSHOT - // DSHOT parameters - timerDMASafeType_t dmaBuffer[DSHOT_PORT_DMA_BUFFER_SIZE]; -#ifdef USE_DSHOT_DMAR - timerDMASafeType_t *dmaBurstBuffer; -#endif -#ifdef USE_DSHOT_BIDIR_TIMER - bool telemetryInputActive; -#endif -#endif } pwmOutputPort_t; -typedef struct { - pwmOutputPort_t * pwmPort; // May be NULL if motor doesn't use the PWM port - uint16_t value; // Used to keep track of last motor value - bool requestTelemetry; -} pwmOutputMotor_t; +static pwmOutputPort_t pwmOutputPorts[MAX_PWM_OUTPUTS]; -static DMA_RAM pwmOutputPort_t pwmOutputPorts[MAX_PWM_OUTPUTS]; - -static pwmOutputMotor_t motors[MAX_MOTORS]; +// NULL for a motor without a PWM port: not configured, or driven by DSHOT (dshot/dshot.c) +static pwmOutputPort_t * motors[MAX_MOTORS]; static motorPwmProtocolTypes_e initMotorProtocol; static pwmWriteFuncPtr motorWritePtr = NULL; // Function to write value to motors @@ -166,55 +70,6 @@ static uint8_t allocatedOutputPortCount = 0; static bool pwmMotorsEnabled = true; -#ifdef USE_DSHOT -static timeUs_t digitalMotorUpdateIntervalUs = 0; -static timeUs_t digitalMotorLastUpdateUs; -static timeUs_t lastCommandSent = 0; -static timeUs_t commandPostDelay = 0; -#ifdef USE_DSHOT_BIDIR_TIMER -static bool dshotTelemetryPending = false; -/* One stamp for the whole frame, taken in the main loop just before the frames start, so - * the completion ISR has no clock to read. Turning a port back to output resets the - * counter and period of its timer, which every other port on that timer shares, so no - * port may switch back while a sibling could still be capturing: the reply window is - * therefore waited out once, for all ports, before any of them is touched */ -static timeUs_t dshotTelemetryFrameStampUs = 0; -static timeUs_t dshotTelemetryDeadtimeUs = 0; -// DEBUG_ESC: cycle counter at the frame start, debug[motor] = cycles until its capture is armed -static uint32_t dshotFrameStartCycles = 0; -#endif - -static circularBuffer_t commandsCircularBuffer; -static uint8_t commandsBuff[DHSOT_COMMAND_QUEUE_SIZE]; -static currentExecutingCommand_t currentExecutingCommand; - -static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry); -uint32_t getDshotHz(motorPwmProtocolTypes_e pwmProtocolType); -#ifndef USE_DSHOT_DMAR -static void loadDmaBufferDshot(timerDMASafeType_t *dmaBuffer, uint16_t packet); -#else -static void loadDmaBufferDshotStride(timerDMASafeType_t *dmaBuffer, int stride, uint16_t packet); -#endif - -#ifdef USE_DSHOT_DMAR -burstDmaTimer_t burstDmaTimers[MAX_DMA_TIMERS]; -uint8_t burstDmaTimersCount = 0; -#endif - -#ifdef USE_DSHOT_BIDIR_TIMER -// GCR decode algorithm ported from Betaflight (GPLv3) -static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count); -static bool pwmDshotDecodeTelemetry(void); -static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port); -static void pwmDshotSetDirectionInput(pwmOutputPort_t *port); -static void pwmDshotDmaIrqHandler(DMA_t descriptor); -// Set while bidir pins are plain GPIO, disconnected from their timer: parked low until -// the first frame, or held by the pull only during a flash write. The next frame -// reconnects them (dshotConnectOutputs()). -static bool dshotPinsDisconnected = false; -#endif -#endif - static void pwmOutConfigTimer(pwmOutputPort_t * p, TCH_t * tch, uint32_t hz, uint16_t period, uint16_t value) { p->tch = tch; @@ -283,8 +138,8 @@ static void pwmWriteNull(uint8_t index, uint16_t value) static void pwmWriteStandard(uint8_t index, uint16_t value) { - if (motors[index].pwmPort) { - *(motors[index].pwmPort->ccr) = lrintf((value * motors[index].pwmPort->pulseScale) + motors[index].pwmPort->pulseOffset); + if (motors[index]) { + *(motors[index]->ccr) = lrintf((value * motors[index]->pulseScale) + motors[index]->pulseOffset); } } @@ -299,8 +154,8 @@ void pwmShutdownPulsesForAllMotors(uint8_t motorCount) { for (int index = 0; index < motorCount; index++) { // Set the compare register to 0, which stops the output pulsing if the timer overflows - if (motors[index].pwmPort) { - *(motors[index].pwmPort->ccr) = 0; + if (motors[index]) { + *(motors[index]->ccr) = 0; } } } @@ -308,10 +163,9 @@ void pwmShutdownPulsesForAllMotors(uint8_t motorCount) void pwmDisableMotors(void) { pwmMotorsEnabled = false; -#ifdef USE_DSHOT_BITBANG - // The 4-way interface takes the pins next: finish the frame and reply in flight first - if (dshotBitbangIsActive()) { - dshotBitbangStop(); +#ifdef USE_DSHOT + if (isMotorProtocolDshot()) { + dshotStop(); } #endif } @@ -321,140 +175,11 @@ void pwmEnableMotors(void) pwmMotorsEnabled = true; } -#ifdef USE_DSHOT -/* - * Wait (bounded) until the keep-alive stream of this port is sending its idle padding. - * CCR holds the slot last written by DMA: a bit length while a data bit is in flight, - * 0 in the padding. Waiting for the data -> padding transition leaves a full - * DSHOT_KEEPALIVE_GAP_US before the DMA wraps to the next frame, so the stream can be - * stopped with the last frame complete and the line low. - */ -static void dshotWaitForKeepalivePadding(const pwmOutputPort_t *port) -{ - const timeUs_t start = micros(); - while (*port->ccr == 0 && (micros() - start) < DSHOT_KEEPALIVE_WAIT_TIMEOUT_US); - while (*port->ccr != 0 && (micros() - start) < DSHOT_KEEPALIVE_WAIT_TIMEOUT_US); -} -#endif - void pwmSetMotorDMACircular(bool circular) { #ifdef USE_DSHOT - if (!isMotorProtocolDshot()) { - return; - } - - int motorCount = getMotorCount(); - const uint32_t dshotHz = getDshotHz(initMotorProtocol); - const uint32_t keepaliveSlots = DSHOT_KEEPALIVE_SLOTS(dshotHz); - // A frame started by pwmCompleteMotorUpdate() may still be in flight for this long - const uint32_t frameUs = DSHOT_DMA_BUFFER_SIZE * DSHOT_MOTOR_BITLENGTH * 1000000UL / dshotHz; - -#ifdef USE_DSHOT_BITBANG - if (dshotBitbangIsActive()) { - // Bitbang ports idle as plain GPIO: before the write finish the exchange in flight - // and leave the lines to their pulls; the next frame takes the pins back - if (circular) { - dshotBitbangDisconnect(); - } - return; - } -#endif - -#ifdef USE_DSHOT_BIDIR_TIMER - // No keep-alive frames for bidir: the ESC sees a frame gap for the flash write, as in - // Betaflight, with the line held at its idle level only by the pull. - if (useDshotTelemetry) { - if (circular && !dshotPinsDisconnected) { - // Complete the DSHOT exchange before the write: let a frame in flight finish, - // with the deadtime as margin for its completion IRQ, then wait out and decode - // the reply, which turns every port back to output - delayMicroseconds(frameUs + DSHOT_TELEMETRY_DEADTIME_US); - while (!pwmDshotDecodeTelemetry()) { } - - // Disconnect the pins from the timers so nothing drives the line during the - // write; the next frame after it reconnects them - for (int i = 0; i < motorCount; i++) { - const pwmOutputPort_t *port = motors[i].pwmPort; - if (port && port->configured) { - const bool baseInverted = port->tch->timHw->output & TIMER_OUTPUT_INVERTED; - IOConfigGPIO(IOGetByTag(port->tch->timHw->tag), baseInverted ? IOCFG_IPD : IOCFG_IPU); - } - } - dshotPinsDisconnected = true; - } - return; - } -#endif - - if (circular) { - // A frame started by pwmCompleteMotorUpdate() may still be in flight: let it finish - // and keep the line low for one full gap before the keep-alive stream starts - delayMicroseconds(frameUs + DSHOT_KEEPALIVE_GAP_US); - - // Load a zero-throttle packet into the shared keep-alive buffer. The padding slots - // must be zero (line low between frames); DMA_RAM is NOLOAD and not cleared at - // startup, so clear it explicitly. - uint16_t packet = prepareDshotPacket(0, false); - ZERO_FARRAY(dshotKeepaliveBuffer); -#ifdef USE_DSHOT_DMAR - for (int i = 0; i < motorCount; i++) { - if (motors[i].pwmPort && motors[i].pwmPort->configured) { - loadDmaBufferDshotStride(&dshotKeepaliveBuffer[motors[i].pwmPort->tch->timHw->channelIndex], 4, packet); - } - } -#else - loadDmaBufferDshot(dshotKeepaliveBuffer, packet); -#endif - } - -#ifdef USE_DSHOT_DMAR - // Burst DMA: one DMA stream per timer, shared across channels - for (int i = 0; i < burstDmaTimersCount; i++) { - burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[i]; - // Find the first motor using this timer to get the TCH for DMA state - for (int m = 0; m < motorCount; m++) { - if (motors[m].pwmPort && motors[m].pwmPort->configured && motors[m].pwmPort->tch - && motors[m].pwmPort->tch->timHw->tim == burstDmaTimer->timer) { - if (circular) { - impl_pwmBurstDMASetCircular(burstDmaTimer, motors[m].pwmPort->tch, true, dshotKeepaliveBuffer, keepaliveSlots * 4); - } else { - // Atomic so no ISR can delay the stop past the padding into the next frame - ATOMIC_BLOCK(NVIC_PRIO_MAX) { - dshotWaitForKeepalivePadding(motors[m].pwmPort); - impl_pwmBurstDMASetCircular(burstDmaTimer, motors[m].pwmPort->tch, false, burstDmaTimer->dmaBurstBuffer, DSHOT_DMA_BUFFER_SIZE * 4); - } - } - break; - } - } - } -#else - // Per-channel DMA: one DMA stream per motor - for (int i = 0; i < motorCount; i++) { - if (motors[i].pwmPort && motors[i].pwmPort->configured && motors[i].pwmPort->tch) { - if (circular) { - impl_timerPWMSetDMACircular(motors[i].pwmPort->tch, true, dshotKeepaliveBuffer, keepaliveSlots); - } else { - // Atomic so no ISR can delay the stop past the padding into the next frame - ATOMIC_BLOCK(NVIC_PRIO_MAX) { - dshotWaitForKeepalivePadding(motors[i].pwmPort); - impl_timerPWMSetDMACircular(motors[i].pwmPort->tch, false, motors[i].pwmPort->dmaBuffer, DSHOT_DMA_BUFFER_SIZE); - } - } - } - } -#endif - - if (!circular) { - // The streams were stopped while sending padding, so CCR is already 0 and the lines - // stay low until pwmCompleteMotorUpdate() sends the next frame. Enforce it in case a - // wait above timed out; the timer would otherwise keep repeating the last bit. - for (int i = 0; i < motorCount; i++) { - if (motors[i].pwmPort && motors[i].pwmPort->configured) { - *motors[i].pwmPort->ccr = 0; - } - } + if (isMotorProtocolDshot()) { + dshotSetDMACircular(circular); } #else UNUSED(circular); @@ -484,491 +209,6 @@ static pwmOutputPort_t * motorConfigPwm(const timerHardware_t *timerHardware, fl return port; } -#ifdef USE_DSHOT -uint32_t getDshotHz(motorPwmProtocolTypes_e pwmProtocolType) -{ - switch (pwmProtocolType) { - case(PWM_TYPE_DSHOT600): - return MOTOR_DSHOT600_HZ; - case(PWM_TYPE_DSHOT300): - return MOTOR_DSHOT300_HZ; - default: - case(PWM_TYPE_DSHOT150): - return MOTOR_DSHOT150_HZ; - } -} - -#ifdef USE_DSHOT_DMAR -static uint8_t getBurstDmaTimerIndex(TIM_TypeDef *timer) -{ - for (int i = 0; i < burstDmaTimersCount; i++) { - if (burstDmaTimers[i].timer == timer) { - return i; - } - } - burstDmaTimers[burstDmaTimersCount++].timer = timer; - return burstDmaTimersCount - 1; -} -#endif - -#ifdef USE_DSHOT_BIDIR_TIMER -// The CC1..CC4 DMA request bits sit next to each other in DIER on every supported MCU -static uint32_t dshotDmaSource(const pwmOutputPort_t *port) -{ - STATIC_ASSERT(TIM_DMA_CC2 == TIM_DMA_CC1 << 1 && TIM_DMA_CC4 == TIM_DMA_CC1 << 3, tim_dma_cc_bits_adjacent); - return TIM_DMA_CC1 << port->tch->timHw->channelIndex; -} - -// Per-channel DMA request bit in DIER; the LL and SPL drivers only offer fixed-channel variants -static inline void dshotDmaReqEnable(TIM_TypeDef *tim, uint32_t dmaSource) -{ - SET_BIT(tim->DIER, dmaSource); -} - -static inline void dshotDmaReqDisable(TIM_TypeDef *tim, uint32_t dmaSource) -{ - CLEAR_BIT(tim->DIER, dmaSource); -} - -// Register slices of this port's timer channel for the direction switch: the channel's -// byte in CCMR1/CCMR2 and its nibble in CCER. Derived on the fly, the shifts cost a few cycles. -typedef struct { - __typeof__(((TIM_TypeDef *)0)->CCMR1) *ccmr; // CCMRx is 16 bits wide on F4, 32 on F7/H7 - uint32_t ccmrShift; - uint32_t ccmrMask; // the channel's byte plus its OCxM[3] bit - uint32_t ccerShift; - uint32_t ccerMask; -} dshotChannelRegs_t; - -static dshotChannelRegs_t dshotChannelRegs(const pwmOutputPort_t *port) -{ - const uint32_t channelIndex = port->tch->timHw->channelIndex; - TIM_TypeDef *tim = port->tch->timHw->tim; - dshotChannelRegs_t regs; - regs.ccmr = (channelIndex < 2) ? &tim->CCMR1 : &tim->CCMR2; - regs.ccmrShift = 8 * (channelIndex & 1); - regs.ccmrMask = 0xFF << regs.ccmrShift; -#ifdef TIM_CCMR1_OC1M_3 - // F7/H7 keep a fourth OCxM bit outside the channel byte; F4 has none - regs.ccmrMask |= TIM_CCMR1_OC1M_3 << regs.ccmrShift; -#endif - regs.ccerShift = 4 * channelIndex; - regs.ccerMask = 0xF << regs.ccerShift; - return regs; -} - -// CCMRx channel byte for capture: CCxS=01 (TI direct), ICxPSC=0, ICxF=0010 (fDTS, N=4) -#define DSHOT_CCMR_INPUT (TIM_CCMR1_CC1S_0 | TIM_CCMR1_IC1F_1) -// CCMRx channel byte for output: CCxS=00, OCxM=110 (PWM1); preload is added once CCR is zeroed -#define DSHOT_CCMR_OUTPUT (TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1) -// CCER channel nibble for capture: both edges, channel on -#define DSHOT_CCER_INPUT (TIM_CCER_CC1E | TIM_CCER_CC1P | TIM_CCER_CC1NP) - -static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count) -{ - uint32_t value = 0; - uint32_t oldValue = buffer[0]; - int bits = 0; - - for (uint32_t i = 1; i <= count; i++) { - int len; - if (i < count) { - const int diff = buffer[i] - oldValue; - if (bits >= 21) { - break; - } - len = (diff + 8) / 16; - if (len < 1 || len > 21) { - // Edges closer than half a GCR bit or further apart than a whole frame - return DSHOT_TELEMETRY_INVALID; - } - } else { - len = 21 - bits; - if (len < 1) { - // All bits accounted for, no trailing run left to infer - break; - } - } - - value <<= len; - value |= 1 << (len - 1); - if (i < count) { - oldValue = buffer[i]; - } - bits += len; - } - - if (bits != 21) { - return DSHOT_TELEMETRY_INVALID; - } - - static const uint32_t decode[32] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 0, 13, 14, 15, - 0, 0, 2, 3, 0, 5, 6, 7, 0, 0, 8, 1, 0, 4, 12, 0 - }; - - uint32_t decodedValue = decode[value & 0x1f]; - decodedValue |= decode[(value >> 5) & 0x1f] << 4; - decodedValue |= decode[(value >> 10) & 0x1f] << 8; - decodedValue |= decode[(value >> 15) & 0x1f] << 12; - - uint32_t csum = decodedValue; - csum ^= csum >> 8; - csum ^= csum >> 4; - - if ((csum & 0xf) != 0xf) { - return DSHOT_TELEMETRY_INVALID; - } - - return decodedValue >> 4; -} - -static void pwmDshotSetDirectionOutput(pwmOutputPort_t *port) -{ - // Bidirectional DSHOT is carried on inverted (idle-high) signalling - flip the - // channel's normal polarity whenever telemetry is active, matching Betaflight. - const bool inverted = ((port->tch->timHw->output & TIMER_OUTPUT_INVERTED) != 0) ^ useDshotTelemetry; - - // Telemetry input capture widens ARR to 0xffff (see pwmDshotSetDirectionInput); - // restore the DSHOT bit period now, bypassing the ARR preload shadow so it - // takes effect immediately instead of after the next update event. - TIM_TypeDef *tim = port->tch->timHw->tim; - CLEAR_BIT(tim->CR1, TIM_CR1_ARPE); - tim->ARR = DSHOT_MOTOR_BITLENGTH - 1; - SET_BIT(tim->CR1, TIM_CR1_ARPE); - tim->CNT = 0; - - // Channel back to PWM1 output. CCxS is only writable with the channel off, and CCR is - // zeroed before OCxPE goes back on so the stale capture value can't give one bit period - // of output before the first update event. Idle state (CR2 OISx) is untouched. - const dshotChannelRegs_t regs = dshotChannelRegs(port); - CLEAR_BIT(tim->CCER, regs.ccerMask); - MODIFY_REG(*regs.ccmr, regs.ccmrMask, DSHOT_CCMR_OUTPUT << regs.ccmrShift); - *port->ccr = 0; - SET_BIT(*regs.ccmr, TIM_CCMR1_OC1PE << regs.ccmrShift); - uint32_t ccer; - if (port->tch->timHw->output & TIMER_OUTPUT_N_CHANNEL) { - ccer = TIM_CCER_CC1NE | (inverted ? TIM_CCER_CC1NP : 0); - } else { - ccer = TIM_CCER_CC1E | (inverted ? TIM_CCER_CC1P : 0); - } - MODIFY_REG(tim->CCER, regs.ccerMask, ccer << regs.ccerShift); - - // Stream back to memory-to-peripheral; timerPWMPrepareDMA() sets count and addresses and - // enables it for the next frame. The capture may still be draining (the decode loop only - // cleared EN), so wait for EN to read 0 before touching CR, then clear all five event - // flags: EN=1 is ignored while any of them is set (RM0433). - DMA_Stream_TypeDef *stream = port->tch->dma->ref; - for (uint32_t timeout = 10000; timeout && (stream->CR & DMA_SxCR_EN); timeout--) { } - DMA_CLEAR_FLAG(port->tch->dma, DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_TEIF | DMA_IT_DMEIF | DMA_IT_FEIF); - stream->CR = (stream->CR & ~(DMA_SxCR_DIR | DMA_SxCR_EN)) | DMA_SxCR_DIR_0; - port->telemetryInputActive = false; -} - -FAST_CODE static void pwmDshotSetDirectionInput(pwmOutputPort_t *port) -{ - // Runs in the DMA completion ISR for every motor in turn, so it only writes registers: - // no HAL/LL init calls, and the stream is reconfigured in place (hardware clears its EN - // bit at end of transfer, the wait below only covers the flag/EN ordering). - // pwmOutputPorts lives in non-cacheable DMA_RAM, so read tch once. - TCH_t *tch = port->tch; - TIM_TypeDef *tim = tch->timHw->tim; - const dshotChannelRegs_t regs = dshotChannelRegs(port); - - // Widen ARR so the free-running counter doesn't wrap every DSHOT bit period - // (20 ticks) while timing GCR edges, which span ~21 bits per telemetry frame. - // ARPE is set, so this lands at the next update event, within one bit period. - tim->ARR = 0xffff; - -#if defined(STM32H7) - // H7 errata workaround (matches Betaflight): reconfiguring the channel from output - // compare to input capture can glitch the pin for a cycle while CCMR/CCER are mid-update. - // Drive it as a plain GPIO output at the preset ODR level meanwhile. Only MODER changes; - // pull, speed and AF stay as dshotConnectOutputs() set them. - const IO_t io = IOGetByTag(tch->timHw->tag); - GPIO_TypeDef *gpio = IO_GPIO(io); - const uint32_t moderShift = 2 * IO_GPIOPinIdx(io); - MODIFY_REG(gpio->MODER, GPIO_MODER_MODE0_Msk << moderShift, GPIO_MODER_MODE0_0 << moderShift); -#endif - - // Channel to input capture, both edges, filter N=4. CCxS is only writable with the channel off. - CLEAR_BIT(tim->CCER, regs.ccerMask); - MODIFY_REG(*regs.ccmr, regs.ccmrMask, DSHOT_CCMR_INPUT << regs.ccmrShift); - MODIFY_REG(tim->CCER, regs.ccerMask, DSHOT_CCER_INPUT << regs.ccerShift); - -#if defined(STM32H7) - MODIFY_REG(gpio->MODER, GPIO_MODER_MODE0_Msk << moderShift, GPIO_MODER_MODE0_1 << moderShift); -#endif - - // Stream to peripheral-to-memory: addresses, FIFO and request stay from the output frame. - // Clear all five event flags first, EN=1 is ignored while any of them is set (RM0433). - DMA_Stream_TypeDef *stream = tch->dma->ref; - for (uint32_t timeout = 1000; timeout && (stream->CR & DMA_SxCR_EN); timeout--) { } - DMA_CLEAR_FLAG(tch->dma, DMA_IT_TCIF | DMA_IT_HTIF | DMA_IT_TEIF | DMA_IT_DMEIF | DMA_IT_FEIF); - const uint32_t cr = (stream->CR & ~(DMA_SxCR_DIR | DMA_SxCR_EN)) | DMA_SxCR_TCIE; - stream->CR = cr; - stream->NDTR = GCR_TELEMETRY_INPUT_LEN; - stream->CR = cr | DMA_SxCR_EN; - dshotDmaReqEnable(tim, dshotDmaSource(port)); - port->telemetryInputActive = true; -} - -// Connect bidir DSHOT pins to their timer AF (idle-high). Called on the first -// real motor update so the line only goes high microseconds before frames start, -// keeping it low through the ESC's boot-time bootloader-entry window. -static void dshotConnectOutputs(void) -{ - for (int index = 0; index < getMotorCount(); index++) { - pwmOutputPort_t *port = motors[index].pwmPort; - if (port && port->configured) { - const timerHardware_t *timHw = port->tch->timHw; - const IO_t io = IOGetByTag(timHw->tag); - // The pull must match this channel's *un-flipped* polarity - // (pwmDshotSetDirectionOutput flips OCPolarity for bidir, but the GCR - // listen phase still idles toward the same physical level either way). - const bool baseInverted = timHw->output & TIMER_OUTPUT_INVERTED; -#if defined(STM32H7) - // Preset ODR to the bidir idle level once - the H7 OC->IC erratum workaround - // in pwmDshotSetDirectionInput() disconnects the pin from the timer and relies - // on this cached ODR bit (matches Betaflight) instead of redriving the level. - baseInverted ? IOLo(io) : IOHi(io); -#endif - IOConfigGPIOAF(io, baseInverted ? IOCFG_AF_PP_PD : IOCFG_AF_PP_UP, timHw->alternateFunction); - } - } -} - -// Takes over the stream's completion interrupt from the timer driver on bidir ports: once -// the frame is out the port is turned round to capture the ESC reply, and -// pwmDshotDecodeTelemetry() turns it back before the next frame. Runs once per motor per -// frame, back to back, so it lives in ITCM where available. -FAST_CODE static void pwmDshotDmaIrqHandler(DMA_t descriptor) -{ - if (!DMA_GET_FLAG_STATUS(descriptor, DMA_IT_TCIF)) { - return; - } - - // userParam is the motor index (see motorConfigDshot()) - pwmOutputPort_t *port = motors[descriptor->userParam].pwmPort; - - // The stream disabled itself at end of transfer (normal mode). The DMA request must go - // too: CCR is 0 after the frame, so compare matches keep a request pending and the stream - // would serve it as a bogus first capture the moment it is re-enabled for input. - dshotDmaReqDisable(port->tch->timHw->tim, dshotDmaSource(port)); - - // Same bookkeeping as the timer driver's handler (timerPWMDMAInProgress()) - if (port->tch->dmaState == TCH_DMA_ACTIVE) { - port->tch->dmaState = TCH_DMA_IDLE; - } - - if (!port->telemetryInputActive) { - pwmDshotSetDirectionInput(port); - dshotTelemetryPending = true; - - // DEBUG_ESC: debug[motor] = cycles from the frame start to this capture being armed - // (H7: /480 = us, F7: /216) - if (debugMode == DEBUG_ESC && descriptor->userParam < DEBUG32_VALUE_COUNT) { - debug[descriptor->userParam] = ticks() - dshotFrameStartCycles; - } - } - - DMA_CLEAR_FLAG(descriptor, DMA_IT_TCIF); -} - -// DMA has already captured the telemetry waveform before this runs. Keep the -// decode path out of the fast motor-update caller on constrained F7 targets. -static bool NOINLINE pwmDshotDecodeTelemetry(void) -{ - if (!dshotTelemetryPending) { - return true; - } - - // Wait out the reply window of the frame before switching any port back (see - // dshotTelemetryFrameStampUs) - if ((micros() - dshotTelemetryFrameStampUs) < dshotTelemetryDeadtimeUs) { - return false; - } - - // Cleared before the loop: a completion IRQ landing while the loop runs re-arms it, so a - // port the loop has already passed is picked up by the next call instead of being left - // in input for the following frame - dshotTelemetryPending = false; - - for (int motorIndex = 0; motorIndex < getMotorCount(); motorIndex++) { - pwmOutputPort_t *port = motors[motorIndex].pwmPort; - if (!port || !port->configured || !port->telemetryInputActive) { - continue; - } - - uint32_t edges = 0; - edges = GCR_TELEMETRY_INPUT_LEN - port->tch->dma->ref->NDTR; - dshotDmaReqDisable(port->tch->timHw->tim, dshotDmaSource(port)); - CLEAR_BIT(port->tch->dma->ref->CR, DMA_SxCR_EN); - - // Too few edges is no reply at all - uint16_t rawValue = DSHOT_TELEMETRY_NOEDGE; - if (edges > MIN_GCR_EDGES) { - // No cache maintenance: pwmOutputPorts is DMA_RAM, which the H7 MPU maps non-cacheable - rawValue = dshotDecodeTelemetryPacket((const uint32_t *)port->dmaBuffer, edges); - } - - const uint16_t processed = dshotProcessPacket(rawValue, motorIndex); - if (processed != DSHOT_TELEMETRY_INVALID && processed != DSHOT_TELEMETRY_NOEDGE) { -#ifdef USE_ESC_SENSOR - // Nothing to publish before the first eRPM value (an EDT frame may come first) - escSensorData_t data; - if (getDshotEscSensorData(&data, motorIndex)) { - escSensorSetDshotData(motorIndex, data.rpm, data.temperature, data.voltage, data.current); - } -#endif - } - - pwmDshotSetDirectionOutput(port); - } - - // Re-armed during the loop: some port is in input again, hold the frame until it is back - return !dshotTelemetryPending; -} -#endif // USE_DSHOT_BIDIR_TIMER - -static pwmOutputPort_t * motorConfigDshot(const timerHardware_t * timerHardware, uint32_t dshotHz, bool enableOutput, uint8_t motorIndex) -{ - UNUSED(motorIndex); - // Try allocating new port - pwmOutputPort_t * port = pwmOutConfig(timerHardware, OWNER_MOTOR, dshotHz, DSHOT_MOTOR_BITLENGTH, 0, enableOutput); - - if (!port) { - return NULL; - } - -#ifdef USE_DSHOT_BIDIR_TIMER - if (enableOutput && useDshotTelemetry) { - // Bidir signalling idles high, but holding the line high with no edges - // during ESC boot triggers the BLHeli/Bluejay bootloader-entry check - // (~150ms of continuous high right after the ESC's startup melody). The - // first INAV frame goes out seconds after this pin is configured, so the - // ESC would enter its bootloader, time out and reset - replaying the - // startup melody. Park the pin so the ESC sees low, like normal DSHOT - // idle, and defer the AF connect until the first frame goes out - // (dshotConnectOutputs()). On TIMER_OUTPUT_INVERTED hardware the pin - // level is re-inverted downstream, so park high there. - const IO_t io = IOGetByTag(timerHardware->tag); - IOConfigGPIO(io, IOCFG_OUT_PP); - (timerHardware->output & TIMER_OUTPUT_INVERTED) ? IOHi(io) : IOLo(io); - dshotPinsDisconnected = true; - } -#endif - - // Configure timer DMA -#ifdef USE_DSHOT_DMAR - uint8_t burstDmaTimerIndex = getBurstDmaTimerIndex(timerHardware->tim); - if (burstDmaTimerIndex >= MAX_DMA_TIMERS) { - return NULL; - } - - port->dmaBurstBuffer = &dmaBurstBuffer[burstDmaTimerIndex][0]; - burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[burstDmaTimerIndex]; - burstDmaTimer->dmaBurstBuffer = port->dmaBurstBuffer; - - if (timerPWMConfigDMABurst(burstDmaTimer, port->tch, port->dmaBurstBuffer, sizeof(port->dmaBurstBuffer[0]), DSHOT_DMA_BUFFER_SIZE)) { - port->configured = true; - } -#else - if (timerPWMConfigChannelDMA(port->tch, port->dmaBuffer, sizeof(port->dmaBuffer[0]), DSHOT_DMA_BUFFER_SIZE)) { - // Only mark as DSHOT channel if DMA was set successfully - ZERO_FARRAY(port->dmaBuffer); - port->configured = true; -#ifdef USE_DSHOT_BIDIR_TIMER - if (useDshotTelemetry) { - // Inverted signalling and per-frame direction switching; the port takes the - // stream's completion interrupt over from the timer driver - dshotTelemetryDeadtimeUs = DSHOT_TELEMETRY_DEADTIME_US + 1000000 * (DSHOT_TELEMETRY_WINDOW_SLOTS * DSHOT_MOTOR_BITLENGTH) / dshotHz; -#if defined(USE_HAL_DRIVER) - // FIFO threshold 1/4 for both directions (the F7/H7 timer driver set FULL), so - // captured edges reach memory one word at a time and the decode never finds a - // partial reply still sitting in the FIFO. Set once here; the direction switch - // leaves FCR alone. The F4 driver runs the stream in direct mode, which already - // writes every word straight away. - port->tch->dma->ref->FCR = DMA_SxFCR_DMDIS; -#endif - pwmDshotSetDirectionOutput(port); - // The handler gets the motor index: it reaches the port through motors[] and uses - // the index straight as the debug slot - dmaSetHandler(port->tch->dma, pwmDshotDmaIrqHandler, NVIC_PRIO_TIMER_DMA, motorIndex); - } -#endif - } -#endif - - return port; -} - -#ifdef USE_DSHOT_DMAR -static void loadDmaBufferDshotStride(timerDMASafeType_t *dmaBuffer, int stride, uint16_t packet) -{ - int i; - for (i = 0; i < 16; i++) { - dmaBuffer[i * stride] = (packet & 0x8000) ? DSHOT_MOTOR_BIT_1 : DSHOT_MOTOR_BIT_0; // MSB first - packet <<= 1; - } - dmaBuffer[i++ * stride] = 0; - dmaBuffer[i++ * stride] = 0; -} -#else -static void loadDmaBufferDshot(timerDMASafeType_t *dmaBuffer, uint16_t packet) -{ - for (int i = 0; i < 16; i++) { - dmaBuffer[i] = (packet & 0x8000) ? DSHOT_MOTOR_BIT_1 : DSHOT_MOTOR_BIT_0; // MSB first - packet <<= 1; - } - // Frame reset slots: rewritten every time, a bidir port captures edges into this buffer - dmaBuffer[16] = 0; - dmaBuffer[17] = 0; -} -#endif - -static uint16_t prepareDshotPacket(const uint16_t value, bool requestTelemetry) -{ - // The telemetry bit asks for a serial telemetry packet on the ESC's telemetry wire; - // the eRPM reply on the motor line is triggered by the inverted checksum alone, so - // bidir leaves the bit to the serial ESC sensor's round-robin requests - uint16_t packet = (value << 1) | (requestTelemetry ? 1 : 0); - - // compute checksum - int csum = 0; - int csum_data = packet; - for (int i = 0; i < 3; i++) { - csum ^= csum_data; // xor data by nibbles - csum_data >>= 4; - } -#ifdef USE_DSHOT_BIDIR - if (useDshotTelemetry) { - csum = ~csum; - } -#endif - csum &= 0xf; - - // append checksum - packet = (packet << 4) | csum; - - return packet; -} -#endif - -#if defined(USE_DSHOT) -static void motorConfigDigitalUpdateInterval(uint16_t motorPwmRateHz) -{ - digitalMotorUpdateIntervalUs = 1000000 / motorPwmRateHz; - digitalMotorLastUpdateUs = 0; -} - -static void pwmWriteDigital(uint8_t index, uint16_t value) -{ - // Just keep track of motor value, actual update happens in pwmCompleteMotorUpdate() - // DSHOT and some other digital protocols use 11-bit throttle range [0;2047] - motors[index].value = constrain(value, 0, 2047); -} - bool isMotorProtocolDshot(void) { // We look at cached `initMotorProtocol` to make sure we are consistent with the initialized config @@ -981,223 +221,31 @@ bool isMotorProtocolDigital(void) return isMotorProtocolDshot(); } -// A motor with an output behind it: a timer port, or a bitbanged pin -static bool isMotorOutputConfigured(int index) +void pwmRequestMotorTelemetry(int motorIndex) { -#ifdef USE_DSHOT_BITBANG - if (dshotBitbangIsActive()) { - return dshotBitbangMotorIsConfigured(index); +#ifdef USE_DSHOT + if (isMotorProtocolDigital()) { + dshotRequestTelemetry(motorIndex); } +#else + UNUSED(motorIndex); #endif - return motors[index].pwmPort && motors[index].pwmPort->configured; } -void pwmRequestMotorTelemetry(int motorIndex) +void pwmCompleteMotorUpdate(void) { - if (!isMotorProtocolDigital()) { - return; - } - - const int motorCount = getMotorCount(); - for (int index = 0; index < motorCount; index++) { - if (isMotorOutputConfigured(index) && index == motorIndex) { - motors[index].requestTelemetry = true; - } - } -} - #ifdef USE_DSHOT -void sendDShotCommand(dshotCommands_e cmd) { - circularBufferPushElement(&commandsCircularBuffer, (uint8_t *) &cmd); -} - -void initDShotCommands(void) { - circularBufferInit(&commandsCircularBuffer, commandsBuff,DHSOT_COMMAND_QUEUE_SIZE, sizeof(dshotCommands_e)); - - currentExecutingCommand.remainingRepeats = 0; -} - -static int getDShotCommandRepeats(dshotCommands_e cmd) { - int repeats = 1; - - switch (cmd) { - case DSHOT_CMD_EXTENDED_TELEMETRY_ENABLE: - case DSHOT_CMD_SPIN_DIRECTION_NORMAL: - case DSHOT_CMD_SPIN_DIRECTION_REVERSED: - repeats = 10; - break; - default: - break; - } - - return repeats; -} - -// NOINLINE: pwmCompleteMotorUpdate() is inlined into the ITCM scheduler; commands are rare -static bool NOINLINE executeDShotCommands(void){ - - timeUs_t tNow = micros(); - - if(currentExecutingCommand.remainingRepeats == 0) { - const int isTherePendingCommands = !circularBufferIsEmpty(&commandsCircularBuffer); - if (isTherePendingCommands && (tNow - lastCommandSent > DSHOT_COMMAND_INTERVAL_US)){ - //Load the command - dshotCommands_e cmd; - circularBufferPopHead(&commandsCircularBuffer, (uint8_t *) &cmd); - currentExecutingCommand.cmd = cmd; - currentExecutingCommand.remainingRepeats = getDShotCommandRepeats(cmd); - commandPostDelay = DSHOT_COMMAND_INTERVAL_US; - } else { - if (commandPostDelay) { - if (tNow - lastCommandSent < commandPostDelay) { - return false; - } - commandPostDelay = 0; - } - - return true; - } - } - for (uint8_t i = 0; i < getMotorCount(); i++) { - motors[i].requestTelemetry = true; - motors[i].value = currentExecutingCommand.cmd; - } - if (tNow - lastCommandSent >= DSHOT_COMMAND_DELAY_US) { - currentExecutingCommand.remainingRepeats--; - lastCommandSent = tNow; - return true; - } else { - return false; - } -} -#endif - -void pwmCompleteMotorUpdate(void) { // This only makes sense for digital motor protocols - if (!isMotorProtocolDigital()) { - return; - } - -#ifdef USE_DSHOT_BIDIR_TIMER - if (useDshotTelemetry && !pwmDshotDecodeTelemetry()) { - return; - } -#endif -#ifdef USE_DSHOT_BITBANG - if (dshotBitbangIsActive() && !dshotBitbangDecodeTelemetry()) { - return; - } -#endif - - int motorCount = getMotorCount(); - timeUs_t currentTimeUs = micros(); - -#ifdef USE_DSHOT_BIDIR - if (useDshotTelemetry) { - escSensorFrameWindowUpdate(currentTimeUs / 1000); - } -#endif - - // Enforce motor update rate - if ((digitalMotorUpdateIntervalUs == 0) || ((currentTimeUs - digitalMotorLastUpdateUs) <= digitalMotorUpdateIntervalUs)) { - return; - } - - digitalMotorLastUpdateUs = currentTimeUs; - -#ifdef USE_DSHOT - if (isMotorProtocolDshot()) { - -#ifdef USE_DSHOT_BITBANG - if (dshotBitbangIsActive()) { - // No frames while the motors are disabled: the 4-way interface owns the pins then - if (!pwmMotorsEnabled || !executeDShotCommands()) { - return; - } - for (int index = 0; index < motorCount; index++) { - if (dshotBitbangMotorIsConfigured(index)) { - dshotBitbangWrite(index, prepareDshotPacket(motors[index].value, motors[index].requestTelemetry)); - motors[index].requestTelemetry = false; - } - } - dshotBitbangUpdateComplete(); - return; - } -#endif - -#ifdef USE_DSHOT_BIDIR_TIMER - if (dshotPinsDisconnected) { - dshotConnectOutputs(); - dshotPinsDisconnected = false; - } -#endif - - if (!executeDShotCommands()) { - return; - } - -#ifdef USE_DSHOT_DMAR - for (int index = 0; index < motorCount; index++) { - if (motors[index].pwmPort && motors[index].pwmPort->configured) { - uint16_t packet = prepareDshotPacket(motors[index].value, motors[index].requestTelemetry); - loadDmaBufferDshotStride(&motors[index].pwmPort->dmaBurstBuffer[motors[index].pwmPort->tch->timHw->channelIndex], 4, packet); - motors[index].requestTelemetry = false; - } - } - - for (int burstDmaTimerIndex = 0; burstDmaTimerIndex < burstDmaTimersCount; burstDmaTimerIndex++) { - burstDmaTimer_t *burstDmaTimer = &burstDmaTimers[burstDmaTimerIndex]; - pwmBurstDMAStart(burstDmaTimer, DSHOT_DMA_BUFFER_SIZE * 4); - } -#else - // Generate DMA buffers - for (int index = 0; index < motorCount; index++) { - if (motors[index].pwmPort && motors[index].pwmPort->configured) { - uint16_t packet = prepareDshotPacket(motors[index].value, motors[index].requestTelemetry); - loadDmaBufferDshot(motors[index].pwmPort->dmaBuffer, packet); - timerPWMPrepareDMA(motors[index].pwmPort->tch, DSHOT_DMA_BUFFER_SIZE); - motors[index].requestTelemetry = false; - } - } - -#ifdef USE_DSHOT_BIDIR_TIMER - if (useDshotTelemetry) { - // Reference for the reply window; the completion ISRs don't read the clock - dshotTelemetryFrameStampUs = micros(); - if (debugMode == DEBUG_ESC) { - dshotFrameStartCycles = ticks(); - } - } -#endif - - // Start DMA on all timers - for (int index = 0; index < motorCount; index++) { - if (motors[index].pwmPort && motors[index].pwmPort->configured) { - timerPWMStartDMA(motors[index].pwmPort->tch); - } - } -#endif + if (isMotorProtocolDigital()) { + dshotCompleteMotorUpdate(pwmMotorsEnabled); } #endif } -#else // digital motor protocol - -// This stub is needed to avoid ESC_SENSOR dependency on DSHOT -void pwmRequestMotorTelemetry(int motorIndex) -{ - UNUSED(motorIndex); -} - -#endif - void pwmMotorPreconfigure(void) { // Keep track of initial motor protocol initMotorProtocol = motorConfig()->motorPwmProtocol; -#ifdef USE_DSHOT_BIDIR - useDshotTelemetry = motorConfig()->useDshotTelemetry && getMotorProtocolProperties(initMotorProtocol)->isDSHOT; -#endif #ifdef BRUSHED_MOTORS initMotorProtocol = PWM_TYPE_BRUSHED; // Override proto @@ -1220,15 +268,8 @@ void pwmMotorPreconfigure(void) case PWM_TYPE_DSHOT600: case PWM_TYPE_DSHOT300: case PWM_TYPE_DSHOT150: -#ifdef USE_DSHOT_BITBANG - // Bidirectional DSHOT is bitbanged on this MCU (dshot_bitbang.c); plain DSHOT - // stays on the timers - if (useDshotTelemetry) { - dshotBitbangInit(getDshotHz(initMotorProtocol) / DSHOT_MOTOR_BITLENGTH); - } -#endif - motorConfigDigitalUpdateInterval(getEscUpdateFrequency()); - motorWritePtr = pwmWriteDigital; + dshotInit(initMotorProtocol, getEscUpdateFrequency()); + motorWritePtr = dshotWriteMotor; break; #endif @@ -1250,7 +291,7 @@ void pwmMotorPreconfigure(void) /** * This function return the PWM frequency based on ESC protocol. We allow customer rates only for Brushed motors - */ + */ uint32_t getEscUpdateFrequency(void) { switch (initMotorProtocol) { case PWM_TYPE_BRUSHED: @@ -1282,68 +323,42 @@ bool pwmMotorConfig(const timerHardware_t *timerHardware, uint8_t motorIndex, bo { switch (initMotorProtocol) { case PWM_TYPE_BRUSHED: - motors[motorIndex].pwmPort = motorConfigPwm(timerHardware, 0.0f, 0.0f, getEscUpdateFrequency(), enableOutput); + motors[motorIndex] = motorConfigPwm(timerHardware, 0.0f, 0.0f, getEscUpdateFrequency(), enableOutput); break; case PWM_TYPE_ONESHOT125: - motors[motorIndex].pwmPort = motorConfigPwm(timerHardware, 125e-6f, 125e-6f, getEscUpdateFrequency(), enableOutput); + motors[motorIndex] = motorConfigPwm(timerHardware, 125e-6f, 125e-6f, getEscUpdateFrequency(), enableOutput); break; case PWM_TYPE_MULTISHOT: - motors[motorIndex].pwmPort = motorConfigPwm(timerHardware, 5e-6f, 20e-6f, getEscUpdateFrequency(), enableOutput); + motors[motorIndex] = motorConfigPwm(timerHardware, 5e-6f, 20e-6f, getEscUpdateFrequency(), enableOutput); break; #ifdef USE_DSHOT case PWM_TYPE_DSHOT600: case PWM_TYPE_DSHOT300: case PWM_TYPE_DSHOT150: -#ifdef USE_DSHOT_BITBANG - if (dshotBitbangIsActive()) { - // Only the pin is taken, its timer channel stays free; the pin joins its GPIO - // port's group in dshotBitbangPostInit(), once every other timer user has chosen - return dshotBitbangMotorConfig(timerHardware, motorIndex, enableOutput); - } -#endif - motors[motorIndex].pwmPort = motorConfigDshot(timerHardware, getDshotHz(initMotorProtocol), enableOutput, motorIndex); - break; + return dshotMotorConfig(timerHardware, motorIndex, enableOutput); #endif case PWM_TYPE_STANDARD: - motors[motorIndex].pwmPort = motorConfigPwm(timerHardware, 1e-3f, 1e-3f, getEscUpdateFrequency(), enableOutput); + motors[motorIndex] = motorConfigPwm(timerHardware, 1e-3f, 1e-3f, getEscUpdateFrequency(), enableOutput); break; default: - motors[motorIndex].pwmPort = NULL; + motors[motorIndex] = NULL; break; } - return (motors[motorIndex].pwmPort != NULL); + return (motors[motorIndex] != NULL); } -// After every other timer and DMA user has had its pick (fc_init). Bitbang DSHOT needs a -// whole spare timer: without one the motors go back to plain DSHOT on their own timer -// channels and bidirectional telemetry stays off for this boot, rather than blocking arming -// over a feature the airframe can fly without. +// After every other timer and DMA user has had its pick (fc_init) bool pwmMotorPostInit(void) { -#ifdef USE_DSHOT_BITBANG - if (dshotBitbangIsActive() && !dshotBitbangPostInit()) { - LOG_ERROR(PWM, "Bitbang DSHOT unavailable (status %d), bidirectional DSHOT off", dshotBitbangGetStatus()); - dshotBitbangRelease(); - useDshotTelemetry = false; - - const uint32_t dshotHz = getDshotHz(initMotorProtocol); - for (int index = 0; index < getMotorCount(); index++) { - const timerHardware_t *timHw; - bool enableOutput; - if (!dshotBitbangGetMotorOutput(index, &timHw, &enableOutput)) { - continue; - } - motors[index].pwmPort = motorConfigDshot(timHw, dshotHz, enableOutput, index); - if (motors[index].pwmPort == NULL) { - return false; - } - } +#ifdef USE_DSHOT + if (isMotorProtocolDshot()) { + return dshotMotorPostInit(); } #endif return true; @@ -1352,13 +367,13 @@ bool pwmMotorPostInit(void) // Helper function for ESC passthrough ioTag_t pwmGetMotorPinTag(int motorIndex) { -#ifdef USE_DSHOT_BITBANG - if (dshotBitbangIsActive()) { - return dshotBitbangGetMotorPinTag(motorIndex); +#ifdef USE_DSHOT + if (isMotorProtocolDshot()) { + return dshotGetMotorPinTag(motorIndex); } #endif - if (motors[motorIndex].pwmPort) { - return motors[motorIndex].pwmPort->tch->timHw->tag; + if (motors[motorIndex]) { + return motors[motorIndex]->tch->timHw->tag; } else { return IOTAG_NONE; @@ -1370,14 +385,14 @@ ioTag_t pwmGetMotorPinTag(int motorIndex) // on HAL targets a bare IOConfigGPIO(IOCFG_AF_PP) programs AF0 and the timer loses the pin. void pwmRestoreMotorPin(int motorIndex) { -#ifdef USE_DSHOT_BITBANG - if (dshotBitbangIsActive()) { - dshotBitbangRestoreMotorPin(motorIndex); +#ifdef USE_DSHOT + if (isMotorProtocolDshot()) { + dshotRestoreMotorPin(motorIndex); return; } #endif - if (motors[motorIndex].pwmPort) { - const timerHardware_t *timHw = motors[motorIndex].pwmPort->tch->timHw; + if (motors[motorIndex]) { + const timerHardware_t *timHw = motors[motorIndex]->tch->timHw; IOConfigGPIOAF(IOGetByTag(timHw->tag), IOCFG_AF_PP, timHw->alternateFunction); } } diff --git a/src/main/drivers/pwm_output.h b/src/main/drivers/pwm_output.h index 622713432ea..f31896a68e9 100644 --- a/src/main/drivers/pwm_output.h +++ b/src/main/drivers/pwm_output.h @@ -32,11 +32,6 @@ typedef enum { DSHOT_CMD_SPIN_DIRECTION_REVERSED = 21, } dshotCommands_e; -typedef struct { - dshotCommands_e cmd; - int remainingRepeats; -} currentExecutingCommand_t; - void pwmRequestMotorTelemetry(int motorIndex); ioTag_t pwmGetMotorPinTag(int motorIndex); @@ -64,6 +59,7 @@ bool pwmServoConfig(const struct timerHardware_s *timerHardware, uint8_t servoIn void pwmWriteBeeper(bool onoffBeep); bool beeperPwmInit(ioTag_t tag, uint16_t frequency); +// DSHOT commands, implemented by the DSHOT driver (dshot/dshot.c; pwm_output_rp2350.c on RP2350) void sendDShotCommand(dshotCommands_e cmd); void initDShotCommands(void); diff --git a/src/main/fc/fc_core.c b/src/main/fc/fc_core.c index a79c29b5555..2590e8a13d2 100644 --- a/src/main/fc/fc_core.c +++ b/src/main/fc/fc_core.c @@ -37,7 +37,7 @@ #include "drivers/time.h" #include "drivers/system.h" #include "drivers/pwm_output.h" -#include "drivers/bidir_dshot.h" +#include "drivers/dshot/bidir_dshot.h" #include "drivers/pwm_mapping.h" #include "sensors/sensors.h" diff --git a/src/main/fc/fc_init.c b/src/main/fc/fc_init.c index 7dfcda4c3db..fb5755f8969 100644 --- a/src/main/fc/fc_init.c +++ b/src/main/fc/fc_init.c @@ -50,8 +50,8 @@ #include "drivers/compass/compass.h" #include "drivers/bus.h" #include "drivers/dma.h" -#include "drivers/bidir_dshot.h" -#include "drivers/dshot_bitbang.h" +#include "drivers/dshot/bidir_dshot.h" +#include "drivers/dshot/dshot_bitbang.h" #include "drivers/exti.h" #include "drivers/io.h" #include "drivers/flash.h" diff --git a/src/main/fc/fc_msp.c b/src/main/fc/fc_msp.c index efa95e668c1..f619cfa45df 100644 --- a/src/main/fc/fc_msp.c +++ b/src/main/fc/fc_msp.c @@ -47,7 +47,7 @@ #include "drivers/compass/compass.h" #include "drivers/compass/compass_msp.h" #include "drivers/barometer/barometer_msp.h" -#include "drivers/bidir_dshot.h" +#include "drivers/dshot/bidir_dshot.h" #include "drivers/pitotmeter/pitotmeter_msp.h" #include "sensors/battery_sensor_fake.h" #include "drivers/bus_i2c.h" diff --git a/src/main/flight/rpm_filter.c b/src/main/flight/rpm_filter.c index 7e3c98e7d75..fe605894596 100644 --- a/src/main/flight/rpm_filter.c +++ b/src/main/flight/rpm_filter.c @@ -38,7 +38,7 @@ #include "common/maths.h" #include "common/filter.h" #include "flight/mixer.h" -#include "drivers/bidir_dshot.h" +#include "drivers/dshot/bidir_dshot.h" #include "sensors/esc_sensor.h" #include "fc/config.h" #include "fc/settings.h" diff --git a/src/main/sensors/esc_sensor.c b/src/main/sensors/esc_sensor.c index 88c60921e61..4b250bf9a99 100644 --- a/src/main/sensors/esc_sensor.c +++ b/src/main/sensors/esc_sensor.c @@ -41,7 +41,7 @@ #include "config/parameter_group_ids.h" #include "flight/mixer.h" -#include "drivers/bidir_dshot.h" +#include "drivers/dshot/bidir_dshot.h" #include "drivers/pwm_output.h" #include "sensors/esc_sensor.h" #include "drivers/pwm_mapping.h" diff --git a/src/main/target/common_post.h b/src/main/target/common_post.h index 997d6bfce61..b6d3ff447ba 100644 --- a/src/main/target/common_post.h +++ b/src/main/target/common_post.h @@ -193,13 +193,13 @@ extern uint8_t __config_end; // motors from a PIO program that only transmits, so the setting is hidden there // and stays off. STM32F7 is excluded as well for now, F7 targets lack the flash. // - USE_DSHOT_BIDIR_TIMER: the motor timer channels send the frame and are turned -// round to capture the reply (pwm_output.c). STM32F4 and STM32H7. +// round to capture the reply (dshot/dshot.c). STM32F4 and STM32H7. // - USE_DSHOT_BITBANG: the motor pins are driven as plain GPIO by DMA, paced by a // spare TMR1/TMR8 channel, and sampled the same way for the reply // (dshot_bitbang.c). AT32F43x, where timer channel 4 cannot capture both edges // (see AT32_BIDIR_DSHOT.md in the repository root). Used whenever // dshot_bidir_enabled is on and a whole TMR8 or TMR1 is free, otherwise the motors -// fall back to plain DSHOT on their timers (pwmMotorPostInit()). +// fall back to plain DSHOT on their timers (dshotMotorPostInit()). #if defined(USE_DSHOT_DMAR) && !defined(USE_DSHOT) #error "USE_DSHOT_DMAR requires USE_DSHOT" #endif From a6fe37e47ba13164362b4b8d68d1de323e0fab03 Mon Sep 17 00:00:00 2001 From: Error414 Date: Wed, 4 Nov 2026 08:21:11 +0100 Subject: [PATCH 33/37] DSHOT BIDIR - remove debug line for debug --- src/main/drivers/dshot/dshot_bitbang.c | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/drivers/dshot/dshot_bitbang.c b/src/main/drivers/dshot/dshot_bitbang.c index 8d500e6bbdf..7800ba3b587 100644 --- a/src/main/drivers/dshot/dshot_bitbang.c +++ b/src/main/drivers/dshot/dshot_bitbang.c @@ -224,7 +224,6 @@ static uint16_t bbDmaSource(uint8_t channelIndex) // in timerCtx; this driver does not, so its own pacers do not show up here. static bool bbTimerIsFree(tmr_type *tim) { - return false; // TEMPORARY: forces the fallback to plain timer DSHOT for testing, remove before commit const uint8_t timerIndex = lookupTimerIndex(tim); if (timerIndex >= HARDWARE_TIMER_DEFINITION_COUNT) { return false; From 86532dfee8d899c7d0256519534de9756e910945 Mon Sep 17 00:00:00 2001 From: Error414 Date: Sun, 8 Nov 2026 21:31:41 +0100 Subject: [PATCH 34/37] DSHOT BIDIR - Stale ESC readings remain marked fresh --- src/main/drivers/dshot/bidir_dshot.c | 19 ++++++++++++++----- src/main/drivers/dshot/bidir_dshot.h | 2 ++ src/main/drivers/dshot/dshot.c | 2 +- src/main/drivers/dshot/dshot_bitbang.c | 2 +- src/main/sensors/esc_sensor.c | 11 ++++++----- 5 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/main/drivers/dshot/bidir_dshot.c b/src/main/drivers/dshot/bidir_dshot.c index b511263ac4c..828ce58e366 100644 --- a/src/main/drivers/dshot/bidir_dshot.c +++ b/src/main/drivers/dshot/bidir_dshot.c @@ -140,14 +140,20 @@ uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex) return rawValue; } +// lastErpmMs starts at 0, so this is also false before the first eRPM frame (an EDT frame may +// come first); the first DSHOT frame goes out long after the first DSHOT_ERPM_TIMEOUT_MS of boot +bool isDshotMotorTelemetryFresh(uint8_t motorIndex) +{ + return millis() - motorTelemetry[motorIndex].lastErpmMs <= DSHOT_ERPM_TIMEOUT_MS; +} + float getMotorFrequencyHz(uint8_t motorIndex) { - const dshotTelemetryMotorState_t *state = &motorTelemetry[motorIndex]; - if (millis() - state->lastErpmMs > DSHOT_ERPM_TIMEOUT_MS) { + if (!isDshotMotorTelemetryFresh(motorIndex)) { return 0.0f; } - return state->telemetryData[DSHOT_TELEMETRY_TYPE_ERPM] * erpmToHz; + return motorTelemetry[motorIndex].telemetryData[DSHOT_TELEMETRY_TYPE_ERPM] * erpmToHz; } float getDshotRpm(uint8_t motorIndex) @@ -161,11 +167,14 @@ bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex) return false; } - const dshotTelemetryMotorState_t *state = &motorTelemetry[motorIndex]; - if ((state->telemetryTypes & (1 << DSHOT_TELEMETRY_TYPE_ERPM)) == 0) { + // Not the sticky ERPM bit of telemetryTypes: once eRPM has timed out, an EDT frame must not + // hand the ESC sensor a timed-out RPM and the old values as fresh data + if (!isDshotMotorTelemetryFresh(motorIndex)) { return false; } + const dshotTelemetryMotorState_t *state = &motorTelemetry[motorIndex]; + // escSensorData_t units: rpm (mechanical), degrees C, 0.01 V, 0.01 A. EDT reports // the temperature in degrees C, the voltage in 0.25 V and the current in 1 A steps. data->rpm = lrintf(getDshotRpm(motorIndex)); diff --git a/src/main/drivers/dshot/bidir_dshot.h b/src/main/drivers/dshot/bidir_dshot.h index 4ecdd37115e..867837ad85f 100644 --- a/src/main/drivers/dshot/bidir_dshot.h +++ b/src/main/drivers/dshot/bidir_dshot.h @@ -59,6 +59,8 @@ void initDshotTelemetry(void); bool isDshotTelemetryActive(void); uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex); float getDshotRpm(uint8_t motorIndex); +// True while the motor's last eRPM frame is within the timeout; EDT frames do not count +bool isDshotMotorTelemetryFresh(uint8_t motorIndex); // Mechanical frequency from the last decoded eRPM frame, unfiltered (see bidir_dshot.c); 0 once it is stale float getMotorFrequencyHz(uint8_t motorIndex); bool getDshotEscSensorData(escSensorData_t *data, uint8_t motorIndex); diff --git a/src/main/drivers/dshot/dshot.c b/src/main/drivers/dshot/dshot.c index 2f8d84c1e16..e6d6e360c64 100644 --- a/src/main/drivers/dshot/dshot.c +++ b/src/main/drivers/dshot/dshot.c @@ -558,7 +558,7 @@ static bool NOINLINE dshotDecodeTelemetry(void) const uint16_t processed = dshotProcessPacket(rawValue, motorIndex); if (processed != DSHOT_TELEMETRY_INVALID && processed != DSHOT_TELEMETRY_NOEDGE) { #ifdef USE_ESC_SENSOR - // Nothing to publish before the first eRPM value (an EDT frame may come first) + // Nothing to publish without a fresh eRPM value (an EDT frame may come first, or outlive it) escSensorData_t data; if (getDshotEscSensorData(&data, motorIndex)) { escSensorSetDshotData(motorIndex, data.rpm, data.temperature, data.voltage, data.current); diff --git a/src/main/drivers/dshot/dshot_bitbang.c b/src/main/drivers/dshot/dshot_bitbang.c index 7800ba3b587..3c8c75a4418 100644 --- a/src/main/drivers/dshot/dshot_bitbang.c +++ b/src/main/drivers/dshot/dshot_bitbang.c @@ -810,7 +810,7 @@ bool dshotBitbangDecodeTelemetry(void) const uint16_t processed = dshotProcessPacket(rawValue, motorIndex); if (processed != DSHOT_TELEMETRY_INVALID && processed != DSHOT_TELEMETRY_NOEDGE) { #ifdef USE_ESC_SENSOR - // Nothing to publish before the first eRPM value (an EDT frame may come first) + // Nothing to publish without a fresh eRPM value (an EDT frame may come first, or outlive it) escSensorData_t data; if (getDshotEscSensorData(&data, motorIndex)) { escSensorSetDshotData(motorIndex, data.rpm, data.temperature, data.voltage, data.current); diff --git a/src/main/sensors/esc_sensor.c b/src/main/sensors/esc_sensor.c index 4b250bf9a99..ad64e455955 100644 --- a/src/main/sensors/esc_sensor.c +++ b/src/main/sensors/esc_sensor.c @@ -332,15 +332,16 @@ void escSensorUpdate(timeUs_t currentTimeUs) { #ifdef USE_DSHOT_BIDIR if (isDshotTelemetryActive()) { - // The motor driver refreshes the data with every decoded frame. Age it at the serial - // poll rate, so a silent ESC drops out of the combined values the same way (the serial - // poll timer doubles as the aging clock, nothing polls here) + // The motor driver refreshes the data with every decoded frame and knows when an ESC + // went silent, so there is no poll to age by: an ESC whose eRPM timed out leaves the + // combined values until it replies again. Checked at the serial poll rate (the poll + // timer doubles as the clock), since this runs from the busy loop const timeMs_t currentTimeMs = currentTimeUs / 1000; if (currentTimeMs - escTriggerTimeMs >= ESC_REQUEST_TIMEOUT_MS) { escTriggerTimeMs = currentTimeMs; for (int i = 0; i < MAX_SUPPORTED_MOTORS; i++) { - if (escSensorData[i].dataAge < ESC_DATA_INVALID) { - escSensorData[i].dataAge++; + if (escSensorData[i].dataAge < ESC_DATA_INVALID && !isDshotMotorTelemetryFresh(i)) { + escSensorData[i].dataAge = ESC_DATA_INVALID; escSensorDataNeedsUpdate = true; } } From ba4d2c73a63054ff9a7c21d2ce4e203067d59d01 Mon Sep 17 00:00:00 2001 From: Error414 Date: Sun, 8 Nov 2026 21:58:03 +0100 Subject: [PATCH 35/37] DSHOT BIDIR - Silent ESC replies appear unmeasured --- docs/development/msp/README.md | 6 ++-- docs/development/msp/msp_messages.json | 6 ++-- src/main/drivers/dshot/bidir_dshot.c | 35 +++++++++++++++++-- src/main/drivers/dshot/bidir_dshot.h | 4 +++ src/main/drivers/dshot/dshot.c | 22 ++---------- src/main/drivers/dshot/dshot_bitbang_decode.c | 29 +-------------- src/main/fc/fc_msp.c | 5 +-- 7 files changed, 48 insertions(+), 59 deletions(-) diff --git a/docs/development/msp/README.md b/docs/development/msp/README.md index 4c5fcf89b5f..031a9dda9d7 100644 --- a/docs/development/msp/README.md +++ b/docs/development/msp/README.md @@ -4188,10 +4188,10 @@ When the MSP JSON specification changes, bump `msp_messages.json` version: |Field|C Type|Size (Bytes)|Units|Description| |---|---|---|---|---| | `escRpm` | `uint32_t` | 4 | RPM | RPM reported by the ESC | -| `frameSuccess` | `uint8_t` | 1 | % | Share of telemetry replies decoded in the last closed window. 255 when no reply was expected in that window | -| `frameTotal` | `uint16_t` | 2 | frames | Telemetry replies expected in the last closed window, missing ones included | +| `frameSuccess` | `uint8_t` | 1 | % | Share of the counted telemetry replies that decoded in the last closed window. 255 when nothing was counted in that window | +| `frameTotal` | `uint16_t` | 2 | frames | Telemetry replies counted in the last closed window. Serial ESC telemetry: one per request, a missing reply included. Bidirectional DSHOT: only replies that reached the capture, a missing reply is not counted | -**Notes:** Requires `USE_ESC_SENSOR` or `USE_DSHOT_BIDIR`. 7 bytes per motor, `getMotorCount()` entries. Source follows the RPM filter: bidirectional DSHOT when `isDshotTelemetryActive()`, serial ESC telemetry otherwise. The frame statistics come from fixed back-to-back windows of `ESC_FRAME_WINDOW_MS` (1 s), so they change once per window. A reply counts as missing when the ESC stays silent, fails CRC/GCR decoding or (serial) times out. Sources without frame counting (SRXL2) always report 255 / 0. +**Notes:** Requires `USE_ESC_SENSOR` or `USE_DSHOT_BIDIR`. 7 bytes per motor, `getMotorCount()` entries. Source follows the RPM filter: bidirectional DSHOT when `isDshotTelemetryActive()`, serial ESC telemetry otherwise. The frame statistics come from fixed back-to-back windows of `ESC_FRAME_WINDOW_MS` (1 s), so they change once per window. A counted reply fails when it does not pass CRC/GCR decoding or (serial) times out. Bidirectional DSHOT counts only replies that were at least partly captured, as Betaflight does, since an ESC may skip replies when busy; an ESC that never replies therefore reports 255 / 0, the same as a source without frame counting (SRXL2). ## `MSP2_INAV_ESC_TELEM (8257 / 0x2041)` **Description:** Retrieves the full telemetry data structure reported by each ESC. diff --git a/docs/development/msp/msp_messages.json b/docs/development/msp/msp_messages.json index 0f69ef03788..6c116ee0d54 100644 --- a/docs/development/msp/msp_messages.json +++ b/docs/development/msp/msp_messages.json @@ -9851,20 +9851,20 @@ { "name": "frameSuccess", "ctype": "uint8_t", - "desc": "Share of telemetry replies decoded in the last closed window. 255 when no reply was expected in that window", + "desc": "Share of the counted telemetry replies that decoded in the last closed window. 255 when nothing was counted in that window", "units": "%" }, { "name": "frameTotal", "ctype": "uint16_t", - "desc": "Telemetry replies expected in the last closed window, missing ones included", + "desc": "Telemetry replies counted in the last closed window. Serial ESC telemetry: one per request, a missing reply included. Bidirectional DSHOT: only replies that reached the capture, a missing reply is not counted", "units": "frames" } ], "repeating": "getMotorCount()" }, "variable_len": "getMotorCount()", - "notes": "Requires `USE_ESC_SENSOR` or `USE_DSHOT_BIDIR`. 7 bytes per motor, `getMotorCount()` entries. Source follows the RPM filter: bidirectional DSHOT when `isDshotTelemetryActive()`, serial ESC telemetry otherwise. The frame statistics come from fixed back-to-back windows of `ESC_FRAME_WINDOW_MS` (1 s), so they change once per window. A reply counts as missing when the ESC stays silent, fails CRC/GCR decoding or (serial) times out. Sources without frame counting (SRXL2) always report 255 / 0.", + "notes": "Requires `USE_ESC_SENSOR` or `USE_DSHOT_BIDIR`. 7 bytes per motor, `getMotorCount()` entries. Source follows the RPM filter: bidirectional DSHOT when `isDshotTelemetryActive()`, serial ESC telemetry otherwise. The frame statistics come from fixed back-to-back windows of `ESC_FRAME_WINDOW_MS` (1 s), so they change once per window. A counted reply fails when it does not pass CRC/GCR decoding or (serial) times out. Bidirectional DSHOT counts only replies that were at least partly captured, as Betaflight does, since an ESC may skip replies when busy; an ESC that never replies therefore reports 255 / 0, the same as a source without frame counting (SRXL2).", "description": "Retrieves the RPM and telemetry link quality reported by each ESC." }, "MSP2_INAV_ESC_TELEM": { diff --git a/src/main/drivers/dshot/bidir_dshot.c b/src/main/drivers/dshot/bidir_dshot.c index 828ce58e366..6bcd808bbe0 100644 --- a/src/main/drivers/dshot/bidir_dshot.c +++ b/src/main/drivers/dshot/bidir_dshot.c @@ -24,9 +24,10 @@ #include "platform.h" #include "drivers/dshot/bidir_dshot.h" -// Bidirectional DSHOT telemetry only: eRPM / EDT decoding, RPM state for the RPM filter and -// the ESC sensor. Frame generation, DMA and DSHOT commands for plain DSHOT live in -// dshot.c under USE_DSHOT. Every user of this API is guarded by USE_DSHOT_BIDIR. +// Bidirectional DSHOT telemetry only: GCR symbol decoding shared by the timer and bitbang +// capture paths, eRPM / EDT decoding, RPM state for the RPM filter and the ESC sensor. Frame +// generation, DMA and DSHOT commands for plain DSHOT live in dshot.c under USE_DSHOT. Every +// user of this API is guarded by USE_DSHOT_BIDIR. // // Values are published as decoded, unfiltered: frames arrive at the DSHOT frame rate, which // follows the scheduler's idle time rather than any fixed period, so smoothing belongs to the @@ -55,6 +56,34 @@ bool useDshotTelemetry = false; static dshotTelemetryMotorState_t motorTelemetry[MAX_SUPPORTED_MOTORS]; static float erpmToHz; +uint16_t dshotDecodeGcr(uint32_t value) +{ + // An invalid quintet must fail the frame by itself (as in Betaflight's bitbang decoder, + // its timer decoder maps them to 0): with 0 a frame with two damaged quintets passes + // whenever the nibbles happen to XOR to 0xf, and the checksum alone misses one in sixteen +#define iv 0xffffffff + value &= 0xfffff; + static const uint32_t decode[32] = { + iv, iv, iv, iv, iv, iv, iv, iv, iv, 9, 10, 11, iv, 13, 14, 15, + iv, iv, 2, 3, iv, 5, 6, 7, iv, 0, 8, 1, iv, 4, 12, iv }; +#undef iv + + uint32_t decodedValue = decode[value & 0x1f]; + decodedValue |= decode[(value >> 5) & 0x1f] << 4; + decodedValue |= decode[(value >> 10) & 0x1f] << 8; + decodedValue |= decode[(value >> 15) & 0x1f] << 12; + + uint32_t csum = decodedValue; + csum = csum ^ (csum >> 8); // xor bytes + csum = csum ^ (csum >> 4); // xor nibbles + + if ((csum & 0xf) != 0xf || decodedValue > 0xffff) { + return DSHOT_TELEMETRY_INVALID; + } + + return decodedValue >> 4; +} + static uint32_t dshotDecodeErpmTelemetryValue(uint16_t value) { if (value == 0x0fff) { diff --git a/src/main/drivers/dshot/bidir_dshot.h b/src/main/drivers/dshot/bidir_dshot.h index 867837ad85f..fb2b5be76e9 100644 --- a/src/main/drivers/dshot/bidir_dshot.h +++ b/src/main/drivers/dshot/bidir_dshot.h @@ -57,6 +57,10 @@ extern bool useDshotTelemetry; void initDshotTelemetry(void); bool isDshotTelemetryActive(void); +// The 21 GCR bits of a reply (start bit on top, each run of the line packed as 1000...) to the +// 16-bit telemetry value without its checksum; DSHOT_TELEMETRY_INVALID for a quintet that is +// no GCR symbol or a failed checksum +uint16_t dshotDecodeGcr(uint32_t value); uint16_t dshotProcessPacket(uint16_t rawValue, uint8_t motorIndex); float getDshotRpm(uint8_t motorIndex); // True while the motor's last eRPM frame is within the timeout; EDT frames do not count diff --git a/src/main/drivers/dshot/dshot.c b/src/main/drivers/dshot/dshot.c index e6d6e360c64..e116a9e66c8 100644 --- a/src/main/drivers/dshot/dshot.c +++ b/src/main/drivers/dshot/dshot.c @@ -306,7 +306,7 @@ static dshotChannelRegs_t dshotChannelRegs(const dshotMotor_t *motor) // CCER channel nibble for capture: both edges, channel on #define DSHOT_CCER_INPUT (TIM_CCER_CC1E | TIM_CCER_CC1P | TIM_CCER_CC1NP) -// GCR decode algorithm ported from Betaflight (GPLv3) +// Edge timestamps to GCR bits, ported from Betaflight (GPLv3); the symbols are decoded in bidir_dshot.c static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t count) { uint32_t value = 0; @@ -345,25 +345,7 @@ static uint16_t dshotDecodeTelemetryPacket(const uint32_t buffer[], uint32_t cou return DSHOT_TELEMETRY_INVALID; } - static const uint32_t decode[32] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 0, 13, 14, 15, - 0, 0, 2, 3, 0, 5, 6, 7, 0, 0, 8, 1, 0, 4, 12, 0 - }; - - uint32_t decodedValue = decode[value & 0x1f]; - decodedValue |= decode[(value >> 5) & 0x1f] << 4; - decodedValue |= decode[(value >> 10) & 0x1f] << 8; - decodedValue |= decode[(value >> 15) & 0x1f] << 12; - - uint32_t csum = decodedValue; - csum ^= csum >> 8; - csum ^= csum >> 4; - - if ((csum & 0xf) != 0xf) { - return DSHOT_TELEMETRY_INVALID; - } - - return decodedValue >> 4; + return dshotDecodeGcr(value); } static void dshotSetDirectionOutput(dshotMotor_t *motor) diff --git a/src/main/drivers/dshot/dshot_bitbang_decode.c b/src/main/drivers/dshot/dshot_bitbang_decode.c index 3ccf102573c..370867c03ac 100644 --- a/src/main/drivers/dshot/dshot_bitbang_decode.c +++ b/src/main/drivers/dshot/dshot_bitbang_decode.c @@ -51,33 +51,6 @@ static uint32_t minMargin = UINT32_MAX; static timeUs_t nextMarginCheckUs = 0; static uint32_t preambleSkip = 0; -// The GCR run lengths were packed MSB first into value as 1000... groups; strip the start -// bit, map the four GCR quintets to nibbles and verify the checksum -static uint32_t decodeGcrValue(uint32_t value) -{ -#define iv 0xffffffff - value &= 0xfffff; - static const uint32_t decode[32] = { - iv, iv, iv, iv, iv, iv, iv, iv, iv, 9, 10, 11, iv, 13, 14, 15, - iv, iv, 2, 3, iv, 5, 6, 7, iv, 0, 8, 1, iv, 4, 12, iv }; -#undef iv - - uint32_t decodedValue = decode[value & 0x1f]; - decodedValue |= decode[(value >> 5) & 0x1f] << 4; - decodedValue |= decode[(value >> 10) & 0x1f] << 8; - decodedValue |= decode[(value >> 15) & 0x1f] << 12; - - uint32_t csum = decodedValue; - csum = csum ^ (csum >> 8); // xor bytes - csum = csum ^ (csum >> 4); // xor nibbles - - if ((csum & 0xf) != 0xf || decodedValue > 0xffff) { - return DSHOT_TELEMETRY_INVALID; - } - - return decodedValue >> 4; -} - uint32_t dshotBitbangDecode(const uint16_t *buffer, uint32_t count, uint32_t bit, bool idleHigh) { const timeUs_t now = micros(); @@ -180,7 +153,7 @@ uint32_t dshotBitbangDecode(const uint16_t *buffer, uint32_t count, uint32_t bit value |= 1 << (nlen - 1); } - return decodeGcrValue(value); + return dshotDecodeGcr(value); } #endif // USE_DSHOT_BITBANG diff --git a/src/main/fc/fc_msp.c b/src/main/fc/fc_msp.c index f619cfa45df..81a9d5675a6 100644 --- a/src/main/fc/fc_msp.c +++ b/src/main/fc/fc_msp.c @@ -1980,8 +1980,9 @@ static bool mspFcProcessOutCommand(uint16_t cmdMSP, sbuf_t *dst, mspPostProcessF #endif } sbufWriteU32(dst, rpm); - // Link quality of the last closed window; 255 when no reply was expected in it - // (boot, no telemetry source, a source without frame counting such as SRXL2) + // Link quality of the last closed window; 255 when nothing was counted in it + // (boot, no telemetry source, a source without frame counting such as SRXL2, + // a bidir DSHOT ESC that never replies: those windows are not counted) const escFrameCounter_t *frames = escSensorFrameCounter(i); const bool framesKnown = frames->lastWindowTotal > 0; sbufWriteU8(dst, framesKnown ? frames->lastWindowSuccess : 255); From 38d0de59190258f0b477bee6ca7e6c50ca9fd332 Mon Sep 17 00:00:00 2001 From: Error414 Date: Sun, 22 Nov 2026 17:43:27 +0100 Subject: [PATCH 36/37] DSHOT BIDIR - move settings to end of config structs --- src/main/flight/mixer.c | 6 +++--- src/main/flight/mixer.h | 10 ++++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/main/flight/mixer.c b/src/main/flight/mixer.c index 0ec3ac21994..06928b4817b 100644 --- a/src/main/flight/mixer.c +++ b/src/main/flight/mixer.c @@ -89,13 +89,11 @@ PG_RESET_TEMPLATE(reversibleMotorsConfig_t, reversibleMotorsConfig, .neutral = SETTING_3D_NEUTRAL_DEFAULT ); -PG_REGISTER_WITH_RESET_TEMPLATE(motorConfig_t, motorConfig, PG_MOTOR_CONFIG, 12); +PG_REGISTER_WITH_RESET_TEMPLATE(motorConfig_t, motorConfig, PG_MOTOR_CONFIG, 11); PG_RESET_TEMPLATE(motorConfig_t, motorConfig, .motorPwmProtocol = SETTING_MOTOR_PWM_PROTOCOL_DEFAULT, .motorPwmRate = SETTING_MOTOR_PWM_RATE_DEFAULT, - .useDshotTelemetry = 0, - .useDshotEdt = 0, .mincommand = SETTING_MIN_COMMAND_DEFAULT, .motorPoleCount = SETTING_MOTOR_POLES_DEFAULT, // Most brushless motors that we use are 14 poles #ifdef USE_MOTOR_SRXL2 @@ -103,6 +101,8 @@ PG_RESET_TEMPLATE(motorConfig_t, motorConfig, .srxl2TelemetryRate = SETTING_ESC_SRXL2_TELEMETRY_RATE_DEFAULT, .srxl2Telemetry = SETTING_ESC_SRXL2_TELEMETRY_DEFAULT, #endif + .useDshotTelemetry = 0, // must stay 0, see motorConfig_t + .useDshotEdt = 0, // must stay 0, see motorConfig_t ); PG_REGISTER_ARRAY_WITH_RESET_FN(timerOverride_t, HARDWARE_TIMER_DEFINITION_COUNT, timerOverrides, PG_TIMER_OVERRIDE_CONFIG, 0); diff --git a/src/main/flight/mixer.h b/src/main/flight/mixer.h index d11fe1ae3af..18f2c0e8991 100644 --- a/src/main/flight/mixer.h +++ b/src/main/flight/mixer.h @@ -93,8 +93,6 @@ typedef struct motorConfig_s { uint16_t mincommand; // This is the value for the ESCs when they are not armed. In some cases, this value must be lowered down to 900 for some specific ESCs uint16_t motorPwmRate; // The update rate of motor outputs (50-498Hz) uint8_t motorPwmProtocol; - uint8_t useDshotTelemetry; - uint8_t useDshotEdt; uint16_t digitalIdleOffsetValue; uint8_t motorPoleCount; // Magnetic poles in the motors for calculating actual RPM from eRPM provided by ESC telemetry #ifdef USE_MOTOR_SRXL2 @@ -123,6 +121,14 @@ typedef struct motorConfig_s { uint8_t srxl2Telemetry; // read ESC telemetry off the SRXL2 link uint8_t srxl2TelemetryRate; // how often to ask the ESC for telemetry, as srxl2TelemetryRate_e #endif + /* + * Appended without a parameter group version bump. The first of these lands + * on the tail padding byte of the older record, which older configurations + * stored as zero (see above). That is harmless only because both default to + * 0 (off): a field added here with a non-zero default needs a pad byte first. + */ + uint8_t useDshotTelemetry; // bidirectional DSHOT (eRPM telemetry on the motor line) + uint8_t useDshotEdt; // extended DSHOT telemetry (temperature, voltage, current) } motorConfig_t; PG_DECLARE(motorConfig_t, motorConfig); From ef25528a0dc18accaa6b9c8b66652d2a9b25f98b Mon Sep 17 00:00:00 2001 From: Error414 Date: Fri, 27 Nov 2026 20:16:15 +0100 Subject: [PATCH 37/37] DSHOT BIDIR - fix wrong merge --- src/main/drivers/dma.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/drivers/dma.h b/src/main/drivers/dma.h index 94c626d3697..f91a1fe7cd3 100644 --- a/src/main/drivers/dma.h +++ b/src/main/drivers/dma.h @@ -135,6 +135,9 @@ DMA_t dmaGetByRef(const DMA_Stream_TypeDef * ref); DMA_t dmaGetByRef(const dma_channel_type * ref); void dmaMuxEnable(DMA_t dma, uint32_t dmaMuxid); +// Walks the channel table; NULL past its end. Any channel serves any peripheral through +// the DMAMUX, so a user without a fixed assignment can take whichever is still free. +DMA_t dmaGetByIndex(unsigned index); #endif