In this tutorial, we will explore how to read from a digital I/O pin using the digitalRead() function in Arduino.

On the Arduino Uno board, the digital I/O pins are located on the side of the board near the USB port. These pins are numbered from 0 to 13, but typically pins 0 and 1 are reserved for serial communication.

To begin, let’s build a simple circuit. Connect one lead of a button to GND on the Arduino and the other lead to digital pin #3 (you can use any other digital pin as well).

Next, let’s define the pin number as a constant to avoid using a “magic number” in our code:

#define BUTTON_PIN 3

In the setup() function, we need to configure the pin as an input and enable the internal pull-up resistor:

pinMode(BUTTON_PIN, INPUT_PULLUP);

The INPUT_PULLUP option is needed to ensure that the pin is not floating and susceptible to interference when nothing is connected to it.

In the loop() function, we can read the value of the input pin using the digitalRead() function:

int value = digitalRead(BUTTON_PIN);

The value read can be either 0 or 1, depending on the input. If the button is pressed, Arduino will detect a value of 0. If the button is not pressed, Arduino will detect a value of 1.

We can print this value to the serial output by using the Serial.print() function:

#define BUTTON_PIN 3

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  int value = digitalRead(BUTTON_PIN);
  Serial.print(value);
  delay(1000);
}

Upload the program to the Arduino and open the Serial Monitor in the Arduino IDE to see the output. You should see a continuous stream of 1s until you press the button, at which point you should see a 0.

To further expand the project, let’s control an LED. We can use the built-in LED on the Arduino Uno, which maps to digital I/O pin #13. Modify the code as follows:

#define BUTTON_PIN 3

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  int value = digitalRead(BUTTON_PIN);
  digitalWrite(13, value);
}

In this code, we initialize pin #13 as an output and set its initial state to LOW. We then update the state of the LED based on the value read from the button.

The built-in LED will light up when the program starts and turn off when the button is pressed.

That’s it! You have successfully implemented a digital input reading project using Arduino.

Tags: Arduino, Digital Input, digitalRead, LED, Button