Question

I have a microcontroller and I am sampling the values of an LM335 temperature sensor. The LCD library that I have allows me to display the hexadecimal value sampled by the 10-bit ADC. 10bit ADC gives me values from 0x0000 to 0x03FF.

What I am having trouble is trying to convert the hexadecimal value to a format that can be understood by regular humans.

Any leads would be greatly appreciated, since I am completely lost on the issue.

Was it helpful?

Solution

You could create a "string" into which you construct the decimal number like this (constants depend on what size the value actually, I presume 0-255, whether You want it to be null-terminated, etc.):

char result[4];
char i = 3;
do {

    result[i] = '0' + value % 10;
    value /= 10;
    i--;
}
while (value > 0);

OTHER TIPS

Basically, your problem is how to split a number into decimal digits so you can use your LCD library and send one digit to each cell.

If your LCD is based on 7-segment cells, then you need to output a value from 0 to 9 for each digit, not an ASCII code. The solution by @Roman Hocke is fine for this, provided that you don't add '0' to value % 10

Another way to split a number into digits is to convert it into BCD. For that, there is an algorithm named "double dabble" which allows you to convert your number into BCD without using divisions nor module operations, which can be nice if your microcontroller has no provision for division operation, or this is slower than you need.

"Double dable" algorithm sounds perfect for microcontrollers without provision for the division operation. However, a quick oversight of such algorithm in the Wikipedia shows that it uses dynamic memory, which seems to be worst than a routine for division. Of course, there must be an implementation out there that are not using calls to malloc() and friends.

Just to point out that Roman Hocke's snippet code has a little mistake. This version works ok for decimals in the range 0-255. It can be easily expand it to any range:

void dec2str(uint8_t val, char * res)
{
    uint8_t i = 2;
    do {
        res[i] = '0' + val % 10;
        val /= 10;
        i--;
    } while (val > 0);
    res[3] = 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top