Search code examples
type-conversionatmegausart

USART format data type


i would like to ask, how i can send data via usart as integer, i mean variable which stores number. I am able to send char variable, but terminal shows me ascii presentation of this number and i need to see number. I edited code like shown below but it gives me error: "conflicting types for 'USART_Transmit'"

#include <avr/io.h>
#include <util/delay.h>

#define FOSC 8000000// Clock Speed
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1

void USART_Init( unsigned int ubrr );
void USART_Transmit( unsigned char data );
unsigned char USART_Receive( void );

int main( void )
{
    unsigned char str[5] = "serus";
    unsigned char strLenght = 5;
    unsigned int i = 47;

    USART_Init ( MYUBRR );
    //USART_Transmit('S' );
    while(1)
    {
        /*USART_Transmit( str[i++] );
        if(i >= strLenght)
        i = 0;*/
        USART_Transmit(i);
        _delay_ms(250);
    }
    return(0);
}

void USART_Init( unsigned int ubrr )
{
    /* Set baud rate */
    UBRR0H = (unsigned char)(ubrr>>8);
    UBRR0L = (unsigned char)ubrr;
    /* Enable receiver and transmitter */
    UCSR0B = (1<<RXEN)|(1<<TXEN);
    /* Set frame format: 8data, 2stop bit */
    UCSR0C = (1<<USBS)|(3<<UCSZ0);
}

void USART_Transmit( unsigned int data )
{
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<UDRE)) )
    ;
    /* Put data into buffer, sends the data */
    UDR0 = data;
}

unsigned char USART_Receive( void )
{
    /* Wait for data to be received */
    while ( !(UCSR0A & (1<<RXC)) )
    ;
    /* Get and return received data from buffer */
    return UDR0;
}

Do you have any ideas what is wrong? PS: I hope you understand what im trying to explain.


Solution

  • I like to use sprintf to format numbers for serial.

    At the top of your file, put:

    #include <stdio.h>
    

    Then write some code in a function like this:

    char buffer[16];
    sprintf(buffer, "%d\n", number);
    char * p = buffer;
    while (*p) { USART_Transmit(*p++); }
    

    The first two lines construct a null-terminated string in the buffer. The last two lines are a simple loop to send all the characters in the buffer. I put a newline in the format string to make it easier to see where one number ends and the other begins.