MCUdude / MegaCoreX

An Arduino hardware package for ATmega4809, ATmega4808, ATmega3209, ATmega3208, ATmega1609, ATmega1608, ATmega809 and ATmega808
GNU Lesser General Public License v2.1
239 stars 47 forks source link

Tinary Nano 4808 analogRead() returns 255 from all analog pins #151

Closed Telmac1802 closed 2 years ago

Telmac1802 commented 2 years ago

Hello

I have a few solar cells and lead acid battery. I tryed to measure a battery voltage using analogRead() and a resistor divider in Tinary Nano 4808 and MegaCoreX v1.0.10. AnalogRead() returns reading 255 from every analog pin (A0-A11). I could not get a real useful reading using analogRead(). The issue resembles: https://github.com/MCUdude/MegaCoreX/issues/128, but is not the same.

On the file https://github.com/MCUdude/MegaCoreX/blob/master/megaavr/variants/nano-4808/pins_arduino.h on line 77 there is a calculation if a pin is an analog pin or not:

define digitalPinToAnalogInput(p) (((p) < 8) ? (p) : ((p) >= 14 && (p) >= 25) ? (p) : NOT_A_PIN) .

I found a working analogRead()-solution of all pins A0-A11 using following definition on line 77:

define digitalPinToAnalogInput(p) ((((p) < 8) && (p)>3) ? ((p)+8) : ((p) >= 14 && (p) <= 17) ? ((p)-14) : ((p) >= 18 && (p) <= 21) ? ((p)-6) : (((p) >= 22) && ((p) <= 25)) ? ((p)-18) : NOT_A_PIN)

I hope it will be usefull for other Nano 4808 owners also.

MCUdude commented 2 years ago

Thank you for submitting this issue! You're absolutely right, the macro is not right at all. I've modified your macro a little to accept both 0-11 and A0-A11 as input parameters. The fix will be present in the next boards manager release.

#define digitalPinToAnalogInput(p)     (((p) <= 3) ? (p) : \
                                       ((p) <= 7)  ? ((p) + 8) : \
                                       ((p) <= 11) ? ((p) - 4) : \
                                       ((p) >= 14  && (p) <= 17) ? ((p) - 14) : \
                                       ((p) >= 22  && (p) <= 25) ? ((p) - 18) : \
                                       ((p) >= 18  && (p) <= 21) ? ((p) - 6)  : NOT_A_PIN)