#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
// ------------------------
// PINAGEM
// ------------------------
#define ENC_CLK 4
#define ENC_DT 5
#define ENC_SW 6
#define MUTE_PIN 10
#define SWITCH_A 11
#define SWITCH_B 12
#define LED1 13
#define LED2 14
// ------------------------
volatile int encoderPos = 50; // volume inicial
volatile bool encoderMoved = false;
int lastEncoderValue = 50;
// ------------------------
int lastMuteState = HIGH;
bool lastSel = false;
// ------------------------
// ISR do encoder
// ------------------------
void IRAM_ATTR readEncoder() {
int clk = digitalRead(ENC_CLK);
int dt = digitalRead(ENC_DT);
if (clk == dt) encoderPos++;
else encoderPos--;
encoderPos = constrain(encoderPos, 0, 100);
encoderMoved = true;
}
void setup() {
Serial.begin(115200);
// LCD
Wire.begin(33, 35);
lcd.init();
lcd.backlight();
// Encoder
pinMode(ENC_CLK, INPUT_PULLUP);
pinMode(ENC_DT, INPUT_PULLUP);
pinMode(ENC_SW, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENC_CLK), readEncoder, CHANGE);
// Mute e seletor
pinMode(MUTE_PIN, INPUT_PULLUP);
pinMode(SWITCH_A, INPUT_PULLUP);
pinMode(SWITCH_B, INPUT_PULLUP);
// LEDs
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
// Tela inicial
lcd.setCursor(0, 0);
lcd.print("Volume:");
lcd.setCursor(0, 1);
lcd.print(encoderPos);
lcd.print("%");
}
void loop() {
bool mute = digitalRead(MUTE_PIN) == LOW;
bool posA = digitalRead(SWITCH_A) == LOW;
bool posB = digitalRead(SWITCH_B) == LOW;
bool seletor = posB; // B=fone B / A=fone A
// ------------------------
// MUTE
// ------------------------
if (mute != lastMuteState) {
lcd.clear();
if (mute) {
lcd.setCursor(0, 0);
lcd.print("MUTADO");
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
} else {
lcd.setCursor(0, 0);
lcd.print("Som ativo");
delay(1500);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Volume:");
lcd.setCursor(0, 1);
lcd.print(encoderPos);
lcd.print("%");
}
lastMuteState = mute;
}
// ------------------------
// SELETOR DE FONES
// ------------------------
if (seletor != lastSel && !mute) {
lcd.clear();
if (seletor) {
lcd.setCursor(0, 0);
lcd.print("Fone B");
Serial.println("Fone B Selecionado");
digitalWrite(LED1, LOW);
digitalWrite(LED2, HIGH);
} else {
lcd.setCursor(0, 0);
lcd.print("Fone A");
Serial.println("Fone A Selecionado");
digitalWrite(LED1, HIGH);
digitalWrite(LED2, LOW);
}
delay(1500);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Volume:");
lcd.setCursor(0, 1);
lcd.print(encoderPos);
lcd.print("%");
lastSel = seletor;
}
// ------------------------
// VOLUME — ENCODER ROTATIVO
// ------------------------
if (!mute && encoderMoved) {
encoderMoved = false;
if (abs(encoderPos - lastEncoderValue) >= 2) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Volume:");
lcd.setCursor(0, 1);
lcd.print(encoderPos);
lcd.print("%");
lastEncoderValue = encoderPos;
}
}
delay(20);
}