Pages: [1]   Go Down
Author Topic: trouble with simple IF...ELSE  (Read 394 times)
0 Members and 1 Guest are viewing this topic.
NZ
Offline Offline
Jr. Member
**
Karma: 1
Posts: 91
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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);
  }

}
Logged

France
Offline Offline
God Member
*****
Karma: 34
Posts: 987
Scientia potentia est.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Make it static, or global. Actually it is erased when the function is exited, and recreated each time the function is called.
Code:
void BlinkLED13()
{
  // blinks LED 13
  static int pinstate;
Logged

NZ
Offline Offline
Jr. Member
**
Karma: 1
Posts: 91
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Sweet.
Thanks for that
Logged

Des Moines, WA - USA
Offline Offline
God Member
*****
Karma: 25
Posts: 779
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:
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:
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.
Logged

Des Moines, WA - USA
Offline Offline
God Member
*****
Karma: 25
Posts: 779
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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'.
« Last Edit: December 22, 2012, 08:15:52 pm by lloyddean » Logged

Pages: [1]   Go Up
Jump to: