0
0
Embedded Cprogramming~5 mins

Reading digital input pin state in Embedded C

Choose your learning style9 modes available
Introduction

We read a digital input pin to know if it is ON or OFF, like checking if a button is pressed.

To detect if a button is pressed on a device.
To check if a sensor is triggered or not.
To read a switch position in a control panel.
To monitor if a door is open or closed using a magnetic sensor.
Syntax
Embedded C
int pinState = digitalRead(pinNumber);

pinNumber is the number of the input pin you want to read.

digitalRead() returns HIGH (1) if the pin is ON, or LOW (0) if it is OFF.

Examples
Reads the state of digital pin 2 and stores it in buttonState.
Embedded C
int buttonState = digitalRead(2);
Checks if pin 5 is ON, then runs code inside the if block.
Embedded C
if (digitalRead(5) == HIGH) {
  // do something when pin 5 is ON
}
Sample Program

This program reads the state of a button connected to pin 7. It prints "Button is PRESSED" when the button is pressed, otherwise it prints "Button is NOT pressed" every half second.

Embedded C
#include <Arduino.h>

const int buttonPin = 7;  // input pin number

void setup() {
  pinMode(buttonPin, INPUT);  // set pin as input
  Serial.begin(9600);         // start serial communication
}

void loop() {
  int buttonState = digitalRead(buttonPin);  // read pin state
  if (buttonState == HIGH) {
    Serial.println("Button is PRESSED");
  } else {
    Serial.println("Button is NOT pressed");
  }
  delay(500);  // wait half a second before reading again
}
OutputSuccess
Important Notes

Make sure to set the pin mode to INPUT before reading the pin.

Use pull-up or pull-down resistors to avoid random readings (floating pins).

digitalRead() only reads digital signals: ON (HIGH) or OFF (LOW).

Summary

Use digitalRead(pin) to check if a digital input pin is ON or OFF.

Always set the pin as INPUT before reading.

Reading digital pins helps detect buttons, switches, and sensors.