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?

Michel Keijzers
  • 13,014
  • 7
  • 41
  • 58
ElectronSurf
  • 814
  • 4
  • 17
  • 43

1 Answers1

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);
Michel Keijzers
  • 13,014
  • 7
  • 41
  • 58