#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Initialize the LCD with I2C address 0x27 (common address)
LiquidCrystal_I2C lcd(0x27, 16, 2); // 16 columns and 2 rows
// Stepper motor pins
const int stepPin = 2;
const int dirPin = 3;
// 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(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(forwardButtonPin, INPUT_PULLUP);
pinMode(reverseButtonPin, INPUT_PULLUP);
pinMode(resetButtonPin, INPUT_PULLUP); // Set reset button pin mode
// 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) {
digitalWrite(dirPin, HIGH); // Set direction to forward
stepMotor();
steps++;
} else if (movingReverse) {
digitalWrite(dirPin, LOW); // Set direction to reverse
stepMotor();
steps--;
}
// 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
}
void stepMotor() {
digitalWrite(stepPin, HIGH);
delayMicroseconds(1000); // Adjust for step speed
digitalWrite(stepPin, LOW);
delayMicroseconds(1000); // Adjust for step speed
}