STANNUM
Open the simulator

Tutorials / Input

Push button

A momentary contact: HIGH while released, LOW while pressed — the first digital input.

Parts in the example:
  • LED
  • Button
  • Potentiometer
The Button block as it appears on the canvas.

What it is

A tactile switch closes a contact while you hold it. Wired between a GPIO and ground, with the chip's internal pull-up resistor on (pinMode(pin, INPUT_PULLUP)), the pin reads HIGH at rest and LOW while pressed. That inversion — “pressed is LOW” — trips up every beginner once.

In the simulator

The block is the button itself: press it with the mouse (or a finger, on a tablet) and hold. The Contact setting picks the kind: normally open (NA), the usual one, or normally closed (NF), which inverts the levels.

Pins

PinWhat it is
Ssignal — to a GPIO configured as an input
GNDthe other side of the contact — to a GND symbol

Wiring

The circuit below is the example Blink with button and potentiometer from the lab — open it with Project → Open example… and it comes ready to run.

The wired circuit, as the lab draws it.
Button pinGoes to
SD4 on the board (GPIO 4)
GNDa GND symbol

Settings

Double-click the block's title bar to open its card, then the Settings tab. Changes apply to the running simulation right away.

The Settings tab of the Button.
SettingAcceptsDefaultNotes
ContactNormally open (NA) · Normally closed (NF)Normally open (NA)NA: HIGH when released, LOW when pressed. NF inverts it.

Code

sketch.cpp
#include <Arduino.h>

const int LED = 2;
const int BOTAO = 4;
const int POT = 34;

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  pinMode(BOTAO, INPUT_PULLUP);
  Serial.println("ready");
}

void loop() {
  // the potentiometer sets the blink speed
  int leitura = analogRead(POT);
  int intervalo = map(leitura, 0, 4095, 60, 1000);

  // while the button is held down the LED stays on
  if (digitalRead(BOTAO) == LOW) {
    digitalWrite(LED, HIGH);
    delay(100);
    return;
  }

  digitalWrite(LED, HIGH);
  delay(intervalo);
  digitalWrite(LED, LOW);
  delay(intervalo);
  Serial.printf("pot=%d interval=%d\n", leitura, intervalo);
}

pinMode(BOTAO, INPUT_PULLUP), then digitalRead(BOTAO) == LOW means pressed. In the example, holding the button keeps the LED on; released, the LED blinks at the speed set by the potentiometer.

Run it

Press Build and run. The first build of a project takes a while; after that, only what changed is rebuilt.

The simulation running: the canvas reacts and the serial monitor shows what the code prints.

Press and hold the button on the canvas: the LED stays on and the blinking stops. Release it and the blink resumes.

How the simulation models it

Try this

  1. Count presses and print the count on every release — you will need to remember the previous reading.
  2. Switch the contact to NF in Settings and see the readings invert without touching the code.
  3. Add a second button that halves the blink interval while held.

See also