#include <ESP32Servo.h>
// Create a servo object
Servo myservo;
// Pin for servo signal
int servoPin = 15;
const int potPin = 25; // Pin connected to the potentiometer
int sensorValue = 0; // Variable to store the value coming from the potentiometer
const int redPin = 35; // Blue pin of the RGB LED
const int greenPin = 27; // Green pin of the RGB LED
const int bluePin = 12; // Red pin of the RGB LED
void setup() {
// Attach the servo to the pin
myservo.attach(servoPin);
// Optional: you can set the initial position of the servo
// myservo.write(90); // Set servo to mid-point (90°)
Serial.begin(9600); // Initialize serial communication at 9600 baud rate
pinMode(redPin, OUTPUT); // Set the red pin as an output
pinMode(greenPin, OUTPUT); // Set the green pin as an output
pinMode(bluePin, OUTPUT); // Set the blue pin as an output
}
void loop() {
// Move the servo back and forth
for (int pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (int pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
// read the value from the potentiometer
sensorValue = analogRead(potPin);
// print the results to the serial monitor
Serial.print("sensorValue: ");
Serial.println(sensorValue);
// Control the color of the RGB LED based on the degree intervals
if (sensorValue == 0) {
analogWrite(redPin, 0);
analogWrite(greenPin, 0);
analogWrite(bluePin, 0);
} else if (sensorValue > 0 && sensorValue <= 60) {
analogWrite(redPin, 255);
analogWrite(greenPin, 0);
analogWrite(bluePin, 0);
} else if (sensorValue > 60 && sensorValue <= 100) {
analogWrite(redPin, 0);
analogWrite(greenPin, 0);
analogWrite(bluePin, 255);
} else if (sensorValue > 100 && sensorValue <= 130) {
analogWrite(redPin, 255);
analogWrite(greenPin, 255);
analogWrite(bluePin, 0);
} else if (sensorValue > 130 && sensorValue < 180) {
analogWrite(redPin, 0);
analogWrite(greenPin, 255);
analogWrite(bluePin, 0);
} else if (sensorValue == 180) {
analogWrite(redPin, 255);
analogWrite(greenPin, 0);
analogWrite(bluePin, 255);
}
delay(100); // Small delay to make reading more stable
}
}