To make this, you will need:
To build the assembly:
The resistor in step 3 is called a ‘pull-down’ resistor because it ‘pulls’ the voltage of Pin 2 down to 0V (GND) when the switch is open. We have included a short additional explanation of this at the bottom of the page, but this isn’t part of the main course content.
For more information on attaching push buttons, look up push-button on the Arduino webpage.
Code
This set of instructions will light up an LED attached to pin 13 when the button attached to pin 2 is pressed. When you use the Arduino IDE program, the code can be found by clicking File→Examples→02.Digital→Button.
Light up an LED on pin 13 while the button on pin 2 is pressed.
*/
Just like last week, here’s a description of the new functions we’ve just used (don’t hesitate to click on the links below which will take you to the Arduino reference pages).
- Declaring a constant: as with a variable, we come with this line to store the value to the right of the equal sign in
led
.
const int led = 13;
The key word const
indicates that we don’t want the value of ‘led’ to be able to changed by the program.
- New instructions:
digitalRead
reads the state of the pin and returnsHIGH
if the voltage is at the power supply voltage (in this case 5V) orLOW
if the pin is at 0V.
digitalRead(buttonPin);
The value returned by
digitalRead
can be stored in a variable as follows:
buttonState = digitalRead(buttonPin);
if
lets us test a statement to see if it’s true, and then run some code if it is. In our program Button, we want to do something “if” the button is pressed, so we’re going to compare buttonState with the valueHIGH
as follows:
if(buttonState == HIGH)
else
: the code after this key word will be executed if the preceding test is false. In Button, if the button is not pressed we want the LED off.
NOTE this content is provided for information only and is not required for the quiz or lab.
The resistor connected to the switch is called a ‘pull-down’ resistor: it ensures the voltage we read at Pin 2 is 0V whenever the switch is ‘open’ (not pressed).
When we press the switch, we make an electrical connection between +5V and Pin 2. If we then release the switch, that connection to GND through a resistor allows the voltage at Pin 2 to return to 0V. Without this resistor, Pin 2 might retain an electrical charge we don’t want it to, so it might not always read 0V if the switch is open. For more information, see the Arduino Playground page on Pull-up and Pull-down resistors.
Leave a Reply
You must be logged in to post a comment.