Dear all,
I was hoping you can help me troubleshoot something.
I am using Arduino Mega with NEMA 17 Mercury Motor SM-42BYG011-25 and A4988 Step Driver.
When i try to increase the speed, the motor starts making scratching noise or missing steps.
Can you review my code and tell me if there is a problem in the code or that's just the limit speed of the motor.
I'd like at least 1500-1700 RPM speed from the NEMA 17 motor and i can barely get 600 RPM.
Thank you a lot.
#include <AccelStepper.h>
// Define the connections to the A4988 driver
#define stepPin 2
#define dirPin 3
#define enPin 4 // Define the enable pin
#define runButtonPin 7 // Define the run button pin
#define holdButtonPin 8 // Define the hold button pin
// Create an instance of AccelStepper
AccelStepper stepper(AccelStepper::DRIVER, stepPin, dirPin);
// State variable to keep track of motor running state
bool isMotorRunning = false;
bool lastRunButtonState = HIGH;
bool lastHoldButtonState = HIGH;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
// Set the pins as outputs or inputs as required
pinMode(enPin, OUTPUT);
pinMode(runButtonPin, INPUT_PULLUP); // Use internal pull-up resistor for run button
pinMode(holdButtonPin, INPUT_PULLUP); // Use internal pull-up resistor for hold button
// Set initial direction and speed
digitalWrite(dirPin, HIGH); // Set the direction
stepper.setMaxSpeed(700); // Set maximum speed
stepper.setAcceleration(400); // Set acceleration
stepper.setSpeed(650); // Set initial speed (lowered for testing)
// Enable the driver initially
digitalWrite(enPin, LOW); // Enable the driver
}
void loop() {
// Check if the run button is pressed
if (debounceButton(runButtonPin, &lastRunButtonState)) {
isMotorRunning = true;
digitalWrite(enPin, LOW); // Enable the driver
}
// Check if the hold button is pressed
if (debounceButton(holdButtonPin, &lastHoldButtonState)) {
isMotorRunning = false;
digitalWrite(enPin, HIGH); // Disable the driver
}
if (isMotorRunning) {
// Run the motor
stepper.runSpeed();
} else {
// Stop the motor by not calling runSpeed()
// The stepper will be disabled, allowing it to move freely
digitalWrite(stepPin, LOW); // Ensure step pin is low
}
}
// Simple debounce function
bool debounceButton(int buttonPin, bool *lastButtonState) {
bool reading = digitalRead(buttonPin);
if (reading != *lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading == LOW) {
*lastButtonState = reading;
return true;
}
}
*lastButtonState = reading;
return false;
}