Go Down

Topic: trouble with simple IF...ELSE (Read 458 times) previous topic - next topic

fiddler

I can't for the life of me work out why the code below doesn't work.
Never gets to the ELSE statement, something keeps changing the "pinstate" back to zero

Cheers
K

Code: [Select]

void BlinkLED13()
{
  // blinks LED 13
  int pinstate;      // state of the output pin

  if (pinstate == 0)
  {
    digitalWrite(ledPin, pinstate);
    pinstate = 1; 
    delay(100);
  }
  else
  {
    digitalWrite(ledPin, pinstate);
    pinstate = 0;
    delay(100);
  }

}


guix

Make it static, or global. Actually it is erased when the function is exited, and recreated each time the function is called.
Code: [Select]

void BlinkLED13()
{
 // blinks LED 13
 static int pinstate;

fiddler


lloyddean

Moving 'pinstate' outside of the 'BlinkLED13' function would do pretty much the same thing.

Code: [Select]

int pinstate;

void BlinkLED13()
{
    // blinks LED 13
    if ( pinstate == 0 )
    {
        digitalWrite(ledPin, pinstate);
        pinstate = 1; 
        delay(100);
    }
    else
    {
        digitalWrite(ledPin, pinstate);
        pinstate = 0;
        delay(100);
    }
}


When pins are set as OUTPUT 'digitalWrite' tracks the last value written to it which can then be read with 'digitalRead'.  Combining this with the '!' not operator will allow your code to be simplified as -

Code: [Select]

void BlinkLED13()
{
    // blinks LED 13
    digitalWrite(ledPin, ! digitalWrite(ledPin));
    delay(100);
}


I do find your choice of the function name, 'BlinkLED13', to be somewhat misleading as it simply changes the LED to it's opposite state.

lloyddean

#4
Dec 22, 2012, 09:55 pm Last Edit: Dec 23, 2012, 02:15 am by lloyddean Reason: 1
That concept of a 'blink' does not match mine.

This one I consider more a 'toggle' as it requires multiple explicit calls to the function in order to 'blink'.

Go Up