Reputation: 439
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.
Upvotes: 1
Views: 1162
Reputation: 32398
The problem you're having is that power
is an integer, so when you /100
you're actually ending up with a result of 0
due to the rules of integer division. This means that when you multiply it by period
, the whole result is 0
.
Depending on your precision requirements it may be sufficient to make to make power
a double, however be aware that (power/100)*period
will 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 since power*period
becomes a large number before the division makes anything a 0
. With integer division, where you put the brackets can be the difference between getting a 0
or 7600000
(in your case).
Upvotes: 6
Reputation: 17655
make newduty and power as double
. because of integer type it giving 0
Upvotes: 0