32#include "tmc5160_version.h"
37template <
typename Port>
43template <
typename Port>
44concept DeclaresGpioSet =
47template <
typename Port>
49 requires { ExactHook<Port, bool(
CtrlPin,
GpioSignal)
noexcept>::Take(&Port::GpioSet); };
51template <
typename Port>
52concept DeclaresGpioGet =
53 requires(Port& port,
bool& level) { port.GpioGet(
InputPin::Diag0, level); };
55template <
typename Port>
57 requires { ExactHook<Port, bool(
InputPin,
bool&)
noexcept>::Take(&Port::GpioGet); };
59template <
typename Port>
60concept DeclaresDelayUs =
requires(Port& port) { port.DelayUs(1_u32); };
62template <
typename Port>
63concept HasDelayUs =
requires { ExactHook<Port, void(uint32_t)
noexcept>::Take(&Port::DelayUs); };
65template <
typename Port>
66concept DeclaresSckHz =
requires(
const Port& port) { port.SckHz(); };
68template <
typename Port>
69concept HasSckHz =
requires { ExactHook<Port, uint32_t()
noexcept>::Take(&Port::SckHz); };
71template <
typename Port>
72concept DeclaresLog =
requires(Port& port) { port.Log(
LogLevel::Info,
""); };
74template <
typename Port>
76 requires { ExactHook<Port, void(
LogLevel,
const char*)
noexcept>::Take(&Port::Log); };
79template <
typename Port>
80void DelayUs(Port& port, uint32_t us)
noexcept {
81 if constexpr (HasDelayUs<Port>) {
84 static_assert(kAlwaysFalse<Port>,
85 "tmc5160: the port must implement `void DelayUs(uint32_t us) noexcept`");
90template <
typename Port>
91void Log(Port& port,
LogLevel level,
const char* message)
noexcept {
92 if constexpr (HasLog<Port>) {
93 port.Log(level, message);
95 static_cast<void>(port);
96 static_cast<void>(level);
97 static_cast<void>(message);
144template <AnyPort Port>
147 !detail::DeclaresGpioSet<Port> || detail::HasGpioSet<Port>,
148 "tmc5160: the optional GpioSet hook must be `bool GpioSet(CtrlPin, GpioSignal) noexcept`");
150 !detail::DeclaresGpioGet<Port> || detail::HasGpioGet<Port>,
151 "tmc5160: the optional GpioGet hook must be `bool GpioGet(InputPin, bool&) noexcept`");
152 static_assert(!detail::DeclaresDelayUs<Port> || detail::HasDelayUs<Port>,
153 "tmc5160: the DelayUs hook must be `void DelayUs(uint32_t us) noexcept`");
154 static_assert(!detail::DeclaresSckHz<Port> || detail::HasSckHz<Port>,
155 "tmc5160: the optional SckHz hook must be `uint32_t SckHz() const noexcept`");
157 !detail::DeclaresLog<Port> || detail::HasLog<Port>,
158 "tmc5160: the optional Log hook must be `void Log(LogLevel, const char* message) noexcept`");
166 explicit TMC5160(Port& port,
const Config& config = {})
noexcept : port_(port), config_(config) {}
262 return initialized_ && fault_;
747 static constexpr
bool kSpi =
SpiPort<Port>;
749 Result<
void> initialize() noexcept;
751 Result<
void> clearGstat() noexcept;
755 Result<
void> finishTuning() noexcept;
756 Result<
void> ready() const noexcept;
757 Result<
void> readyMotion() const noexcept;
758 Result<
void> readyController() const noexcept;
761 Result<
void> checkIntact() noexcept;
763 void noteReset() noexcept;
764 Result<
void> readyOff() const noexcept;
765 Result<
void> readyStop() const noexcept;
772 [[nodiscard]] static constexpr
Verify offVerify(
Verify verify) noexcept;
774 [[nodiscard]] static constexpr
Verify busVerify(
Verify verify) noexcept;
777 Result<
void> rampStop(
bool immediate,
bool zero_coils,
Verify verify) noexcept;
779 [[nodiscard]]
bool beginSequence() noexcept;
780 Result<
void> endSequence(
bool watched,
Result<
void> result) noexcept;
781 Result<
void> fail(
Error error, const
char* message) noexcept;
782 [[nodiscard]] uint32_t vmaxLimit() const noexcept;
784 Error datagram(uint8_t cmd, uint32_t value, uint32_t& reply) noexcept;
785 Error observe(uint8_t status) noexcept;
786 Error uartRead(uint8_t reg, uint32_t& value) noexcept;
787 Error uartWrite(uint8_t reg, uint32_t value) noexcept;
788 Error uartExchange(const detail::UartFrame& tx, std::
size_t tx_len, detail::UartFrame& rx,
789 std::
size_t rx_len) noexcept;
790 Error readMany(std::span<const uint8_t> addresses, std::span<uint32_t> out) noexcept;
791 Result<uint32_t> readReg(uint8_t address) noexcept;
792 Result<uint32_t> readChecked(uint8_t address) noexcept;
793 Result<uint32_t> readControlled(uint8_t address) noexcept;
794 Result<
void> sendReg(uint8_t address, uint32_t value,
Verify verify, uint32_t& word,
795 uint32_t& reply) noexcept;
796 Result<
void> writeReg(uint8_t address, uint32_t value,
Verify verify) noexcept;
797 Result<
void> writeRegs(std::span<const detail::Write> writes,
Verify verify) noexcept;
798 Result<
void> verifyWrite(uint8_t address, uint32_t word,
Verify verify) noexcept;
801 Result<
void> ensureStopped() noexcept;
802 [[nodiscard]]
bool stuckLow(uint32_t value) const noexcept;
804 [[nodiscard]]
Error lineCheck(uint32_t value) noexcept;
809 Result<
void> pushConfig(const
Config& next, std::span<const uint8_t> which,
812 Result<
void> sendConfig(const
Config& next, std::span<const uint8_t> which,
814 Result<
void> setField(
Config next, std::span<const uint8_t> which,
Verify verify) noexcept;
817 void waitUartRecovery() noexcept;
822 BeginReport report_{};
823 std::array<uint32_t, 128> shadow_{};
827 detail::UartFrame uart_tx_{};
828 detail::UartFrame uart_rx_{};
829 uint32_t uart_counter_{0};
831 uint8_t last_status_{0};
832 bool initialized_{
false};
833 bool enabled_{
false};
835 bool watch_reset_{
false};
838 bool intact_checked_{
false};
839 bool direct_mode_{
false};
840 bool direct_unsure_{
false};
842 bool started_{
false};
843 bool off_pending_{
false};
844 bool ramp_written_{
false};
845 bool hold_at_run_{
false};
853#include "../src/tmc5160.ipp"
Driver for one TMC5160 on a platform port.
Definition tmc5160.hpp:145
Result< int32_t > ReadEncoderLatch() noexcept
Result< uint32_t > ReadLostSteps() noexcept
Result< int32_t > ReadPosition() noexcept
bool HasFault() const noexcept
Definition tmc5160.hpp:261
uint8_t GetLastStatusByte() const noexcept
Definition tmc5160.hpp:713
Result< void > ClearRampEvents(uint32_t mask) noexcept
Clear RAMP_STAT events: only the write-to-clear bits (mask 0x10CC) are ever written.
Result< void > SetDiag(const Diag &diag, Verify verify=Verify::None) noexcept
Change the DIAG outputs (GCONF); bits of the other SD_MODE are refused.
Result< int32_t > ReadEncoderPosition() noexcept
Result< void > Disable(Verify verify=Verify::None) noexcept
Disable the driver: DRV_ENN inactive first, then TOFF 0, then (motion-controller mode) the ramp gener...
Result< GlobalStatus > ReadGlobalStatus() noexcept
TMC5160(Port &port, const Config &config={}) noexcept
Bind the driver to a port and store the configuration. No I/O, cannot fail.
Definition tmc5160.hpp:166
void GetConfig() const &&=delete
Not on a temporary driver: the reference would dangle (KB-CPP20-044).
Result< void > SetStandstill(const Standstill &standstill, Verify verify=Verify::None) noexcept
Set the standstill behaviour: IHOLDDELAY, TPOWERDOWN and fast standstill detection.
TMC5160(const TMC5160 &)=delete
One driver object per chip.
Result< void > MoveBy(int32_t delta, Verify verify=Verify::None) noexcept
Move relative to the present position: reads XACTUAL, adds delta, writes XTARGET.
bool IsEnabled() const noexcept
Definition tmc5160.hpp:253
void GetCurrentPlan() const &&=delete
Not on a temporary driver: the reference would dangle (KB-CPP20-044).
Result< Events > Service() noexcept
After a DIAG0 interrupt: read GSTAT, DRV_STATUS, RAMP_STAT and ENC_STATUS and clear the events that w...
Result< MicrostepCurrents > ReadMicrostepCurrents() noexcept
Result< uint32_t > ReadRegister(uint8_t address) noexcept
Read one readable register once, with no decoding (bring-up).
Result< uint32_t > ReadMicrostepCounter() noexcept
Result< void > SetStopOnStall(bool enable, Verify verify=Verify::None) noexcept
Stop on stall (sg_stop); needs TCOOLTHRS of 1 or more and no soft stop.
const BeginReport & GetBeginReport() const &noexcept
Definition tmc5160.hpp:214
Result< void > SetStealthChop(const StealthChop &stealth, TuningPolicy policy=TuningPolicy::HoldAtRunForAt1, Verify verify=Verify::None) noexcept
Change StealthChop (PWMCONF and GCONF.en_pwm_mode). Switching it on needs standstill (the check of En...
Result< void > SetSwitches(const Switches &switches, Verify verify=Verify::None) noexcept
Change the reference switches and stop behaviour (SW_MODE).
TMC5160 & operator=(const TMC5160 &)=delete
One driver object per chip.
const Config & GetConfig() const &noexcept
Definition tmc5160.hpp:738
bool IsInitialized() const noexcept
Definition tmc5160.hpp:196
Result< void > MoveTo(int32_t position, Verify verify=Verify::None) noexcept
Move to an absolute position (position mode); the motor starts at once. Writes XTARGET,...
Result< void > ClearGlobalStatus(uint32_t mask) noexcept
Clear GSTAT bits (write 1 to clear); bit 0 of mask is reset, 1 drv_err, 2 uv_cp.
Result< bool > Diag1Active() noexcept
Result< void > SetThresholds(const Thresholds &thresholds, Verify verify=Verify::None) noexcept
Set TPWMTHRS, TCOOLTHRS, THIGH and the hysteresis bit.
Result< int32_t > ReadLatchedPosition() noexcept
Result< void > SetStallGuard(const StallGuard &stall, Verify verify=Verify::None) noexcept
Set StallGuard2 (SGT and SFILT in COOLCONF).
const units::CurrentPlan & GetCurrentPlan() const &noexcept
Definition tmc5160.hpp:296
Result< void > SetPositionCompare(int32_t position) noexcept
Arm the position compare output (X_COMPARE, DIAG1 pulse).
Result< EncoderStatus > ReadEncoderStatus() noexcept
Result< void > EnsureInitialized() noexcept
Start the chip, once: the only way to initialise the driver.
Result< void > ReleaseStall() noexcept
Release a stall stop: hold, check standstill (the check of Enable()), clear event_stop_sg....
Result< void > Enable(Verify verify=Verify::None) noexcept
Enable the driver: DRV_ENN active (when the port can), then TOFF from the configuration.
Result< void > SetMicrostepTable(const MicrostepTable &table) noexcept
Write a microstep table. Needs MSCNT = 0 (read first), a motor at rest and a table that passes CheckT...
Result< void > SetFlags(const Flags &flags, Verify verify=Verify::None) noexcept
Change the general flags (GCONF).
Result< void > ClearEncoderEvents(bool n_event, bool deviation_warn) noexcept
Clear encoder events (write 1 to clear).
Result< void > ExitDirectMode() noexcept
Leave direct mode in the safe order: hold, clear direct_mode, XTARGET = XACTUAL.
Result< DriverStatus > ReadDriverStatus() noexcept
Result< RampStatus > ReadRampStatus() noexcept
Result< void > SetRamp(const RampProfile &ramp, Verify verify=Verify::None) noexcept
Replace the six-point ramp: the nine ramp registers in the order the datasheet allows.
Result< uint32_t > ReadStallGuard() noexcept
Result< void > EnterDirectMode() noexcept
Enter direct mode: the coil currents come from XTARGET (page 110). Needs Ack::DirectMode in the confi...
Result< void > SetDirectCurrents(int32_t coil_a, int32_t coil_b) noexcept
Write the two coil currents in direct mode (XTARGET: A in bits 8..0, B in bits 24....
Result< bool > PositionReached() noexcept
Result< void > SetHomePosition(int32_t position) noexcept
Set the position counter (homing result): needs standstill (the check of Enable()); holds first,...
Result< uint32_t > ReadClockTrim() noexcept
Result< OtpImage > ReadOtp() noexcept
Result< uint32_t > ReadInterfaceCounter() noexcept
Result< void > RunVelocity(int32_t velocity, Verify verify=Verify::None) noexcept
Run at a constant velocity until stopped.
Result< void > Stop(StopKind kind, Verify verify=Verify::None) noexcept
Bring the motor to rest.
Result< void > SetCoolStep(const CoolStep &cool, Verify verify=Verify::None) noexcept
Set CoolStep (COOLCONF); needs TCOOLTHRS of 1 or more when semin is non-zero.
Result< units::CurrentPlan > SetCurrent(uint32_t run_ma, uint32_t hold_ma, Verify verify=Verify::None) noexcept
Set the run and hold current from the declared motor and sense resistor.
void GetBeginReport() const &&=delete
Not on a temporary driver: the reference would dangle (KB-CPP20-044).
Result< void > SetBridge(const Bridge &bridge, AckSet ack={}, Verify verify=Verify::None) noexcept
Write DRV_CONF from declared values; needs the driver disabled.
Result< StealthChopState > ReadStealthChopState() noexcept
Result< void > ProgramNode(uint8_t from_node, uint8_t new_node, bool nao_level) noexcept
Program another node address into the chip at from_node (UART only), and set the NAO level.
Result< void > SetChopper(const Chopper &chopper, Verify verify=Verify::None) noexcept
Change the chopper (CHOPCONF); TOFF is written as 0 while the driver is disabled.
Result< uint32_t > ReadStepTime() noexcept
Result< Offsets > ReadOffsets() noexcept
Result< void > SetEncoderPosition(int32_t position) noexcept
Set the encoder counter.
Result< void > SetMaxVelocity(uint32_t vmax, Verify verify=Verify::None) noexcept
Change VMAX (a running move follows it). VMAX must be at least VSTART, the chip's and the profile's (...
Result< void > Deinitialize() noexcept
Switch the driver off (DRV_ENN inactive, TOFF 0) and mark the driver uninitialised.
Result< void > SetProtection(const Protection &protection, AckSet ack={}, Verify verify=Verify::None) noexcept
Write SHORT_CONF and the diss2g, diss2vs bits from declared values; needs the driver disabled.
Result< int32_t > ReadTarget() noexcept
Result< Snapshot > ReadSnapshot() noexcept
Result< void > SetEncoder(const Encoder &encoder, Verify verify=Verify::None) noexcept
Write ENCMODE, ENC_CONST and ENC_DEVIATION.
Result< uint32_t > Identify() noexcept
Result< void > ClearFaults() noexcept
Recover from a latched error once its cause is gone: disable (which stops the ramp generator),...
Result< InputPins > ReadInputs() noexcept
Result< int32_t > ReadVelocity() noexcept
Result< void > SetDcStep(const DcStep &dcstep, Verify verify=Verify::None) noexcept
Set DcStep (VDCMIN and DCCTRL); needs the default table, high_fullstep, high_const_off,...
Result< bool > Diag0Active() noexcept
Satisfied by a port of exactly one bus kind.
Definition tmc5160.hpp:38
Satisfied by a class that derives from SpiInterface<Port> and implements the required hooks with exac...
Definition tmc5160_spi_interface.hpp:89
Satisfied by a class that derives from UartInterface<Port> and implements the required hooks with exa...
Definition tmc5160_uart_interface.hpp:74
constexpr uint32_t kMaxChain
Longest SPI daisy chain the driver frames.
Definition tmc5160_types.hpp:580
LogLevel
Severity passed to the optional Log() hook.
Definition tmc5160_types.hpp:171
InputPin
Input pins the port may read through the optional GpioGet() hook.
Definition tmc5160_types.hpp:186
Verify
Extra traffic a setter spends to prove a write (handbook KB-ARCH-041).
Definition tmc5160_types.hpp:212
StopKind
How Stop() brings the motor to rest (section 6.3.2, page 43).
Definition tmc5160_types.hpp:263
CtrlPin
Output pins the port may drive through the optional GpioSet() hook.
Definition tmc5160_types.hpp:179
GpioSignal
Logical level of a control pin; the port maps it to the physical polarity.
Definition tmc5160_types.hpp:193
Error
Why a call failed. Every call of the driver returns one of these in its Result.
Definition tmc5160_types.hpp:39
@ Info
Lifecycle events: initialised, reset.
@ Diag0
DIAG0_SWN: interrupt or error output.
@ DrvEnn
DRV_ENN, active low on the package pin: ACTIVE means the driver is enabled.
@ Hold
Velocity stays constant; used as the safe state.
@ ACTIVE
The pin function is asserted.
The TMC5160 driver: everything it declares lives here; internals in detail.
Definition tmc5160.hpp:34
TuningPolicy
What SetStealthChop() does about IHOLD while the chip tunes itself (page 58, 65).
Definition tmc5160.hpp:110
@ LeaveHoldAtRun
Leave IHOLD = IRUN; the caller restores it with SetCurrent().
@ HoldAtRunForAt1
Wait the AT#1 time at IHOLD = IRUN, then restore the hold current.
constexpr uint32_t kDatagramBytes
A datagram is 40 bits; the whole datagram (5 bytes per chip in a chain) is one CSN low period.
Definition tmc5160_spi_interface.hpp:47
A set of acknowledgements.
Definition tmc5160_types.hpp:288
What start-up learned about the chip.
Definition tmc5160_status.hpp:136
Gate driver settings (DRV_CONF, section 6.1 page 35); written only when declared.
Definition tmc5160_types.hpp:406
Chopper configuration (CHOPCONF, section 6.5.2 page 51).
Definition tmc5160_types.hpp:345
Everything EnsureInitialized() writes to the chip. See docs/configuration.md.
Definition tmc5160_types.hpp:536
CoolStep (COOLCONF, section 13, page 87).
Definition tmc5160_types.hpp:384
DcStep (VDCMIN, DCCTRL, section 17, page 100).
Definition tmc5160_types.hpp:399
DIAG0 and DIAG1 outputs (GCONF bits 5 to 13, section 6.1 page 32).
Definition tmc5160_types.hpp:436
DRV_STATUS, decoded (page 56).
Definition tmc5160_status.hpp:31
ENC_STATUS, decoded (page 45).
Definition tmc5160_status.hpp:69
Incremental encoder (ABN), written only when declared.
Definition tmc5160_types.hpp:503
What Service() found and cleared.
Definition tmc5160_status.hpp:117
General flags (GCONF).
Definition tmc5160_types.hpp:428
GSTAT, decoded (page 33).
Definition tmc5160_status.hpp:24
MSCURACT, decoded (page 47): the unscaled microstep currents, -255 to 255.
Definition tmc5160_status.hpp:111
A microstep table (MSLUT, MSLUTSEL, MSLUTSTART, section 6.5 page 47).
Definition tmc5160_types.hpp:511
OFFSET_READ, decoded (page 36).
Definition tmc5160_status.hpp:88
OTP_READ, decoded (page 35, 37).
Definition tmc5160_status.hpp:94
Short protection (SHORT_CONF, section 11.2 page 78); written only when declared.
Definition tmc5160_types.hpp:417
The six-point ramp (page 40). Defaults are the datasheet's quick-start values (page 116).
Definition tmc5160_types.hpp:452
RAMP_STAT, decoded (page 44).
Definition tmc5160_status.hpp:50
The value of a call, or why there is none.
Definition tmc5160_types.hpp:111
One pipelined batch of the values a monitor wants together.
Definition tmc5160_status.hpp:125
StallGuard2 (COOLCONF, section 13, page 87).
Definition tmc5160_types.hpp:393
Standstill behaviour (IHOLD_IRUN.IHOLDDELAY, TPOWERDOWN, GCONF.faststandstill).
Definition tmc5160_types.hpp:338
PWM_SCALE and PWM_AUTO, decoded (page 48).
Definition tmc5160_status.hpp:103
StealthChop settings (PWMCONF, GCONF.en_pwm_mode, section 6.5.2 page 54).
Definition tmc5160_types.hpp:363
Reference switches and stop behaviour (SW_MODE, page 43).
Definition tmc5160_types.hpp:465
Velocity thresholds as TSTEP values (page 39); 0 disables.
Definition tmc5160_types.hpp:376
The registers a current request turns into (page 36, 38).
Definition tmc5160_units.hpp:45
Compile-time helpers of the TMC5160 driver: typed integer literals, exact hook matching,...
TMC5160 register map: addresses, access rules, reserved bits and reset values.
The SPI port of the TMC5160 driver: the CRTP base, the SpiPort concept and the bus requirements.
Decoded status registers of the TMC5160 and the pure decoders and encoders that build and read regist...
Public types of the TMC5160 driver: errors, Result<T>, configuration, validation and advice.
The UART port of the TMC5160 driver: the CRTP base, the UartPort concept and the bus requirements.
Pure integer conversions between datasheet register units and physical units, and the current plan th...