好吧,这是一个奇怪的问题-这个问题以前曾以各种形式提出过,并且总是以a)不够准确和b)随着时间而变得不准确的观点结束。 / p>
我理解这一点-但我正在做一个实验,以查看是否可以通过考虑其他证据来源来提高准确性(例如,如果预先绘制了地图,那么从指南针与路线相结合可以提供另一个证据来源。
问题是我的代码显然是垃圾-因此,欢迎您提出意见。我怀疑这可能是牛皮纸袋错误!
我的 ViewController.h 看起来像这样:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UIAccelerometerDelegate> {
UIAccelerometer *accelerometer;
long last_speed;
long distance_travelled;
long lastAccel;
long long lastTime;
IBOutlet UITextField* speedView;
IBOutlet UITextField* distanceView;
}
@end
我的 ViewController.m 看起来像这样:
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
lastAccel = 0;
last_speed = 0;
distance_travelled = 0;
lastTime = (long)(NSTimeInterval)([NSDate.date timeIntervalSince1970] * 1000.0);
accelerometer = UIAccelerometer.sharedAccelerometer;
accelerometer.updateInterval = 0.1;
accelerometer.delegate = self;
}
- (void)accelerometer:(UIAccelerometer *)meter
didAccelerate:(UIAcceleration *)acceleration
{
long long currentTime = (long)(NSTimeInterval)([NSDate.date timeIntervalSince1970] * 1000.0);
long long deltaTime = currentTime - lastTime;
lastTime = currentTime;
long accel_x = acceleration.x;
long accel_y = acceleration.y;
long accel_z = acceleration.z;
long integrated_acceleration = sqrtl(accel_x*accel_x + accel_y*accel_y + accel_z*accel_z);
long average_acceleration = (lastAccel + integrated_acceleration) / 2;
long speed = last_speed + (average_acceleration * deltaTime);
long average_speed = (speed + last_speed) / 2;
distance_travelled = distance_travelled + (average_speed * deltaTime);
last_speed = speed;
lastAccel = integrated_acceleration;
[speedView setText:[NSString stringWithFormat:@"%ld", speed]];
[distanceView setText:[NSString stringWithFormat:@"%ld", distance_travelled]];
}
@end
运行代码时,速度和距离会持续增加,并且永远不会考虑减速(我减速)-因此,即使我停下来,速度和距离也会继续增加。
即使按照“这将有点不准确”的标准,这也太过分了!
所有想法和意见都受到感激(几乎-我知道这是不准确的!)
答案 0 :(得分:2)
您无法使用UIAccelerometer计算速度。
请找到链接以获取更多说明:How to calculate speed using accelerometer in ios