Category

Programming

Category

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.

How to blink (or flash) a LED without delay() and detect button pushes

One of the limitations of the delay() function is that nothing else can really be done. This presents a problem when you want to flash a LED while waiting for a pushbutton to be pressed.

Flashing the LED with millis() and using a flag variable to find if the LED should be flashing solves this problem.

Consider this another example to my virtual millis() cookbook.

This code (below) should work with both Arduino (AVR) and Energia (supported boards), but to be honest, I haven’t had a chance to test it on my MSP430 yet.

The Arduino Library provides functions like shiftOut() and digitalWrite().  These functions are simple and effective, but they are slow. Of course, they’re doing a lot more than just toggling bits. Faster isn’t always necessary and can sometimes lead to more difficult debugging.  And as Donald Knuth said,

…premature optimization is the root of all evil.

So what happens, when you do need to optimize? For example, if shiftOut() is too slow for your project, what do you do?  In Ralph’s post, Fastest AVR software SPI in the West, he breaks down different SPI code implementations into their assembly code.

To make the best optimization, you need to change compiler flags. So this is, in my opinion, an interesting case study in what kind of performance benefit you can get when you do some serious optimization.

Of course, you really shouldn’t, unless you need it…

Check out his post: Fastest AVR software SPI in the West

Knuth quote from his paper “StructuredProgrammingWithGoToStatements.”