views:

58

answers:

2

I have the following code in my microcontroller project:

if (newThrottle < currentThrottle)
{
    for (int set = currentThrottle; set >= newThrottle; set--)
    {
        // Perform actions to set the throttle
    }
}
else
{
    for (int set = currentThrottle; set <= newThrottle; set++)
    {
        // Perform actions to set the throttle
    }
}

If it's not blatantly obvious, this code snippet is used to ramp the motor throttle up or down from its current value to a new value.

Is there any more elegant way to write this?

+2  A: 
int add = (newThrottle > currentThrottle) ? 1 : -1;

while (newThrottle != currentThrottle)
{
    // do your stuff
    currentThrottle += add;
}
NullUserException
This works well. Thanks!
chris12892
Wow you guys are fast. I only just noticed that.
chris12892
Hmm.. the only issue that I am having is that it doesn't seem to ever get down to zero. For example, if I ask it to ramp up to 40 then later back down again to 0, it doesn't seem to ever hit 0. any ideas?
chris12892
@chris: See this: http://ideone.com/lU3mP. You'd have to set the `newThrottle = -1` to have the body of the loop executed.
NullUserException
I see. thanks! I eventually realized what was wrong.
chris12892
+1  A: 

I'd consider doing something like this:

int step = newThrottle < currentThrottle ? -1 : 1;

for (int set = currentThrottle; set != newThrottle; set += step)
{
    // perform actions to set the throttle
}

If you don't mind some code that's harder to decipher, you could consider something like this:

int step = (newThrottle < oldThrottle) - (newThrottle > oldThrottle);

I think I'd use the first version though -- at least IMO, it's easier to read and understand. The second also depends on true converting to 1 and false converting to 0.

Jerry Coffin