In this project, we'll expand on the code in the previous project to create a flashing flash light with multiple functions. Our new flashlight will have several modes that it rotates through on each press of the button. This is common in lots of flashlights you can buy today, and it is generally software that makes it possible.

The hardware for this flashlight will be the same as the last flashlight project — two independent circuits, one for the LED and one for the button:

Refer back to if you have any questions about how to wire these circuits.

Write the code.

For this implementation of the flashlight, we're going to create three modes — each will do something different. Mode 0 will turn the flashlight off, Mode 1 will turn the flashlight on and Mode 2 will flash the light.

In order to do that, we'll have to track which mode we're in at any given time, and we'll have to write the code for each of the modes. We'll start by writing some initialization code and implementing Mode 0. The program will be similar to the previous project, except we'll add some code highlighted with arrows below:

Let's take a look at the code we added:

Give it a try. Currently, Mode 0 turns the light off, and Modes 1 and 2 turn the light on. So, as you click through the modes, what you'll see is the light turning on, and then two presses later turning off.

So far, we've added a bunch of code, but we haven't added a lot of functionality. But, we have laid the groundwork to add the two new modes in the next step.

Note that the flashlight will continue to work until you manually stop the program.

Improve the code.

Now, let's add some functionality to Modes 1 and 2. Mode 1 will work as before (just turn the light on). Mode 2 will make the light flash. To do this, we'll add a counter that keeps track of how many times we've gone through the while loop, so we'll know whether the light should be on or off each time through the loop.

Here's what our next version of the code looks like:

Let's look at what was added here:

Give this new "flashing" flashlight a try.

  1. We used a counter to set the period of time for each flash when in the flashing mode. Change the counter to slow down (or speed up) the flashing rate.

  2. Can you add a fourth mode that flashes at a faster rate?

  3. The flash mode flashes 50% on and 50% off. Can you change this to a quick blink, by making it flash 10% on and 90% off?

  4. The flashing can be more complicated than just a simple on/off cycle. Can you change the flash to 5 quick flashes followed by 2 slow flashes, and then repeat?