#include <AccelStepper.h>

// Pin definitions
#define STEP_PIN 2
#define DIR_PIN 3
#define SAFETY_BUTTON_PIN 4
#define CW_BUTTON_PIN 5
#define CCW_BUTTON_PIN 6
#define POTENTIOMETER_PIN A0

// Create an instance of the AccelStepper class
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);

// Variables
int safetyButtonState = 0;
int cwButtonState = 0;
int ccwButtonState = 0;
int potentiometerValue = 0;
int motorSpeed = 0;

void setup() {
  // Set up pin modes
  pinMode(SAFETY_BUTTON_PIN, INPUT_PULLUP);
  pinMode(CW_BUTTON_PIN, INPUT_PULLUP);
  pinMode(CCW_BUTTON_PIN, INPUT_PULLUP);

  // Set the maximum speed and acceleration for the stepper motor
  stepper.setMaxSpeed(1000); // Adjust as needed
  stepper.setAcceleration(500); // Adjust as needed
}

void loop() {
  // Read the safety button state
  safetyButtonState = digitalRead(SAFETY_BUTTON_PIN);

  // Only respond to other buttons if the safety button is pressed
  if (safetyButtonState == LOW) {
    // Read the clockwise and counterclockwise button states
    cwButtonState = digitalRead(CW_BUTTON_PIN);
    ccwButtonState = digitalRead(CCW_BUTTON_PIN);

    // Read the potentiometer value to set the motor speed
    potentiometerValue = analogRead(POTENTIOMETER_PIN);
    motorSpeed = map(potentiometerValue, 0, 1023, 100, 1000); // Map to desired speed range
    stepper.setMaxSpeed(motorSpeed);

    // Determine motor direction based on button presses
    if (cwButtonState == LOW && ccwButtonState == HIGH) {
      stepper.setSpeed(motorSpeed); // Clockwise
    } else if (ccwButtonState == LOW && cwButtonState == HIGH) {
      stepper.setSpeed(-motorSpeed); // Counterclockwise
    } else {
      stepper.setSpeed(0); // Stop
    }
  } else {
    // Stop the motor if the safety button is not pressed
    stepper.setSpeed(0);
  }

  // Run the stepper motor
  stepper.runSpeed();
}
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
A4988