digitalRead()
Description
Reads the value from a specified digital pin, either HIGH or LOW.
Syntax
digitalRead(pin)
Parameter Values
- pin: the Arduino pin number you want to read
Return Values
- HIGH or LOW. The returned type is int.
Example Code
Sets pin 13 to the same value as pin 7, declared as an 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
}
※ NOTES AND WARNINGS:
- 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, Pro Mini, and Mini's A6 and A7 pins, which can only be used as analog inputs.
int ledPin = A5; // LED connected to digital pin A5
int inPin = A0; // pushbutton connected to digital pin A0
int val = 0; // variable to store the read value
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin A5 as output
pinMode(inPin, INPUT); // sets the digital pin A0 as input
}
void loop() {
val = digitalRead(inPin); // read the input pin
digitalWrite(ledPin, val); // sets the LED to the button's value
}
See Also
- Language : digitalWrite()
- Language : pinMode()
- Example : Arduino - Button
- Example : Arduino - Touch Sensor
- Example : Arduino - Door Sensor
- Example : Description of the digital pins
※ ARDUINO BUY RECOMMENDATION
Arduino UNO R3 | |
Arduino Starter Kit |
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.
Additionally, some links direct to products from our own brand, DIYables.