#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <AccelStepper.h> // Include the AccelStepper library
// Initialize the LCD with I2C address 0x27 (common address)
LiquidCrystal_I2C lcd(0x27, 16, 2); // 16 columns and 2 rows
// Define stepper motor connections and motor interface type
#define stepPin 2
#define dirPin 3
AccelStepper stepper(AccelStepper::DRIVER, stepPin, dirPin); // Create an instance of the AccelStepper class
// Button pins
const int forwardButtonPin = 7;
const int reverseButtonPin = 8;
const int resetButtonPin = 9; // Reset button pin
// Variables
int steps = 0;
bool movingForward = false;
bool movingReverse = false;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize the LCD with the number of columns and rows
lcd.begin(16, 2); // Specify 16 columns and 2 rows
lcd.backlight();
// Set pin modes
pinMode(forwardButtonPin, INPUT_PULLUP);
pinMode(reverseButtonPin, INPUT_PULLUP);
pinMode(resetButtonPin, INPUT_PULLUP); // Set reset button pin mode
// Set initial speed and acceleration
stepper.setMaxSpeed(1000); // Set maximum speed
stepper.setAcceleration(500); // Set acceleration
// Display initial message
lcd.setCursor(0, 0);
lcd.print("Steps: ");
lcd.setCursor(0, 1);
lcd.print(steps);
}
void loop() {
// Check button states
if (digitalRead(forwardButtonPin) == LOW) {
movingForward = true;
movingReverse = false;
} else if (digitalRead(reverseButtonPin) == LOW) {
movingReverse = true;
movingForward = false;
} else {
movingForward = false;
movingReverse = false;
}
// Check reset button state
if (digitalRead(resetButtonPin) == LOW) {
steps = 0; // Reset steps to zero
lcd.setCursor(0, 1);
lcd.print("Reset "); // Display reset message
delay(500); // Debounce delay
} else {
// Move the stepper motor
if (movingForward) {
stepper.move(100); // Move forward by 100 steps
steps += 100;
} else if (movingReverse) {
stepper.move(-100); // Move backward by 100 steps
steps -= 100;
}
// Update the stepper motor position
stepper.run();
// Update the LCD and Serial output
lcd.setCursor(6, 0);
lcd.print(steps);
Serial.print("Steps: ");
Serial.println(steps);
}
delay(100); // Adjust delay for speed control
}