#include <ESP32Servo.h>
// Create a servo object
Servo myservo;
// Pin for servo signal
int servoPin = 15;
const int meterPin = 25; // Pin connected to the potentiometer
int meterValue = 0; // Variable to store the value coming from the potentiometer
const int redPin = 26; // Red pin of the RGB LED
const int greenPin = 34; // Green pin of the RGB LED
const int bluePin = 14; // Blue 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
meterValue = analogRead(meterPin);
// print the results to the serial monitor
Serial.print("meterValue: ");
Serial.println(meterValue);
// Control the color of the RGB LED based on the degree intervals
if (meterValue == 0) {
analogWrite(redPin, 0);
analogWrite(greenPin, 0);
analogWrite(bluePin, 0);
} else if (meterValue > 0 && meterValue <= 60) {
analogWrite(redPin, 255);
analogWrite(greenPin, 0);
analogWrite(bluePin, 0);
} else if (meterValue > 60 && meterValue <= 100) {
analogWrite(redPin, 0);
analogWrite(greenPin, 0);
analogWrite(bluePin, 255);
} else if (meterValue > 100 && meterValue <= 130) {
analogWrite(redPin, 255);
analogWrite(greenPin, 255);
analogWrite(bluePin, 0);
} else if (meterValue > 130 && meterValue < 180) {
analogWrite(redPin, 0);
analogWrite(greenPin, 255);
analogWrite(bluePin, 0);
} else if (meterValue == 180) {
analogWrite(redPin, 255);
analogWrite(greenPin, 0);
analogWrite(bluePin, 255);
}
delay(100); // Small delay to make reading more stable
}
}