Page 1 of 1

Button loop not working

Posted: 28 Sep 2010 07:46
by roro36
My code is trying to just swap the state of the output of portC. Originally, RC0 is on and RC1 and RC2 are off. When the button is pressed it should alter the state of the LEDs connected to PORTC. When I switch on, RC0 lights up and this is correct. When I press either button on B4 or B5 the lights do the correct thing with C0 going off and C1 and 2 conming on. After that though, the next button press causes all the lights to turn on and then remain that way forever, no further button presses work. Here is my code:

Code: Select all

while (1) {
    if (Button(&PORTB, 4, 1, 1))  {              // detect logical one on RB1 pin
      oldstate4 = 1;                }
    if (oldstate4 && Button(&PORTB, 4, 1, 0)) {  // detect one-to-zero transition on RB1 pin
      PORTC = ~PORTC;
      oldstate4 = 0; }
    if (Button(&PORTB, 5, 1, 1))    {            // detect logical one on RB1 pin
      oldstate5 = 1;                  }
    if (oldstate5 && Button(&PORTB, 5, 1, 0)) {  // detect one-to-zero transition on RB1 pin
      PORTC = ~PORTC;
      oldstate5 = 0;    }
  }          // endless loop
Edited by admin: Code Tag

Re: Button loop not working

Posted: 30 Sep 2010 14:22
by tihomir.losic
Hello,

unfortunately, I didn't reproduce your report.
Please, try to compile and run following code, I hope that it'll solve your error:

Code: Select all

bit oldstate4, oldstate5;                        // Old state flag

void main() {

  ANSEL  = 0;                                    // Configure AN pins as digital I/O
  ANSELH = 0;
  C1ON_bit = 0;                                  // Disable comparators
  C2ON_bit = 0;

  TRISC = 0x00;                                  // Configure PORTC as output
  PORTC = 0b00000001;                            // Initial PORTC value
//  oldstate = 0;

while (1) {
    if (Button(&PORTB, 4, 1, 1)){                // detect logical one on RB1 pin
      oldstate4 = 1;}
    if (oldstate4 && Button(&PORTB, 4, 1, 0)){   // detect one-to-zero transition on RB1 pin
      PORTC = ~PORTC;
      oldstate4 = 0;}
    if (Button(&PORTB, 5, 1, 1)){                // detect logical one on RB1 pin
      oldstate5 = 1;}
    if (oldstate5 && Button(&PORTB, 5, 1, 0)){   // detect one-to-zero transition on RB1 pin
      PORTC = ~PORTC;
      oldstate5 = 0;}
  }         
}
Best regards,

Losic Tihomir