Search code examples
iosobjective-caccelerometercore-motion

Sit-Up counter using CMDeviceMotion


I'm trying to replicate a fitness app similar to Runtastic's Fitness Apps.

Sit-Ups

This our first app that uses the phone’s built-in accelerometer to detect movement. You need to hold the phone against your chest then sit up quickly enough and high enough for the accelerometer to register the movement and the app to count 1 sit-up. Be sure to do a proper sit-up by going high enough!

I did a prototype app similar to this question here and tried to implement a way to count sit-ups.

- (void)viewDidLoad {
    [super viewDidLoad];

    int count = 0;
    
    motionManager = [[CMMotionManager alloc]init];
    
    if (motionManager.deviceMotionAvailable)
    {
        motionManager.deviceMotionUpdateInterval = 0.1;
        
        [motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {

            // Get the attitude of the device
            CMAttitude *attitude = motion.attitude;
            
            // Get the pitch (in radians) and convert to degrees.
            double degree = attitude.pitch * 180.0/M_PI;
            
            NSLog(@"%f", degree);

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update some UI
                
                if (degree >=75.0)
                {
                    //it keeps counting if the condition is true!
                    count++;
                    self.lblCount.text = [NSString stringWithFormat:@"%i", count];
                }
            });   
        }];
    
        NSLog(@"Device motion started");
    }    
    else
    {
        NSLog(@"Device motion unavailable");
    }
}

The if condition statement works, as if I place the device on my chest and do a proper sit-up, but the problem about this if statement is that it will just continue counting and I would want it to only count when the device has gone back to it's original position.

Can anyone come up with a logical implementation for this?


Solution

  • A simple boolean flag did the trick:

    __block BOOL situp = NO;
    
    
    if (!situp)
    {
        if (degree >=75.0)
        {
            count++;
            self.lblCount.text = [NSString stringWithFormat:@"%i", count];
            situp = YES;
        }
    }
    
    else
    {
        if (degree <=10.0)
        {
            situp = NO;
        }
    }
    

    Not the best logical implementation here, but it gets the job done...