Cautionary note about shared analog inputs when choosing which analog inputs to use
Last time I briefly went over how to use the alternative analog inputs on ADCs 0 to 4. It went like this:
- set SH0ALT to 0 / 1 to use AN0 / AN45 on ADC0
- set SH1ALT to 0 / 1 to use AN1 / AN46 on ADC1,
- set SH2ALT to 0 / 1 to use AN2 / AN47 on ADC2,
- set SH3ALT to 0 / 1 to use AN3 / AN48 on ADC3 or
- set SH4ALT to 0 / 1 to use AN4 / AN49 on ADC4 respectively.
At the time I didn't realise the full implications of that. I was working on a project yesterday and saw this:
I was trying to use AN45, but there didn't seem to be a flag to check to see if the ADC conversion had completed, so I went to check the datasheet. Sure enough, I found this:
What I was expecting was ADCDATA45, ADCDATA46, ADCDATA47, ADCDATA48 and ADCDATA49, but it ended at ADCDATA44. Then suddenly I remember the pins could be used as alternative inputs and went back to look at the ADC block diagram again:
That confirmed it for me. You can use AN45 as an input OR you can use AN0 as an input, and they will both work on ADC0. However, you can not use them at the same time!
Yes, I'm sure you could keeping setting and clearing SH0ALT to use them both but that is not what I'm referring to. I'm referring to a situation where you look at the datasheet and think you can attach signal A to AN0 and signal B to AN45 and read them in at the same time.
So how to use AN45 then? Well, you set SH0ALT to 1 and then write the code as if you are actually using AN0. That is, you still use all the ADC0 bit settings and flags (like ADCDATA0, ARDY0, TRGSRC0, etc.) as if you were using AN0 but the PIC32MZ will know that you are actually using AN45 instead of AN0 because you've set SH0ALT to 1.
TL;DR ADC inputs AN45, AN46, AN47, AN48 and AN49 are shared with ADC inputs AN0, AN1, AN2, AN3 and AN4 respectively. You can use, for example, either AN0 or AN45 but you can not use both at the same time for different signals.
And yes, it seems obvious now but I think this is a potentially very dangerous design trap that you might fall into if you don't know about it so I'm uploading it in the hopes that someone who needs this will find it.