cavratmegahyperterminalusart

AVR HyperTerminal not displaying sensor values


I need to read values form a distance sensor in volts. The sensor sends the voltages binary values to the MUC (ATmega8) and then the ATmega8 communicates to my PC using the USART with an RS-232 cable. The readings displayed on the PC are weird random characters. I don't understand what am I doing wrong.

Here is my code:

// USART communicating with ATmega8
#include <avr/io.h>
#include <inttypes.h>
#include <util/delay.h>
#include <string.h>

// 1 MHz, baud rate 9600
#define F_CPU 1000000

char *Bestbelieve = "t \r\n";

void InitADC()
{
    ADMUX =  (0<<REFS1)|(1<<REFS1);                      // For Aref=internal;
    ADCSRA = (1<<ADEN)|(0<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); // Prescaler division factor = 8
}

uint16_t ReadADC()
{
    ADMUX = 0x05;

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

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

    // Clear ADIF by writing one to it.
    // Note you may be wondering why we have write one to clear it.
    // This is standard way of clearing bits in io as said in datasheets.
    // The code writes '1', but it results in setting the bit to '0' !!!

    ADCSRA |= (1<<ADIF);

    return(ADC);
}

void Wait()
{
    uint8_t i;
    for(i=0; i<20; i++)
        _delay_loop_2(0);
}

char USARTReadChar()
{
    // Wait until data is available
    while(!(UCSRA & (1<<RXC)))
    {
        // Do nothing
    }

    // Now the USART has got the data from the host
    // and is available in its buffer

    return UDR;
}

void USARTWriteChar(char* data)
{
    // Wait until the transmitter is ready
    while(*data)
    {
        while(!(UCSRA & (1<<UDRE)))
        {
            // Do nothing
        }

        // Now write the data to the USART buffer

        UDR = *data;
        data++;
    }
}

void USARTInit(uint16_t ubrr_value)
{
    UBRRL = 12;
    UBRRH = 0;
    UCSRC = (1<<URSEL) | (3<<UCSZ0);
    UCSRB = (1<<RXEN)  | (1<<TXEN);
    UCSRA = (1<<U2X);
}

int main()
{
    uint16_t adc_result;

    // Initialize the ADC
    InitADC();

    USARTInit(12); // UBRR = 12

    // Loop forever
    while(1)
    {
        adc_result = ReadADC(); // Read the analog value from channel-0
        char *result[15];
        sprintf(result, "%d", adc_result);
        Wait();

        USARTWriteChar(adc_result);

        /* The code continuously has 't' outputted and skipped lines.
        */
    }
}

Solution

  • You are using sprintf to format your data into result. However, you then use USARTWriteChar on your binary value adc_result.

    You need to print out result instead, presumably with a loop over the characters calling USARTWriteChar.