Reputation: 35
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;
}
Hello, my current code here allows me to press down pushbutton S1 and print a statement to the console, while increasing it every time I press it down. It also allows me to decrease it as well every time I press down push button S2. However, my problem is that when I start increasing and want to decrease the value, it will increase once more before decreasing (also happens the other way, if I try to increase after decreasing, it will decrease once more before increasing). I would like to know why that is and what can I do to make it so the program doesn't make that happen and decreases/increases immediately. Thank you
Upvotes: 0
Views: 159
Reputation: 1
You are printing the counter value before is updated, so you are seeing the value before pushing the button. Try to update counter and then print the result:
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);
}
Upvotes: 0