CHANNAR
CHANNAR

Reputation: 1

if and else if conditons inside a while loop

I have the following code for running 3 steppers at a time with different numbers of steps n1, n2 and n3. It does not run the n3 motor if used as follows, but if we remove the if condition then it runs.

int n1 = 0;
int n2 = 0;
int n3 = 100
while (n1 > 0 || n2 > 0 || n3 > 0) {
    if (n3 > 0 && n1 == 0 && n2 == 0) {
        current_port_value = XGpio_DiscreteRead(&GpioOutput, LED_CHANNEL);
        new_port_value = (current_port_value & ~0X02);
        XGpio_DiscreteWrite( & GpioOutput, LED_CHANNEL, new_port_value);
        current_port_value = XGpio_DiscreteRead(&GpioOutput, LED_CHANNEL);
        new_port_value = (current_port_value | 0X04);
        XGpio_DiscreteWrite( & GpioOutput, LED_CHANNEL, new_port_value);
        current_port_value = XGpio_DiscreteRead(&GpioOutput, LED_CHANNEL);
        new_port_value = (current_port_value | 0X08);
        XGpio_DiscreteWrite( & GpioOutput, LED_CHANNEL, new_port_value);
        current_port_value = XGpio_DiscreteRead(&GpioOutput, LED_CHANNEL);
        new_port_value = (current_port_value | 0X40);
        XGpio_DiscreteWrite( & GpioOutput, LED_CHANNEL, new_port_value);
        current_port_value = XGpio_DiscreteRead(&GpioOutput, LED_CHANNEL);
        new_port_value = (current_port_value | 0X80);
        XGpio_DiscreteWrite( & GpioOutput, LED_CHANNEL, new_port_value);
        for (Delay = 0; Delay < LED_DELAY; Delay++);
        current_port_value = XGpio_DiscreteRead(&GpioOutput, LED_CHANNEL);
        new_port_value = (current_port_value & ~0X80);
        XGpio_DiscreteWrite( & GpioOutput, LED_CHANNEL, new_port_value);
        for (Delay = 0; Delay < LED_DELAY; Delay++);
    }
    n1--;
    n2--;
    n3--;
}

Upvotes: 0

Views: 63

Answers (1)

J0e3gan
J0e3gan

Reputation: 8938

The if block will run exactly once as-is. First iteration of the loop, n1, n2, and n3 will obviously have their initial values – 0, 0, and 100 respectively. Second iteration, n1, n2, and n3 will have the values -1, -1, and 99 respectively because you are decrementing each of them after the if block. Clearly it is not true that n3 > 0 && n1 == 0 && n2 == 0 on second iteration then.

My sense regarding your immediate issue then, confirmed by your comments, is that you do not want the numbers of steps (n1, n2, or n3) to be negative. Using n1 as an example, simply do not decrement numbers of steps when they are not greater than or equal to one – e.g. change n1--; to if (n1 > 0) n1--;.

Upvotes: 3

Related Questions