Arduino analog pin as digital pin | applied electronics engineering

Latest

Arduino analog pin as digital pin

By Applied Electronics - Sunday, February 5, 2017 No Comments
We show here how to use Arduino analog pin as digital pin with examples. As you know Arduino UNO has 14 dedicated digital input/output pins. But if you need more you can use the 6 analog input/output as well for digital input/output. Hence Arduino has 20 digital input output pins.

It means that you can use the analog pin as conventional digital pins. As for programming, you will use the same digital input output functions, that is, the Arduino digitalWrite and digitalRead functions.

Shown in the following is the proteus simulation of the analog pins as digital pins. First we will show the digitalWrite() function then the digitalRead() functions.

Arduino analog pin as digital pin using digitalWrite()

We will use the digitalWrite() function to turn ON and OFF a LED which will connected to A2 analog pin. The following is the proteus simulation.

 Arduino analog pin as digital pin using digitalWrite()


Program Code


Program Code for using Arduino analog pin as digital pin is as follows.


void setup(){
   pinMode(A2, OUTPUT);
   }
   
void loop(){
   
   digitalWrite(A2, HIGH);
   delay(100);
   digitalWrite(A2, LOW);
   delay(100);
}

In the program code we have used A2 analog pin for connecting LED. We have used the digitalWrite() function to write to this pin.

Arduino analog pin as digital pin using digitalRead()

Similarly, we can use digitalRead() function to read values from analog pins. In the following example we connect a switch to the A0 analog pin. We read value on this analog pin using digitalRead() function. Then according to the state of the input we turn either ON or OFF the LED of the previous example.

See the example below.

 Arduino analog pin as digital pin using digitalRead()


Program code

The program code for this example is below.

void setup(){
   pinMode(A2, OUTPUT);
   pinMode(A0, INPUT);
   }
   
void loop(){
   
   int x = digitalRead(A0);
   
   if(x == LOW)
   {
      digitalWrite(A2, LOW);
   }
   else
   {
      digitalWrite(A2, HIGH);
   }
   delay(100); 
 
 }

The program code uses the pinMode function to declare the A0 pin as an input. Then in the main loop function we read in the state of the switch connected to analog pin A0 and store it in variable called x. Now depending upon the value of x which can be LOW or HIGH, we turn on the LED LOW or HIGH.

So in this way you can use the Arduino analog pin as digital pin.

If you like this tutorial share it. Also subscribe to our blog posts for more tutorials and other tips and tricks.

Meanwhile see another Arduino trick- Arduino without External Pullup or Pulldown Resistor.

No Comment to " Arduino analog pin as digital pin "