Measuring velocity via iPhone SDK

后端 未结 5 717

I need to implement a native iPhone app to measure the velocity of the phone (basically a speedometer). I know that you can do so via the CoreLocation API fairly easily, bu

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 21:54

    From a practical standpoint, you are not going get accurate velocity from forces acting on the accelerometer.

    Use the GPS with readings taken at 1 minute intervals and put the GPS to sleep inbetween.

    Here is an example:

    SpeedViewController.h

    CLLocationManager *locManager;
    CLLocationSpeed speed;
    NSTimer *timer;
    
    @property (nonantomic,retain) NSTimer *timer;
    

    SpeedViewController.m

    #define kRequiredAccuracy 500.0 //meters
    #define kMaxAge 10.0 //seconds
    
    - (void)startReadingLocation {
        [locManager startUpdatingLocation];
    }
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
        NSTimeInterval ageInSeconds = [newLocation.timestamp timeIntervalSinceNow];
    
        //ensure you have an accurate and non-cached reading
        if( newLocation.horizontalAccuracy > kRequiredAccuracy || fabs(ageInSeconds) > kMaxAge )
            return;
    
        //get current speed    
        currentSpeed = newLocation.speed;
    
        //this puts the GPS to sleep, saving power
        [locManager stopUpdatingLocation]; 
    
        //timer fires after 60 seconds, then stops
        self.timer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(timeIntervalEnded:) userInfo:nil repeats:NO];
    }
    
    //this is a wrapper method to fit the required selector signature
    - (void)timeIntervalEnded:(NSTimer*)timer {
        [self startReadingLocation];
    }
    

提交回复
热议问题