Electronic – Converting from int to string for AVR ATmega32

atmegaavravr-gccc

I am trying to read data from the ADC and display it on a HD44870 compatible LCD with an ATmega32. As the data from the ADC is a 10-bit unsigned integer, the LCD expects a string, some conversion is necessary. Below is the function i wrote to accomplish this conversion.

char *int_to_str(uint16_t num, uint8_t len){
    uint8_t i;
    char *str;
    str[len]='\0';
    for(i=(len-1); i>=0; i--){
        str[i] = '0' + num % 10;
        num/=10;
    }
    return str;
}

However, the above function does not work. I just get a blank display where the numbers should be displayed. I am currently using itoa() and it works. However, i would prefer to write my own since size of the resulting executable is critical. Thank you.

Best Answer

There is no reason why sprintf wouldn't work. This basically prints a string to a buffer instead of standard output.

As an example

char string[256];
int value = 5;
memset(string,0,sizeof(string[0])*256); // Clear all to 0 so string properly represented
sprintf(string,"Value: %d",value);

string will now contain the string "Value: 5"