Reads the value from a specified digital pin, either HIGH or LOW.
Use the following function to read the value of a digital pin:
digitalRead(pin)
The function admits the following parameter:
pin: the Arduino pin number you want to read.
The function returns the boolean state of the read pin as HIGH or LOW.
Control the Arduino built-in LED on pin 13 (output) by assigning the same value of a push button connected to pin 7 (input).
int ledPin = 13; // LED connected to digital pin 13
int inPin = 7; // pushbutton connected to digital pin 7
int val = 0; // variable to store the read value
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin 13 as output
pinMode(inPin, INPUT); // sets the digital pin 7 as input
}
void loop() {
val = digitalRead(inPin); // read the input pin
digitalWrite(ledPin, val); // sets the LED to the button's value
}
If the pin isn’t connected to anything, digitalRead() can return either HIGH or LOW (and this can change randomly).
The analog input pins can be used as digital pins, referred to as A0, A1, etc. The exception is the Arduino Nano, Arduino Pro Mini, and Arduino Mini’s A6 and A7 pins, which can only be used as analog inputs.