tags:

views:

118

answers:

2

The following code does not yield the answer I expect when I multiple a float * 12.

void setup_timer_parameters(float micro_seconds)
{
   //constants
   calibration = 0;

   //calculables
   periods_needed = micro_seconds * 12 + calibration;

   target_overflows = periods_needed / 65536;
   overflows_counter = target_overflows;

   temp = periods_needed - (target_overflows * 65536);
   leftover = (long)temp;
   //int overflows_needed = micro_seconds % timer_period;
   printf(lcd_putc, "\fPN%05f TMP%05f\nTO%05f LO%05f", periods_needed, temp, target_overflows, leftover);
}

void main(){
   setup_timer_parameters(20000F);
}

For some reason my display shows me that periods_needed is -518! Why isn't it 20000*12 = 240000?

+1  A: 

This is not strictly ANSI C, but try this:

void setup_timer_parameters(float micro_seconds)
{
   //constants
   float calibration = 0;

   //calculables
   float periods_needed = micro_seconds * 12.0 + calibration;

   float target_overflows = periods_needed / 65536;
   float overflows_counter = target_overflows;

   float temp = periods_needed - (target_overflows * 65536);
   float leftover = (long)temp;
   //int overflows_needed = micro_seconds % timer_period;


   fprintf(lcd_putc, "\fPN%05f TMP%05f\nTO%05f LO%05f", periods_needed, temp, target_overflows, leftover);
}

int main(int argc, char** argv)
{
   setup_timer_parameters(20000F);
   return 0;
}

It doesn't look like you declared any variable types, which will really upset things unless they're declared elsewhere (?). You might want to change the types depending on whether you really need floats, i.e, a long int might do for some of these, or a double if you need more precision.

If you need arbitrary precision look up MPFR/MPIR.

Ninefingers
probably `fprintf`?
vladr
Definitely fprintf, looks like lcd_putc might be a handle to an lcd display?
Ninefingers
They are all declared as floats elsewhere. Sorry for not including all my code. As a matter of fact nothing is being casted at all. Using 12.0 rather than 12 didn't change the answer.
Adam
+2  A: 

Are you compiling for an embedded platform?

Maybe your default int is just 2 Byte wide, in which case 12 * 20000 would overflow.

Andreas Klebinger