Issue sending c char* over USART

611 views Asked by At

I am converting hex bytes into strings and sending them over uart to a terminal on my computer. I am receiving strange (almost correct) output and I cannot figure out why. This is all done in AVR. Here is the relevant code snippets:

while(true)
{
    wan_usart_transmit_string(generateString());
}

Generate String:

char *generateString()
{
    char *c = "";
    char d[5];
    sprintf(d, "%02X", 0x61);
    c = strcat(c, d);
    return c;
}

wan_usart_transmit_string:

void wan_usart_transmit_string(char * data)
{
    unsigned char c = *data;

    while (c)
    {
        while (!(UCSR0A & (1 << UDRE0)));
        UDR0 = c;
        c = *(++data);
    }
}

Output: 61611611116111111116161161111611111111... etc...

The generateString method will eventually look ahead so many positions into a circular buffer and concatenate all of the ASCII values up to that position into a single string, which will subsequently be sent over USART. So it looks a little funky right now. This was just a test snippet to make sure it operates correctly before I made it function dynamically.

2

There are 2 answers

1
this On BEST ANSWER

You need to allocate some memory for the string you are going to return from generateString().

Currently you are pointing c char* c = "" to a string literal and then you try to write into it causing undefined behavior.

Use malloc:

char *c = malloc(sizeof( *c )*10);
c[0] = '\0';  //nul terminate so you get an empty string
char d[5];
sprintf(d, "%02X", 0x61);   //you can sprintf directly into c
c = strcat(c, d);
return c;
0
mstagg On

I was able to get the output I was looking for by using the following code in the generateString method:

char *generateString(){
    char *c;
    char d[5];
    sprintf(d, "%02X", 0x61);
    return c;
}