通过加速度计在iPhone上检测任何硬敲击

21

我正在尝试检测在iPhone上任何地方发生的击打,而不仅仅是在iPhone屏幕上。这里有一个链接展示了这是可能的。

基本上我想要做的是,在用户将手机放在口袋中的情况下,如果用户在iPhone上敲打3次,那么就发送警报。我已经能够检测到这3次敲打,但我也会获得以下错误的警报:1)如果用户在行走,2)挥动手机,3)跑步。我需要检查用户是否只是在他的iPhone上打了3次。

以下是我的代码。

- (void)accelerometer:(UIAccelerometer *)accelerometer
        didAccelerate:(UIAcceleration *)acceleration
{
    if (handModeOn == NO)
    {
        if(pocketFlag == NO)
            return;
    }

    float accelZ = 0.0;
    float accelX = 0.0;
    float accelY = 0.0;

    accelX = (acceleration.x * kFilteringFactor) + (accelX * (1.0 - kFilteringFactor));
    accelY = (acceleration.y * kFilteringFactor) + (accelY * (1.0 - kFilteringFactor));
    accelZ = (acceleration.z * kFilteringFactor) + (accelZ * (1.0 - kFilteringFactor));

        self.z.text = [NSString stringWithFormat:@"%0.1f", -accelZ];

        if((-accelZ >= [senstivity floatValue] && timerFlag) || (-accelZ <= -[senstivity floatValue] && timerFlag)|| (-accelX >= [senstivity floatValue] && timerFlag) || (-accelX <= -[senstivity floatValue] && timerFlag) || (-accelY >= [senstivity floatValue] && timerFlag) || (-accelY <= -[senstivity floatValue] && timerFlag))
        {
            timerFlag = false;
            addValueFlag = true;
            timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
        }

        if(addValueFlag)
        {
            if (self.xSwitch.on)
            {
                NSLog(@"X sWitch is on");
                [self.accArray addObject:[NSNumber numberWithFloat:-accelX]];
            }
            if (self.ySwitch.on)
            {
                NSLog(@"Y Switch is on");
                [self.accArray addObject:[NSNumber numberWithFloat:-accelY]];
            }
            if (self.zSwitch.on)
            {
                NSLog(@"Z Switch is on");
                [self.accArray addObject:[NSNumber numberWithFloat:-accelZ]];
            }

        }
    //}
}

- (void)timerTick:(NSTimer *)timer1
{
    [timer1 invalidate];
    addValueFlag = false;
    int count = 0;

    for(int i = 0; i < self.accArray.count; i++)
    {
        if(([[self.accArray objectAtIndex:i] floatValue] >= [senstivity floatValue]) || ([[self.accArray objectAtIndex:i] floatValue] <= -[senstivity floatValue]))
        {
            count++;
            [self playAlarm:@"beep-1" FileType:@"mp3"];
        }

        if(count >= 3)
        {
            [self playAlarm:@"06_Alarm___Auto___Rapid_Beeping_1" FileType:@"caf"];
            [self showAlert];
            timerFlag = true;
            [self.accArray removeAllObjects];
            return;
        }
    }
    [self.accArray removeAllObjects];
    timerFlag = true;
}
任何帮助都将不胜感激。

谢谢。

这正是我正在寻找的!你有找到解决方案吗? - Jonovono
@sajoo,您最终找到了解决方案吗?很愿意和您讨论这个问题。我的电子邮件应该在我的个人资料中。祝好运! - Jonovono
@Jonovono 是的,我已经实现了。等我回到电脑前,我会尝试发布我的解决方案。或者如果你想和我交流,这是我的电子邮件地址:m.sijjeel@gmail.com - sajjoo
4个回答

13

你应该对加速度计数据应用高通滤波。这将给你信号中的峰值——尖锐的敲击。

我快速搜索了“UIAccelerometer high pass filter”,发现了几个结果。最简单的代码是对加速度计输入进行滚动平均,然后从瞬时读数中减去这个平均值以找到突变。当然也有更复杂的方法。

一旦你有了识别尖锐敲击的代码,你需要编写能检测连续3次尖锐敲击的代码。


