I am trying to do some simple variable manipulation in a embedded C/C++ environment. For some reason I consistently am getting zeros as a result.
Here is the code
void Heater::setPower( int newpower )
{
printf("1 new power %d\n",newpower);
if(newpower != power)
power = newpower;
else
return;
printf("2 new power %d\n",power);
// Set Duty
long unsigned int newduty = 0;
// Protect from divide by zero
if(power <= 0)
{
printf("2.5 zeroed\n");
newduty = 0;
power = 0;
}
else
newduty = period*(power/100);
printf("3 setduty %lu period %lu\n", newduty, period);
setDuty(newduty);
}
Here is the output I receive
1 new power 76
2 new power 76
3 setduty 0 period 10000000
So I know that the received number is 76. I know is makes it past the first hurdle, and the second. But somehow in the simple math equation it becomes zero. “period” is a long unsigned int as well and is declared in the class def, but you can see the output is appropriate.
Why is this dropping to zero consistently? What is missing? Do I need to include something special for the larger numbers or can I not use simple operators * and / on a long unsigned int or something?
I am dealing with high numbers (x<=10,000,000) because I am using kernel level pwm.
The problem you’re having is that
poweris an integer, so when you/100you’re actually ending up with a result of0due to the rules of integer division. This means that when you multiply it byperiod, the whole result is0.Depending on your precision requirements it may be sufficient to make to make
powera double, however be aware that(power/100)*periodwill generally produce a fractional result and so storing the result in a double may also be required.If you have to stick with integers just do
((power*period)/100)this will give you a reasonably accurate result sincepower*periodbecomes a large number before the division makes anything a0. With integer division, where you put the brackets can be the difference between getting a0or7600000(in your case).