为什么计数器在减少之前增加?

时间:2014-08-13 17:17:19

标签: msp430 code-composer

P1DIR |= 0x01;                          // Set P1.0 (GREEN LED) to output direction
P4DIR |= 0x40;                          // Set P4.6 (RED LED) to output direction
P1OUT |= 0x01;                          // Set GREEN LED on
P4OUT |= 0x40;                          // Set RED LED on

P1REN |= 0x02;                          // enable P1.1 (Pushbutton S2)
P1DIR &= ~0x02;                         // enable read port P1.1 (Pushbutton S2)

P4REN |= 0x20;                          // enable P4.5 (Pushbutton S1)
P4DIR &= ~0x20;                         // enable read port P4.5 (PushButton S1)

volatile unsigned int i;
unsigned int counter = 0;

while(1)
{

    if((P4IN & BIT5)== 0)   // is the pushbutton S2 pressed? (P1.1)
    {
        printf("c= %d\r\n",counter);
        P4OUT ^= 0x40;      // toggle RED LED
        i = 10000;
        do i--;
        while(i != 0);
        counter++;
    }

    if((P1IN & 0x02)==0)
    {
        printf("c= %d\r\n",counter);
        counter--;
    }

    if((P1IN & 0x02)==0)
    {
        P1OUT |= 0x01;      // turn on GREEN LED when pushbutton is pressed
        P4OUT ^= 0x40;      // toggle RED LED
        i = 10000;
        do i--;
        while(i != 0);
    }

    else
    {
        P1OUT &= ~0x01;     // Turns off GREEN LED

        P4OUT ^= 0x40;      // toggle RED LED
        i = 10000;
        do i--;
        while(i != 0);
    }
}
return 0;

}

你好,我现在的代码允许我按下按钮S1并向控制台打印一个语句,每次按下它时都会增加它。每次按下按钮S2时,它也允许我减少它。然而,我的问题是,当我开始增加并希望减少该值时,它会在减少之前再次增加(另一种方式是,如果我在减少之后尝试增加,它将在增加之前再次减少)。我想知道为什么会这样,我该怎么做才能使程序不会发生这种情况并立即减少/增加。谢谢

1 个答案:

答案 0 :(得分:0)

您在更新之前打印计数器值,因此您在按下按钮之前会看到该值。尝试更新计数器,然后打印结果:

if((P4IN & BIT5)== 0)   // is the pushbutton S2 pressed? (P1.1)
{
    counter++;
    printf("c= %d\r\n",counter);
    P4OUT ^= 0x40;      // toggle RED LED
    i = 10000;
    do i--;
    while(i != 0);
}

if((P1IN & 0x02)==0)
{
    counter--;
    printf("c= %d\r\n",counter);
}