📅  最后修改于: 2023-12-03 14:39:19.645000             🧑  作者: Mango
DigitalRead is a function in Arduino programming language that allows you to read the state of a digital input pin. It is commonly used to read the state of a switch, a button, or any other digital sensor connected to an Arduino board.
In this guide, we will explore the syntax, usage, and example of the DigitalRead function in Arduino.
The syntax for the DigitalRead function is as follows:
int digitalRead(uint8_t pin);
pin
(uint8_t): the number of the digital pin you want to read. This can be any valid digital pin number on the Arduino board.The DigitalRead function returns an integer value representing the state of the specified digital pin. It can be either HIGH
(1) or LOW
(0).
Here is an example that demonstrates how to use the DigitalRead function in Arduino:
int switchPin = 2; // digital pin for the switch
int switchState = 0; // variable to store the switch state
void setup() {
pinMode(switchPin, INPUT); // initialize the switch pin as INPUT
Serial.begin(9600); // initialize the Serial communication
}
void loop() {
switchState = digitalRead(switchPin); // read the state of the switch pin
Serial.println(switchState); // print the switch state to the Serial monitor
delay(100); // a small delay for stability
}
In this example, we define a variable switchPin
which represents the digital pin number for the switch. We also declare a variable switchState
to store the state of the switch. In the setup()
function, we set the switchPin
as an input pin using pinMode()
. We also initialize the Serial communication using Serial.begin()
to enable printing the switch state to the Serial monitor.
In the loop()
function, we continuously read the state of the switch pin using digitalRead()
and store it in the switchState
variable. Then, we print the switch state to the Serial monitor using Serial.println()
. Finally, we add a small delay using delay()
for stability.
Make sure to connect the switch to the designated digital pin and observe the switch state in the Serial monitor of the Arduino IDE.
Note: The value of switchState
will be 1 when the switch is closed (high voltage) and 0 when the switch is open (low voltage).
The digitalRead()
function is a useful tool in Arduino programming to read the state of digital input pins. It opens up endless possibilities for interacting with external digital sensors and switches. Make sure to understand the principles behind this function and experiment with various input scenarios to broaden your Arduino programming skills.