Intro to Arduino – Part 6 – Using Buttons

In this part of the tutorial that came with the Arduino starter kit they are going to show you how to use buttons to turn one of your LEDs on and off.

Using buttons is a critical part of programming a robot for the robotics competition. The driver will need to use buttons on the joystick or controller to tell the robot to do certain things (such as picking up a game piece or throwing a ball). Right now we are still keeping things bite-sized and simple; today we turn an LED on and off on-demand, but soon you will be programming your team’s bots to do awesome things!

Please download and read through chapter 5 from the tutorial and follow the steps as you did for the previous chapter:

Again, when you get to the code section copy and paste the code below into a blank codebender window and upload it to your Arduino:


int ledPin = 5;
int buttonApin = 9;
int buttonBpin = 8;

byte leds = 0;

void setup() 
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);  
  pinMode(buttonBpin, INPUT_PULLUP);  
}

void loop() 
{
  if (digitalRead(buttonApin) == LOW)
  {
    digitalWrite(ledPin, HIGH);
  }
  if (digitalRead(buttonBpin) == LOW)
  {
    digitalWrite(ledPin, LOW);
  }
}

If this went well, you are cruising! Speed bumps do occur though, so if you run into any along the way bring your project to your coach or mentor and we’ll take a look together to see where its going awry.

Chances are you will not be creating a set of buttons from scratch like this for your driver to control the robot with. It is much more likely that you will be writing code to react to buttons on an xBox controller or joystick, but the principles are the same.

Its also possible that a button, or something very similar to a button, may be installed on the robot itself to trigger certain things. For example, perhaps when the robot drives into a wall a button on the front of the robot may be pressed which causes the robot to back up. Or perhaps when a ball falls into a certain location, the ball may hit a button that causes the ball to be thrown into the air.

Once you are ready, head to the next lesson to learn about a cousin of the button called the tilt switch.