#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define PHOTO_PIN A0
#define SWITCH_PIN 2
#define SERVO_PIN 9
#define LED_LOCAL 7
#define LED_REMOTE 8
// Initialize the LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo servo;
enum Mode {
AUTO,
MANUAL
};
Mode currentMode = AUTO;
int angle = 90; // Initial angle
int previousAngle = 90; // Previous angle for comparison
void setup() {
// Initialize Serial communication
Serial.begin(9600);
// Initialize LCD
lcd.init();
lcd.backlight();
// Attach servo to pin
servo.attach(SERVO_PIN);
// Set switch pin as input
pinMode(SWITCH_PIN, INPUT_PULLUP);
// Set LED pins as output
pinMode(LED_LOCAL, OUTPUT);
pinMode(LED_REMOTE, OUTPUT);
}
void loop() {
// Read the switch state to determine the mode
if (digitalRead(SWITCH_PIN) == LOW) {
currentMode = AUTO;
} else {
currentMode = MANUAL;
}
// Control servo based on the current mode
if (currentMode == AUTO) {
// Auto mode: Control servo with photoresistor
int lightLevel = analogRead(PHOTO_PIN);
angle = map(lightLevel, 0, 1023, 0, 180); // Map light level to servo angle
} else {
// Manual mode: Control servo with serial input
if (Serial.available() > 0) {
angle = Serial.parseInt(); // Read angle from serial input
angle = constrain(angle, 0, 180); // Limit angle within valid range
Serial.read(); // Clear newline character
}
}
// If the angle has changed, update the servo angle
if (angle != previousAngle) {
servo.write(angle); // Set servo angle
previousAngle = angle; // Update previous angle
}
// Display mode and angle on LCD
lcd.clear();
lcd.setCursor(0, 0);
if (currentMode == AUTO) {
lcd.print("Auto Mode ");
digitalWrite(LED_LOCAL, LOW); // Turn off local mode LED
digitalWrite(LED_REMOTE, HIGH); // Turn on remote mode LED
} else {
lcd.print("Manual Mode ");
digitalWrite(LED_LOCAL, HIGH); // Turn on local mode LED
digitalWrite(LED_REMOTE, LOW); // Turn off remote mode LED
}
lcd.setCursor(0, 1);
lcd.print("Angle: ");
lcd.print(angle);
// Print current status to Serial Monitor
if (currentMode == MANUAL) {
Serial.print("Manual Mode: ");
} else {
Serial.print("Auto Mode: ");
}
Serial.println(angle);
delay(100); // Small delay for stability
}