03 September 2012

How To #7: Use Arduino #2

In this How To, I'll teach you about how to use Arduino beyond blinking an LED.
So, in the other Arduino How To, I taught you how to download and use the Arduino IDE, write your first program, and blink an LED. The LED would just blink on and off every second, without any type of input. In this post, we'll control the LED via a pushbutton. To do this, you'll need the following items: an Arduino, a pushbutton, an LED, a breadboard or protoshield, the Arduino IDE installed, and some wire. First, we'll hook up the hardware. Push the pushbutton into the breadboard, and connect one side of it to the red rail on the breadboard. Next connect a 10K ohm resistor between the other side of the pushbutton and the blue rail on the breadboard. Connect a wire from the same side of the pushbutton you connected the 10K ohm resistor and push it into Arduino's digital pin 2. Finally, push the LED into digital pin 13 and ground, and connect two wires from 5V and GND from the Arduino and connect them to the rails of the breadboard. Now the hardware is done. Time to start the software. Open up the Arduino IDE and copy and paste this into a free sketch:
//Pushbutton sketch
// Turns an LED on digital pin 13 on when a button is pressed.

const int button  = 2;
const int led = 13;
int buttonState = 0;

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

void loop()
{
buttonState = digitalRead(button);
if (buttonState = HIGH) {
digitalWrite(led, HIGH);
} else {
digitalWrite(led, LOW);
}
}

When you upload the sketch, wait a few moments and press the button when it says done uploading. You should see the LED turn on when you press it and turn off when you are not pressing it. Congrats, you made a pushbutton controlled LED!

No comments: