Hey all. I am brand new to Arduino and can't seem to figure out how to get my Uno R3 to control a Nema 23 stepper motor with a DM542T controller. I have checked and rechecked my wiring and believe it to be correct so I am left with thinking my sketch is the problem. I am trying to use two momentary switches and a potentiometer to control the direction and speed of the motor. Any advice would be greatly appreciated.
#include <AccelStepper.h>
// Define the stepper motor connections
#define STEP_PIN 2
#define DIR_PIN 5
// Define the switch pins
#define CLOCKWISE_SWITCH 7
#define COUNTER_CLOCKWISE_SWITCH 8
// Define the potentiometer pin
#define POTENTIOMETER_PIN A0
// Create an AccelStepper object
AccelStepper stepper(1, STEP_PIN, DIR_PIN);
// Variables to store switch state
int clockwiseSwitchState = 0;
int counterClockwiseSwitchState = 0;
void setup() {
// Set the switch pins as INPUT_PULLUP
pinMode(CLOCKWISE_SWITCH, INPUT_PULLUP);
pinMode(COUNTER_CLOCKWISE_SWITCH, INPUT_PULLUP);
// Set the potentiometer pin as INPUT
pinMode(POTENTIOMETER_PIN, INPUT);
// Set stepper motor speed and acceleration
stepper.setMaxSpeed(1000.0);
stepper.setAcceleration(500.0);
}
void loop() {
// Read switch states
clockwiseSwitchState = digitalRead(CLOCKWISE_SWITCH);
counterClockwiseSwitchState = digitalRead(COUNTER_CLOCKWISE_SWITCH);
// If clockwise switch is pressed, move the motor clockwise
if (clockwiseSwitchState == LOW) {
stepper.setSpeed(AnalogReadMapped(POTENTIOMETER_PIN, 0, 1000));
stepper.move(100); // Adjust the steps per revolution as needed
stepper.runSpeed();
}
// If counter-clockwise switch is pressed, move the motor counter-clockwise
else if (counterClockwiseSwitchState == LOW) {
stepper.setSpeed(-AnalogReadMapped(POTENTIOMETER_PIN, 0, 1000));
stepper.move(-100); // Adjust the steps per revolution as needed
stepper.runSpeed();
}
// If no switch is pressed, stop the motor
else {
stepper.setCurrentPosition(0);
}
}
// Function to map analog input to a specific range
int AnalogReadMapped(int pin, int fromLow, int fromHigh, int toLow, int toHigh) {
return map(analogRead(pin), fromLow, fromHigh, toLow, toHigh);
}
// Overloaded function with default mapping range (0-1023 to 0-255)
int AnalogReadMapped(int pin, int toLow, int toHigh) {
return AnalogReadMapped(pin, 0, 1023, toLow, toHigh);
}