This is a blog for people interested in technology. I'll be posting projects and tutorials on things such as Arduino, IoT devices, Electronics, Machine Learning and whatever springs to mind.

How to Use and LED & Switch with Arduino

Use Arduino to light an LED when a switch is pressed

Connect an LED to pin 13 and a switch to pin 2 as shown below.

The Switch is connected between pin 2 and ground (GND) but inside the Arduino we enable an internal PULLUP resistor on pin 2 so that the pin is pulled HIGH if the switch is not pressed and sis pulled LOW if the switch is pressed.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

/*

* Pullup sketch

* a switch connected to pin 2 lights the LED on pin 13

*/

constintledPin = 13; // output pin for the LED

constintinputPin = 2; // input pin for the switch

voidsetup() {

pinMode(ledPin, OUTPUT);

pinMode(inputPin, INPUT);

digitalWrite(inputPin,HIGH); // turn on internal pull-up on the inputPin

}

voidloop(){

intval = digitalRead(inputPin); // read input value

if(val == LOW) // check if the input is LOW

{

digitalWrite(ledPin, HIGH); // turn LED ON

}

else

{

digitalWrite(ledPin, LOW); // turn LED OFF

}

}

Try These Things to Make it Better:

Change the program to make an On/Off Toggle function; i.e. Press the button to turn the LED ON, Press it again to turn the LED OFF.

For the solution see the code below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

/*

* Toggle Switch sketch

* a switch connected to pin 2 lights the LED on pin 13

*/

constintledPin = 13; // output pin for the LED

constintinputPin = 2; // input pin for the switch

intval_old = HIGH ; // initialise the switch value

intLED_state = LOW; // initialise the LED state

voidsetup() {

pinMode(ledPin, OUTPUT);

pinMode(inputPin, INPUT);

digitalWrite(inputPin,HIGH); // turn on internal pull-up on the inputPin

}

voidloop(){

intval = digitalRead(inputPin); // read input value

if(val_old== HIGH && val == LOW) // check if the input is LOW but was HIGH

{

if(LED_state == LOW) {

digitalWrite(ledPin, HIGH); // turn LED ON if it was OFF

LED_state = HIGH; // Remember we just made the LED HIGH

}

else

{

digitalWrite(ledPin, LOW); // turn LED OFF if it was ON

LED_state = LOW; // Remember we just made the LED LOW

}

}

val_old = val; // This will be the old value next time

delay(100); // Delay to avoid ground bounce

}

Try changing the delay(100) command to delay(1). See how the switch does not switch cleanly between states. Instead it bounces. The delay() command helps by stopping execution of the program for 100ms which is enough time for the switch to stop bouncing.