2

I'm reading two digital inputs and one analog input. For [reasons] I must use A0 and A1 as digital ins, and A2 as an analog in.

I'm uncertain about how the Arduino hardware deals with mixing analog and digital inputs on the same port. For speed, I'm reading like this:

 uint8_t raw = PINC;
 boolean digitalA = (bool)(raw & 1);  // read A0
 boolean digitalB = (bool)(raw & 2);  // read A1
 int analogC = analogRead(A2);

Will the raw reading of the port interfere with the analogRead in any way? I did see a caveat about mixing A & D, but it only had to do with noise introduced in the analog ins when doing digital outs. Would reading analog first minimize that?

Jim Mack
  • 269
  • 6
  • 14

2 Answers2

2

What you are trying to do is perfectly safe. In fact, you reading PINC will have no effect whatsoever on the input circuitry. You are just reading an I/O register and, whether you read it or not, this register is updated on every clock cycle from a set of comparators that monitor the pin voltages.

Just for completeness, I should mention that it is possible to disable the comparators that update the register. The Atmel datasheet recommends to disable them if you want the lowest possible ADC noise. If you follow that recommendation, then reading PINC will just return zero. The Arduino core library does not disable them: the input comparators are thus always active, and you can get a meaningful value by reading that digital input register.

Edit: You can selectivly disable the input comparator on the pin A2 by issuing DIDR0 |= _BV(ADC2D);. But that is only useful if you really need to maximize the accuracy.

Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81
1

In general, most embedded processors multiplex external pins into specialized internal circuits. Circuits which check standard fixed threshold crossings (digital inputs), circuits which check variable threshold crossings (comparators) and circuit which combine comparators with a variable settable reference (analog to digital converter) to name only three.

Usually a pin is multiplexed to a particular internal circuit only once during initialization. Switching between internal circuits as part of normal operation is tricky and can lead to unexpected results.

Analog reads are often problematic because of noise. However, it is unlikely that reading the state of a digital input will effect the conversion of the ADC circuit.

It would be far more effective to read the actual processor's application note you are using and understand that processor's ADC issues. You may be surprised that the number is significant bits (usable bits) are less than the number found in the ADC register. Or that you can increase the number of significant bits simply by adding averaging to your software.

st2000
  • 7,513
  • 2
  • 13
  • 19