The following code does not yield the answer I expect when I multiply 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;
ov开发者_运维知识库erflows_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?
Are you compiling for an embedded platform?
Maybe your default int is just 2 Byte wide, in which case 12 * 20000 would overflow.
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.
精彩评论