Our Arduino will need to know or sense if a key is placed into the keyhole. This is an input that will be given on one of the Arduinos I/O pins.
Arduino can take an input from the outside world using the digitalRead()
function.
A function in programming can be thought of as a task or a group of tasks that performs or does something. There are functions to add two numbers, there are functions that can check the number of letters in a word, and there are many more. You can even write your own functions in a program.
The digitalRead()
function is one such function that gets input from the outside world through one of Arduinos I/O pins.
You will also be introduced to conditional statements, namely the if and else statements, which help the Arduino make decisions depending on certain conditions.
Let's write a program that takes input from a button, and depending on whether the button is pressed or not, turns on and off an LED. You learned how to blink an LED in the previous chapter using the digitalWrite()
function. Using what you learned, we shall hook up a new circuit to our breadboard and see how digital input on the I/O pins as well as conditional statements work:
//Initializing a variable to store the value of the button state int state = 0; // the setup function runs once when you press reset or power the board void setup() { // initialize digital I/O pins pinMode(2, INPUT); pinMode(13, OUTPUT); } // the loop function runs over and over again forever void loop() { state = digitalRead(2); if ( state == HIGH ) digitalWrite(13, HIGH); else digitalWrite(13, LOW); }
Connect a button to the Arduino as follows:
The equivalent connections will be like this:
Image source: https://www.arduino.cc/en/Tutorial/Button
13.58.247.31