使用 CMDeviceMotion 的仰卧起坐计数器

Sit-Up counter using CMDeviceMotion

我正在尝试复制类似于 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!

我做了一个类似于这个问题的原型应用程序 并尝试实现一种计算仰卧起坐的方法。

- (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");
    }
}

if 条件语句有效,就好像我将设备放在胸前并做一个正确的仰卧起坐一样,但是这个 if 语句的问题是它会继续计数,我希望它只计数当设备回到原来的位置时。

谁能想出一个合乎逻辑的实现方式?

一个简单的布尔标志就可以了:

__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;
    }
}

这里不是最好的逻辑实现,但它完成了工作...