Go Down

Topic: Addressing Both Digital and Analog Pins of the Same Number (Read 398 times) previous topic - next topic


Nov 05, 2012, 04:18 am Last Edit: Nov 05, 2012, 05:01 am by Nick Gammon Reason: 1
Just starting out with Arduino and I cannot find any documentation that clearly explains how to simultaneously address an analog and digital pin with the same number. For example, take the provided AnalogWrite tutorial from the Arduino reference. The documentation is as follows.

Code: [Select]
int ledPin = 9;      // LED connected to digital pin 9
int analogPin = 3;   // potentiometer connected to analog pin 3
int val = 0;         // variable to store the read value

void setup()
 pinMode(ledPin, OUTPUT);   // sets the pin as output

void loop()
 val = analogRead(analogPin);   // read the input pin
 analogWrite(ledPin, val / 4);  // analogRead values go from 0 to 1023, analogWrite values from 0 to 255

This all makes perfect sense to me, but say I wished to keep the potentiometer wiper attached to analog pin 3, but also connect the LED to digital pin 3. The global variables are merely assigned to a digit, but make no differentiation between analog and digital.


Moderator edit: [code] ... [/code] tags added. (Nick Gammon)


Nov 05, 2012, 04:46 am Last Edit: Nov 05, 2012, 04:55 am by retrolefty Reason: 1
The global variables are merely assigned to a digit, but make no differentiation between analog and digital.

That is because the analogRead() function is smart and knows that when passed the value of 3 that it will use pin A3 not digital pin 3.

Note the following all read the same analog voltage wired to the first physical analog input pin on a Uno board:


Therefore you can certainly have a analogRead(3) and a digitalRead(3) in the same sketch with no hardware or software conflict as they are addressing different physical pins. Also in case you didn't already know it the analog input pins can be used as digital input or output pins by using (an a Uno board) pin numbers 14 to 19 to use the analog pins A0 to A5.

Note that the numbering scheme relationship is different for a mega board, but the principals and capabilities are the same.



Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131