// Include the AccelStepper library
#include <AccelStepper.h>
// Define the stepper motor connections
#define STEP_PIN 2
#define DIR_PIN 3
#define RELAY_PIN 12
#define POT_PIN A0 // Define the analog input pin for the potentiometer
#define SWITCH_PIN_RIGHT 5 // Define the switch pin for changing the rotation direction
#define SWITCH_PIN_LEFT 6
// Create a new AccelStepper object
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
// Variables to store the potentiometer value and switch state
int potValue = 0;
int switchState1 = 0;
int switchState2 = 0;
void setup() {
// Set the maximum speed and acceleration of the stepper motor
stepper.setMaxSpeed(1000);
stepper.setAcceleration(0);
// Set the pinMode for the switch pin
pinMode(SWITCH_PIN_RIGHT, INPUT_PULLUP); // Using INPUT_PULLUP to enable internal pull-up resistor
pinMode(SWITCH_PIN_LEFT, INPUT_PULLUP);
pinMode(RELAY_PIN, OUTPUT);
}
void loop() {
// Read the potentiometer value
potValue = analogRead(POT_PIN);
// Map the potentiometer value to a speed range
int speed = map(potValue, 0, 1023, 0, 1000);
// Set the speed and direction of the stepper motor
stepper.setSpeed(speed);
// Read the switch state
switchState1 = digitalRead(SWITCH_PIN_RIGHT);
switchState2 = digitalRead(SWITCH_PIN_LEFT);
if (switchState1 == LOW && switchState2 == HIGH) // Switch left pressed
{
digitalWrite(RELAY_PIN, HIGH);
stepper.setSpeed(-speed); // Reverse direction by setting negative speed
}
else if (switchState1 == HIGH && switchState2 == LOW) // Switch right pressed
{
digitalWrite(RELAY_PIN, HIGH);
stepper.setSpeed(speed); // Forward direction by setting speed
}
else
{
digitalWrite(RELAY_PIN, LOW);
stepper.setSpeed(0); // Ha egyik kapcsoló sem van lenyomva, a motor álljon meg
}
// Move the stepper motor one step
stepper.runSpeed();
}