#include <Arduino.h>
#include <ESP32Encoder.h>
// Pin definitions
const int BUZZER_PIN = 25;
const int LED_PIN = 2;
const int ENCODER_CLK = 32;
const int ENCODER_DT = 33;
const int ENCODER_SW = 34;
// Sound frequencies
const int BROWN_NOISE_FREQ = 100;
const int WHITE_NOISE_FREQ = 1000;
const int PINK_NOISE_FREQ = 300;
const int CRICKET_SOUND_FREQ = 4000;
// Encoder setup
ESP32Encoder encoder;
// State variables
bool isOn = false;
int currentSound = 0; // 0: Brown, 1: White, 2: Pink, 3: Cricket
int volume = 127; // 0-255
unsigned long buttonPressStartTime = 0;
bool buttonPressed = false;
// Function prototypes
void togglePower();
void cycleSounds();
void updateVolume();
void playSound();
void setup() {
Serial.begin(115200);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(ENCODER_SW, INPUT_PULLUP);
encoder.attachHalfQuad(ENCODER_CLK, ENCODER_DT);
encoder.setCount(127); // Start at middle volume
}
void loop() {
// Check encoder button
if (digitalRead(ENCODER_SW) == LOW) {
if (!buttonPressed) {
buttonPressed = true;
buttonPressStartTime = millis();
} else if (millis() - buttonPressStartTime > 1500) {
togglePower();
while (digitalRead(ENCODER_SW) == LOW) delay(10); // Wait for button release
buttonPressed = false;
}
} else if (buttonPressed) {
if (millis() - buttonPressStartTime <= 1500) {
cycleSounds();
}
buttonPressed = false;
}
// Check encoder rotation
static int lastCount = 0;
int count = encoder.getCount();
if (count != lastCount) {
volume = constrain(count, 0, 255);
encoder.setCount(volume);
lastCount = volume;
updateVolume();
}
// Play sound if device is on
if (isOn) {
playSound();
} else {
noTone(BUZZER_PIN); // Turn off sound
}
}
void togglePower() {
isOn = !isOn;
digitalWrite(LED_PIN, isOn);
Serial.println(isOn ? "Power On" : "Power Off");
}
void cycleSounds() {
if (isOn) {
currentSound = (currentSound + 1) % 4;
Serial.println("Sound changed to: " + String(currentSound));
}
}
void updateVolume() {
Serial.println("Volume: " + String(volume));
}
void playSound() {
int frequency;
switch (currentSound) {
case 0: frequency = BROWN_NOISE_FREQ; break;
case 1: frequency = WHITE_NOISE_FREQ; break;
case 2: frequency = PINK_NOISE_FREQ; break;
case 3: frequency = CRICKET_SOUND_FREQ; break;
}
tone(BUZZER_PIN, frequency);
// Simulate volume control by adjusting duty cycle
int dutyCycle = map(volume, 0, 255, 0, 255);
analogWrite(BUZZER_PIN, dutyCycle);
}