AR-9Pemula

LED Control with a Push Button (Push)

4.8(114)
253 selesai
LED Control with a Push Button (Push)
Just like a doorbell: the light stays on as long as you press, and goes off when you let go. The Arduino keeps listening to the button; while it's pressed the LED is on, and the moment you lift your finger it turns off. This simplest of circuits shows you how the board feels a touch from the outside world.

Video

Gambar Rajah Litar

LED Control with a Push Button (Push) - Gambar Rajah Litar

Kod Sumber

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   LED Control with a Push Button (Push)
4// ─────────────────────────────────────────
5// The LED stays on while the button is held and turns off when it is
6// released (push). Shows reading a button with digitalRead and if-else.
7//
8// Pins:
9//   D13 -> Button, other leg to 5V
10//   D13 -> 10k resistor to GND (pull-down)
11//   D7  -> LED (with a 330 ohm resistor)
12
13void setup() {
14  pinMode(13, INPUT);    // Button input (external pull-down)
15  pinMode(7, OUTPUT);    // LED output
16}
17
18void loop() {
19  if (digitalRead(13) == HIGH) {   // Is the button pressed?
20    digitalWrite(7, HIGH);         // Pressed: LED on
21  } else {
22    digitalWrite(7, LOW);          // Released: LED off
23  }
24}
25

Soalan Lazim

What is a 10 kΩ resistor used for?

It is a pull-down resistor: it ensures a stable LOW reading by pulling the pin to GND when the button is not pressed. Without this resistor, the pin would be left floating and would read a random HIGH or LOW, causing the LED to flicker on its own.

Can I connect a button without using a resistor?

Yes, using `pinMode(pin, INPUT_PULLUP)` enables the Arduino's internal pull-up resistor. In this case, the button is connected between the pin and GND, and the logic is reversed: it reads LOW when pressed and HIGH when released.

Which pins on the button should I use?

On 4-pin buttons, the two opposite pins are already connected internally. Place the button over the empty space in the center of the breadboard and use the diagonal pins; this way, you can be sure you’re selecting the correct pins.

What is the difference between "Push" and "On-Off"?

In push mode, the LED lights up only while you hold down the button. In on-off (toggle) mode, each press changes the LED's state, and the LED stays on even after you release the button; this requires a state variable.