SunFounder 3in1 Kit
4.3 3. Digital Read
Sensors capture real-world information, which is then communicated to the main board via pins (some digital, some
analog) so that the computer can know the reality of the situation.
Therefore, the Arduino board can know the working status of digital sensors by reading the value of digital pins like
buttons, IR obstacle avoidance module.
Here are the required functions.
• pinMode(pin, mode): Configure the specific pin as INPUT or OUTPUT, here it needs to be set as INPUT.
Syntax
pinMode(pin, mode)
Parameters
– pin: the Arduino pin number to set the mode of.
– mode: INPUT, OUTPUT, or INPUT_PULLUP.
• digitalRead(pin): Read the value (level state) from the specified digital pin.
Syntax
digitalRead(pin)
Parameters
– pin: the Arduino pin number you want to read
Returns
HIGH or LOW
Example of Digital Read
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
1. Pull Up & Pull Down.
digitalRead() may produce random, indeterminate values if the pin is not getting a level signal.
So directing the input pins to a known state can make the project more reliable. When using an
input component such as a button, it is usually necessary to connect a pull-up or pull-down resistor in
parallel to the digital input pin.
Apart from connecting a pull-up resistor, you can also set the pin mode to INPUT_PULLUP in the code,
for example pinMode(pin,INPUT_PULLUP). In this case, the pin will access the Atmega’s built-in
pull-up resistor via software, and it will have the same effect as connecting a pull-up resistor.
104 Chapter 4. Basic Projects