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时减少它。然而,我的问题是,当我开始增加并想要减少值时,它将在减少之前再次增加(也会发生另一种情况,如果我在减少之后尝试增加,它将在增加之前再次减少)。我想知道为什么会发生这种情况,以及我可以做些什么来使程序不会立即减少/增加这种情况。谢谢
发布于 2014-08-14 01:55:57
您在更新之前打印计数器值,因此您在按下按钮之前看到了该值。尝试更新计数器,然后打印结果:
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);
}https://stackoverflow.com/questions/25292322
复制相似问题