How to read switch input in arduino? | applied electronics engineering


How to read switch input in arduino?

By Applied Electronics - Wednesday, January 18, 2017 No Comments
Reading input from switches is fundamental in interfacing microcontroller to the outside world. With arduino we can do this using one of the digital pins. But we also want to display that the switch is working so we connect a LED to another digital pin.

Below is the figure of how you should connect the arduino.

How to read switch input in arduino?

In the figure above(made in proteus), digital pin 13 is connected to the button and then to a +5V. This +5V power comes from the +5V supply of the arduino. The resistor R2 is a pulldown resistor of value 10KOhm which is needed for proper working of the circuit. Then the digital pin 10 is connected to a LED whose other end is grounded via 220Ohm resistor.

When the switch is pressed the LED should turn ON, otherwise it should remain OFF. We have to write program or sketch in arduino IDE. The following is the required program.

const int led = 10;
const int button = 13;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT);

void loop() {
 if (digitalRead(button) == LOW)
  digitalWrite(led, LOW);

In the program, we rename the pin 10 and 13 to led and button for easier working while writing the program. In the setup function we make the led and button the output and input to tell the microcontroller that these are to be treated as output and input direction. Then in the loop function we continously check the state of the switch by reading the switch state. This is done via the digitalRead( ) function which is compared to either LOW value. Now if it LOW which is the switch is not pressed it should remain LOW. Else we want it to go HIGH.

You can watch the proteus simulation video below.

See next How to read analog signal into Arduino.

No Comment to " How to read switch input in arduino? "