First time trying to directly modify the ADC registers for some new functionality.
I am trying to create a function to read the core voltage of the uC for the series 1 uC. Using DrAzzy's megaTinyCore, the information in App Note 2447 and the work done in ATtiny 0 Series programming on the cheap | Hackaday.io
the code looks like this
float MeasureVcc() {
byte bacVREF,bacMUXPOS,bacCTRLC, bacCTRLA;
// save the states of all the registers prior to reading
// bacVREF = VREF.CTRLA;
// bacMUXPOS = ADC0.MUXPOS;
// bacCTRLC = ADC0.CTRLC;
// bacCTRLA = ADC0.CTRLA;
/* The App Note AN2447 uses Atmel Start to configure Vref but we'll do it explicitly in our code*/
VREF.CTRLA = VREF_ADC0REFSEL_1V1_gc; /* Set the Vref to 1.1V*/
/* The following section is directly taken from Microchip App Note AN2447 page 13*/
ADC0.MUXPOS = ADC_MUXPOS_INTREF_gc /* ADC internal reference, the Vbg*/;
ADC0.CTRLC = ADC_PRESC_DIV4_gc /* CLK_PER divided by 4 */
| ADC_REFSEL_VDDREF_gc /* Vdd (Vcc) be ADC reference */
| 0 << ADC_SAMPCAP_bp; /* Sample Capacitance Selection: disabled */
float Vcc_value = 0; /* measured Vcc value */
ADC0.CTRLA = 1 << ADC_ENABLE_bp /* ADC Enable: enabled */
| 1 << ADC_FREERUN_bp /* ADC Free run mode: enabled */
| ADC_RESSEL_10BIT_gc; /* 10-bit mode */
ADC0.COMMAND |= 1; // start running ADC
do {
Vcc_value = ( 0x400 * 1.1 ) / ADC0.RES /* calculate the Vcc value */;
} while (ADC0.INTFLAGS);
ADC0.COMMAND |= 0; // stop running ADC
// restore the values
// VREF.CTRLA = bacVREF;
// ADC0.MUXPOS = bacMUXPOS;
// ADC0.CTRLC = bacCTRLC;
// ADC0.CTRLA = bacCTRLA;
return Vcc_value;
}
The code works if I use it in a loop by itself, but if after calling the function, I use an analogRead(), the value comes back -1. If I uncomment what I thought would save and restore the settings used in the function for setting ADC0, the function does not work correctly any more.
Am doing the save/restore incorrectly? Any help would be appreciated.