|
HF-TMC51x0 Driver (TMC5130 & TMC5160) 0.1.0-dev
Hardware Agnostic C++ Driver for the TMC51x0 (TMC5130 & TMC5160)
|
C++17 hardware-agnostic driver for Trinamic TMC51x0 stepper motor controllers (TMC5130 & TMC5160) with advanced features
📖 📚🌐 Live Complete Documentation - Interactive guides, examples, and step-by-step tutorials
HF-TMC51x0 is a comprehensive, production-ready C++17 driver for the Trinamic TMC51x0 stepper motor controller ICs (TMC5130 & TMC5160). The TMC51x0 family includes sophisticated stepper motor drivers supporting advanced features including stealthChop for silent operation, spreadCycle for high torque, StallGuard2 for stall detection, and encoder support for closed-loop control.
This driver provides complete feature coverage of all 47 TMC51x0 registers with 100+ public API methods organized into intuitive, well-structured subsystems. It supports multi-chip communication via SPI daisy chaining and UART multi-node addressing, physical unit conversions (mm, degrees, RPM, belt teeth), automatic parameter tuning, sensorless homing, and many other advanced features not found in other TMC51x0 drivers. The driver automatically detects and supports both TMC5130 and TMC5160 chips.
The driver is built with a subsystem-based architecture that organizes functionality into logical groups, making it easy to find and use the features you need:
The driver uses CRTP (Curiously Recurring Template Pattern) for hardware-agnostic communication interfaces, allowing it to run on any platform (ESP32, STM32, Arduino, Raspberry Pi, etc.) with SPI or UART. This design provides zero runtime overhead while maintaining complete platform independence.
The driver targets the entire TMC51x0 family with a single class. Chip-specific features degrade gracefully with ErrorCode::UNSUPPORTED when called on a chip that lacks them.
| Feature | TMC5130 | TMC5160 |
|---|---|---|
| Internal motion controller (ramp gen) | ✅ | ✅ |
| StealthChop2 / SpreadCycle / CoolStep | ✅ | ✅ |
| StallGuard2 sensorless load detection | ✅ | ✅ |
| ABN encoder + index homing | ✅ | ✅ |
| SPI daisy-chain / UART multi-node | ✅ | ✅ |
| Integrated MOSFETs (≤ 2 A_RMS) | ✅ | — |
| External gate driver (≤ 20 A peak) | — | ✅ |
| Higher V_M range | up to 46 V | up to 60 V |
| Short-to-supply / short-to-GND protect | basic | advanced (S2VS / S2G levels) |
| Power-stage configuration (DRV_CONF) | limited | full |
Chip detection is automatic during Initialize(). See docs/tmc5130_support.md for the complete differences list.
driver.status)VerifySetup())driver.stallGuard)driver.tuning)driver.homing)FindBounds())driver.powerStage)driver.status)TMC51x0DaisyChain helper class for easy managementTMC51x0MultiNode helper class for multi-device managementFor a fully-stubbed MySPI template plus daisy-chain, units, and Result<T> patterns, see docs/quickstart.md, docs/platform_integration.md, and the Multi-chip / Units / Error-handling cookbook.
**
Result<T>pattern**: every method returns a lightweightResult<T>carrying either a value or anErrorCode(no exceptions). Check withif (auto r = ...; !r)orr.IsOk(). Full code list andValue()/ValueOr()patterns are in docs/troubleshooting.md. Quick Start above omits checks for brevity — production code should always inspect the result.
For detailed installation instructions, see docs/installation.md.
All methods return
Result<T>types. Check withIsOk()/operator boolbefore usingValue(). See the full API Reference for complete signatures and return types, and docs/troubleshooting.md for the fullErrorCodelist.
The TMC51x0 class is organized into intuitive subsystems for easy access to functionality:
| Method | Description |
|---|---|
SetRampMode() | Set mode: POSITIONING, VELOCITY_POS, VELOCITY_NEG, HOLD |
SetTargetPosition() | Set target position (unit-aware: Steps, Mm, Deg, RPM) |
SetMaxSpeed() | Set maximum velocity (unit-aware) |
SetAcceleration() | Set acceleration/deceleration (unit-aware) |
IsTargetReached() | Check if position target reached |
Stop() | Stop motor immediately |
| Method | Description |
|---|---|
ConfigureReferenceSwitch() | Configure endstops/reference switches |
| Method | Description |
|---|---|
SetModeChangeSpeeds() | Convenience setter for TPWMTHRS/TCOOLTHRS/THIGH |
| Method | Description |
|---|---|
ConfigurePowerStage() | Configure DRV_CONF (power MOSFET drive, BBM, OT) |
ConfigureShortProtection() | Configure SHORT_CONF levels (short protection) |
driver.motorControl)| Method | Description |
|---|---|
Enable() / Disable() | Enable/disable motor driver |
SetCurrent() | Set run and hold currents (IRUN, IHOLD) |
SetStealthChopEnabled() | Enable/disable silent StealthChop mode |
ConfigureChopper() | Configure SpreadCycle chopper settings |
ConfigureStealthChop() | Configure StealthChop PWM settings |
ConfigureMotorCurrent() | Auto-calculate current from motor specs |
driver.stallGuard)| Method | Description |
|---|---|
GetStallGuardResult() | Read StallGuard2 value (0-1023) |
ConfigureStallGuard() | Configure StallGuard2 threshold and filter |
EnableStopOnStall() | Enable/disable automatic stop on stall |
IsStallDetected() | Check if stall event was detected |
driver.status)| Method | Description |
|---|---|
GetStatus() | Get comprehensive driver status struct |
GetGlobalStatus() | Read GSTAT (reset, drv_err, uv_cp) |
IsOpenLoadA() / IsOpenLoadB() | Check for open load conditions |
IsOvertemperature() | Check overtemperature flag |
GetLostSteps() | Read lost steps counter |
VerifySetup() | Run comprehensive startup verification |
driver.tuning)| Method | Description |
|---|---|
AutoTuneStallGuard() | Automatic SGT tuning with current reduction (recommended) |
TuneStallGuard() | SGT tuning with velocity range analysis |
Both return results via StallGuardTuningResult | Optimal SGT, velocity compatibility, achievable velocities |
driver.homing)| Method | Description |
|---|---|
FindBounds() | Find mechanical limits and home (StallGuard, encoder, or switch) |
FindBoundsStallGuard() | Bounds finding using StallGuard2 specifically |
PerformSensorlessHoming() | Single-direction sensorless homing |
PerformSwitchHoming() | Homing using reference switches |
PerformEncoderIndexHoming() | Homing to encoder N-channel index |
driver.encoder)| Method | Description |
|---|---|
Configure() | Configure encoder settings |
SetResolution() | Set motor steps, encoder PPR, invert direction |
SetAllowedDeviation() | Set deviation threshold for step loss detection |
GetPosition() | Read encoder position |
IsDeviationWarning() | Check if deviation threshold exceeded |
driver.powerStage)| Method | Description |
|---|---|
ConfigureShortProtection() | Configure short circuit protection (S2VS, S2G) |
ConfigurePowerStage() | Configure MOSFET drive strength and BBM |
driver.thresholds)| Method | Description |
|---|---|
SetModeChangeSpeeds() | Set StealthChop/CoolStep/high-speed thresholds |
SetStealthChopVelocityThreshold() | Set TPWMTHRS threshold |
SetModeHysteresis() | Configure hysteresis for smooth mode transitions |
driver.communication)| Method | Description |
|---|---|
SetDaisyChainPosition() | Set SPI daisy chain position |
ConfigureUartNodeAddress() | Configure UART node address and send delay |
SetClkFreq() | Set clock frequency |
| Class/Method | Description |
|---|---|
TMC51x0DaisyChain<CommType, MaxDevices> | High-level manager for SPI daisy chaining |
TMC51x0MultiNode<CommType> | High-level manager for UART multi-node addressing |
chain[0], chain[1], ... | Access individual drivers in chain |
| Function | Description |
|---|---|
MmToSteps() / StepsToMm() | Convert between millimeters and steps |
RpmToStepsPerSec() / StepsPerSecToRpm() | Convert between RPM and steps/s |
| Default Units: Velocity functions default to Unit::RevPerSec (revolutions per second) for user-friendly operation | | DegreesToSteps() / StepsToDegrees() | Convert between degrees and steps |
For complete API documentation with all methods and parameters, see docs/api_reference.md.
Comprehensive ESP32 examples are available in examples/esp32/main/, demonstrating all major features. Build and flash using the project scripts (see examples/esp32/README.md).
internal_ramp_comprehensive_test.cpp** – Main test suite covering core init, motor control, ramp control, StealthChop, StallGuard2, encoder, reference switches, diagnostics, and protection in one integrated testinternal_ramp_sinusoidal.cpp** – Back-and-forth positioning with BackAndForthMotion class, configurable via SELECTED_TEST_RIGfatigue_test_espnow/main.cpp** – Production fatigue test: bounds finding, point-to-point motion, ESP-NOW remote control, UART consolestallguard_tuning.cpp** – Automatic StallGuard2 threshold (SGT) tuning with AutoTuneStallGuard()bounds_finding_test.cpp** – Standalone bounds finding: searches for mechanical limits, homes to centerspi_daisy_chain_comprehensive_test.cpp** – SPI daisy chain setup and multi-motor coordination (2+ drivers required)uart_multi_node_comprehensive_test.cpp** – UART multi-node addressing (placeholder implementation)abn_encoder_reader.cpp** – Continuous ABN encoder position readingAll examples use a unified test rig selection (SELECTED_TEST_RIG) for compile-time motor/board/platform configuration. See docs/examples.md for detailed walkthroughs.
Complete Documentation on GitHub Pages
| Guide | Description |
|---|---|
| Quick Start | Minimal working example, Result<T> primer, subsystem overview |
| Installation | Cloning, compiler requirements, include paths |
| Hardware Setup | Wiring, power supply, sense resistors |
| Platform Integration | Implementing MySPI / MyUART for your board (ESP32, STM32, Arduino) |
| Guide | Description |
|---|---|
| API Reference | Complete method signatures, return types, and parameters |
| Configuration | DriverConfig fields, chopper tuning, StealthChop parameters |
| Examples | Progressively harder walkthroughs with explanations |
| Error Handling | Result<T>, ErrorCode, common patterns |
| Troubleshooting | Error codes, common failures, recovery strategies |
| Guide | Description |
|---|---|
| Sensorless Homing | StallGuard2 homing and bounds finding |
| Advanced Configuration | CoolStep, dcStep, StealthChop tuning |
| Multi-Chip Communication | SPI daisy chain and UART multi-node |
| GPIO Pin Configuration | DIAG0/DIAG1, STEP/DIR, reference switches |
| TMC5130 Support | Differences from TMC5160, compatibility notes |
For local browsing, see the docs directory.
| Resource | Link |
|---|---|
| Trinamic TMC5160 product page | https://www.analog.com/en/products/tmc5160.html |
| Trinamic TMC5130 product page | https://www.analog.com/en/products/tmc5130.html |
| TMC5160 datasheet (ADI/Trinamic) | https://www.analog.com/media/en/technical-documentation/data-sheets/tmc5160_datasheet.pdf |
| TMC5130 datasheet (ADI/Trinamic) | https://www.analog.com/media/en/technical-documentation/data-sheets/tmc5130_datasheet.pdf |
| StallGuard2 / CoolStep / StealthChop2 application notes | https://www.analog.com/en/products/landing-pages/001/trinamic-application-notes.html |
| ESP-IDF SPI / UART | https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/index.html |
| C++17 language reference | https://en.cppreference.com/w/cpp/17 |
Pull requests and suggestions are welcome! Please follow the existing code style and include tests for new features.
This project is licensed under the GNU General Public License v3.0. See the [LICENSE](LICENSE) file for details.