3.2.3 Code Example for ATmega328PB
To quickly implement the method into a real project, generating an Atmel START Project based on the ATmega328PB is recommended.
- Connect an ATmega328PB XPRO Mini board to the computer via a Mini-USB cable
- Open Atmel Studio 7.0 and click File → New → Atmel START Example Project
- Type "ATmega328PB", then select the "ATmega328PB Xplained Mini", and click "CREATE NEW PROJECT" in the window
- Select AVCC as ADC reference and 1.1V internal reference voltage as ADC input, then click "GENERATE PROJECT"
- Type "Battery Voltage Measurement without using I/O pin on ATmega328PB" as the project name
- Wait for the completion of the project generation to be finished and then locate the main.c file
The simplest way is to check or update three items based on the generated project:
- Let Vbg act as ADC input.
- Let VCC act as ADC
reference.
ADMUX = (0x01 << REFS0) /* AVCC with external capacitor at AREF pin */ | (0 << ADLAR) /* Left Adjust Result: disabled */ | (0x0e << MUX0) /* Internal Reference (VBG) */; - Start the ADC and calculate the
result in the main
while(1).
float Vcc_value = 0 /* measured Vcc value */; uint16_t ADC_RES_L = 0; uint16_t ADC_RES_H = 0; while(1) { if (ADCSRA & (0x01 << ADIF)) /* check if ADC conversion complete */ { ADC_RES_L = ADCL; ADC_RES_H = ADCH; Vcc_value = ( 0x400 * 1.1 ) / (ADC_RES_L + ADC_RES_H * 0x100) /* calculate the Vcc value */; } }