4
这与过滤加速度计数据流中的敲击有关。冲量状的轻拍将具有特征光谱图(频率组合),当适当的过滤器响应高于阈值时,可以检测到。这是iPhone上非常常见的操作,建议查看官方文档,如此处所示。我链接的示例代码为您提供两个重要内容:高通滤波器的官方示例代码和一个可绘制加速度计数据的示例应用程序。您可以使用它来可视化您的敲击、步数和跳跃,以更好地了解为什么您的过滤器会误报。此外,互联网是过滤器设计的丰富资源 - 如果您需要制作非常高质量的过滤器,您可能需要查阅相关文献。不过,我认为一个合适的二阶滤波器可能已足够。
@implementation HighpassFilter

- (id)initWithSampleRate:(double)rate cutoffFrequency:(double)freq
{
    self = [super init];

    if (self != nil)
    {
        double dt = 1.0 / rate;
        double RC = 1.0 / freq;
        filterConstant = RC / (dt + RC);
    }

    return self;    
}

- (void)addAcceleration:(UIAcceleration *)accel
{
    double alpha = filterConstant;   

    if (adaptive)
    {
        double d = Clamp(fabs(Norm(x, y, z) - Norm(accel.x, accel.y, accel.z)) / kAccelerometerMinStep - 1.0, 0.0, 1.0);
        alpha = d * filterConstant / kAccelerometerNoiseAttenuation + (1.0 - d) * filterConstant;
    }

    x = alpha * (x + accel.x - lastX);
    y = alpha * (y + accel.y - lastY);
    z = alpha * (z + accel.z - lastZ);

    lastX = accel.x;
    lastY = accel.y;
    lastZ = accel.z;
}

- (NSString *)name
{
    return adaptive ? @"Adaptive Highpass Filter" : @"Highpass Filter";
}

@end

重要的是,这个过滤器是方向无关的,因为只过滤加速度的大小。这对于使响应看起来正常至关重要。否则,用户可能会感觉需要从不同的角度轻敲才能找到最佳位置。

另外,如果这项任务证明过于困难和琐碎,我强烈建议捕获您的数据(例如以WAV文件的形式),并使用任何常见的信号分析程序来更好地了解它出了什么问题。请参见Baudline


0

这是我如何实现它的。

- (void)accelerometer:(UIAccelerometer *)accelerometer
        didAccelerate:(UIAcceleration *)acceleration
{
    if (pause)
    {
        return;
    }
    if (handModeOn == NO)
    {
        if(pocketFlag == NO)
            return;
    }

//  float accelZ = 0.0;
//  float accelX = 0.0;
//  float accelY = 0.0;

    rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));
    rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor));
    rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor));

    float accelX = acceleration.x - rollingX;
    float accelY = acceleration.y - rollingY;
    float accelZ = acceleration.z - rollingZ;

    if((-accelZ >= [senstivity floatValue] && timerFlag) || (-accelZ <= -[senstivity floatValue] && timerFlag)|| (-accelX >= [senstivity floatValue] && timerFlag) || (-accelX <= -[senstivity floatValue] && timerFlag) || (-accelY >= [senstivity floatValue] && timerFlag) || (-accelY <= -[senstivity floatValue] && timerFlag))
    {
        timerFlag = false;
        addValueFlag = true;
        timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
    }

    if(addValueFlag)
    {
        [self.accArray addObject:[NSNumber numberWithFloat:-accelX]];
        [self.accArray addObject:[NSNumber numberWithFloat:-accelY]];
        [self.accArray addObject:[NSNumber numberWithFloat:-accelZ]];
    }
}

以下是代码的描述。我在我的设置中添加了一个灵敏度设置,用户可以设置加速度计的灵敏度。因此,如果我得到的值等于或大于该灵敏度,则启动一个1.5秒的计时器,然后在这1.5秒内检查其他值。一旦计时器结束,我现在拥有了数组中加速度计的值,这些值等于或大于灵敏度。然后,在timerTick方法中,我从数组中检查是否有3到4个需要的值。我触发Alert方法,表示检测到了强烈的敲击。 - sajjoo

