Skip to content

Instantly share code, notes, and snippets.

@StuffAndyMakes
Created January 25, 2025 17:45
Show Gist options
  • Save StuffAndyMakes/5d05e7bd0ded5e3478c7aa9035102551 to your computer and use it in GitHub Desktop.
Save StuffAndyMakes/5d05e7bd0ded5e3478c7aa9035102551 to your computer and use it in GitHub Desktop.
Automotive Stepper TMC2208 Test
/*
* Testing little dashboard steppers with a TMC2208 stepper driver (all from Amazon)
* Stepper: https://a.co/d/4dKBO58
* Driver: https://a.co/d/bby0QgZ
*
* Tested on an Arduino UNO clone.
*
* Code will run the stepper to the maximum clockwise, then back to the 0 stop.
* It will then pick random steps to jump to (clockwise or counterclockwise)
* and do that indefinitely.
*/
#include <Arduino.h>
// Pin Definitions
#define EN_PIN 8 // LOW: Driver enabled, HIGH: Driver disabled
#define STEP_PIN 9 // Step on the rising edge
#define DIR_PIN 10 // Set stepping direction
// Number of steps to move in each direction
#define TOTAL_STEPS 2560 // 1/2 step (300 µs delay seems better)
#define STEP_DELAY 300 // Delay in microseconds between each step
#define BACKWARD 1
#define FORWARD 0
void step(int steps, int direction);
void setup()
{
// Configure pin modes
pinMode(EN_PIN, OUTPUT);
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
// Initialize pin states
digitalWrite(DIR_PIN, LOW); // Set initial direction
digitalWrite(EN_PIN, LOW); // Enable the driver
// initialize position
step(TOTAL_STEPS, FORWARD);
step(TOTAL_STEPS, BACKWARD);
delay(1000);
}
int currentPosition = 0;
void loop()
{
long wait = random(250, 1000);
delay(wait);
int nextPosition = random(0, TOTAL_STEPS);
int direction = currentPosition > nextPosition ? BACKWARD : FORWARD;
if (direction == BACKWARD)
{
step(currentPosition - nextPosition, direction);
}
else
{
step(nextPosition - currentPosition, direction);
}
currentPosition = nextPosition;
}
void step(int steps, int direction)
{
// set the direction pin
digitalWrite(DIR_PIN, direction == FORWARD ? HIGH : LOW);
// repeat pin toggle for each step
for (int i = 0; i < steps; i++)
{
// Toggle the step pin
digitalWrite(STEP_PIN, LOW);
digitalWrite(STEP_PIN, HIGH);
// Wait for the specified delay
delayMicroseconds(STEP_DELAY);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment