arduino / ArduinoCore-megaavr

Arduino Core for the ATMEGA4809 CPU
103 stars 62 forks source link

Possible off-by-one error in analogRead? #117

Open diyelectromusic opened 2 years ago

diyelectromusic commented 2 years ago

For the Nano Every, NUM_ANALOG_INPUTS is set to 14, presumably to allow for AIN12 and AIN13 to be used for A4 and A5. For the Wifi Ref 2 NUM_ANALOG_INPUTS is set to 6.

In analogRead there is a test of the pin number returned from digitalPinToAnalogInput() to check that it is within a sensible range for the hardware, but I think there may be an off-by-one error here. I think the code: if(pin > NUM_ANALOG_INPUTS) return NOT_A_PIN;

Should be: if(pin >= NUM_ANALOG_INPUTS) return NOT_A_PIN;

In practice this probably doesn't cause any problems unless NUM_ANALOG_INPUTS is updated in the future to 16 for the Nano (or 8 for the Uno).

As an aside, setting NUM_ANALOG_INPUTS to 14 in pins_arduino.h for the Nano Every does seem slightly misleading, as the number of supported analog inputs is still just 8, but having it mapped onto channels up to 12 and 13 seems to have forced the higher number in NUM_ANALOG_INPUTS, in which case I'm not quite sure why this isn't set to the actual number of analog channels - i.e. 16?

Kevin