I'm having some trouble on the code below, while trying to convert a PWM duty cycle to a variable that represents it as percentage and displaying it on the serial monitor. The result displayed on the monitor is always 0, except for when the duty cycle is at 255 (duty = 255 -> (255/255)*100 = 100, so it gets to be an integer and can be displayed).
I'm pretty sure that the problem is something within the function, as it calculates as float type (duty/255) and then stores the result in an integer variable, but I'm not able to deal with it and find any solution. I tried some type conversion functions but could not get around this (maybe I did it the wrong way..). If you guys could show me a solution, I'd very much appreciate it.
//This goes on loop()
analogWrite(ledPin, duty_cycle);
int level = Level_PWM(duty_cycle);
Serial.print("LED level: ");
Serial.print(level);
Serial.println(" %");
//This is the function for conversion
int Level_PWM(int duty){
int level_pwm;
level_pwm = (duty/255)*100);
return level_pwm;
}
hadriel26:
Ok, rewriting as (duty*100)/255 worked, but using conversion to float not. Could you tell me how you'd do it? Thanks for your help!
I would just use the integer method as float math is more taxing and pointless in this instance: you don't have an float input or output, so no need to touch floats in the intermediate math.
You got a point. I managed to work on the float conversion just for learning purposes, but rewriting the math that other way is much better. Thanks for your time!
Then the duty/255 will be evaluated as an integer division, with result 0, and that zero will be assigned to the float.
If you want this calculation to work, you need to "force" the division on the right-hand-side to be performed as a floating point division. These will all work:
int duty=240 ;
float ratio = ((float)duty)/255 ; // works
float ratio2= duty/255.0 ; // works
float ratio3=(float)(duty/255) ; // won't work. The integer division will be zero before conversion to float.
float ratio4= (float)duty/255 ;
/* might work, if the (float)duty is calculated. I can't remember, so I would avoid writing this */
float ratio5 = duty * 100 / 255 ; // calculates a percentage, it is still a truncated integer division