AnalogRead; Zero Crossing

After a narrow reading of the code and datasheet, I discovered that the ADC is working in unsigned single-ended mode. In this mode, the ADC is measured between the input and a voltage value that is (Vref - Offset). Vref, in our case, is 0V and Offset was measured using a multimeter as 10.3mV.

To solve this problem, an unconventional method was used. I changed the operation mode to signed single-ended (that will show negative values also) and then I defined that, if the value is negative, the function returns 0. So, now analogueRead() is capable to sense voltage variations in a range between 0 and 2.05V. The changes were made in the file: LithneDuino\hardware\xmegaduino\cores\xmega\wiring_analogue.c

int analogRead12(uint8_t pin)
{
ADC_t* adc;
#if defined(ADCB) //Atxmega128a1 has 2 8 channel ADCs
if ( pin < 8 ) {
adc = &ADCA;
} else if ( pin < 16 ) {
adc = &ADCB;
pin -= 8;
#else //Atxmega32a4 has 1 12 channel ADC
if ( pin < 12 ) {
adc = &ADCA;
#endif
} else {
return -1;
}
pin = adcToChannel(pin);
adc->CTRLB |= 0b10000; //sets pin CONVMODE to enable signed mode
adc->REFCTRL = analog_reference << ADC_REFSEL_gp;
adc->CH0.MUXCTRL = pin << ADC_CH_MUXPOS_gp; // Select pin for positive input
adc->CH0.CTRL |= ADC_CH_START_bm; // Start conversion
while ( 0 == (adc->CH0.INTFLAGS & ADC_CH_CHIF_bm) ); // wait for adc to finish
adc->CH0.INTFLAGS = 1;
uint16_t result = adc->CH0RES;
if(result & 0x8000) return 0; //if result < 0
else return result;
}
int analogRead(uint8_t pin)
{
return analogRead12(pin) >> 1; // divide by 2 to return a value between 0 and 1023
}