0

I want to enable user to change the duration of PWM from 0 to 255, the number should be in minute and increase/decrease with two push buttons.

(X) x 255 / 60000 = minute

In above example each time plus button pressed value (X) will multiple by the numbers of button pressed.

if (plusButton == HIGH) {
    PWMduration += (X);
}

The nearest number i found is 235.29 which equals to almost 1 minute:

235.29 x 255 / 60000 = 0.9999

How can i round that number to 1? or is there any other alternative solution to calculate this?

  • Use 235.294117647? – Majenko Jun 25 at 11:50
  • @Majenko equals 0.99999999999975 – Hamed Jun 25 at 11:54
  • In float terms that's 1. I don't think you can actually represent 1 in a float. – Majenko Jun 25 at 11:55
  • so what's the solution? can i convert it to int? – Hamed Jun 25 at 11:57
  • 3
    What you want to do is calculate the delay based on the number of minutes. Not change the delay depending on the number of button presses. Keep the minutes as an integer. Then use that integer to calculate how long each delay interval should be. – Majenko Jun 25 at 12:12
1

You can cast it to an integer after adding an offset.

Casting to an int will lower the value to the lowest integer value (e.g. 0.9975 will become 0). However, if you want an accuracy of 0.5 (e.g. all values from 0.5 <= x < 1.5 should be 1.0), than add 0.5, thus:

int roundedValue = (int)(0.9975 + 0.5);

If you use constants and want to calculate with it, either add .0 to it, or use a f(loat) or d(ouble) postfix, e.g.:

float f = 12.0 / 3.0;

or

float f = 12f / 3f;

Than calculate the rounded value:

int roundedValue = (int)(f + 0.5);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.