Arduino digitalWrite and digitalRead | applied electronics engineering

Latest

Arduino digitalWrite and digitalRead

By Applied Electronics - Saturday, February 4, 2017 No Comments
Arduino digitalWrite and digitalRead are the two functions used to control the digital input/output pins. We write HIGH or LOW values using digitalWrite. HIGH means 5V and LOW means 0V. Similarly we use the digitalRead function to read either HIGH or LOW value into the Arduino microcontroller.

Here we show how to use these functions.

digitalWrite() example

Suppose you want to send out 5V and 0V alternatively, that is HIGH and LOW, to one of the digital pin, say pin 2 to which a LED is connected as shown.


 
The program code to do this is given below.

void setup() {
   // Set pin 2 as a digital Output
   pinMode(2, OUTPUT);
}

void loop(){
   // Set pin 2 HIGH
   digitalWrite(2, HIGH);
   // Wait 100 milliseconds
   delay(100);
   // Set pin 2 LOW
   digitalWrite(2, LOW);
   // Wait 100 milliseconds
   delay(100);
}

First we have to setup the digital pin mode either as input or output in the setup function. Since we want to write to the digital pin we have to set the pin 2 as output. This is done using the pinMode function. Then in the main loop function we use the digitalWrite() function to write HIGH first, then LOW with delay of 100 millisecond between them. digitalWrite() function accepts two parameters, the pin number which is 2 in this case and the value to write which is either HIGH or LOW.

digitalRead() example


 Suppose you want to read values into arduino microcontroller like state of a switch for example. In this cases you will use the digitalRead() function. But there is no way to know whether the microcontroller of the Arduino has read the input. So we will connect an output LED as in the example above and write the value read to this LED circuit. See the circuit diagram below.

If we close the switch at pin 4 then the LED at pin 2 will turn on.


The program code to do this is below.

void setup() {
   // Set pin 4 as a digital Input
   pinMode(4, INPUT);
   // Set pin 2 as a digital Output
   pinMode(2, OUTPUT);
}

void loop(){
   // Read pin 4 and store in variable var
   int var = digitalRead(4);
   
   // Send var to output pin 2
   digitalWrite(2, var);
   delay(10);

}

In the setup function we set the pinMode for the pin 2 and 4. Since using pin 4 we are reading the switch state we set it as input. The pin 2 is output as before. In the main loop we use the digitalRead() function to read in the switch state, which can be either HIGH or LOW. To this function we just pass the pin number which is 4 in this example. Then we store the read value as var, which is a variable. Then we send this variable var to the pin 2 using digitalWrite() function.

See other arduino tutorials:

No Comment to " Arduino digitalWrite and digitalRead "