Private Variables and LEDs

I played around with my Arduino starter kit and read a few pages in Making Embedded Systems (more on it here). Now I am ready to blink the built-in LED of my board.


My first approach looked like this:

#define LED LED_BUILTIN

void setup() 
{
  SetupLED();
}

void loop() 
{
  EnableLED();
  delay(1000);
  
  DisableLED();
  delay(1000);
}

void SetupLED()
{
  pinMode (LED, OUTPUT);
  DisableLED();
}

void EnableLED()
{
  digitalWrite(LED, HIGH);
}

void DisableLED()
{
  digitalWrite(LED, LOW);
}

 

As next step I tried to remove the explicit LOW and HIGH to make it more sophisticated. I want to toggle the LED independent of it’s current state.

 

As far as I know, I can’t read the state of the LED if I’m using the pin as output. So I need a local variable to hold the current LED state and keep it in sync.

 

At first, I was confused because there are no access modifiers in processing. All variables put at the top of the file are global. It’s a really bad practice to make variables global that handle internal state. Other people could set the variable and mess up your state. Or worse, they read your variable and depend there logic on the internal working of your system. This can cause strange bugs where changeing the content of a private function can compromise an unrelated system.

 

After searching the web, I found that a variable in function scope can be made persistent by adding the static keyword. It seems a bit strange to me.

Is this the way to go in processing?

 

#define LED LED_BUILTIN

void setup() 
{
  SetupLED();
}

void loop() 
{
  ToggleLED();
  delay(1000);
}

void SetupLED()
{
  pinMode (LED, OUTPUT);
  DisableLED();
}

void ToggleLED()
{
  // Kind of persistant variable but in function scope.
  // Is only LOW the first time the function is called.
   static int persistentValue = LOW;

  if (persistentValue == LOW)
      EnableLED();
  else
      DisableLED();

  persistentValue = !persistentValue;
}

void EnableLED()
{
  digitalWrite(LED, HIGH);
}

void DisableLED()
{
  digitalWrite(LED, LOW);
}

 

Leave a Comment

two × five =