Files
42_EXT_03_42chips/module05/ex00/adc.c
2025-03-14 14:15:49 +01:00

27 lines
1.4 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "header.h"
// Table 14-6. Port C Pins Alternate Functions
// - PC0 -> ADC0 (ADC Input Channel 0)
// -> PCINT8 (Pin Change Interrupt 8)
//
// 24.2 : The ADC generates a 10-bit result which is presented in the ADC Data Registers, ADCH and ADCL
//
// START A CONVERSTION in single conversion mode :
// - disabling the Power Reduction ADC bit, PRADC
// - writing a logical one to the ADC Start Conversion bit, ADSC
void adc_init(uint8_t prescaler_value) {
ADMUX = (1 << REFS0); // Table 24-3 : set voltage reference, AVCC with external capacitor at AREF pin
ADCSRA = (1 << ADEN); // 24.9.2 : enable ADC
ADCSRA |= ADC_PRESCALE_SET(prescaler_value); // Table 24-5 : prescaler ADC
}
uint16_t adc_read(uint8_t channel) {
CLEAR(PRR, PRADC); // 24.3 : ensure power reduction is disabled for ADC, (10.11.3 : PRR Power Reduction Register)
ADMUX = (ADMUX & 0b11110000) | (channel & 0b1111); // Table 24-4 : Select ADC channel, (Table 14-6 : alternate function for RV1 on PC0 -> ADC0)
ADMUX |= (1 << ADLAR); // 24.9.1 : enable left adjust result
ADCSRA |= (1 << ADSC); // 24.9.2 : Start conversion, ADSC: ADC Start Conversion
while (ADCSRA & (1 << ADSC)); // Wait for completion
return ADCH; // 24.9.3 : ADC updated only when ADCH is read, not ADCL, so for 8 bits precision uses left adjust result to only read ADCH
}