Arduino Digital Switch

by Rezz on October 12, 2011

This is basic for your arduino projects, input switch read from digital input. When ever switch pressed, LED will turn on.

Parts List;
1) 1x Arduino
2) 1x 5mm red LED
3) 1x 10kΩ resistor
4) 1x Switch
5) Jumper wire

Instruction;
1) Connect cathode lead of LED (shorter lead) to ground pin and anode lead of LED (longer lead) to pin 13.

2) Add switch to breadboard, connect one of the switch lead to 5V pin.

3) Add 10kΩ resistor as in diagram and connect another switch lead to digital pin 2.

4) Connect GND to 10kΩ resistor.

Upload this code to your arduino

/*
  Digital Switch
  Reads a digital input on pin 2, when pressed LED light up.
 
  Coded by: arduinoprojects101.com
*/

void setup() {
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  int switchValue = digitalRead(2);
  digitalWrite(13, switchValue);
}

pinMode(2, INPUT);
set digital pin 2 as input (from switch)

pinMode(13, OUTPUT);
set digital pin 13 as outpur (for LED on/off)

int switchValue = digitalRead(2);
read digital input from digital pin 2 (HIGH or LOW) and store to variable switchValue.

digitalWrite(13, switchValue);
turn on LED when switch pressed.

Leave a Comment

Previous post:

Next post: