#define FOSC 1843200 // Clock Speed
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1
volatile uint16_t adcResult = 0; // Variable to hold the ADC result
void setup() {
Serial.begin(9600); // Initialize Serial communication
init_adc(); // Initialize the ADC
sei(); // Enable global interrupts
}
void loop() {
// The ADC value will be updated when the interrupt occurs
Serial.print("ADC Value: ");
Serial.println(adcResult); // Print the ADC result
delay(500); // Add a delay for readability
}
void init_adc() {
ADMUX = 0x40; // Reference: AVCC, Input Channel: ADC0
ADCSRA = 0x87; // Enable ADC, Prescaler: 128
ADCSRA |= (1 << ADIE); // Enable ADC interrupt
ADCSRA |= (1 << ADEN); // Enable the ADC
ADCSRA |= (1 << ADSC); // Start the first conversion
}
ISR(ADC_vect) {
uint8_t lowByte = ADCL; // Read the low byte of ADC result
uint8_t highByte = ADCH; // Read the high byte of ADC result
adcResult = ((uint16_t)highByte << 8) | lowByte; // Combine the high and low bytes to form a 10-bit result
ADCSRA |= (1 << ADSC); // Start the next conversion
}
// USART Initialization
void USART_Init(unsigned int ubrr) {
/* Set baud rate */
UBRR0H = (unsigned char)(ubrr >> 8);
UBRR0L = (unsigned char)ubrr;
UCSR0B = (1 << RXEN0) | (1 << TXEN0); /* Enable receiver and transmitter */
UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); /* Set frame format: 8 data bits, 1 stop bit */
}
// The USART Transmitter
void USART_Transmit(unsigned char data) {
while (!(UCSR0A & (1 << UDRE0))); /* Wait for empty transmit buffer */
UDR0 = data; /* Put data into buffer, sends the data */
}
//USART_Transmit
void USART_Transmit(unsigned int data) {
while (!(UCSR0A & (1 << UDRE0))); /* Wait for empty transmit buffer */
UCSR0B &= ~(1 << TXB80); /* Copy 9th bit to TXB8 */
if (data & 0x0100)
UCSR0B |= (1 << TXB80);
UDR0 = data;/* Put data into buffer, sends the data */
}