Search code examples
arduinodelayaccelerometercircuitadafruit

Adafruit: Circuit Playground - Using delay to get accelerometer data after an Tap event


Hi guys I am trying to read out the accelerometer data after an Tap event. The idea is after detect a tap event, it plays a tone using the playTone function, waits 2 seconds and then register XYZ data from the accelerometer. The problem I am facing is using the delay. This does not seem to work as XYZ are written directly after the Tap event. You can you the code below and check on the serial monitor:

Code:

#include <Adafruit_CircuitPlayground.h>
#include <Wire.h>
#include <SPI.h>

#define CLICKTHRESHHOLD 120

int registry=1; //set initial move

void setup(void) {
  while (!Serial);
  Serial.begin(9600);
  CircuitPlayground.begin();
}

void printAxis() {
  float x, y, z;
  x = CircuitPlayground.motionX();
  y = CircuitPlayground.motionY();
  z = CircuitPlayground.motionZ();
  Serial.print("X: ");
  Serial.print(x);
  Serial.print("  Y: ");
  Serial.print(y);
  Serial.print("  Z: ");
  Serial.println(z);

}

void tap() {
  CircuitPlayground.playTone(50, 100);
  Serial.print("Registry Number: " );
  Serial.println(registry);
  printAxis();
  registry++;

}

void loop() {

// Only take action when either button is pressed.
  if ( (CircuitPlayground.leftButton()  == true) ) {
    CircuitPlayground.setAccelRange(LIS3DH_RANGE_2_G);

      // Tapping function
      CircuitPlayground.setAccelTap(1, CLICKTHRESHHOLD);

  // have a procedure called when a tap is detected
    attachInterrupt(digitalPinToInterrupt(7), tap, RISING);
    }
}

I tried to add the delay function within the loop, within the printAxis. But it seems to freeze when using delay-

  Serial.print("Delaying...");
  delay(2000);
  Serial.print("Delay ready!");

Do you guys have any tips or recommendations? Best!


Solution

  • I figured it out. I am answering this in case someone faces a similar problem.

    Firstly I set the interrupt only in the setup.

    void setup(void) {
    while (!Serial);
    Serial.begin(9600);
    CircuitPlayground.begin();
    CircuitPlayground.setAccelRange(LIS3DH_RANGE_2_G);
    CircuitPlayground.setAccelTap(1, CLICKTHRESHHOLD);
    attachInterrupt(digitalPinToInterrupt(7), isTapped, FALLING);
    tapped = false;
    }
    

    Then I created a boolean 'Tapped' flag which was set in the interrupt handler. In the loop, the Tapped flag is watched. If set, then I perform the delays... The loop looks like this:

    bool tapped;
    void isTapped() {
    tapped = true;
    }
    ...
    if (tapped) {
    delay(3000);
    Serial.println("Now!" );
    tap();
    tapped = false;
    }