#include <ESP32Servo.h>
// Pin definitions
const int ledPin = 22;
const int speedButtonPin = 2;
const int oscillateButtonPin = 4;
const int servoPin = 27;
// Button states
const int NUM_SPEEDS = 4;
int currentSpeed = 0;
// Servo
Servo fanServo;
int servoPos = 90;
int servoStep = 1;
int minServoPos = 45;
int maxServoPos = 135;
bool oscillate = false;
// Timing
unsigned long lastDebounceTimeSpeed = 0;
unsigned long lastDebounceTimeOscillate = 0;
const int debounceDelay = 1000;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(speedButtonPin, INPUT_PULLUP);
pinMode(oscillateButtonPin, INPUT_PULLUP);
fanServo.attach(servoPin);
Serial.begin(9600);
}
void loop() {
// Read button states
int speedButtonState = digitalRead(speedButtonPin);
int oscillateButtonState = digitalRead(oscillateButtonPin);
// Check if the speed button is pressed
if (speedButtonState == LOW) {
unsigned long currentTime = millis();
if ((currentTime - lastDebounceTimeSpeed) > debounceDelay) {
lastDebounceTimeSpeed = currentTime;
// Update the fan speed
currentSpeed = (currentSpeed + 1) % NUM_SPEEDS;
Serial.print("Fan speed: ");
Serial.println(currentSpeed);
}
}
// Check if the oscillate button is pressed
if (oscillateButtonState == LOW) {
unsigned long currentTime = millis();
if ((currentTime - lastDebounceTimeOscillate) > debounceDelay) {
lastDebounceTimeOscillate = currentTime;
// Toggle oscillation setting
oscillate = !oscillate;
if (oscillate) {
Serial.println("Oscillator: ON");
} else {
Serial.println("Oscillator: OFF");
}
}
}
// Control the LED (DC motor) based on the fan speed
int pwmValue = map(currentSpeed, 0, NUM_SPEEDS - 1, 0, 255);
analogWrite(ledPin, pwmValue);
// Control the servo motor for oscillation
if (oscillate) {
servoPos += servoStep;
if (servoPos >= maxServoPos || servoPos <= minServoPos) {
servoStep = -servoStep; // Reverse direction
}
fanServo.write(servoPos);
delay(20 * (NUM_SPEEDS - currentSpeed + 1)); // Oscillation speed depends on the fan speed
}
}