#include <Servo.h>
#include <LiquidCrystal_I2C.h>
Servo myServo; // Create servo object to control a servo
int servoPin = 11; // Define the pin for the servo motor
int startButtonPin = 4; // Define the pin for the start button
int stopButtonPin = 3; // Define the pin for the stop button
int angle = 0; // Initial angle for the servo
int lastAngle = 0; // Variable to store the last angle position
int servoSpeed = 5; // Speed of servo movement (smaller delay for faster movement)
bool isServoMoving = false; // Flag to track servo movement
LiquidCrystal_I2C lcd(0x27, 16, 2); // Initialize the LCD with I2C address 0x27 and 16x2 display
void setup() {
myServo.attach(servoPin); // Attach the servo on defined pin to the servo object
pinMode(startButtonPin, INPUT_PULLUP); // Set the start button pin as input with internal pull-up resistor
pinMode(stopButtonPin, INPUT_PULLUP); // Set the stop button pin as input with internal pull-up resistor
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the LCD backlight
lcd.setCursor(0, 0);
lcd.print("Servo Control");
}
void loop() {
// Start Button Behavior
if (digitalRead(startButtonPin) == LOW && !isServoMoving) {
isServoMoving = true; // Set flag to true when start button is pressed
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Moving Servo...");
while (digitalRead(stopButtonPin) != LOW) {
// Rotate the servo motor continuously in an endless loop
for (angle = lastAngle; angle <= 180; angle++) {
myServo.write(angle);
updateLCD(angle); // Update the LCD display with the current angle
delay(servoSpeed); // Adjust the delay for faster servo speed
if (digitalRead(stopButtonPin) == LOW) {
stopServo(); // Call the function to stop the servo
break; // Exit the for loop
}
}
}
isServoMoving = false; // Reset the flag
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Servo Stopped");
delay(2000); // Delay for 2 seconds
displayMessages(); // Display the specified messages on the LCD
}
}
void stopServo() {
lastAngle = angle; // Save the last angle position
myServo.write(0); // Stop the servo movement
isServoMoving = false; // Reset the flag
}
void updateLCD(int currentAngle) {
lcd.setCursor(0, 1);
lcd.print("Angle: " + String(currentAngle)); // Display the current angle on the LCD
}
void displayMessages() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("1. Don Honorio Ventura State University");
delay(3000); // Display each message for 3 seconds
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("2. College of Industrial Technology");
delay(3000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("3. BSIT Electronics Technology");
delay(3000);
}