# How do I make a counter that counts the amount of active inputs [closed]

I want to make a direction guide using green, yellow and red LEDs. The lights need to change when ever the active input1 reaches a set value, for example:

• Green when the value is lower than 12;
• Yellow when the value is higher than 11 and lower than 20;
• Red when its higher than 19.

I've been searching for a few days but I couldn't find any references.

1 By active inputs I mean, a series of buttons being pressed at the same time, if there is 29 buttons then when less then 12 of them is pressed the green light would be turned on.

• The reference you would look for would be something on the C or C++ language. That would describe the basic structure of "conditional statements" like if (x < 5) {...} and so on. – jose can u c Apr 12 '19 at 16:34
• What do you mean by "active input"? What kind of input, and what does the value indicate? – Duncan C Apr 12 '19 at 18:17

You need something like:

const int BUTTON_MAX = 29;
const int button[BUTTON_MAX] = { 5, 6, 7, ... };
const int GREEN_LED = 2;
const int YELLOW_LED = 3;
const int RED_LED = 4;
int current_led;

void setup()
{
// Setup inputs (buttons)
for (int i = 0; i < BUTTON_MAX; i++) pinMode(button[i], INPUT_PULLUP);

// Setup outputs (led)
pinMode(GREEN_LED, OUTPUT);
pinMode(YELLOW_LED, OUTPUT);
pinMode(RED_LED, OUTPUT);

// Initial state
current_led = GREEN_LED;
digitalWrite(GREEN_LED, HIGH);
digitalWrite(YELLOW_LED, LOW);
digitalWrite(RED_LED, LOW);
}

void loop()
{
// Count number of active buttons
int count = 0;
for (int i = 0; i < BUTTON_MAX; i++) count += digitalRead(button[i]);

// Map number of active buttons to led
int new_led;
if (count < 12)
new_led = GREEN_LED;
else if (count < 20)
new_led = YELLOW_LED;
else
new_led = RED_LED;

// Check for change and update
if (new_led != current_led) {
digitalWrite(current_led, LOW);
digitalWrite(new_led, HIGH);
current_led = new_led;
}

// Add a few milli-seconds for debounce
delay(20);
}
• This seems like a decent answer, ignoring whatever "active inputs" means... – Duncan C Apr 12 '19 at 21:35
• @DuncanC by active inputs i mean, a series of buttons being pressed at the same time, if there is 29 buttons then when less then 12 of them is pressed the green light would be turned on. not sure if this helps. – oliver sindahl Apr 13 '19 at 9:17
• @oliversindahl thanks for the info. That allows an update to the answer :) – Mikael Patel Apr 13 '19 at 12:55