DShotRMT/DShotRMT.cpp

448 lines
12 KiB
C++
Raw Normal View History

/**
* @file DShotRMT.cpp
2025-07-30 23:36:58 +01:00
* @brief DShot signal generation using ESP32 RMT with bidirectional support
* @author Wastl Kraus
* @date 2025-06-11
* @license MIT
*/
2021-07-04 02:01:26 +01:00
2025-07-30 23:36:58 +01:00
#include "DShotRMT.h"
#include <driver/rmt_tx.h>
2025-07-30 23:36:58 +01:00
// Timing parameters for each DShot mode
// Format: {frame_length_us, ticks_per_bit, ticks_one_high, ticks_one_low, ticks_zero_high, ticks_zero_low}
constexpr dshot_timing_t DSHOT_TIMINGS[] = {
2025-07-30 23:36:58 +01:00
{0, 0, 0, 0, 0, 0}, // DSHOT_OFF
{128, 64, 48, 16, 24, 40}, // DSHOT150
{64, 32, 24, 8, 12, 20}, // DSHOT300
{32, 16, 12, 4, 6, 10}, // DSHOT600
{16, 8, 6, 2, 3, 5} // DSHOT1200
2025-07-30 23:36:58 +01:00
};
2025-08-30 23:21:03 +01:00
// Primary constructor with GPIO number
DShotRMT::DShotRMT(gpio_num_t gpio, dshot_mode_t mode, bool is_bidirectional)
: _gpio(gpio),
_mode(mode),
_is_bidirectional(is_bidirectional),
_timing_config(DSHOT_TIMINGS[mode]),
_rmt_tx_channel(nullptr),
_rmt_rx_channel(nullptr),
_dshot_encoder(nullptr),
_last_erpm(0),
_parsed_packet(0),
_packet{0},
_last_transmission_time(0)
{
// Calculate frame timing including switch/pause time
_frame_timer_us = _timing_config.frame_length_us + DSHOT_SWITCH_TIME;
// Double frame time for bidirectional mode (includes response time)
2025-07-30 23:36:58 +01:00
if (_is_bidirectional)
{
_frame_timer_us = (_frame_timer_us << 1);
}
}
2025-08-30 23:21:03 +01:00
// Constructor using pin number
DShotRMT::DShotRMT(uint16_t pin_nr, dshot_mode_t mode, bool is_bidirectional)
: DShotRMT((gpio_num_t)pin_nr, mode, is_bidirectional)
2025-08-06 22:57:26 +01:00
{
// Delegates to primary constructor with type cast
2025-08-06 22:57:26 +01:00
}
// Initialize DShotRMT
2025-08-28 13:37:02 +01:00
uint16_t DShotRMT::begin()
2022-11-25 15:08:58 +00:00
{
// Initialize TX channel
2025-07-30 23:36:58 +01:00
if (!_initTXChannel())
2025-06-12 23:45:48 +01:00
{
_dshot_log(TX_INIT_FAILED);
2025-07-30 23:36:58 +01:00
return DSHOT_ERROR;
2025-06-12 23:45:48 +01:00
}
// Initialize RX channel only if bidirectional mode is enabled
2025-07-30 23:36:58 +01:00
if (!_initRXChannel() && _is_bidirectional)
{
_dshot_log(RX_INIT_FAILED);
2025-07-30 23:36:58 +01:00
return DSHOT_ERROR;
}
2025-07-29 23:40:09 +01:00
// Initialize DShot encoder
2025-07-30 23:36:58 +01:00
if (!_initDShotEncoder())
{
2025-07-30 23:36:58 +01:00
return DSHOT_ERROR;
}
2025-08-30 23:21:03 +01:00
return DSHOT_OK;
}
// Initialize RMT TX channel
bool DShotRMT::_initTXChannel()
{
// Configure TX channel
_tx_channel_config.gpio_num = _gpio;
_tx_channel_config.clk_src = DSHOT_CLOCK_SRC_DEFAULT;
_tx_channel_config.resolution_hz = DSHOT_RMT_RESOLUTION;
_tx_channel_config.mem_block_symbols = TX_BUFFER_SIZE;
_tx_channel_config.trans_queue_depth = RMT_BUFFER_SIZE;
// Configure transmission
_transmit_config.loop_count = 0; // No automatic loops - real-time calculation
_transmit_config.flags.eot_level = _is_bidirectional ? 1 : 0; // Telemetric Bit used as bidir flag
// Create RMT TX channel
if (rmt_new_tx_channel(&_tx_channel_config, &_rmt_tx_channel) != DSHOT_OK)
{
_dshot_log(TX_INIT_FAILED);
return DSHOT_ERROR;
}
return (rmt_enable(_rmt_tx_channel) == DSHOT_OK);
}
// Initialize RMT RX channel
bool DShotRMT::_initRXChannel()
{
// Configure RX channel parameters
_rx_channel_config.gpio_num = _gpio;
_rx_channel_config.clk_src = DSHOT_CLOCK_SRC_DEFAULT;
_rx_channel_config.resolution_hz = DSHOT_RMT_RESOLUTION;
_rx_channel_config.mem_block_symbols = RX_BUFFER_SIZE;
// Configure reception parameters (TODO: determine optimal ranges)
_receive_config.signal_range_min_ns = 2;
_receive_config.signal_range_max_ns = 64;
// Create RMT RX channel
if (rmt_new_rx_channel(&_rx_channel_config, &_rmt_rx_channel) != DSHOT_OK)
{
_dshot_log(RX_INIT_FAILED);
return DSHOT_ERROR;
}
return (rmt_enable(_rmt_rx_channel) == DSHOT_OK);
}
// Initialize DShot encoder
bool DShotRMT::_initDShotEncoder()
{
// Create copy encoder configuration
rmt_copy_encoder_config_t encoder_config = {};
// Create encoder instance
if (rmt_new_copy_encoder(&encoder_config, &_dshot_encoder) != DSHOT_OK)
{
_dshot_log(ENCODER_INIT_FAILED);
return DSHOT_ERROR;
}
2025-07-30 23:36:58 +01:00
return DSHOT_OK;
2021-06-29 19:05:20 +01:00
}
// Send throttle value
2025-08-06 22:57:26 +01:00
bool DShotRMT::sendThrottle(uint16_t throttle)
{
static uint16_t last_throttle = DSHOT_CMD_MOTOR_STOP;
// Special case: if throttle is 0, use sendCommand() instead
if (throttle == 0)
{
return sendCommand(DSHOT_CMD_MOTOR_STOP);
}
2025-08-30 23:21:03 +01:00
// Log only if throttle is out of range and different from last time
if ((throttle < DSHOT_THROTTLE_MIN || throttle > DSHOT_THROTTLE_MAX) && throttle != last_throttle)
{
_dshot_log(THROTTLE_NOT_IN_RANGE);
}
2025-08-06 22:57:26 +01:00
2025-08-30 23:21:03 +01:00
// Always store the original throttle value
last_throttle = throttle;
2021-06-29 19:05:20 +01:00
// Constrain throttle for transmission and send
uint16_t transmission_throttle = constrain(throttle, DSHOT_THROTTLE_MIN, DSHOT_THROTTLE_MAX);
_packet = _buildDShotPacket(transmission_throttle);
return _sendDShotFrame(_packet);
2025-08-06 22:57:26 +01:00
}
// Send DShot command to ESC
2025-08-06 22:57:26 +01:00
bool DShotRMT::sendCommand(uint16_t command)
{
// Validate command is within DShot specification range
2025-08-05 00:43:19 +01:00
if (command < DSHOT_CMD_MOTOR_STOP || command > DSHOT_CMD_MAX)
2025-08-02 16:20:32 +01:00
{
_dshot_log(COMMAND_NOT_VALID);
2025-08-02 16:20:32 +01:00
return DSHOT_ERROR;
}
2025-08-05 21:01:00 +01:00
// Build packet and transmit
2025-08-06 22:57:26 +01:00
_packet = _buildDShotPacket(command);
return _sendDShotFrame(_packet);
2025-08-02 16:20:32 +01:00
}
// Get RPM from ESC (bidirectional mode only)
2025-08-05 23:32:03 +01:00
uint16_t DShotRMT::getERPM()
{
// Check if bidirectional mode is enabled
2025-07-30 23:36:58 +01:00
if (!_is_bidirectional || !_rmt_rx_channel)
2025-06-14 17:16:45 +01:00
{
_dshot_log(BIDIR_NOT_ENABLED);
return _last_erpm; // Return cached value
2025-07-30 23:36:58 +01:00
}
2025-06-13 20:50:00 +01:00
// Attempt to receive telemetry data
if (!rmt_receive(_rmt_rx_channel, _rx_symbols, TX_BUFFER_SIZE, &_receive_config))
2025-07-30 23:36:58 +01:00
{
_dshot_log(RX_RMT_MODULE_ERROR);
return _last_erpm;
2025-06-14 17:16:45 +01:00
}
// Decode telemetry frame
2025-08-05 23:32:03 +01:00
uint16_t new_erpm = _decodeDShotFrame(_rx_symbols);
2025-07-30 23:36:58 +01:00
if (new_erpm != 0)
{
_last_erpm = new_erpm;
}
2025-06-13 20:50:00 +01:00
return _last_erpm;
}
2025-08-30 23:21:03 +01:00
// Convert eRPM to actual motor RPM
2025-06-14 17:16:45 +01:00
uint32_t DShotRMT::getMotorRPM(uint8_t magnet_count)
{
2025-07-30 23:36:58 +01:00
uint8_t pole_pairs = max(1, magnet_count / 2);
return getERPM() / pole_pairs;
}
2025-08-30 23:21:03 +01:00
// Build a complete DShot packet
dshot_packet_t DShotRMT::_buildDShotPacket(const uint16_t value)
2025-07-30 23:36:58 +01:00
{
2025-08-30 23:21:03 +01:00
// Initialize packet structure
dshot_packet_t packet = {};
2025-06-14 17:16:45 +01:00
2025-08-30 23:21:03 +01:00
// Build packet
packet.throttle_value = value;
packet.telemetric_request = _is_bidirectional ? 1 : 0;
packet.checksum = _calculateCRC(packet);
2025-07-30 23:36:58 +01:00
2025-08-30 23:21:03 +01:00
return packet;
2025-06-14 17:16:45 +01:00
}
2025-08-30 23:21:03 +01:00
// Parse DShot packet into 16-bit format
uint16_t DShotRMT::_parseDShotPacket(const dshot_packet_t &packet)
{
2025-08-30 23:21:03 +01:00
uint16_t data = (packet.throttle_value << 1) | packet.telemetric_request;
2025-07-29 23:40:09 +01:00
2025-08-30 23:21:03 +01:00
// Add CRC checksum
return (data << 4) | _calculateCRC(packet);
}
2025-08-30 23:21:03 +01:00
// Calculate CRC checksum
uint16_t DShotRMT::_calculateCRC(const dshot_packet_t &packet)
{
2025-08-30 23:21:03 +01:00
uint16_t data = (packet.throttle_value << 1) | packet.telemetric_request;
2025-08-30 23:21:03 +01:00
// DShot CRC calculation
uint16_t crc = (data ^ (data >> 4) ^ (data >> 8)) & 0b0000000000001111;
// Invert CRC for bidirectional DShot mode
if (_is_bidirectional)
{
2025-08-30 23:21:03 +01:00
crc = (~crc) & 0b0000000000001111;
}
2025-08-30 23:21:03 +01:00
return crc;
}
// Transmit DShot packet via RMT
uint16_t DShotRMT::_sendDShotFrame(const dshot_packet_t &packet)
2025-06-13 20:50:00 +01:00
{
2025-08-30 23:21:03 +01:00
// Check timing requirements
if (!_timer_signal())
{
return DSHOT_ERROR;
}
// Encode DShot packet into RMT symbols
2025-08-18 21:11:32 +01:00
_encodeDShotFrame(packet, _tx_symbols);
2025-08-05 23:32:03 +01:00
// Calculate transmission data size
size_t tx_size_bytes = DSHOT_BITS_PER_FRAME * sizeof(rmt_symbol_word_t);
2025-08-30 23:21:03 +01:00
// Perform RMT transmission
uint16_t result = rmt_transmit(_rmt_tx_channel, _dshot_encoder, _tx_symbols, tx_size_bytes, &_transmit_config);
2025-08-05 23:32:03 +01:00
if (result != DSHOT_OK)
{
return DSHOT_ERROR;
2025-07-30 23:36:58 +01:00
}
2025-07-29 23:40:09 +01:00
// Update timestamp
_timer_reset();
return DSHOT_OK;
2025-07-30 23:36:58 +01:00
}
// Encode DShot packet into RMT symbol format (placed in IRAM for performance)
bool DShotRMT::_encodeDShotFrame(const dshot_packet_t &packet, rmt_symbol_word_t *symbols)
2025-07-30 23:36:58 +01:00
{
2025-08-30 23:21:03 +01:00
// Parse packet to 16-bit format
_parsed_packet = _parseDShotPacket(packet);
// Convert each bit to RMT symbol
for (int i = 0; i < DSHOT_BITS_PER_FRAME; i++)
{
// Extract bit from packet
bool bit = (_parsed_packet >> (DSHOT_BITS_PER_FRAME - 1 - i)) & 0b0000000000000001;
if (_is_bidirectional)
{
// Bidirectional DShot uses inverted levels - Idle HIGH
symbols[i].level0 = 0;
symbols[i].duration0 = bit ? _timing_config.ticks_one_high : _timing_config.ticks_zero_high;
symbols[i].level1 = 1;
symbols[i].duration1 = bit ? _timing_config.ticks_one_low : _timing_config.ticks_zero_low;
}
else
2025-07-31 12:16:58 +01:00
{
// Standard DShot levels - Idle LOW
symbols[i].level0 = 1;
symbols[i].duration0 = bit ? _timing_config.ticks_one_high : _timing_config.ticks_zero_high;
symbols[i].level1 = 0;
symbols[i].duration1 = bit ? _timing_config.ticks_one_low : _timing_config.ticks_zero_low;
}
2023-04-15 06:45:14 +01:00
}
return DSHOT_OK;
2021-06-29 19:05:20 +01:00
}
// Decode received RMT symbols
2025-08-05 23:32:03 +01:00
uint16_t DShotRMT::_decodeDShotFrame(const rmt_symbol_word_t *symbols)
{
2025-07-30 23:36:58 +01:00
uint16_t received_frame = 0;
// Reconstruct frame from RMT symbols
2025-07-30 23:36:58 +01:00
for (size_t i = 0; i < DSHOT_BITS_PER_FRAME; ++i)
{
// Determine bit value based on pulse duration comparison
2025-08-28 13:37:02 +01:00
bool bit = symbols[i].duration0 > symbols[i].duration1;
received_frame = (received_frame << 1) | bit;
}
2025-08-30 23:21:03 +01:00
// Extract data and CRC from received frame
2025-07-30 23:36:58 +01:00
uint16_t data = received_frame >> 4;
2025-08-05 23:32:03 +01:00
uint16_t received_crc = received_frame & 0b0000000000001111;
// Calculate expected CRC
2025-08-05 23:32:03 +01:00
uint16_t calculated_crc = (data ^ (data >> 4) ^ (data >> 8)) & 0b0000000000001111;
2025-07-30 23:36:58 +01:00
if (_is_bidirectional)
{
calculated_crc = (~calculated_crc) & 0b0000000000001111; // Invert for bidirectional
2025-07-30 23:36:58 +01:00
}
// Validate CRC
2025-07-30 23:36:58 +01:00
if (received_crc != calculated_crc)
{
_dshot_log(CRC_CHECK_FAILED);
return DSHOT_NULL_PACKET;
}
// Remove telemetry bit and return 10-bit value
2025-07-30 23:36:58 +01:00
return data >> 1;
}
2025-08-30 23:21:03 +01:00
// Check if enough time has passed for next transmission
bool DShotRMT::_timer_signal()
{
uint32_t current_time = micros();
// Handle potential overflow
uint32_t elapsed = current_time - _last_transmission_time;
return elapsed >= _frame_timer_us;
}
// Reset transmission timer to current time
bool DShotRMT::_timer_reset()
{
_last_transmission_time = micros();
return DSHOT_OK;
}
// Print timing diagnostic information to specified stream
void DShotRMT::printDshotInfo(Stream &output) const
{
output.println(NEW_LINE);
output.println(" === DShot Signal Info === ");
// Current DShot mode
output.printf("Current Mode: DSHOT%d\n",
2025-08-30 23:21:03 +01:00
_mode == DSHOT150 ? 150 :
_mode == DSHOT300 ? 300 :
_mode == DSHOT600 ? 600 :
_mode == DSHOT1200 ? 1200 : 0);
output.printf("Bidirectional: %s\n", _is_bidirectional ? "YES" : "NO");
// Timing Info
output.printf("Frame Length: %u us\n", _timing_config.frame_length_us);
// Packet Info
output.printf("Current Packet: ");
// Print bit by bit
for (int i = 15; i >= 0; --i)
{
if ((_parsed_packet >> i) & 1)
{
output.print("1");
}
else
{
output.print("0");
}
}
output.printf("\n");
output.printf("Current Value: %u\n", _packet.throttle_value);
}
2025-08-30 23:21:03 +01:00
// Print CPU information
void DShotRMT::printCpuInfo(Stream &output) const
{
output.println(NEW_LINE);
output.println(" === CPU Info === ");
output.printf("Chip Model: %s\n", ESP.getChipModel());
output.printf("Chip Revision: %d\n", ESP.getChipRevision());
output.printf("CPU Freq = %lu MHz\n", ESP.getCpuFreqMHz());
output.printf("XTAL Freq = %lu MHz\n", getXtalFrequencyMhz());
output.printf("APB Freq = %lu Hz\n", getApbFrequency());
}
2025-08-30 23:21:03 +01:00
// Print debug values as stream
void DShotRMT::printDebugStream(Stream &output) const
{
2025-08-30 23:21:03 +01:00
// Debug Values as CSV format
output.print(_mode);
output.print(",");
output.print(_is_bidirectional);
output.print(",");
output.print(_packet.throttle_value);
output.print(",");
2025-08-30 23:21:03 +01:00
// The packet bitwise
for (int i = 15; i >= 0; --i)
{
if ((_parsed_packet >> i) & 1)
{
output.print("1");
}
else
{
output.print("0");
}
}
2025-08-30 23:21:03 +01:00
output.print("*/");
output.print("\n");
}