#include <Wire.h>
#include <AccelStepper.h>
#include <LiquidCrystal_I2C.h>
// Define the step and direction pins
#define STEP_PIN 2
#define DIR_PIN 3
#define movePin 52 // Built-in LED on most Arduino boards
// Define the I2C address of the LCD display
#define LCD_ADDRESS 0x27
// Define the number of columns and rows of the LCD display
#define LCD_COLUMNS 16
#define LCD_ROWS 2
// Create a new instance of the AccelStepper class
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
// Create a new instance of the LiquidCrystal_I2C class
LiquidCrystal_I2C lcd(LCD_ADDRESS, LCD_COLUMNS, LCD_ROWS);
// Define the button pins
const int buttonPins[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // Use digital pins for buttons
#define FORWARD_BUTTON buttonPins[8] // Button for forward movement
#define BACKWARD_BUTTON buttonPins[9] // Button for backward movement
// Define the button pin for resetting the stepper motor count
#define RESET_PIN 16
void setup() {
// Initialize serial communication
Serial.begin(9600); // Start serial communication at 9600 baud
// Set the maximum speed and acceleration
stepper.setMaxSpeed(2000.0); // Adjust as needed
stepper.setAcceleration(600.0); // Adjust as needed
// Set the button pins as input
for (int i = 0; i < 10; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
// Set the LED pin as output
pinMode(movePin, OUTPUT);
// Initialize the LCD display
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Motor Steps:"); // Display title
lcd.setCursor(0, 1);
lcd.print("Steps: 0 "); // Initialize steps display
}
void loop() {
// Update the LCD display with the current motor steps
lcd.setCursor(7, 0); // Set cursor for motor steps
lcd.print(stepper.currentPosition()); // Print the current position
// Print the current position to the Serial Monitor
Serial.print("Current Motor Steps: ");
Serial.println(stepper.currentPosition()); // Output current position to Serial Monitor
// Check for button presses to control motor movement
if (digitalRead(FORWARD_BUTTON) == LOW) { // Button for forward movement
stepper.setSpeed(2000); // Set speed for forward movement
stepper.runSpeed();
} else if (digitalRead(BACKWARD_BUTTON) == LOW) { // Button for reverse movement
stepper.setSpeed(-2000); // Set speed for reverse movement
stepper.runSpeed();
} else {
stepper.stop(); // Stop the motor if no button is pressed
}
// Check for reset button press to reset the stepper motor count
if (digitalRead(RESET_PIN) == LOW) {
stepper.setCurrentPosition(0); // Reset the stepper motor count to zero
stepper.stop(); // Stop the motor if the button is pressed
lcd.clear(); // Clear the LCD
lcd.setCursor(0, 0);
lcd.print("Motor Steps:"); // Reset display
lcd.setCursor(0, 1);
lcd.print("Steps: 0 "); // Initialize steps display
}
delay(100); // Small delay for stability
}