STANNUM
Open the simulator

Tutorials / Input

Slide switch

A contact that stays where you leave it — on/off state, read like a button.

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

What it is

A slide switch is the button's steady cousin: it has two positions and keeps the last one. Electrically it is the same contact between a GPIO and ground, read with the internal pull-up.

In the simulator

The block shows the slider; click it to toggle. Its position is part of the project — it is saved and comes back when the project is opened, like the position of a real switch on a board.

Pins

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

Wiring

Build this circuit yourself: start a New project, add the parts from the catalog and wire them as in the table.

The wired circuit, as the lab draws it.
Switch 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 Switch.
SettingAcceptsDefaultNotes
ContactNormally open (NA) · Normally closed (NF)Normally open (NA)

Code

sketch.cpp
#include <Arduino.h>

// A slide switch has a STATE: it stays where you left it. With the contact
// wired to GND and the internal pull-up on, the pin reads LOW while the
// switch is closed and HIGH while it is open.
const int SWITCH = 4;
const int LED = 2;

void setup() {
  Serial.begin(115200);
  pinMode(SWITCH, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
}

void loop() {
  bool closed = digitalRead(SWITCH) == LOW;
  digitalWrite(LED, closed ? HIGH : LOW);
  Serial.println(closed ? "switch closed - LED on" : "switch open - LED off");
  delay(500);
}

Identical to the button: INPUT_PULLUP and digitalRead() == LOW for closed. The sketch copies the state to an LED and prints it twice a second.

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.

Click the switch: the LED follows and the serial monitor changes from “switch open” to “switch closed”. Click again to open it.

How the simulation models it

Try this

  1. Use the switch as a mode selector: closed, the LED blinks fast; open, it blinks slowly.
  2. Print the state only when it changes, not every half second.

See also