Arduino Project #13: Demonstrating a Digital Input

 

#13: Demonstrating a Digital Input

Our goal in this project is to create a button that turns on an LED for half a second when pressed.



The Algorithm

Here is our algorithm:

1. Test to see if the button has been pressed.

2. If the button has been pressed, then turn on the LED for half a second, and then turn it off.

3. If the button has not been pressed, then do nothing.

4. Repeat indefinitely.

The Hardware

 


Here’s what you’ll need to create this project

:One push button

One LED

One 560 W resistor

One 10 kW resistor

One 100 nF capacitor

Various connecting wires

One breadboard

Arduino and USB cable

 

The Sketch

 

Project 4 - Demonstrating a Digital Input

 

#define LED 12

#define BUTTON 7

void setup()

{

pinMode(LED, OUTPUT); // output for the LED

pinMode(BUTTON, INPUT); // input for the button

}

void loop()

{

 if ( digitalRead(BUTTON) == HIGH )

 {

digitalWrite(LED, HIGH); // turn on the LED

delay(500); // wait for 0.5 seconds

digitalWrite(LED, LOW); // turn off the LED

}

}

 

Making More Decisions with if-then-else

You can add another action to an if statement by using else.

For example, if we rewrite Listing 4-1 by adding else as shown in Listing 4-3, then the LED will turn on if the button is pressed, or else it will be off. Using else forces the Arduino to run another section of code if the test in the if statement is not true.

 

The Sketch

#define LED 12

#define BUTTON 7

void setup()

{

 pinMode(LED, OUTPUT); // output for the LED

pinMode(BUTTON, INPUT); // input for the button

}

void loop()

{

if ( digitalRead(BUTTON) == HIGH )

{

digitalWrite(LED, HIGH);

}

Else

 {

 digitalWrite(LED, LOW);

}

}

 


No comments:

Post a Comment

INSTAGRAM FEED

@soratemplates