Two Buttons at Once
Part of the Inputs section of Coddy's Arduino journey. Lesson 7 of 22.
Each button gets its own pin and its own digitalRead(). The board reads them one after the other, but so fast that it is the same moment to you.
Factory machines often have two buttons far apart, and only run while both are held. Both hands are on the buttons, so neither can be near the blade. That rule is &&, from Combining Conditions:
bool left = digitalRead(2) == LOW;
bool right = digitalRead(3) == LOW;
if (left && right) {
// both buttons are held
}Both pins need INPUT_PULLUP. Forget one and that pin floats, which here reads LOW, as if its button were always held.
Challenge
EasyThe buttons are on pins 2 and 3, both joined to GND, and the LED is on pin 13. Light the LED only while both buttons are held:
- set pins 2 and 3 to
INPUT_PULLUP - read each button into a
bool - light the LED when both are pressed, otherwise turn it off
Press Run, hold one button, then both, then Check.
Try it yourself
const int leftPin = 2;
const int rightPin = 3;
const int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
// set both button pins to INPUT_PULLUP
}
void loop() {
// read both buttons, light the LED only while both are held
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Inputs
Practice on your own: Arduino playground