Introduction
digitalRead() helps you check if a button or switch is ON or OFF by reading the voltage on a pin.
Jump into concepts and practice - no test required
digitalRead() helps you check if a button or switch is ON or OFF by reading the voltage on a pin.
int state = digitalRead(pin);pin is the number of the digital pin you want to read.
The function returns HIGH if the pin is receiving voltage, or LOW if not.
int buttonState = digitalRead(2);
if (digitalRead(7) == HIGH) { // do something }
This program reads a button connected to pin 4. It prints "Button is pressed" when the button is pressed, and "Button is not pressed" when it is not.
const int buttonPin = 4; void setup() { pinMode(buttonPin, INPUT); Serial.begin(9600); } void loop() { int buttonState = digitalRead(buttonPin); if (buttonState == HIGH) { Serial.println("Button is pressed"); } else { Serial.println("Button is not pressed"); } delay(500); }
Make sure to set the pin mode to INPUT before using digitalRead().
Use pull-up or pull-down resistors to avoid random readings when the button is not pressed.
digitalRead() reads if a pin is HIGH or LOW.
Use it to check buttons, switches, or sensors.
Always set pinMode to INPUT before reading.
digitalRead() function do in Arduino?void setup() {
pinMode(2, INPUT);
Serial.begin(9600);
}
void loop() {
int buttonState = digitalRead(2);
Serial.println(buttonState);
delay(500);
}void setup() {
Serial.begin(9600);
}
void loop() {
int state = digitalRead(4);
Serial.println(state);
delay(1000);
}pinMode(3, INPUT);
if (digitalRead(3) == HIGH) {
Serial.println("Pressed");
} else {
Serial.println("Not Pressed");
}
B)
pinMode(3, INPUT);
if (digitalRead(3) == LOW) {
Serial.println("Pressed");
} else {
Serial.println("Not Pressed");
}
C)
pinMode(3, OUTPUT);
if (digitalRead(3) == LOW) {
Serial.println("Pressed");
} else {
Serial.println("Not Pressed");
}
D)
pinMode(3, INPUT_PULLUP);
if (digitalRead(3) == HIGH) {
Serial.println("Pressed");
} else {
Serial.println("Not Pressed");
}