3 Level Crossing Detector
This example shows a basic initialization and setup for the AC peripheral. The application monitors an analog input signal, compares it to a fixed voltage, and notifies the user via interrupt and an output pin every time the input signal crosses the fixed voltage level. The comparator can be used to monitor battery voltage (or any other DC level).
To monitor an external voltage, the AC input must be connected to this voltage using an I/O pin. This pin needs to have the digital input buffer and the pull-up resistor disabled, to have the highest possible input impedance. For the ATmega4809, PORTD pin 2 (PD2/AINP0) is used as AC positive input:
This translates to the following code:
PORTD.PIN2CTRL = PORT_ISC_INPUT_DISABLE_gc;
In the selected application, the AC uses the analog pin as positive input and an internal reference for its negative input. The Voltage Reference (VREF) peripheral must be configured before using the internal voltage reference on negative input.
The VREF provides control registers for selecting between multiple internal reference levels. The internal references are generated from an internal band gap.
A value of 1.5V is selected as reference voltage:
VREF.CTRLA = VREF_AC0REFSEL_1V5_gc;
To enable VREF voltage generation, the output buffer must be enabled after the selection of reference voltage. Do this by setting the AC0REFEN bit from the VREF Control B register:
This translates to the following code:
VREF.CTRLB = VREF_ADC0REFEN_bm;
After configuring the peripherals and the modules required by the AC, the selection of inputs is done using the MUXCTRLA register as follows:
The positive input pin 0 (AINP0) and internal DAC reference are used as AC inputs:
AC0.MUXCTRLA = AC_MUXPOS_PIN0_gc | AC_MUXNEG_DACREF_gc;
#define DACREF_VALUE (VDACREF * 256 / VREF)where VDACREF represents the desired value on the analog comparator input and VREF represents the value selected as internal reference (1.5 Volts).
The output of the comparator is present on the external pin, and the interrupts are enabled on the negative edge to notify the application when the critical level is reached. That is done using the CTRLA register:
These settings translate to the following code:
AC0.CTRLA = AC_ENABLE_bm | AC_INTMODE_NEGEDGE_gc | AC_OUTEN_bm;
The AC peripheral interrupt must be enabled to complete the setup and make the selected interrupt available to the application. Do this by using the CMP bit from the INTCTRL register:
An MCC generated code example for AVR128DA48 with the same functionality as the one described in this section can be found here: