/*
Forum: https://forum.arduino.cc/t/joystick-controlling-leds/1307844
Wokwi: https://wokwi.com/projects/410824564717321217
Original Version see Wokwi: https://wokwi.com/projects/410824037311785985
*/
const byte sensorPin = A0;
const byte buttonPin = 10;
const byte minLedPin = 2;
const byte maxLedPin = 9;
int sensorValue = 0;
int oldSensorValue = -1;
byte status = false;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
for (int i = minLedPin; i <= maxLedPin; i++) {
pinMode(i, OUTPUT);
}
allLedsOn();
}
void loop() {
checkButton();
handleSensor();
}
void setLeds(byte fromPin, byte toPin, byte state) {
for (int i = fromPin; i <= toPin; i++) {
digitalWrite(i, state);
}
}
void allLedsOff(){
setLeds(minLedPin, maxLedPin, LOW);
}
void allLedsOn(){
setLeds(minLedPin, maxLedPin, HIGH);
}
void checkButton() {
static unsigned long lastChange = 0;
static byte state = HIGH;
static byte lastState = HIGH;
byte actState = digitalRead(buttonPin);
if (actState != lastState) {
lastChange = millis();
lastState = actState;
}
if (state != actState && millis() - lastChange > 30) {
state = actState;
if (state == LOW) {
status = !status;
Serial.print(" Button Value = ");
Serial.println(status);
if (status) {
setLeds(minLedPin, maxLedPin, LOW);
}
}
}
}
void handleSensor() {
if (status) {
return;
}
sensorValue = analogRead(sensorPin);
if (sensorValue != oldSensorValue) {
oldSensorValue = sensorValue;
Serial.print("Potentiometer = ");
Serial.println(sensorValue);
handleLeds();
}
}
void handleLeds() {
static byte oldMode = 255;
byte mode = 0;
if (sensorValue >= 172) {
mode = 1;
}
if (sensorValue >= 342) {
mode = 2;
}
if (sensorValue >= 512) {
mode = 3;
}
if (sensorValue >= 682) {
mode = 4;
}
if (sensorValue >= 852) {
mode = 5;
}
if (mode != oldMode){
oldMode = mode;
allLedsOn();
setLeds(minLedPin+mode,minLedPin+mode+2,LOW);
}
}