Slide switch on/off
Read a slide switch as a digital input and report when it changes position.
Input · Beginner
In a real product: Power switch (Consumer electronics): A switch's position is read as on or off.
A slide switch stays where you put it, which makes it good for modes and settings. Its middle pin connects to one end pin or the other, so wiring the ends to 5V and GND makes the middle pin read HIGH or LOW.
What you'll learn
- How a single-pole, double-throw (SPDT) switch is wired
- Detecting a change by remembering the last reading
- Using the board's built-in LED (
LED_BUILTIN, pin 13)
How it works
Pin 1 goes to GND, pin 3 to 5V, and the common pin 2 to pin 4. Slid left, the switch joins 1 and 2, so pin 4 reads LOW. Slid right, it joins 3 and 2, so it reads HIGH. Because the middle pin is always connected to one side, no pull-up is needed.
The loop compares the reading with the last one, and only prints and updates the built-in L LED when it changes.
Try this
- Click the switch while the simulation runs to slide it.
- Use the switch to choose between two blink speeds.
- Wire only pins 2 and 3 and use
INPUT_PULLUPinstead of the 5V connection.
sketch.ino
// A slide switch on pin 4 (its ends on GND and 5V): the built-in LED follows it, and changes are printed.
const int SWITCH = 4;
int last = -1;
void setup() {
pinMode(SWITCH, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
int state = digitalRead(SWITCH);
if (state != last) {
last = state;
digitalWrite(LED_BUILTIN, state);
Serial.println(state == HIGH ? "Switch right: ON" : "Switch left: OFF");
}
delay(10);
}