Advertisement
microrobotics

DRV8825 interfaced with ESP32

Dec 5th, 2024
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Arduino.h>
  2.  
  3. // Pin definitions
  4. #define STEP_PIN 18   // Step pin for DRV8825
  5. #define DIR_PIN 19    // Direction pin for DRV8825
  6. #define ENABLE_PIN 23 // Enable pin for DRV8825 (optional)
  7.  
  8. // Stepper motor parameters
  9. int stepsPerRevolution = 200; // Motor-specific (commonly 200 steps/rev)
  10. int microstepping = 32;       // Microstepping setting (DRV8825 jumpers)
  11. int delayHigh = 1500;         // Duration HIGH in microseconds
  12. int delayLow = 1500;          // Duration LOW in microseconds
  13. int totalSteps;               // Total steps for one revolution
  14.  
  15. void setup() {
  16.   // Initialize pins
  17.   pinMode(STEP_PIN, OUTPUT);
  18.   pinMode(DIR_PIN, OUTPUT);
  19.   pinMode(ENABLE_PIN, OUTPUT);
  20.  
  21.   // Enable the motor
  22.   digitalWrite(ENABLE_PIN, LOW);
  23.  
  24.   // Set direction to forward
  25.   digitalWrite(DIR_PIN, HIGH);
  26.  
  27.   // Calculate total steps per revolution with microstepping
  28.   totalSteps = stepsPerRevolution * microstepping;
  29.  
  30.   Serial.begin(115200);
  31.   Serial.println("Stepper motor initialized.");
  32. }
  33.  
  34. void loop() {
  35.   // Move one full revolution forward
  36.   Serial.println("Moving forward one revolution...");
  37.   moveStepper(totalSteps);
  38.  
  39.   // Pause for a moment
  40.   delay(2000);
  41.  
  42.   // Change direction to backward
  43.   digitalWrite(DIR_PIN, LOW);
  44.   Serial.println("Moving backward one revolution...");
  45.   moveStepper(totalSteps);
  46.  
  47.   // Pause for a moment before repeating
  48.   delay(2000);
  49. }
  50.  
  51. // Function to move the stepper motor a given number of steps
  52. void moveStepper(int steps) {
  53.   for (int i = 0; i < steps; i++) {
  54.     digitalWrite(STEP_PIN, HIGH);  // Set STEP pin HIGH
  55.     delayMicroseconds(delayHigh);  // Wait for HIGH duration
  56.     digitalWrite(STEP_PIN, LOW);   // Set STEP pin LOW
  57.     delayMicroseconds(delayLow);   // Wait for LOW duration
  58.   }
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement