diff --git a/src/ADC/ADC.c b/src/ADC/ADC.c index 7cfc8d3..c926891 100644 --- a/src/ADC/ADC.c +++ b/src/ADC/ADC.c @@ -85,25 +85,29 @@ void ADC_Disable() { RegEdit_ClearBit((void *)&ADCSRA, ADEN); } - uint16_t ADC_ReadValue_Impl(uint8_t adc_chan) { - // RegEdit_SetNum((void *)&ADC0.COMMAND, ADC_STCONV_bm); + if (IsInvalidChannel(adc_chan)) { + return UINT16_MAX; + } - /* Wait until ADC conversion done */ + // start conversion. + RegEdit_SetBit((void *)&ADCSRA, ADSC); - /* - while (!(ADC0.INTFLAGS & ADC_RESRDY_bm)) { - ; - } - */ + /* Wait until ADC conversion done or it times out. */ + uint8_t cycles = 1; + while (1) { + if (!RegEdit_IsBitSet((void *)&ADCSRA, ADSC)) { + break; + } + // if It times out return an invalid value for a 12bit ADC. + else if (cycles >= ADC_WAIT_TIMEOUT) { + return UINT16_MAX; + } + cycles++; + } - /* Clear the interrupt flag by writing 1: */ - // ADC0.INTFLAGS = ADC_RESRDY_bm; - - // uint16_t adc_val = (uint16_t)ADC0.RES; - uint16_t adc_val = 0; - adc_val = adc_val >> 5; - return adc_val; + uint8_t val = ADC; + return val; } // Set the default for the function pointer. diff --git a/src/ADC/ADC.h b/src/ADC/ADC.h index 7eb0f4e..6ad30ab 100644 --- a/src/ADC/ADC.h +++ b/src/ADC/ADC.h @@ -13,6 +13,12 @@ #include #include +/** + * @brief The number of loop cycles it waits for ADC conversion before + * timing out. + */ +#define ADC_WAIT_TIMEOUT 16 + /** * @brief Initializes the AVR hardware in order to accept * Input for ADC usage. @@ -27,7 +33,6 @@ */ void ADC_Init(uint8_t adc_chan); - /** * @brief Returns the pin number for the adc channel or 255 on an error. * @param The ADC channel. @@ -65,5 +70,4 @@ extern uint16_t (*ADC_ReadValue)(uint8_t adc_chan); */ void ADC_Setup(void); - #endif // ADC_H