首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么计数器是先增后减?

为什么计数器是先增后减?
EN

Stack Overflow用户
提问于 2014-08-14 01:17:19
回答 1查看 146关注 0票数 0
代码语言:javascript
复制
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时减少它。然而,我的问题是,当我开始增加并想要减少值时,它将在减少之前再次增加(也会发生另一种情况,如果我在减少之后尝试增加,它将在增加之前再次减少)。我想知道为什么会发生这种情况,以及我可以做些什么来使程序不会立即减少/增加这种情况。谢谢

EN

回答 1

Stack Overflow用户

发布于 2014-08-14 01:55:57

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

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25292322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档