#include <Wire.h>
//#include <Adafruit_GFX.h>
//#include <Adafruit_SSD1306.h>
const int encDt = 12;
const int encClk = 11;
const int encBtn = 13;
const int signalDetect = 9;
const int standby = 22;
const int standbyTime = 10; //in seconds
int XYZ;
volatile int volume = -50;
int oldVolume = volume;
int maxVolume = 0;
int minVolume = -60;
long lastSignalDetect;
//Led drive
const int ledPins[] = {15, 16, 17, 18, 19, 20, 21, 22};
const int ledCount = 8;
const int maxBrightness = 200;
const int minBrightness = 0;
float ledDim;
float ledBarHeight;
void setup() {
// put your setup code here, to run once:
Serial1.begin(115200);
//Serial1.println("Hello, Raspberry Pi Pico!");
//Serial1.println(PIN_WIRE_SDA);
for (XYZ = 0; XYZ < ledCount; XYZ++) {
pinMode(ledPins[XYZ], OUTPUT);
}
pinMode(encClk, INPUT_PULLUP);
pinMode(encDt, INPUT_PULLUP);
pinMode(encBtn, INPUT_PULLUP);
pinMode(signalDetect, INPUT);
pinMode(standby, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
attachInterrupt(digitalPinToInterrupt(encClk), encDecode, FALLING );
lastSignalDetect = millis();
digitalWrite(standby, LOW);
digitalWrite(LED_BUILTIN, LOW);
ledDisplay();
}
void loop() {
// put your main code here, to run repeatedly:
delay(1); // this speeds up the simulation
//encoder volume control
if (oldVolume != volume) {
oldVolume = volume;
Serial1.println(volume);
if (volume > maxVolume) {volume = maxVolume;}
else if(volume < minVolume) {volume = minVolume;}
ledDisplay();
}
//Signal detect
if (digitalRead(signalDetect) == HIGH) {
lastSignalDetect = millis();
if (digitalRead(standby) == LOW) {digitalWrite(standby, HIGH); digitalWrite(LED_BUILTIN, HIGH);}
}
//standby after no signal
if (millis() - lastSignalDetect > standbyTime * 1000 ) {
digitalWrite(standby, LOW);
digitalWrite(LED_BUILTIN, LOW);
}
}
void encDecode () {
if (digitalRead(encDt) == LOW) {volume--;}
else {volume++;}
}
void ledDisplay() {
ledBarHeight = float(minVolume - volume) / (float(minVolume - maxVolume) / float(ledCount));
for (XYZ = 0; XYZ < ledCount; XYZ++) {
if (XYZ < int(ledBarHeight)) {analogWrite(ledPins[XYZ], maxBrightness);}
else if (XYZ > int(ledBarHeight)) {analogWrite(ledPins[XYZ], minBrightness);}
else {analogWrite(ledPins[XYZ], (ledBarHeight - XYZ) * maxBrightness);}
}
}