#include <LiquidCrystal_I2C.h>
#include <Stepper.h>
// LCD for display
LiquidCrystal_I2C lcd(0x27, 20, 4); // 20x4 LCD display
// Stepper motor setup (adjust stepsPerRevolution based on your motor)
const int stepsPerRevolution = 200; // Common stepper motors have 200 or 2048 steps per revolution
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); // 4-wire stepper motor pins
int potentiometer_pin = A0; // Potentiometer connected to A0
// Define buttons
#define bt_F A1 // Clockwise Button
#define bt_S A2 // Stop Button
#define bt_B A3 // Anticlockwise Button
int Mode = 1; // Start in Stop mode
int lastMode = -1; // For detecting mode changes
void setup() {
pinMode(potentiometer_pin, INPUT); // Potentiometer as input
pinMode(bt_F, INPUT_PULLUP); // Clockwise button with internal pull-up
pinMode(bt_S, INPUT_PULLUP); // Stop button with internal pull-up
pinMode(bt_B, INPUT_PULLUP); // Anticlockwise button with internal pull-up
myStepper.setSpeed(1); // Initialize with zero speed
lcd.begin(20, 4); // Initialize LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Stepper Motor Ctrl");
// lcd.setCursor(0, 1);
// lcd.print("By Pot & Buttons");
}
void loop() {
// Read potentiometer value and map it to a motor speed range
int potValue = analogRead(potentiometer_pin);
double lightBrightness = potValue / 4;
double lightLcd = map(lightBrightness, 0, 255, 0, 100);
lcd.setCursor(0, 1);
lcd.print("Brightness "); lcd.print(lightLcd); lcd.print("% ");
analogWrite(6, lightBrightness);
int motorSpeed = map(potValue, 0, 1023, 1, 500); // Increase max RPM to 500
// Update motor speed display on LCD
lcd.setCursor(0, 2);
lcd.print("Speed: ");
lcd.print(map(potValue, 0, 1023, 0, 100)); // Display % speed on LCD
lcd.print("% "); // Clear trailing characters
// Handle button inputs to set the mode
if (digitalRead(bt_F) == LOW) {
Mode = 2; // Clockwise
} else if (digitalRead(bt_S) == LOW) {
Mode = 1; // Stop
} else if (digitalRead(bt_B) == LOW) {
Mode = 3; // Anticlockwise
}
// Display mode on LCD
if (Mode != lastMode) { // Only update if mode has changed
lcd.setCursor(0, 3);
if (Mode == 1) lcd.print(" Stop ");
else if (Mode == 2) lcd.print(" Clockwise ");
else if (Mode == 3) lcd.print(" Anticlockwise ");
lastMode = Mode;
}
// Control motor based on mode and speed
if (motorSpeed > 1) { // Only move the motor if the speed is greater than 0
if (Mode == 2) { // Clockwise
myStepper.setSpeed(motorSpeed); // Set the speed
myStepper.step(stepsPerRevolution / 10); // Increase the number of steps for faster movement
} else if (Mode == 3) { // Anticlockwise
myStepper.setSpeed(motorSpeed); // Set the speed
myStepper.step(-(stepsPerRevolution / 10)); // Increase steps in reverse direction
}
} else {
// Stop the motor when speed is 0
myStepper.setSpeed(1);
}
delay(50); // Reduce delay for smoother motor operation
}