#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 13 // 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 forwardButton = 8; // Button for forward movement
const int backwardButton = 9; // Button for backward movement
const int resetButton = 10; // Button for resetting the motor position
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
pinMode(forwardButton, INPUT_PULLUP);
pinMode(backwardButton, INPUT_PULLUP);
pinMode(resetButton, 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
// Check for button presses to control motor movement
if (digitalRead(forwardButton) == LOW) { // Button for forward movement
stepper.setSpeed(200); // Set speed for forward movement
stepper.runSpeed(); // Run the motor
digitalWrite(movePin, HIGH); // Turn on the move LED
} else if (digitalRead(backwardButton) == LOW) { // Button for reverse movement
stepper.setSpeed(-200); // Set speed for reverse movement
stepper.runSpeed(); // Run the motor
digitalWrite(movePin, HIGH); // Turn on the move LED
} else {
stepper.stop(); // Stop the motor if no button is pressed
digitalWrite(movePin, LOW); // Turn off the move LED
}
// Check for reset button press to reset the stepper motor count
if (digitalRead(resetButton) == 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
}