toggle a switch with

Hello Guys, i am new here.

void setup() {
pinMode(2,INPUT_PULLUP);
}

int lastState=0,p=0,status,q;
void loop() {
status=digitalRead(2);
if(status==p){
display(lastState);
if (status!=p){
lastState=lastState++;
status=p;
} } }

I want to check the condition while switch thatone is connected in IO2 pin, pressed the display function work but if condition is going wrong when i release swich it increse the lastState variable continuously, but i want to increase it at once when switch is toggle.
please help me frnds....

The "if (status!=p)" part will never be true because you put it INSIDE the "if (status==p)".

The code:

lastState=lastState++;

is compiler dependent and definitely NOT recommended. I do not know what the gcc compiler used by the Arduino IDE does with this construct.

Instead, do this:

lastState++;

You want to do something when the switch state BECOMES something rather than when the switch state IS something. There is a state change detection example that demonstrates how to do this.

johnwasser:
The "if (status!=p)" part will never be true because you put it INSIDE the "if (status==p)".

If you edit your code in the ide so that each { and } is on a line of its own, then hit ctrl-T, it will format with nice indentation as below, and it's easy to see what johnwasser is saying.

void setup()
{
  pinMode(2, INPUT_PULLUP);
}

int lastState = 0, p = 0, status, q;
void loop()
{
  status = digitalRead(2);
  if (status == p)
  {
    display(lastState);
    if (status != p)
    {
      lastState = lastState++;
      status = p;
    }
  }
}

vaj4088:

lastState=lastState++;

is compiler dependent and definitely NOT recommended. I do not know what the gcc compiler used by the Arduino IDE does with this construct.

Good catch! I think it was at V1.6.0 that the compiler switched from treating this like:

lastState=lastState+1;

to treating it like

lastState=lastState;