### begin() - Initialize Motor Driver Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Initializes the TMC5160 with power stage and motor parameters, configuring registers for current, chopper settings, and PWM mode. ```APIDOC ## begin(powerParams, motorParams, direction) ### Description Initializes the TMC5160 with power stage and motor parameters. It configures current settings, chopper parameters, stealthChop PWM mode, and sets the initial operating mode. ### Parameters - **powerParams** (PowerStageParameters) - Required - MOSFET timing and gate driver settings. - **motorParams** (MotorParameters) - Required - Current settings and PWM configuration. - **direction** (int) - Required - Motor direction (TMC5160::NORMAL_MOTOR_DIRECTION or TMC5160::INVERSE_MOTOR_DIRECTION). ``` -------------------------------- ### Select Motion Control Modes Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Demonstrates switching between positioning, velocity, and hold modes. Each mode interprets speed and acceleration parameters differently. ```cpp #include TMC5160_SPI motor = TMC5160_SPI(5); void demonstrateRampModes() { // POSITIONING_MODE: Autonomous move to target position // Uses all A, D, V parameters for trapezoidal ramp motor.setRampMode(TMC5160::POSITIONING_MODE); motor.setMaxSpeed(1000); motor.setAcceleration(2000); motor.setTargetPosition(1000); // Move to position 1000 steps while (!motor.isTargetPositionReached()) { delay(10); } // VELOCITY_MODE: Continuous rotation at set velocity // Uses VMAX and AMAX parameters motor.setRampMode(TMC5160::VELOCITY_MODE); motor.setMaxSpeed(500); // Positive = forward, negative = reverse delay(5000); // Run for 5 seconds motor.setMaxSpeed(-500); // Reverse direction delay(5000); // HOLD_MODE: Maintain current velocity until stop event motor.setRampMode(TMC5160::HOLD_MODE); // Velocity remains unchanged motor.stop(); // Stop using configured deceleration } ``` -------------------------------- ### Manage Position and Speed Profiles Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Provides functions for setting target positions, configuring acceleration profiles, and monitoring motion status. Positions are in steps, speeds in steps/second, and accelerations in steps/second^2. ```cpp #include TMC5160_SPI motor = TMC5160_SPI(5); void motionControlExample() { // Set current position (useful after homing) motor.setCurrentPosition(0); // Reset position to zero motor.setCurrentPosition(100, true); // Also update encoder position // Configure ramp speeds for smooth motion motor.setRampSpeeds( 10, // startSpeed: VSTART (steps/sec) 10, // stopSpeed: VSTOP (steps/sec) - must be >= VSTART 200 // transitionSpeed: V1 for acceleration phases ); // Simple acceleration (same accel/decel) motor.setAcceleration(1000); // steps/second^2 // Advanced acceleration profile (different values for each phase) motor.setAccelerations( 2000, // maxAccel: AMAX - acceleration between V1 and VMAX 1500, // maxDecel: DMAX - deceleration between VMAX and V1 3000, // startAccel: A1 - initial acceleration to V1 1000 // finalDecel: D1 - final deceleration from V1 (don't set to 0!) ); // Set maximum speed motor.setMaxSpeed(800); // steps/second // Move to target position (non-blocking) motor.setTargetPosition(2000); // Monitor motion while (!motor.isTargetPositionReached()) { Serial.print("Pos: "); Serial.print(motor.getCurrentPosition()); Serial.print(" Target: "); Serial.print(motor.getTargetPosition()); Serial.print(" Speed: "); Serial.println(motor.getCurrentSpeed()); delay(50); } // Emergency stop motor.stop(); // Stops with configured ramp // Disable/enable driver outputs motor.disable(); // All bridges off motor.enable(); // Resume normal operation } ``` -------------------------------- ### Encoder Configuration and Monitoring Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Methods for configuring quadrature encoder feedback, including resolution, index signal handling, and deviation detection. ```APIDOC ## Encoder Configuration and Monitoring ### Description Methods to configure encoder resolution, index signal behavior, and monitor position deviation for closed-loop feedback. ### Methods - **setEncoderResolution(motorSteps, encResolution, inverted)**: Sets encoder resolution. Returns true if exact match found. - **setEncoderIndexConfiguration(...)**: Configures index (N) signal behavior. - **setEncoderLatching(bool)**: Enables position latching on each encoder revolution. - **setEncoderAllowedDeviation(steps)**: Sets maximum allowed deviation before warning. - **isEncoderDeviationDetected()**: Checks if position deviation has occurred. - **clearEncoderDeviationFlag()**: Clears the deviation flag. ``` -------------------------------- ### Configure Short Circuit Detection with setShortProtectionLevels() Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Adjusts sensitivity for short-to-supply and short-to-ground detection. Use higher values for noisy environments or high-voltage applications to prevent false triggers. ```cpp #include TMC5160_SPI motor = TMC5160_SPI(5); void configureProtection() { // Configure short protection sensitivity motor.setShortProtectionLevels( 6, // s2vsLevel: Short to supply sensitivity (4=highest, 15=lowest) // Recommended: 6-8, default: 6 6, // s2gLevel: Short to ground sensitivity (2=highest, 15=lowest) // Recommended: 6-14, increase at higher voltage, default: 6 1, // shortFilter: Spike filtering (0-3), increase for false triggers // Default: 1 0 // shortDelay: Detection delay (0-1), default: 0 ); // High voltage application (>24V) - reduce sensitivity motor.setShortProtectionLevels(8, 10, 2, 0); // Noisy environment - increase filtering motor.setShortProtectionLevels(6, 6, 3, 1); // Maximum sensitivity (careful - may false trigger) motor.setShortProtectionLevels(4, 2, 0, 0); } ``` -------------------------------- ### Initialize TMC5160 Motor Driver Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Configures power stage and motor parameters before operation. Must be called to set current settings, chopper parameters, and stealthChop PWM mode. ```cpp #include TMC5160_SPI motor = TMC5160_SPI(5); void setup() { SPI.begin(); // Power stage parameters for MOSFET timing TMC5160::PowerStageParameters powerParams; powerParams.drvStrength = 2; // Gate driver current (0=weak, 3=strong) powerParams.bbmTime = 0; // Break-before-make time in nanoseconds powerParams.bbmClks = 4; // Break-before-make in clock cycles // Motor current parameters TMC5160::MotorParameters motorParams; motorParams.globalScaler = 128; // Global current scaler (32-256) motorParams.irun = 31; // Run current (0-31, use 16-31 for best performance) motorParams.ihold = 10; // Hold current (0-31, typically 70% of irun or less) motorParams.freewheeling = TMC5160_Reg::FREEWHEEL_NORMAL; // Standstill behavior motorParams.pwmOfsInitial = 30; // Initial stealthChop PWM offset (0-255) motorParams.pwmGradInitial = 0; // Initial PWM gradient (0-255) // Initialize with normal or inverse motor direction motor.begin(powerParams, motorParams, TMC5160::NORMAL_MOTOR_DIRECTION); // or: motor.begin(powerParams, motorParams, TMC5160::INVERSE_MOTOR_DIRECTION); } ``` -------------------------------- ### setShortProtectionLevels() Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Configures the sensitivity and filtering parameters for short circuit detection (supply and ground). ```APIDOC ## setShortProtectionLevels(s2vsLevel, s2gLevel, shortFilter, shortDelay) ### Description Configures the sensitivity of short circuit detection for both supply and ground shorts. Higher sensitivity values detect smaller shorts but may cause false triggers. ### Parameters - **s2vsLevel** (int) - Required - Short to supply sensitivity (4=highest, 15=lowest). Recommended: 6-8. - **s2gLevel** (int) - Required - Short to ground sensitivity (2=highest, 15=lowest). Recommended: 6-14. - **shortFilter** (int) - Required - Spike filtering (0-3). Increase for false triggers. - **shortDelay** (int) - Required - Detection delay (0-1). ``` -------------------------------- ### Configure TMC5160 Mode Change Speeds Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Set velocity thresholds for automatic switching between stealthChop, spreadCycle, and high-velocity modes using setModeChangeSpeeds(). A threshold of 0 disables the transition. Speeds are in steps/second. ```cpp #include TMC5160_SPI motor = TMC5160_SPI(5); void configureModeTransitions() { // Set speed thresholds for mode switching (all in steps/second) motor.setModeChangeSpeeds( 100, // pwmThrs: Below this speed, use stealthChop (silent mode) 500, // coolThrs: Between this and highThrs, enable coolStep current control 1000 // highThrs: Above this, enable constant Toff and fullstep mode ); // Example: Silent operation only at low speeds motor.setModeChangeSpeeds(50, 0, 0); // stealthChop below 50 steps/sec // Example: Always use stealthChop (very high threshold) motor.setModeChangeSpeeds(10000, 0, 0); // Example: Disable stealthChop entirely motor.setModeChangeSpeeds(0, 500, 1000); } ``` -------------------------------- ### Configure TMC5160 Encoder Resolution and Index Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Set encoder resolution using setEncoderResolution(), which returns true if an exact match is found. Configure index signal behavior with setEncoderIndexConfiguration() and enable latching on revolution with setEncoderLatching(). ```cpp #include TMC5160_SPI motor = TMC5160_SPI(5); void configureEncoder() { // Set encoder resolution matching motor and encoder specs // Returns true if exact match found, false if approximation used bool exactMatch = motor.setEncoderResolution( 200, // motorSteps: steps per motor revolution 1000, // encResolution: encoder pulses per revolution false // inverted: true if encoder rotates opposite to motor ); if (!exactMatch) { Serial.println("Warning: Using approximate encoder ratio"); } // Configure index (N) signal behavior motor.setEncoderIndexConfiguration( TMC5160_Reg::ENCODER_N_RISING_EDGE, // Trigger on rising edge true, // nActiveHigh: N signal polarity true, // ignorePol: ignore A/B polarities for N event false, // aActiveHigh: A polarity for N event validation false // bActiveHigh: B polarity for N event validation ); // Enable position latching on each encoder revolution motor.setEncoderLatching(true); // Set maximum allowed deviation before warning (in steps) motor.setEncoderAllowedDeviation(10); // 0 to disable } ``` -------------------------------- ### Motion Control Functions Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Methods for managing position, speed, and acceleration profiles. ```APIDOC ## Motion Control Functions ### Description Provides methods for position management, speed configuration, and acceleration profiles. ### Methods - **setCurrentPosition(pos, updateEncoder)** - Sets the current position (steps). - **setRampSpeeds(startSpeed, stopSpeed, transitionSpeed)** - Configures ramp speeds. - **setAcceleration(accel)** - Sets simple acceleration (steps/sec^2). - **setAccelerations(maxAccel, maxDecel, startAccel, finalDecel)** - Sets advanced acceleration profile. - **setMaxSpeed(speed)** - Sets maximum speed (steps/sec). - **setTargetPosition(pos)** - Sets target position (steps). - **isTargetPositionReached()** - Returns true if target is reached. - **stop()** - Stops motion using configured ramp. - **enable() / disable()** - Enables or disables driver outputs. ``` -------------------------------- ### Perform Direct Register Access Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Accesses registers directly for advanced configuration not supported by the high-level API. Requires referencing TMC5160_registers.h for specific addresses and bitfield definitions. ```cpp #include TMC5160_SPI motor = TMC5160_SPI(5); void advancedRegisterAccess() { // Read a register uint32_t gstat = motor.readRegister(TMC5160_Reg::GSTAT); // Check if read was successful (important for UART mode) if (motor.isLastReadSuccessful()) { Serial.print("GSTAT: 0x"); Serial.println(gstat, HEX); } // Read driver status with bitfield access TMC5160_Reg::DRV_STATUS_Register drvStatus; drvStatus.value = motor.readRegister(TMC5160_Reg::DRV_STATUS); Serial.print("StallGuard result: "); Serial.println(drvStatus.sg_result); Serial.print("Actual current: "); Serial.println(drvStatus.cs_actual); Serial.print("Standstill: "); Serial.println(drvStatus.stst ? "Yes" : "No"); // Write to a register TMC5160_Reg::CHOPCONF_Register chopConf; chopConf.value = motor.readRegister(TMC5160_Reg::CHOPCONF); chopConf.toff = 5; // Off time chopConf.tbl = 2; // Blanking time chopConf.hstrt_tfd = 4; // Hysteresis start motor.writeRegister(TMC5160_Reg::CHOPCONF, chopConf.value); // Configure stallGuard threshold TMC5160_Reg::COOLCONF_Register coolConf; coolConf.value = 0; coolConf.sgt = 10; // StallGuard threshold (0-127) coolConf.sfilt = 1; // Enable filtering motor.writeRegister(TMC5160_Reg::COOLCONF, coolConf.value); } ``` -------------------------------- ### setModeChangeSpeeds() Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Configures velocity thresholds for automatic switching between stealthChop, spreadCycle, and high-velocity modes. ```APIDOC ## setModeChangeSpeeds() ### Description Configures velocity thresholds for automatic switching between stealthChop (silent), spreadCycle (precise), and high-velocity modes. Setting a threshold to 0 disables that transition. ### Parameters - **pwmThrs** (int) - Below this speed, use stealthChop (silent mode). - **coolThrs** (int) - Between this and highThrs, enable coolStep current control. - **highThrs** (int) - Above this, enable constant Toff and fullstep mode. ``` -------------------------------- ### Direct Register Access Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Methods for reading and writing directly to TMC5160 registers for advanced configuration. ```APIDOC ## Direct Register Access ### Description Provides low-level access to registers for configurations not covered by the high-level API. Register definitions are found in TMC5160_registers.h. ### Methods - **readRegister(address)**: Reads a 32-bit value from the specified register. - **writeRegister(address, value)**: Writes a 32-bit value to the specified register. - **isLastReadSuccessful()**: Returns boolean indicating if the last register read operation was successful (useful for UART mode). ``` -------------------------------- ### Control Motor via SPI Interface Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Initializes and controls a TMC5160 motor driver using the SPI interface. Requires the SWSEL pin to be tied low. ```cpp #include #include const uint8_t SPI_CS = 5; // Chip select pin const uint8_t SPI_DRV_ENN = 8; // Driver enable pin (active low) TMC5160_SPI motor = TMC5160_SPI(SPI_CS); void setup() { Serial.begin(115200); pinMode(SPI_DRV_ENN, OUTPUT); digitalWrite(SPI_DRV_ENN, LOW); // Enable driver // Configure power stage and motor parameters TMC5160::PowerStageParameters powerStageParams; powerStageParams.drvStrength = 2; // MOSFET gate driver current (0-3) powerStageParams.bbmTime = 0; // Break Before Make time in ns (0-24) powerStageParams.bbmClks = 4; // Break Before Make in clock cycles (0-15) TMC5160::MotorParameters motorParams; motorParams.globalScaler = 98; // Global current scaling (32-256) motorParams.irun = 31; // Run current (0-31) motorParams.ihold = 16; // Standstill current (0-31) SPI.begin(); motor.begin(powerStageParams, motorParams, TMC5160::NORMAL_MOTOR_DIRECTION); // Configure motion profile motor.setRampMode(TMC5160::POSITIONING_MODE); motor.setMaxSpeed(400); // steps/second motor.setAcceleration(500); // steps/second^2 delay(1000); // Allow automatic tuning } void loop() { static unsigned long lastMove = 0; static bool direction = false; if (millis() - lastMove > 3000) { lastMove = millis(); direction = !direction; motor.setTargetPosition(direction ? 200 : 0); // Move 200 steps (1 rotation for 200-step motor) } // Monitor position and speed Serial.print("Position: "); Serial.print(motor.getCurrentPosition()); Serial.print(" Speed: "); Serial.println(motor.getCurrentSpeed()); delay(100); } ``` -------------------------------- ### getDriverStatus() Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Retrieves the current error state of the TMC5160 driver, including thermal warnings and short circuit detection. ```APIDOC ## getDriverStatus() ### Description Returns the current error state of the driver including thermal warnings, short circuit detection, and charge pump status. ### Response - **status** (TMC5160::DriverStatus) - The current error state of the driver. ``` -------------------------------- ### UART Communication Statistics Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Methods to monitor and manage UART communication reliability and slave addressing. ```APIDOC ## UART Communication Statistics ### Description Tools to monitor communication reliability, diagnose EMI/wiring issues, and manage slave addresses in UART mode. ### Methods - **setCommunicationMode(mode)**: Sets mode to RELIABLE_MODE (with retries) or STREAMING_MODE. - **resetCommunicationSuccessRate()**: Resets internal success rate counters. - **getReadSuccessRate()**: Returns float (0.0-1.0) representing read success percentage. - **getWriteSuccessRate()**: Returns float (0.0-1.0) representing write success percentage. - **setSlaveAddress(address, naiPinHigh)**: Configures the slave address for the transceiver. ``` -------------------------------- ### setRampMode() - Select Motion Control Mode Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Selects the operational mode for the motor, including positioning, velocity, or hold modes. ```APIDOC ## setRampMode(mode) ### Description Selects between positioning mode (autonomous move to target), velocity mode (continuous rotation at set speed), or hold mode (maintain current velocity). ### Parameters - **mode** (int) - Required - The mode to set: TMC5160::POSITIONING_MODE, TMC5160::VELOCITY_MODE, or TMC5160::HOLD_MODE. ``` -------------------------------- ### Control Motor via UART Interface Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Initializes and controls a TMC5160 motor driver using a single-wire UART interface with an external RS485 transceiver. Requires SD_MODE and SPI_MODE pins to be tied low. ```cpp #include #include const uint8_t UART_TX_EN_PIN = 5; // Transceiver TX enable pin const uint32_t UART_BAUDRATE = 500000; // Up to 750kbps with default clock // Address 0 when NAI pin is LOW TMC5160_UART_Transceiver motor = TMC5160_UART_Transceiver( UART_TX_EN_PIN, // TX enable pin Serial1, // Hardware serial port 0, // Slave address (0-253 if NAI LOW, 1-254 if NAI HIGH) UART_BAUDRATE // Baud rate ); void setup() { Serial.begin(115200); Serial1.begin(UART_BAUDRATE); Serial1.setTimeout(5); // Short timeout for register reads TMC5160::PowerStageParameters powerStageParams; TMC5160::MotorParameters motorParams; motorParams.globalScaler = 98; motorParams.irun = 31; motorParams.ihold = 16; motor.begin(powerStageParams, motorParams, TMC5160::NORMAL_MOTOR_DIRECTION); // Enable reliable communication mode with retries motor.setCommunicationMode(TMC5160_UART_Generic::RELIABLE_MODE); motor.setRampMode(TMC5160::POSITIONING_MODE); motor.setMaxSpeed(400); motor.setAcceleration(500); } void loop() { static unsigned long lastMove = 0; static bool direction = false; if (millis() - lastMove > 3000) { lastMove = millis(); direction = !direction; motor.setTargetPosition(direction ? 200 : 0); } // Check communication success rate Serial.print("Read success: "); Serial.print(motor.getReadSuccessRate() * 100); Serial.print("% Write success: "); Serial.print(motor.getWriteSuccessRate() * 100); Serial.println("%"); delay(100); } ``` -------------------------------- ### Monitor TMC5160 Encoder Position and Deviation Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Read current and latched motor and encoder positions using getCurrentPosition(), getEncoderPosition(), getLatchedPosition(), and getLatchedEncoderPosition(). Check for position deviation with isEncoderDeviationDetected() and clear the flag with clearEncoderDeviationFlag(). ```cpp #include TMC5160_SPI motor = TMC5160_SPI(5); void monitorEncoder() { // Read positions float motorPos = motor.getCurrentPosition(); float encoderPos = motor.getEncoderPosition(); float latchedMotorPos = motor.getLatchedPosition(); float latchedEncoderPos = motor.getLatchedEncoderPosition(); Serial.print("Motor: "); Serial.print(motorPos); Serial.print(" Encoder: "); Serial.print(encoderPos); Serial.print(" Deviation: "); Serial.println(motorPos - encoderPos); // Check for step loss if (motor.isEncoderDeviationDetected()) { Serial.println("WARNING: Position deviation detected!"); // Handle deviation (re-home, reduce speed, etc.) motor.clearEncoderDeviationFlag(); } } ``` -------------------------------- ### Monitor TMC5160 Driver Status Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Use getDriverStatus() to retrieve the current error state of the TMC5160 driver. Check against predefined status codes or use getDriverStatusDescription() for human-readable messages. Handle critical errors like undervoltage, shorts, or overtemperature. ```cpp #include TMC5160_SPI motor = TMC5160_SPI(5); void monitorDriverHealth() { TMC5160::DriverStatus status = motor.getDriverStatus(); switch (status) { case TMC5160::OK: Serial.println("Driver OK"); break; case TMC5160::CP_UV: Serial.println("Charge pump undervoltage!"); break; case TMC5160::S2VSA: Serial.println("Short to supply on phase A!"); break; case TMC5160::S2VSB: Serial.println("Short to supply on phase B!"); break; case TMC5160::S2GA: Serial.println("Short to ground on phase A!"); break; case TMC5160::S2GB: Serial.println("Short to ground on phase B!"); break; case TMC5160::OT: Serial.println("OVERTEMPERATURE! Driver disabled."); break; case TMC5160::OTPW: Serial.println("Overtemperature warning - reduce load"); break; case TMC5160::OTHER_ERR: Serial.println("Unknown driver error"); break; } // Or use the built-in description Serial.println(TMC5160::getDriverStatusDescription(status)); } ``` ```cpp void continuousMonitoring() { while (true) { TMC5160::DriverStatus status = motor.getDriverStatus(); if (status != TMC5160::OK && status != TMC5160::OTPW) { // Critical error - stop motor motor.stop(); Serial.print("CRITICAL: "); Serial.println(TMC5160::getDriverStatusDescription(status)); break; } delay(100); } } ``` -------------------------------- ### Monitor UART Communication Statistics Source: https://context7.com/tommag/tmc5160_arduino/llms.txt Tracks read and write success rates to diagnose wiring or EMI issues in UART mode. Reliable mode enables automatic retries, while streaming mode prioritizes throughput. ```cpp #include TMC5160_UART_Transceiver motor = TMC5160_UART_Transceiver(5, Serial1, 0, 500000); void monitorUARTCommunication() { // Enable reliable mode with automatic retries motor.setCommunicationMode(TMC5160_UART_Generic::RELIABLE_MODE); // Or use streaming mode for maximum throughput (no retries) // motor.setCommunicationMode(TMC5160_UART_Generic::STREAMING_MODE); // Reset statistics motor.resetCommunicationSuccessRate(); // Perform some operations... for (int i = 0; i < 100; i++) { motor.getCurrentPosition(); motor.getCurrentSpeed(); } // Check success rates float readRate = motor.getReadSuccessRate(); float writeRate = motor.getWriteSuccessRate(); Serial.print("Read success rate: "); Serial.print(readRate * 100); Serial.println("%"); Serial.print("Write success rate: "); Serial.print(writeRate * 100); Serial.println("%"); if (readRate < 0.95) { Serial.println("Warning: Communication issues detected"); // Try resetting communication motor.resetCommunication(); } // Change slave address if needed motor.setSlaveAddress(1, true); // Address 1, NAI pin is HIGH motor.setInternalSlaveAddress(1); // Update internal tracking } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.