Search code examples
cpicgpioled

Using CCS Toggle LED With Button


I didn't understand what is wrong with my code. Here what I am trying to do is toggle a led when I press button. And I count my button hits with int count;. If the count number is even LED is high and else LED is low. But when I upload this program, LED stays on. And off only while I hold the button.

while(1){
int buttonState=input_state(pin_a0);

   if(buttonState != lastButtonState){
   count++;
   lastButtonState=buttonState;
     
      if(count%2==0){
      output_high(pin_b0);
      }
      else
      output_low(pin_b0);
}
delay_ms(50);
}

Solution

  • Is your button active-high or active-low ? Is your LED powered active-high or active-low? You need to give that information. I'll give an explanation assuming LED is powered when output is low. Then what follows is, assuming button is active-low, when your button is not pressed,

    buttonState = 1;
    

    So, since

    lastButtonState = 0;
    

    (at the start of the program, I'm assuming)

    You will enter the if clause:

    if(buttonState != lastButtonState){
    ...
    }
    

    This will increase your counter by one and make lastButtonState = buttonState;

    Since count%2 will be 1, your pin will be output_low(pin_b0);... So, at the start of your program, your LED will be ON.

    If you then press the button,

    buttonState=0;
    

    will happen and you will enter the if() clause, again. This will increase your counter by one. And then:

    count%2 = 0;
    

    Will happen. So, you will have

    output_high(pin_b0);
    

    As you can see, when you press the button, your LED will go off. And on when you release the button, your LED will go on Try this:

    while(1){
       int buttonState=input_state(pin_a0);
    
       if(buttonState != lastButtonState){
       lastButtonState=buttonState;
    
          if(buttonState == 1){
              output_high(pin_b0); // LED is off
          }
          else
              output_low(pin_b0); // LED is on
       }
    delay_ms(50);
    }
    

    You don't need the counter.

    EDIT:

    I see you have made this addition to your code:

    if(buttonState==1) 
       count++;
    

    This works. Yet is harder to understand. Try writing something easier to read.