#include <LiquidCrystal.h>
#include <Servo.h>
// LCD Pins: RS, EN, D4, D5, D6, D7
LiquidCrystal lcd(11, 12, A1, A2, A3, A4);
Servo servo;
const int stepPin = 4;
const int dirPin = 3;
const int enPin = 5;
const int buttonPins[] = {7, 8, 9, 10};
const int potPin = A0;
const int ledPin = 2;
int motorMode = 0; // 0: Stepper, 1: Servo
bool motorActive = false;
void setup() {
lcd.begin(16, 2);
lcd.clear();
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(enPin, OUTPUT);
pinMode(ledPin, OUTPUT);
servo.attach(6);
servo.write(0); // Servo position at startup
for (int pin : buttonPins) {
pinMode(pin, INPUT_PULLUP);
}
lcd.print("System Ready");
}
void loop() {
int potValue = analogRead(potPin);
displayPotValue(potValue);
// Check buttons
if (isButtonPressed(buttonPins[0])) { // Button 1
moveMotor(HIGH, 90);
} else if (isButtonPressed(buttonPins[1])) { // Button 2
moveMotor(LOW, 0);
} else if (isButtonPressed(buttonPins[2])) { // Button 3
motorMode = 0;
updateModeDisplay("Stepper");
} else if (isButtonPressed(buttonPins[3])) { // Button 4
motorMode = 1;
updateModeDisplay("Servo");
} else {
motorActive = false;
}
digitalWrite(ledPin, motorActive ? HIGH : LOW);
}
void displayPotValue(int potValue) {
lcd.setCursor(0, 0);
lcd.print("Pot: ");
lcd.print(map(potValue, 0, 1023, 0, 100));
lcd.print(" "); // Clear trailing characters
}
bool isButtonPressed(int pin) {
if (digitalRead(pin) == LOW) {
delay(50); // Debounce delay
return digitalRead(pin) == LOW;
}
return false;
}
void moveMotor(int direction, int servoAngle) {
if (motorMode == 0) {
digitalWrite(dirPin, direction);
stepMotor();
} else {
servo.write(servoAngle);
}
motorActive = true;
}
void stepMotor() {
int potValue = analogRead(potPin);
int delayTime = map(potValue, 0, 1023, 1000, 200);
digitalWrite(enPin, LOW);
digitalWrite(stepPin, HIGH);
delayMicroseconds(delayTime);
digitalWrite(stepPin, LOW);
delayMicroseconds(delayTime);
}
void updateModeDisplay(const char* mode) {
lcd.setCursor(0, 1);
lcd.print("Mode: ");
lcd.print(mode);
lcd.print(" ");
}