09) How to Use a Button

Understanding how to use a button will be your first step into programming a sensor. Although you may not use this code per say, this will be your first lesson on how to receive data from the outside world! Without communications, it can blink, turn, make sounds all it wants, but the robot really comes alive when you can control it using sensors.

Buttons are fairly simple to operate and to wire up. To prevent from drawing too much current from the Arduino, I would use this wiring diagram:

Please use the resistor, it is not for decoration!



Now to receive the signal from this new button that we plugged into port 2, we can use the function called "digitalRead()". digitalRead's only argument is the port number! However, this function returns an boolean value that notifies us if the port is getting enough electricity (HIGH / 1) or not (LOW / 0). We will be saving this response as a local variable and relaying it to the digitalWrite functions "state" argument. This will turn on the light when you press the button! So this is how we will use it:
void setup()
{
}

void loop()
{
  boolean isButtonOn;
  isButtonOn=digitalRead(2);
  digitalWrite(5,isButtonOn);
}

It is not too special, since its just like hooking up a button directly to the led, but you are controlling an LED with code now!

There is not much more you can do with with a button yet, but I will go over more on how to use a button in the next lesson. (This was a pretty short lesson).
Comments