Digital Input

Pins 1-13 can be used as inputs or outputs. So far we've only used them as outputs. You set the pin to be an output in a similar fashion to setting the pin mode to an output as we've done in previous lessons.You will need to build the circuit show in the schematic. Pin 2 will be looking for an input of either HIGH or LOW. Basically it looks for voltage at pin 2. Technically you don't need the 100 ohm resistor. It's there to protect the Arduino chip from a short circuit.The size of the two resistors are not critical. They are a rough guide. The 10k resistor can be as small as 4.7k and there is really no maximum, but if it is too big the results can be unpredictable.The other new part included in this program is an "if...else" statement. An "if...else" statement tests a statement, similar to a "for" loop. In this case, though it tests it only once. If the statement is true it runs the following statement once. If false it does what is under the "else".if (test) {do what is in the brackets if true} else {if the test is false do what is in these brackets}

/*

* Button

* by DojoDave <http://www.0j0.org>

*

* Turns on and off a light emitting diode(LED) connected to digital

* pin 12, when pressing a pushbutton attached to pin 2.

*

* http://www.arduino.cc/en/Tutorial/Button

*/

int ledPin = 12; // choose the pin for the LED

int inputPin = 2; // choose the input pin (for a pushbutton)

int val = 0; // variable for reading the pin status

void setup() {

pinMode(ledPin, OUTPUT); // declare LED as output

pinMode(inputPin, INPUT); // declare pushbutton as input

}

void loop(){

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

if (val == HIGH) { // check if the input is HIGH

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

} else {

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

}

}

Run the program, push the button. What do you see?

Additional tasks

    1. Swap the positions of the push button and the 10k resistor. Run the program again. What do you see? Why is it different?

    2. Change the program so that when the button is pushed the light turns on for 5 seconds and then shuts off.

    3. Build the LED sequencer you built in the last lesson. Have the leds light up one after the other and repeat. When you push the button have them reverse direction.