/*
Copy based on https://wokwi.com/projects/398623243943654401
* Date: 11/11/2024
*Description: This code controls a servo motor using Arduino and displays the angle on an LCD screen.
It allows control via button input. The up and down buttons incrementally changes the servo angle in 1 deg increments.
In addition, a third reset button is provided to return the servo to the original position.
Real-time feedback is provided on the LCD display.
*/
#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
Servo myServo;
int angle = 90; // Start at mid-position (90 degrees)
int increaseButtonPin = 2; // Button to increase servo angle
int decreaseButtonPin = 3; // Button to decrease servo angle
int resetButtonPin = 4; // Button to reset servo to default position (90 degrees)
int leds[10] = {5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; // Digital pins connected to LEDs
// Define LCD properties (columns, rows)
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(9600);
myServo.attach(9); // Assuming the servo is connected to pin 9
pinMode(increaseButtonPin, INPUT_PULLUP); // Set increase button pin as input with internal pull-up resistor 10kOhms
pinMode(decreaseButtonPin, INPUT_PULLUP); // Set decrease button pin as input with internal pull-up resistor 10kOhms
pinMode(resetButtonPin, INPUT_PULLUP); // Set reset button pin as input with internal pull-up resistor 10kOhms
for (int i = 0; i < 10; i++) {
pinMode(leds[i], OUTPUT); // Set LED pins as output
}
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on backlight
lcd.setCursor(0, 0);
lcd.print("Servo: ");
lcd.setCursor(0, 1);
lcd.print("Mode: ");
myServo.write(angle); // Initialize servo to the starting angle
displayAngle(angle);
displayComment("INITIALIZED");
}
void loop() {
if (digitalRead(increaseButtonPin) == LOW) {
increaseAngle();
}
if (digitalRead(decreaseButtonPin) == LOW) {
decreaseAngle();
}
if (digitalRead(resetButtonPin) == LOW) {
resetAngle();
}
}
void increaseAngle() {
if (angle < 180) {
angle += 1;
myServo.write(angle); // Move servo to new angle
displayAngle(angle);
displayComment("UP");
delay(100); // Add delay to debounce
}
}
void decreaseAngle() {
if (angle > 0) {
angle -= 1;
myServo.write(angle); // Move servo to new angle
displayAngle(angle);
displayComment("DOWN");
delay(100); // Add delay to debounce
}
}
void resetAngle() {
angle = 90; // Set angle to default position (90 degrees)
myServo.write(angle); // Move servo to default position
displayAngle(angle);
displayComment("RESET");
delay(100); // Add delay to debounce
}
void displayAngle(int angle) {
lcd.setCursor(7, 0);
lcd.print(" "); // Clear previous servo angle value
lcd.setCursor(7, 0);
lcd.print(angle); // Display current servo angle
}
void displayComment(String mode) {
lcd.setCursor(6, 1);
lcd.print(" "); // Clear previous servo angle value
lcd.setCursor(6, 1);
lcd.print(mode); // Display current servo angle
}