/*
Rotary Encoder volume control example
Usage: rotate the knob to control the value,
click the knob to change between volume/bass/treble.
https://wokwi.com/arduino/projects/304919215794553409
Released under the MIT license.
Copyright (C) 2021, Uri Shaked.
*/
#include <EEPROM.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Fonts/FreeSansBold9pt7b.h>
#include <Fonts/Picopixel.h>
#define CLK A0
#define DT A1
#define SW A2
uint8_t v1;
uint8_t b1;
uint8_t t1;
typedef enum {f1,f2,f3,} Mf;
Mf df1=f1;
Adafruit_SSD1306 display(128, 64, &Wire, -1);
void s8() {
switch (df1) {
case f1:
df1 = f2;
break;
case f2:
df1 = f3;
break;
case f3:
df1 = f1;
break;
}
}
void up(int de) {
switch (df1) {
case f1:
v1 = constrain(v1 + de, 0, 100);
break;
case f2:
b1 = constrain(b1 + de, 0, 100);
break;
case f3:
t1 = constrain(t1 + de, 0, 100);
break;
}
}
void uy() {
display.clearDisplay();
display.setFont();
display.setTextColor(1);
display.setCursor(42, 2);
display.print("Volume");
display.drawRoundRect(10, 12, 102, 9, 2, WHITE);
display.fillRect(11, 13, v1, 7, WHITE);
if (df1 == f1) {
display.setCursor(32, 2);
display.print(">");
}
display.setCursor(48, 22);
display.print("Bass");
display.drawRoundRect(10, 32, 102, 9, 2, WHITE);
display.fillRect(11, 33, b1, 7, WHITE);
if (df1 == f2) {
display.setCursor(38, 22);
display.print(">");
}
display.setCursor(42, 42);
display.print("Treble");
display.drawRoundRect(10, 52, 102, 9, 2, WHITE);
display.fillRect(11, 53, t1, 7, WHITE);
if (df1 == f3) {
display.setCursor(32, 42);
display.print(">");
}
display.display();
}
void setup() {
Serial.begin(115200);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
pinMode(SW, INPUT_PULLUP);
R();
if(df1>254){df1=0;v1=0;b1=0;t1=0;}
uy();
}
long int mo = 0;
int pk = 1;
void loop() {
if (digitalRead(SW)==0&&millis()-mo>300) {mo=millis();s8();uy();}
int clk=digitalRead(CLK);
if(clk!=pk&&clk==0){int dt=digitalRead(DT);int de=dt==1?1:-1;up(de);uy();}
pk=clk;Serial.println(df1);
E();
}
void R() {
v1=EEPROM.read(1);
b1=EEPROM.read(2);
t1=EEPROM.read(3);
df1=EEPROM.read(4);
}
void E() {
EEPROM.update(1,v1);
EEPROM.update(2,b1);
EEPROM.update(3,t1);
EEPROM.update(4,df1);
}