Search code examples
caccelerometer

Detect movement from accelerometer


I have a Micro:Bit. It has an accelerometer, so I'm able to measure acceleration on x,y,z axis.

The idea is to wear it on the arm and send over bluetooth when it detects some movement on the arm.

So, I would like to check the acceleration and generate an event if it passes some kind of threshold, but I don't know how to do this.

This would be something like this:

void onAwake (int x, int y, int z){
    snprintf(buffer, sizeof(buffer), "%i/%i/%i",x,y,z);
    uart->send(ManagedString(buffer));
}

int main() {
    while (1) {
      x = uBit.accelerometer.getX();
      y = uBit.accelerometer.getY();
      z = uBit.accelerometer.getZ();

      // Check if device is getting moved

      if (accel > 1) onAwake(x,y,z); // Some kind of threshold

      sleep(200);
    }
}

Solution

  • I've finally solved it with adding a threshold:

    MicroBit uBit;
    
    char buffer[20];
    int x, nx, y, ny, z, nz;
    int threshold = 100;
    
    void onAwake (int x, int y, int z){
        snprintf(buffer, sizeof(buffer), "%i/%i/%i", x, y, z);
        uart->send(ManagedString(buffer));
    }
    
    int main() {
    
        uBit.init();
    
        x = uBit.accelerometer.getX();
        y = uBit.accelerometer.getY();
        z = uBit.accelerometer.getZ();
    
        while (1) {
           nx = uBit.accelerometer.getX();
           ny = uBit.accelerometer.getY();
           nz = uBit.accelerometer.getZ();
    
           if ((x != nx && abs(x-nx)>threshold) || (y != ny && abs(y-ny)>threshold) || (z != nz && abs(z-nz)>threshold)) {
                onAwake(x,y,z);
           }  
           x = nx; y = ny; z = nz;
           sleep(200);
        }