Flip Detect

To make things easy, let's assume the hourglass timer will be used with the Circuit Playground facing up. The NeoPixels are on that side, so this makes sense. It also let's us use the Z axis of the accelerometer to detect when the Circuit Playground is flipped over. If you want more info on the accelerometer, see the this guide.

The figure below shows a time history of the value returned from CircuitPlayground.motionZ() with the Circuit Playground facing up and down.

The value of 9.8 m/s2 relates to earth gravity. With the Circuit Playground facing up, it is a positive value. With the Circuit Playground facing down, it is a negative value. So we can detect a flip by simply checking the sign of the value.

We start with the Circuit Playground face up and a positive value. The first step is to wait for the value to become negative. Then, once it is negative, we wait for it to become positive again. That's a flip!

Here's a simple sketch that demonstrates this logic being used to detect a flip and then play a tone.

Download: file
///////////////////////////////////////////////////////////////////////////////
// Circuit Playground Flip Detect
//
// Author: Carter Nelson
// MIT License (https://opensource.org/licenses/MIT)

#include <Adafruit_CircuitPlayground.h>

///////////////////////////////////////////////////////////////////////////////
void setup() {
  // Initialize the Circuit Playground
  CircuitPlayground.begin();
}

///////////////////////////////////////////////////////////////////////////////
void loop() {
  // Wait for Circuit Playground to be flipped over (face down)
  while (CircuitPlayground.motionZ() > 0) {};

  // A little debounce
  delay(500);

  // Wait for Circuit Playground to be flipped back over (face up)
  while (CircuitPlayground.motionZ() < 0) {};

  // Make a beep noise.
  CircuitPlayground.playTone(800,1000);
}

The little lines of code that look like:

Download: file
while (CircuitPlayground.motionZ() > 0) {};

are called "parking loops". If we wanted them to actually do something, we would place that code in the {} brackets. In this case all we want to do is wait until the condition being tested becomes true. So the program execution just "parks" here until that happens.

The line of code with the small delay:

Download: file
delay(500);

is needed to prevent false flip detection. This can occur as the processor runs fast enough that it might see a brief positive value immediately after the first negative value, due to noise or small amounts of real motion. By waiting a small amount of time before checking the accelerometer value again, we prevent this.

Next Step

OK, let's use this flip logic to alter our previous code so it behaves more like an hourglass. Instead of resetting the hourglass with the push buttons, we'll use this flip detect.

This guide was first published on Dec 29, 2016. It was last updated on Dec 29, 2016. This page (Flip Detect) was last updated on Apr 04, 2019.