init m05e02, in decimal
This commit is contained in:
47
module05/ex02/adc.c
Normal file
47
module05/ex02/adc.c
Normal file
@@ -0,0 +1,47 @@
|
||||
#include "header.h"
|
||||
|
||||
// 24.2 : The ADC generates a 10-bit result which is presented in the ADC Data Registers, ADCH and ADCL
|
||||
|
||||
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 |= (1 << ADATE); // 24.9.2 : enable Auto Trigger -> it will start a conversion on the selected channel in ADMUX when the selected source (in ADCSRB) is triggered
|
||||
ADCSRA |= (1 << ADIE); // 24.9.2 : enable ADC Interrupt
|
||||
ADCSRA |= ADC_PRESCALE_SET(prescaler_value); // Table 24-5 : prescaler ADC
|
||||
|
||||
ADCSRB = ADC_TRIGGER_TIMER_1_COMPARE_B; // Table 24-6 : ADC Auto Trigger Source
|
||||
ADMUX = (ADMUX & 0b11110000) | (adc_channel & 0b1111); // Table 24-4 : Select ADC channel 0
|
||||
}
|
||||
|
||||
void adc_print_dec(uint16_t value) {
|
||||
char buffer[17] = {0};
|
||||
|
||||
// handle zero case
|
||||
if (value == 0) {
|
||||
buffer[15] = '0';
|
||||
uart_printstr(&buffer[15]);
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t pos = 0;
|
||||
while (value) {
|
||||
uint8_t digit = value % 10;
|
||||
buffer[15 - pos] = digit + '0';
|
||||
value /= 10;
|
||||
pos++;
|
||||
}
|
||||
uart_printstr(&buffer[16 - pos]); // send only from first digit
|
||||
}
|
||||
|
||||
ISR(ADC_vect) { // Table 12-6 : interrupt vector for ADC Conversion Complete
|
||||
uint16_t value = ADC; // 24.9.3.2 : read ADC 16 bits precision
|
||||
adc_print_dec(value);
|
||||
adc_channel = (adc_channel + 1) % 3; // loop through channels
|
||||
ADMUX = (ADMUX & 0b11110000) | (adc_channel & 0b1111); // Table 24-4 : Select ADC channel
|
||||
if (adc_channel != 0) {
|
||||
uart_printstr(", ");
|
||||
ADCSRA |= (1 << ADSC); // 24.9.2 : start next conversion
|
||||
} else {
|
||||
uart_printstr("\r\n");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user