Tag

LaunchPad

Browsing

Flag variables are great, and totally not evil, when you just have two states: ON or OFF. What about when you have multiple states? Is there an option better than creating multiple flag variables?

The C-language has a declaration type just for this purpose. It is called an enumeration, or enum.

Setting up a state machine with enum is a surprisingly simple. Arduino and embedded programmers should use them!

All you need to do is create descriptive tag names, and let the compiler assign them an integer value. Unlike a #define which is just a macro replacement, the compiler treats an enum as your personal variable type.

This behavior comes in handy when you’re creating states for a state machine. I show how to create a simple state machine with enum, to blink an LED with millis(), in this post.

Getting programming questions answered on the internet can be problematic. Programmers love to have opinions, stick to those ideas, and express them to you even when their opinion has nothing to do with your question(s).

Not only am I going to explain how to use flag variables in your code, I am going to encourage their use—which most programmers avoid.

However, this advice comes with two caveats.

  1. This information only applies to limited resource environments like an Arduino, LaunchPad or PIC.
  2. Use flag variables very carefully when you do use them.

The following flag variable usage examples are Arduino-centric but apply to any microcontroller platform, including the Energia project for TI Launchpads.

Recently I realized most of my projects were all Arduino-based.  There are lots of other prototyping platforms available in the market, and the TI LaunchPad, based on the MSP430 is one of them.  In fact, I have had one of these boards sitting in my box of stuff ever since they came out.  At $5, they because an impulse purchase when I was buying some other stuff. So, I dusted off the original box and…