## Scaled integers

4 posts / 0 new
Author
Message

Hi,

I would like to present some float variable on my LCD.
At first it should look like 00.00 then when I add to the variable 64 it should change to the 00.25 value.

I have decided that the best way will be using shcaled integers. I have made a function for it but I have afeeling it is not so perfect. How you usually do this?
Maybe there is a good library for scaling integers?

Below is my code:

What do you think abou it?

```//Global variables:

char buffer;
uint16_t  num;

//chank of code from the main loop

num=((dlugosc*100)/256);
itoa( num, buffer, 10); //funkcja zamieniajaca wartosc z intiger na char
LCD_GoTo(8,0);
scaled_integers(2,buffer);

//desired function for writing on LCD

void scaled_integers(uint8_t scaler,char table[])
{
uint8_t r=0;
uint8_t counter=0;
uint8_t i;

uint16_t table_A;
uint16_t table_B;

for (i=0;i<=8;i++)
{
table_A[i]=0;
table_B[i]=0;
}

while(table[r])
r++;

for (i=0;i<(r-scaler);i++)
{
table_A[i]=table[i];
}
table_A[i++]='\0';

for ( i=(r-scaler);i<=r;i++)
{
table_B[counter]=table[i];
counter++;
}

LCD_WriteText(table_A);
LCD_WriteText(".");
LCD_WriteText(table_B);

}```

I am using:
avr-gcc
atmega32
1000000 Hz for tests

1. Think about your desired range of values. If you intend to only cover +0.00 to 99.99 then you can easily handle it as a uint16_t. You must consider overflow in any intermediate calculations.

2. Choose your scaling value. 100 would be ideal.
then you output using

`sprintf(buf, "%02d.%02d", var/100, var%100);`

3. You can put this as a function that returns a static string buffer, or writes to your LCD.

4. Your current code looks as if it has wrong types.

David.

Can the libc sprintf handle floats? You could just use:

```float var;
var = some_value;
sprintf(buf, "Value: %f", var);
```

Excuse my use of sprintf, it may be rong I never use it anymore. Using floats is pretty wasteful and not necessary if the range of values you want to display can be represented by integers. I think what the last dude said was a good idea...