पाठ 4 / 25

LEDs, Buttons and Pull-ups

pinMode, digitalWrite, digitalRead.

Outputs, inputs and floating pins

pinMode(pin, OUTPUT) lets digitalWrite drive the pin HIGH (near the supply voltage) or LOW (0 V). An LED always needs a series resistor to limit current: on a 5 V Uno R3, around 220 Ω to 1 kΩ is common. The ATmega328P datasheet gives 40 mA per pin as an absolute maximum, so design for well under that (about 20 mA or less) and respect the total-package limit; check your board's datasheet. As an INPUT, an unconnected pin floats and reads random values, so a button needs a pull-up or pull-down resistor to hold a defined level. INPUT_PULLUP enables an internal pull-up: the pin reads HIGH when the button is open and LOW when the button connects it to ground (inverted logic).

Reading and driving pins

Digital pins are either HIGH or LOW; with the right resistors they read buttons and drive LEDs safely.

Three ideas: pins, LEDs and buttons; debouncing; non-blocking timing with millis().
Figure 2.1 — Input, processing and output on digital pins.

Button turns on an LED

Wiring (Uno R3): LED anode via 330 Ω resistor to pin 8, cathode to GND; push button between pin 2 and GND.

const uint8_t LED_PIN = 8;
const uint8_t BUTTON_PIN = 2;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);  // internal pull-up: idle = HIGH
}

void loop() {
  bool pressed = (digitalRead(BUTTON_PIN) == LOW);  // pressed pulls to GND
  digitalWrite(LED_PIN, pressed ? HIGH : LOW);
}

Never short an output

Do not connect an output pin directly to GND or to another output without a resistor. An output driving HIGH into a pin driven LOW can exceed current limits and damage the chip.

त्वरित जाँच: With INPUT_PULLUP and a button wired to GND, what does digitalRead return while the button is pressed?

  • HIGH
  • LOW
  • A random value
  • The analog voltage
Answer

LOW — The button connects the pin to ground, overriding the weak internal pull-up.