#include <Servo.h> // Include the Servo library
const int potPin = A0; // Analog pin connected to the potentiometer's wiper
const int redLedPin = 8; // Digital pin connected to the Red LED
const int greenLedPin = 7; // Digital pin connected to the Green LED
const int servoPin = 3; // Digital pin connected to the servo motor
Servo myServo; // Create a Servo object
void setup() {
pinMode(redLedPin, OUTPUT); // Set Red LED pin as output
pinMode(greenLedPin, OUTPUT); // Set Green LED pin as output
myServo.attach(servoPin); // Attach the servo motor to the specified pin
Serial.begin(9600); // Start serial communication for debugging
Serial.println("Potentiometer Control: Servo and LEDs");
myServo.write(0); // Initialize servo to 0 degrees
}
void loop() {
// Read the analog value from the potentiometer (0-1023)
int potValue = analogRead(potPin);
// Map the potentiometer value to the servo angle (0-180 degrees)
// The map() function is used to re-map a number from one range to another.
// Here, 0-1023 from potentiometer is mapped to 0-180 for servo.
int servoAngle = map(potValue, 0, 1023, 0, 180);
myServo.write(servoAngle); // Move the servo to the calculated angle
// Control the LEDs based on the potentiometer's position
// If potValue is in the lower half (0-511)
if (potValue < 512) {
digitalWrite(redLedPin, HIGH); // Turn on the Red LED
digitalWrite(greenLedPin, LOW); // Turn off the Green LED
}
// If potValue is in the upper half (512-1023)
else {
digitalWrite(redLedPin, LOW); // Turn off the Red LED
digitalWrite(greenLedPin, HIGH); // Turn on the Green LED
}
// Print values to Serial Monitor for debugging
Serial.print("Potentiometer Value: ");
Serial.print(potValue);
Serial.print(" | Servo Angle: ");
Serial.print(servoAngle);
Serial.print(" | Red LED: ");
Serial.print(digitalRead(redLedPin) == HIGH ? "ON" : "OFF");
Serial.print(" | Green LED: ");
Serial.println(digitalRead(greenLedPin) == HIGH ? "ON" : "OFF");
delay(15); // Small delay for stable readings and smoother servo movement
}