An electrical switch or button is a device used to control the flow of electricity in a circuit. It allows the user to open (turn off) or close (turn on) the circuit by making or breaking the electrical connection. Switches come in various types, such as toggle, push-button, and rocker, and are essential for controlling lights, appliances, and other electronic devices.
In this article, we will focus exclusively on buttons used as input devices for microcontrollers,
specifically so-called "tactile switches."
A typical tactile switch is momentary and SPST (Single Pole, Single Throw), which means
that when you press it, it temporarily closes the circuit and opens it again when released.
Configuration: | SPST (Single Pole, Single Throw) |
---|---|
Operating Force: | 160–260 gf (gram-force), depending on model |
Travel Distance: | 0.2mm to 0.5mm |
Contact Resistance (max): | 100mΩ max |
Operating Temperature: | -20°C to +70°C |
Lifespan: | 100000 to 1000000 cycles |
📄 Tactile button datasheet (93 kB)
Terminal
1
+2
and
3
+4
are always connected.
By pressing the button on the tactile switch the connections between those are closed.
To detect a button press with a microcontroller, we use the following generic circuit diagram. In this setup, two buttons are connected with each a pull-up and a pull-down resistor. In practice, we only need one of the two.
The following code reads the state of a push button on a digital input of the microcontroller and outputs the result via the serial interface:
#define PIN_BUTTON 2
void setup() {
pinMode(PIN_BUTTON, INPUT);
Serial.begin(9600);
}
void loop() {
static bool switchOn = false;
if (digitalRead(PIN_BUTTON) == HIGH) {
if (!switchOn) {
switchOn = true;
Serial.println("Switch ON");
}
} else {
if (switchOn) {
switchOn = false;
Serial.println("Switch OFF");
}
}
delay(10);
}