#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define the connections to the A4988 driver
#define STEP_PIN 2
#define DIR_PIN 3
#define BUTTON_UP 4
#define BUTTON_DOWN 5
// Define the number of steps per revolution for your stepper motor
#define STEPS_PER_REV 600
// Define positions for each floor (in steps)
#define FLOOR_1 0
#define FLOOR_2 600
#define FLOOR_3 1200
// Variable to track the current floor
int currentFloor = 1;
// Initialize the LCD with the found address
LiquidCrystal_I2C lcd(0x27, 16, 2); // Change 0x27 to your I2C address if different
void setup() {
// Set the pin modes
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
pinMode(BUTTON_UP, INPUT_PULLUP);
pinMode(BUTTON_DOWN, INPUT_PULLUP);
// Initialize the LCD
lcd.begin(16,2);
lcd.backlight();
updateLCD();
// Initialize the direction to clockwise
digitalWrite(DIR_PIN, LOW);
}
void loop() {
// Read the button states
bool buttonUp = !digitalRead(BUTTON_UP); // Inverted because of INPUT_PULLUP
bool buttonDown = !digitalRead(BUTTON_DOWN);
if (buttonUp && currentFloor < 3) {
// Move to the next floor up
moveToFloor(currentFloor + 1);
} else if (buttonDown && currentFloor > 1) {
// Move to the next floor down
moveToFloor(currentFloor - 1);
}
}
void moveToFloor(int targetFloor) {
int targetPosition;
switch(targetFloor) {
case 1:
targetPosition = FLOOR_1;
break;
case 2:
targetPosition = FLOOR_2;
break;
case 3:
targetPosition = FLOOR_3;
break;
}
int stepsToMove = targetPosition - (currentFloor - 1) * STEPS_PER_REV;
if (stepsToMove > 0) {
digitalWrite(DIR_PIN, HIGH); // Clockwise
} else {
digitalWrite(DIR_PIN, LOW); // Counterclockwise
stepsToMove = -stepsToMove;
}
for (int i = 0; i < stepsToMove; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(1000); // Adjust the delay to control speed
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(1000); // Adjust the delay to control speed
}
// Update the current floor
currentFloor = targetFloor;
updateLCD();
}
void updateLCD() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Current Floor: ");
lcd.setCursor(0, 1);
lcd.print(currentFloor);
}