When I am searching for something inside a loop, I find that the
simplest thing to do is to just break
out of the loop once I found it.
This was frowned upon in the days when structured programming was a hot
thing, but as long as it makes things simpler, you should not be ashamed
to break
:
const int button_pins[] = {2, 3, 4};
const char * const urls[] = {"foo.com", "bar.org", "baz.net"};
const char * url; // the selected URL
void setup()
{
Serial.begin(9600);
// Configure input pins.
for (int i = 0; i < 3; i++)
pinMode(button_pins[i], INPUT_PULLUP);
// Find first button pressed.
int i; // button index
for (i = 0; ; i = i==2 ? 0 : i+1) {
if (digitalRead(button_pins[i]) == LOW)
break;
}
// The button index selects the URL.
url = urls[i];
Serial.print("Selected URL: ");
Serial.println(url);
}
void loop() {}
The for
loop above is written as an endless loop (no end condition).
The expression i = i==2 ? 0 : i+1
means: “if i
is 2
, make it 0
,
otherwise make it i+1
”. In other words, we are endlessly looping i
over 0, 1 and 2.
Now, it may well happen that you actually do not care about which button
was pressed once you have selected the proper URL. In this case, you can
use the URL pointer as a “flag” that tells you when you can end the
loop:
// First button pressed selects the URL.
for (int i = 0; !url; i = i==2 ? 0 : i+1) {
if (digitalRead(button_pins[i]) == LOW)
url = urls[i];
}
Where !url
means “the URL has not been found”. This works because the
C runtime initializes url
to zero, which is interpreted as false
in
boolean context.
Addendum: If you are likely to add new button/URL pairs, you can
make this easier by structuring the list as an array of structs:
const struct {
int pin; // pin number
const char *url; // associated URL
} buttons[] = {
{2, "foo.com"},
{3, "bar.org"},
{4, "baz.net"}
// etc. just add to this list as needed.
};
const size_t button_count = sizeof buttons / sizeof buttons[0];
Then the search becomes:
for (int i = 0; !url; i = i==button_count-1 ? 0 : i+1) {
if (digitalRead(buttons[i].pin) == LOW)
url = buttons[i].url;
}