簡體   English   中英

通過加速度計檢測iPhone上任何位置的硬點擊

[英]Detect hard taps anywhere on iPhone through accelerometer

我試圖檢測可能在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;
}

任何幫助將非常感激。

謝謝

您應該對加速度計數據應用高通濾波器。 這將給你信號尖峰 - 尖銳的水龍頭。

我對“UIAccelerometer高通濾波器”進行了快速搜索,發現了幾次點擊。 最簡單的代碼采用加速度計輸入的滾動平均值,然后從瞬時讀數中減去該平均值以發現突然變化。 毫無疑問,更復雜的方法也是如此。

一旦你擁有識別尖銳水龍頭的代碼,你就需要制作能夠連續檢測到3個尖銳水龍頭的代碼。

正如另一個答案所建議的那樣,這與從加速度計數據流中過濾抽頭有關。 脈沖式抽頭將具有特征頻譜圖(頻率組合),當來自適當濾波器的響應高於閾值時,可以檢測到該頻譜圖。

這是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

以下是我如何實現它。

- (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]];
    }
}

一些好的答案。 這是一些有效的代碼。 我將其實現為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM