Contents

Concepts

We know what a switch is, but what can we do with it?

One of the uses of a switch is to tell the controller to activate/deactivate different components. In this case we are going to use the switch to turn on and off an LED. We will do this by checking to see if the switch is pressed. When it is pressed, we will turn on the LED. when it is released, we will turn off the LED.

Physical connection

The first thing you will need to do is find somewhere on the robot to attach the bump switch. You can follow the pictures or come up with your own method depending on your chassis.

Parts to connect the switch

Connecting the switch

Switch connected

Wiring

To wire the connections, you will need two wires, two jumper cables, a 470Ω (yellow-purple-brown) resistor and an LED of any color. We will be using Digital port 2 for the bump switch, and digital port 5 for the LED. Remember to leave the motors connected, even though you will not be using them.

schematic diagram for the program start switch

NOTE: A switch is a very basic component. In fact, the VEX switch does not even use the red wire - they leave it in so the look flows with the other 3-wire sensors. We will not be using it.

NOTE: Because of the nature of the component, it will not matter if you put it on backwards.

Virtual breadboard layout

breadboard layout

Configuring RobotC

Now that we have everything connected, we need to tell ROBOTC how to configure the pins before we can program. We need to tell ROBOTC that we have the LED connected to pin 5, called "led", configured as Digital Out. We also need to to configure digital pin 2 as Digital In and name it "ledSwitch".

configuring the pin for the switch controlled LED

Once that is done you should have the following at the top of your source code file.

Programming

Now that ROBOTC knows what goes where, we can work on writing the code.

We want the Arduino to turn the LED on when the button is pressed, and turn the LED off when it is not pressed. To do this we will need an indefinite while loop, and a way to decide what to do based on the status of the switch. There are lots of different ways to do this, but for now, we will just use a second while loop that only runs when the button is pressed.

We already know how to turn LEDs on and off, but how do we check the state of the button? Well, we use the following command.

SensorValue[ledSwitch] == 1

The "==" means to check if the values to either side are equal. If the values are equal, then it will return true, otherwise it will return false. So by placing that code inside the second while loop's condition, we can make that loop only run when the switch is pressed.