0
0
AutocadHow-ToBeginner · 3 min read

How to Use digitalRead in Arduino: Simple Guide and Example

Use digitalRead(pin) to read the state of a digital input pin on an Arduino. It returns HIGH if the pin is receiving voltage and LOW if not. Make sure to set the pin mode to INPUT before reading.
📐

Syntax

The digitalRead() function reads the value from a specified digital pin on the Arduino board. It returns HIGH or LOW depending on the voltage level.

  • pin: The number of the digital pin you want to read.

Before using digitalRead(), set the pin mode to INPUT using pinMode(pin, INPUT);.

arduino
int value = digitalRead(pin);
💻

Example

This example reads the state of a pushbutton connected to digital pin 2 and turns on the built-in LED on pin 13 when the button is pressed.

arduino
const int buttonPin = 2;
const int ledPin = 13;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(buttonPin);
  Serial.println(buttonState);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
  delay(100);
}
Output
1 1 1 ... (when button pressed) 0 0 0 ... (when button released)
⚠️

Common Pitfalls

Common mistakes when using digitalRead() include:

  • Not setting the pin mode to INPUT before reading, which can cause unreliable readings.
  • Forgetting to use a pull-down or pull-up resistor, which can leave the pin floating and cause random values.
  • Confusing digitalRead() with analogRead(), which reads analog voltage levels.
arduino
/* Wrong way: missing pinMode setup */
int buttonState = digitalRead(2); // May give random results

/* Right way: */
pinMode(2, INPUT);
int buttonState = digitalRead(2);
📊

Quick Reference

FunctionDescription
pinMode(pin, INPUT)Set pin as input to read signals
digitalRead(pin)Read digital value (HIGH or LOW) from pin
HIGHPin voltage is high (usually 5V or 3.3V)
LOWPin voltage is low (0V)
INPUT_PULLUPSet pin as input with internal pull-up resistor

Key Takeaways

Always set the pin mode to INPUT before using digitalRead.
digitalRead returns HIGH or LOW depending on the pin voltage.
Use pull-up or pull-down resistors to avoid floating inputs.
digitalRead works only on digital pins, not analog inputs.
Check wiring carefully to get reliable readings.