/*
* ADC.c
*
* Created: 05/04/2025 11:08:43
* Author : Paulo H. Langone
* Board : LabGenios Nano
*/
#define F_CPU 16000000UL
#include <stdio.h>
#include <avr/io.h>
#include <util/delay.h>
#include "usart.h"
/*
* @brief Initialize ADC
*/
void adc_init()
{
// AVCC with external capacitor at AREF pin
ADMUX |= (1 << REFS0);
// ADC Enable and ADPS = 128 (111)
ADCSRA |= ((1 << ADEN) | (7 << ADPS0));
// Get first conversion and do nothing
ADCSRA |= (1 << ADSC);
while(ADCSRA & (1 << ADSC));
}
/*
* @brief Performs an ADC read in a selected channel
* @param uint8_t channel channel to be read
* @return read from the selected ADC channel
*/
uint16_t adc_read(uint8_t channel)
{
// Wait for any possible conversion to end
while(ADCSRA & (1 << ADSC));
// Select channel
ADMUX |= (channel << MUX0);
// Get conversion
ADCSRA |= (1 << ADSC);
while(ADCSRA & (1 << ADSC));
// Return conversion
return (ADCL | (ADCH << 8));
}
/*
* Main function
*/
int main(void)
{
adc_init(); // Initialize ADC
usart_init(9600, SERIAL_8N1); // Initialize USART
uint16_t trimpot;
char msg[20];
while (1)
{
trimpot = adc_read(6); // Perform a read at channel 6 (trimpot from LabGenios nano board)
sprintf(msg, "ADC: %d\r\n", trimpot); // Format the message
usart_write_str(msg); // Send the message via USART
_delay_ms(500); // Wait 500ms for next read
}
}