Thursday, August 1, 2024

ADC to serial print

 #include <avr/io.h>

#include <util/delay.h>

#include <stdlib.h>  // Include for itoa()


int main(void) {

    // Initialize ADC

    ADMUX |= (1 << REFS0); // Reference voltage is AVcc

    ADCSRA |= (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); // Enable ADC and set prescaler to 128


    // Initialize USART

    UBRR0H = 0x00;

    UBRR0L = 0x67; // Set baud rate to 9600 with 16 MHz clock

    UCSR0B = (1 << RXEN0) | (1 << TXEN0); // Enable receiver and transmitter

    UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // Set frame format: 8 data bits, 1 stop bit


    char str[10]; // Buffer to hold the ADC value string


    while (1) {

        // Start ADC conversion on ADC0 (assuming ADC0 is connected to the desired input)

        ADMUX = 0x40; // Set the ADC channel to ADC0

        ADCSRA |= (1 << ADSC); // Start conversion

        while (ADCSRA & (1 << ADSC)); // Wait for conversion to complete

        

        int x = ADC; // Read ADC value

        itoa(x, str, 10); // Convert ADC value to string in base 10


        // Send the string over USART

        for (int i = 0; str[i] != '\0'; i++) {

            while (!(UCSR0A & (1 << UDRE0))); // Wait for the transmit buffer to be empty

            UDR0 = str[i]; // Send the character

        }

        while (!(UCSR0A & (1 << UDRE0)));

        UDR0 = '\n';

        _delay_ms(1); // Delay 1 second

    }


    return 0;

}


No comments:

Post a Comment