Long variable not printing correctly

Hi people,

I'm having a strange problem while trying to print to an LCD.

I have a variable that goes from 0 to 10 and I wish to print that 10000 times larger. So the actual value should go from 0 to 100000. Everything works fine up to 32767 at which point the variable shows up as negative and counting down to zero and then counts up to 32767 and so on...

This is the behaviour I would expect from an int variable, however both the variable and calculation are declared as a float:

long rpm = 0; // The actual output
byte myvar = 0;  // The 0-10 Variable

rpm = (long(myvar*10000);

In fact, 9*10000 is reported as 24464!

I don't understand: is this a limitation of the lcd.print library? Or what exactly am I missing!?

Edit:
I'm using Arduino 1.6.0

You cannot make the variable "long" by type casting after the (wrong) result of the int calculation is fixed.

You have to do a calculation with a "long" constant to create a long result.

rpm = myvar*10000L;

Thanks.

This appears to work if I print the variable directly, however using a sprint function I still get the same result.

For example:

sprintf(lcd_1, "RPM   %6d", rpm); 
lcd.print(lcd_1);

//Returns 24464

lcd.print(rpm);

//Returns 90000

Am I declaring a variable incorrectly or just a limitation?

Thanks

casemod:
This appears to work if I print the variable directly, however using a sprint function I still get the same result.

The placeholder "%d" is for integer decimal formatting only, not for 'long'.

For "long decimal" formatting try:

sprintf(lcd_1, "RPM   %6ld", rpm);

To get the correct result displayed, you will have to do two things correctly:

  • correct 'long' calculation
  • correct 'long' formatting