// Motor Control Pins
#define STEP_PIN 18 // PUL+
#define DIR_PIN 19 // DIR+
#define ENABLE_PIN 21 // ENA+
// Button Pins
#define RESET_BUTTON 25
#define CW_BUTTON 26
#define CCW_BUTTON 27
#define FINE_CW_BUTTON 32
#define FINE_CCW_BUTTON 33
// Limit Switch Pin
#define LIMIT_SWITCH_PIN 34 // Connect to a limit switch for homing
// Motor Step Delay (Adjust for Speed)
#define STEP_DELAY 500 // Microseconds
#define FINE_STEP 10 // Number of steps for fine adjustment
#define ROUGH_STEP 100 // Number of steps for rough adjustment
void setup() {
// Set motor pins as outputs
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
pinMode(ENABLE_PIN, OUTPUT);
// Enable the motor driver
digitalWrite(ENABLE_PIN, LOW); // Active LOW
// Set button pins as inputs with pull-up resistors
pinMode(RESET_BUTTON, INPUT_PULLUP);
pinMode(CW_BUTTON, INPUT_PULLUP);
pinMode(CCW_BUTTON, INPUT_PULLUP);
pinMode(FINE_CW_BUTTON, INPUT_PULLUP);
pinMode(FINE_CCW_BUTTON, INPUT_PULLUP);
// Set limit switch pin as input
pinMode(LIMIT_SWITCH_PIN, INPUT_PULLUP);
// Perform homing on power-on
homeMotor();
}
void loop() {
// Check Reset Button
if (digitalRead(RESET_BUTTON) == LOW) {
homeMotor(); // Reset to initial position
}
// Check CW Drive Button
if (digitalRead(CW_BUTTON) == LOW) {
driveMotor(true); // Drive CW
}
// Check CCW Drive Button
if (digitalRead(CCW_BUTTON) == LOW) {
driveMotor(false); // Drive CCW
}
// Check Fine CW Adjust Button
if (digitalRead(FINE_CW_BUTTON) == LOW) {
fineAdjust(true); // Fine adjust CW
}
// Check Fine CCW Adjust Button
if (digitalRead(FINE_CCW_BUTTON) == LOW) {
fineAdjust(false); // Fine adjust CCW
}
}
// Function to move motor continuously in a direction
void driveMotor(bool clockwise) {
digitalWrite(DIR_PIN, clockwise ? LOW : HIGH); // Set direction
for (int i = 0; i < ROUGH_STEP; i++) { // Fine adjustment steps
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(STEP_DELAY);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(STEP_DELAY);
}
delay(200); // Debounce delay
}
// Function for fine adjustment
void fineAdjust(bool clockwise) {
digitalWrite(DIR_PIN, clockwise ? LOW : HIGH); // Set direction
for (int i = 0; i < FINE_STEP; i++) { // Fine adjustment steps
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(STEP_DELAY);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(STEP_DELAY);
}
delay(200); // Debounce delay
}
// Function to home the motor
void homeMotor() {
digitalWrite(DIR_PIN, HIGH); // Move CCW towards the home position
while (digitalRead(LIMIT_SWITCH_PIN) == HIGH) { // Wait until limit switch is triggered
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(STEP_DELAY);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(STEP_DELAY);
}
delay(1000); // Pause after homing
}