Two buttons, one LED, on an Arduino Uno
Button A on pin 9 lights the LED on pin 5 and button B on pin 8 puts it out. Neither button needs a resistor: the chip’s own pull-ups hold both pins high. The whole build, an Arduino Uno and 4 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Two buttons, one LED: the left button turns it on, the right one off.
//
// pin 5 the LED, through 220 ohm to GND
// pin 9 button A (on), its other leg to GND
// pin 8 button B (off), its other leg to GND
//
// Neither button has a resistor. INPUT_PULLUP switches on the chip's own
// pull-up, which holds the pin at 5 V until the button joins it to ground.
// So a pin reads HIGH while its button is up and LOW while it is held.
//
// The LED stays the way the last button left it. That is the difference from
// a button wired straight to an LED: the board remembers.
const int LED_PIN = 5;
const int BUTTON_ON = 9;
const int BUTTON_OFF = 8;
bool lit = false;
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_ON, INPUT_PULLUP);
pinMode(BUTTON_OFF, INPUT_PULLUP);
Serial.begin(9600);
Serial.println("Mokxi Uno: button A on pin 9 lights the LED, button B on pin 8 puts it out");
}
void loop() {
if (digitalRead(BUTTON_ON) == LOW && !lit) {
lit = true;
digitalWrite(LED_PIN, HIGH);
Serial.println("on");
}
if (digitalRead(BUTTON_OFF) == LOW && lit) {
lit = false;
digitalWrite(LED_PIN, LOW);
Serial.println("off");
}
delay(5);
}
Parts list
6 parts, plus the jumper wires. Every one is in the editor's parts bin.
- 1 × Arduino Uno R3
- 1 × Half breadboard
- 1 × Resistor, 220 Ω
- 1 × LED, red
- 2 × Pushbutton
How it is wired
5 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Ground: Arduino Uno R3 pin GND; LED, red pin C; Pushbutton (1) pin 2a; Pushbutton (2) pin 2a
- Arduino Uno R3 pin 9; Pushbutton (1) pin 1a
- Arduino Uno R3 pin 8; Pushbutton (2) pin 1a
- Arduino Uno R3 pin 5; Resistor, 220 Ω pin 1
- Resistor, 220 Ω pin 2; LED, red pin A
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.