Scaled integers

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

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?
Could you present your approach?
Maybe there is a good library for scaling integers?

Below is my code:

What do you think abou it?

//Global variables:

char buffer[8];
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[8];
			uint16_t table_B[8];
			
			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

Thanks in advance for help

Adam

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

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.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

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...

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks for trying to help me :)

Actually I wanted to create such a rutine as here:

https://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=38996&highlight=fixed+point

Once again thank you and whish you all Merry Chrstmas

Adam