Question

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 USART with and RS232 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>


//1MHZ Baud 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); //Prescalar div factor =8
}

uint16_t ReadADC()
{

    ADMUX=0x05;

    //Start 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 result in setting 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 a data is available

    while(!(UCSRA & (1<<RXC)))
    {
        //Do nothing
    }

    //Now USART has got data from host
    //and is available is 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 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 ADC
        InitADC();

        USARTInit(12);    //UBRR = 12

        //Loop forever

        while(1)
        {

            adc_result=ReadADC();           // Read 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.
            */

        }
    }
Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top