-11
一些好的答案。这里是一些可用的代码。我将其实现为UIGestureRecognizer的子类,以便您可以轻松地将其放置并附加到UIView或UIButton上。一旦触发,它将把“压力”设置为0.0f至2.0f之间的浮点数。您还可以选择设置要识别的最小和最大压力。享受吧。
#import <UIKit/UIKit.h>

#define CPBPressureNone         0.0f
#define CPBPressureLight        0.1f
#define CPBPressureMedium       0.3f
#define CPBPressureHard         0.8f
#define CPBPressureInfinite     2.0f

@interface CPBPressureTouchGestureRecognizer : UIGestureRecognizer <UIAccelerometerDelegate> {
@public
float pressure;
float minimumPressureRequired;
float maximumPressureRequired;

@private
float pressureValues[30];
uint currentPressureValueIndex;
uint setNextPressureValue;
}

@property (readonly, assign) float pressure;
@property (readwrite, assign) float minimumPressureRequired;
@property (readwrite, assign) float maximumPressureRequired;

@end


//
//  CPBPressureTouchGestureRecognizer.h
//  PressureSensitiveButton
//
//  Created by Anthony Picciano on 3/21/11.
//  Copyright 2011 Anthony Picciano. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions
//  are met:
//  1. Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//  
//  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
//  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
//  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
//  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

#import <UIKit/UIGestureRecognizerSubclass.h>
#import "CPBPressureTouchGestureRecognizer.h"

#define kUpdateFrequency            60.0f
#define KNumberOfPressureSamples    3

@interface CPBPressureTouchGestureRecognizer (private)
- (void)setup;
@end

@implementation CPBPressureTouchGestureRecognizer
@synthesize pressure, minimumPressureRequired, maximumPressureRequired;

 - (id)initWithTarget:(id)target action:(SEL)action {
self = [super initWithTarget:target action:action];
if (self != nil) {
   [self setup]; 
}
return self;
}

 - (id)init {
self = [super init];
if (self != nil) {
    [self setup];
}
return self;
}

- (void)setup {
minimumPressureRequired = CPBPressureNone;
maximumPressureRequired = CPBPressureInfinite;
pressure = CPBPressureNone;

[[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0f / kUpdateFrequency];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
}

#pragma -
#pragma UIAccelerometerDelegate methods

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
int sz = (sizeof pressureValues) / (sizeof pressureValues[0]);

// set current pressure value
pressureValues[currentPressureValueIndex%sz] = acceleration.z;

if (setNextPressureValue > 0) {

    // calculate average pressure
    float total = 0.0f;
    for (int loop=0; loop<sz; loop++) total += pressureValues[loop]; 
    float average = total / sz;

    // start with most recent past pressure sample
    if (setNextPressureValue == KNumberOfPressureSamples) {
        float mostRecent = pressureValues[(currentPressureValueIndex-1)%sz];
        pressure = fabsf(average - mostRecent);
    }

    // caluculate pressure as difference between average and current acceleration
    float diff = fabsf(average - acceleration.z);
    if (pressure < diff) pressure = diff;
    setNextPressureValue--;

    if (setNextPressureValue == 0) {
        if (pressure >= minimumPressureRequired && pressure <= maximumPressureRequired)
            self.state = UIGestureRecognizerStateRecognized;
        else
            self.state = UIGestureRecognizerStateFailed;
    }
}

currentPressureValueIndex++;
 }

 #pragma -
 #pragma UIGestureRecognizer subclass methods

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
setNextPressureValue = KNumberOfPressureSamples;
self.state = UIGestureRecognizerStatePossible;
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
self.state = UIGestureRecognizerStateFailed;
}

- (void)reset {
pressure = CPBPressureNone;
setNextPressureValue = 0;
currentPressureValueIndex = 0;
}

 @end

4
你难道没有读过原始问题和问题吗?这怎么可能是一个可行的解决方案呢? - holex
@holex 抱歉,我仍然在想是谁用我的账户发布了这个帖子。更新答案。 - JohnWick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接