arduino / arduino/ArduinoCore-megaavr

Possible off-by-one error in analogRead?

Open
#117 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
111
Forks
65
PR merge metrics
No merged PRs in 30d

Description

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

Contributor guide

No contributing guide indexed for this repository

Research direction

Start at the analogRead range check and the NUM_ANALOG_INPUTS definitions in pins_arduino.h for the Nano Every and WiFi Rev2. Compare the boundary with the board's digitalPinToAnalogInput mappings, then determine whether the off-by-one concern and the constant's documented meaning require changes. Done means the valid analog pin range is correct for both boards and the behavior is covered by applicable tests, if available.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
embedded-iot
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.