#include <ESP32Servo.h>
// Define pin assignments
#define BUTTON_INTERRUPT_PIN 2 // Button to trigger preset position
#define SERVO_COUNT 8 // Total number of servos
#define TIMER_INTERVAL 2000 // Timer interval for eyelid servos
// Servo pins
const int servoPins[SERVO_COUNT] = {18, 19, 21, 22, 23, 25, 26, 27};
// Potentiometer pins for 6 servos
const int potPins[6] = {32, 33, 34, 35, 36, 39};
// Servo objects (library)
Servo servos[SERVO_COUNT];
// Timer and state tracking
unsigned long lastTimerUpdate = 0;
bool eyelidState = false; // Toggles eyelid servos
// Interrupt Service Routine (ISR) - Moves servos to preset positions
void moveToPreset() {
for (int i = 0; i < SERVO_COUNT; i++) {
servos[i].write((i + 1) * 20); // 20°, 40°, 60°, ..., 180°
}
delay(500);
}
// Reads potentiometers and updates servo positions
void updateServoPositions() {
for (int i = 0; i < 6; i++) {
int potValue = analogRead(potPins[i]);
int angle = map(potValue, 0, 4095, 0, 180);
servos[i].write(angle);
}
}
// Toggles eyelid servos between 0° and 90°
void updateEyelidServos() {
if (millis() - lastTimerUpdate >= TIMER_INTERVAL) {
eyelidState = !eyelidState;
servos[6].write(eyelidState ? 90 : 0);
servos[7].write(eyelidState ? 90 : 0);
lastTimerUpdate = millis();
}
}
void setup() {
Serial.begin(115200);
// Attach servos
for (int i = 0; i < SERVO_COUNT; i++) {
servos[i].attach(servoPins[i], 500, 2400);
}
// Configure button interrupt
pinMode(BUTTON_INTERRUPT_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BUTTON_INTERRUPT_PIN), moveToPreset, FALLING);
}
void loop() {
updateServoPositions(); // Update servos controlled by potentiometers
updateEyelidServos(); // Update eyelid servos periodically
}