Y'all, the Arduino Tutorials has a page about push button counting and activating the on-board LED. I thought to extend it and got stuck in a chasm of Lockdown fuelled OCD then wondered if there was a way to maximise efficiency of the code.
background
This Arduino website introduces the concept of pushing a single push button multiple times but it only counts up then rolls over. https://www.arduino.cc/en/Tutorial/StateChangeDetection
objective
Single push button to light LED's then, instead of rolling over, to roll back down the array.
setup
4x LEDS attached to pins 2, 4, 6, 8 each attached to a 220k resistor
1x push button attached to pin 11, no resistor
Queries: how can this code be made as memory efficient as possible?
I have tried trimming it down but that has limited impact on memory. I have also explored direct digital write but hit a wall in implementation.
Also, I note that the majority of examples online which include a push button do not use the INPUT_PULLUP method. Is there a reason why using that method could become problematic?
Thank you in advance for your input and time and hope that others find this useful.
Code:
int leds[] = {2, 4, 6, 8};
int numLEDS = 4;
int buttonPin = 11;
int pushCount = 4;
int prevCount = 0;
int buttonState = 0;
int lastButtonState = 0;
void setup()
{
pinMode(buttonPin, INPUT_PULLUP);
for (int i = 0; i < numLEDS; i++)
pinMode( leds[i], OUTPUT);
for (int i = 0; i == numLEDS; i++)
digitalWrite(leds[i], LOW);
}
void pinSelector() {
buttonState = digitalRead(buttonPin);
if (lastButtonState != buttonState && buttonState == LOW) {
if (pushCount >= 0) {
pushCount--;
for (int i = (numLEDS - 1); i >= 0; i--) {
digitalWrite(leds[i], LOW);
digitalWrite(leds[pushCount], HIGH);
}
}
if (pushCount < 0 && prevCount <= 4) {
prevCount++;
for (int i = 0; i <= (numLEDS - 1); i++) {
digitalWrite(leds[i], LOW);
digitalWrite(leds[prevCount], HIGH);
}
}
}
if (prevCount == 3) {
pushCount = 3;
prevCount = 0;
}
delay(50);
lastButtonState = buttonState;
}
void loop() {
pinSelector();
}