Button loop not working

General discussion on mikroC.
Post Reply
Author
Message
roro36
Posts: 9
Joined: 21 Sep 2010 08:10

Button loop not working

#1 Post by roro36 » 28 Sep 2010 07:46

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

User avatar
tihomir.losic
mikroElektronika team
Posts: 2138
Joined: 02 Dec 2009 14:16
Location: Serbia
Contact:

Re: Button loop not working

#2 Post by tihomir.losic » 30 Sep 2010 14:22

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
mikroElektronika [Support team]

Post Reply

Return to “mikroC General”