#include <AccelStepper.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int directionPin = 8;
const int stepPin = 9;
const int buttonPin1 = 2; // Start/Stop button
const int buttonPin2 = 3; // Toggle direction button
const int numberOfSteps = 360;
const int pulseWidthMicros = 20;
const int millisBetweenSteps = 10;
const int potentiometerPin = A3;
bool clockwise = true; // Variable to track the direction of the stepper motor
bool motorRunning = false; // Variable to track if the motor is currently running
AccelStepper stepper(1, stepPin, directionPin); // Using interface 1 (step/direction) and assigning pins
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
pinMode(3, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(5, OUTPUT);
pinMode(buttonPin1, INPUT); // Internal pull-up resistor enabled for button 1 pin
pinMode(buttonPin2, INPUT); // Internal pull-up resistor enabled for button 2 pin
pinMode(potentiometerPin, INPUT);
stepper.setMaxSpeed(1); // Set the maximum speed in steps per second
stepper.setAcceleration(1); // Set the acceleration in steps per second per second
}
void loop() {
int a = map(analogRead(potentiometerPin),0,1023,0,100);
stepper.setMaxSpeed(a); // Set the maximum speed in steps per second
stepper.setAcceleration(a); // Set the acceleration in steps per second per second
Serial.println(analogRead(potentiometerPin));
if(digitalRead(3)) digitalWrite(LED_BUILTIN, HIGH);
else digitalWrite(LED_BUILTIN, LOW);
if(digitalRead(2)) digitalWrite(5, HIGH);
else digitalWrite(5, LOW);
// Toggle direction button
// Serial.println(digitalRead(buttonPin1));
// if(clockwise) Serial.println("Clockwise");
// else Serial.println("Anticlockwise");
if (digitalRead(buttonPin2) == HIGH) {
// Toggle the direction of the stepper motor
clockwise = !clockwise;
}
// Start/Stop button
if (digitalRead(buttonPin1) == HIGH) {
if (!motorRunning) {
// Start the motor movement in the selected direction
if (clockwise) {
stepper.moveTo(1); // Move the motor a fixed number of steps in one direction
} else {
stepper.moveTo(-1); // Move the motor a fixed number of steps in the opposite direction
}
stepper.run(); // Start the motor movement
motorRunning = true; // Set motorRunning to true
} else {
// Stop the motor movement
stepper.stop(); // Immediately stop the motor
stepper.setCurrentPosition(0); // Reset the current position to zero
motorRunning = false; // Set motorRunning to false
}
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Rotation Direction:");
lcd.setCursor(0, 1);
lcd.print(directionPin);
delay(1000);
}