#include <LiquidCrystal_I2C.h> // For the I2C LCD
#include <Keypad.h> // For the 4x4 keypad
#include <Stepper.h> // For the stepper motor control
// Define the LCD
LiquidCrystal_I2C lcd(0x27, 20, 4);
// Define the keypad
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Define the stepper motor
const int stepsPerRevolution = 200; // Change this value based on your motor's specification
Stepper stepper(stepsPerRevolution,10, 11, 12, 13); // (steps, step pin, direction pin)
// Variables
long currentPosition = 0;
long targetPosition = 0;
const int maxPoints = 1;
long points[maxPoints];
int currentPoint = 0;
void setup() {
lcd.init();
lcd.backlight();
displayCurrentPoint();
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') {
targetPosition = key - '0'; // Convert the key to a position in mm
targetPosition = stepsPerRevolution; // Adjust this value based on your stepper's specification
points[currentPoint] = targetPosition;
currentPoint = (currentPoint + 1) % maxPoints;
displayCurrentPoint();
moveToPosition(targetPosition);
} else if (key == '#') {
// Stop the motor and rest for 1 second
stepper.setSpeed(60);
delay(1000);
}
}
}
void moveToPosition(long target) {
stepper.step(target - currentPosition);
currentPosition = target;
delay(1000); // Rest for 1 second
}
void displayCurrentPoint() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Point ");
lcd.print(currentPoint + 1);
lcd.setCursor(0, 1);
lcd.print("Target: ");
lcd.print(points[currentPoint] / stepsPerRevolution); // Convert back to mm
}