PUSH ON/OFF Switch PIC 16F877A, MikroC

/*Project : Push Button ON/OFF
 MCU      : 16F877A/ 8MHz/
 Author    : Asanka Lakmal Morawaka
 Compiler: MikroC
 http://beslakmal.blogspot.com/ */


bit oldstate;    // bit variable to recognize state of switch
bit switchState; // bit variable to recognize present state of switch
void main()
{
  TRISC.F0 = 1; //Configure 1st bit of PORTD as input
  TRISB.F0 = 0; //Configure 1st bit of PORTB as output
  TRISB.F1 = 0; //Configure 1st bit of PORTB as output

  do
  {
    if(Button(&PORTC,0,1,1))   //If switch is pressed
        {
      oldstate =1; }     // update oldstate flag

    if(Button(&PORTC,0,1,0)&& oldstate && !(switchState) )//If the switch is relased
         {
         PORTB.F1 = 1;    //  LED ON
         switchState=1;   // update switchState flag
         oldstate =0;       // update oldstate flag
       }
     if(Button(&PORTC,0,1,0) && oldstate && switchState)  { //If the switch is relased
       PORTB.F1 =0;     // LED OFF
       oldstate=0;          // update oldstate flag
       switchState=0;}  // update switchState flag
    }
 while(1);
}


Here is more simple code which I found later,

 /* Project name: PushButton

 * Description:
     This program control a light using a push button.
        http://beslakmal7.blogspot.com/p/line-follower.html
 * Test configuration:
     MCU:             PIC 18F4520
     Oscillator:      8.0000 MHz Crystal
     Ext. Modules:    None.
     SW:              mikroC PRO for PIC
                      http://www.mikroe.com/mikroc/pic/   */


bit oldstate;                                    // Old state flag

void main() {

  TRISB0_bit = 1;                                // set RB0 pin as input
  TRISC = 0x00;                                  // Configure PORTC as output
  PORTC = 0x01;                                  // Initial PORTC value
  oldstate = 0;

  do {
    if (Button(&PORTB, 0, 1, 1)) {               // Detect logical one
      oldstate = 1;                                             // Update flag
    }
    if (oldstate && Button(&PORTB, 0, 1, 0)) {   // Detect one-to-zero transition
      PORTC.F0 = ~PORTC.F0;                            // Invert PORTC
      oldstate = 0;                              // Update flag
    }
  } while(1);                                    // Endless loop
}




No comments:

Post a Comment