开发者

Most elegant way to write a piece of code that handles ramping up and down?

开发者 https://www.devze.com 2023-01-11 16:50 出处:网络
I have the following code in my microcontroller project: if (newThrottle < currentThrottle) { for (int set = currentThrottle; set >= newThrottle; set--)

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 <= newT开发者_运维问答hrottle; 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?


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

while (newThrottle != currentThrottle)
{
    // do your stuff
    currentThrottle += add;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消