iOS Development-coremotion Framework (accelerometer and gyroscope)

Source: Internet
Author: User

Coremotion is a framework dedicated to motion, which contains two parts of accelerometers and gyroscopes, before iOS4 the accelerometer is the Uiaccelerometer class responsible for collecting data, Now generally use coremotion to deal with the acceleration process, but because Uiaccelerometer is relatively simple, the same people are used. Accelerometer is determined by three axes, the user's most common operation of the device movement, shaking the phone (shake a shake), tilt the phone can be detected by the device, the accelerometer can detect linear changes, gyroscope can better detect the deflection of the action, according to the user's action to make the corresponding action, iOS simulator does not simulate the above actions, the real-machine debugging requires a developer account.

Acceleration Meter

Accelerometer in x, Y, z three directions, reference:

If you only need to know the direction of the device, do not need to know the direction of the vector angle, then you can use Uidevice to operate, but also according to the direction of the line to judge, in particular, you can refer to the official Apple code:

-(void) Viewdidload {     //Request to turn on accelerometer and begin receiving Accelerometer events     [[Uidevice Curr Entdevice] begingeneratingdeviceorientationnotifications];     [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (orientationchanged:) Name: Uideviceorientationdidchangenotification Object:nil];} -(void) orientationchanged: (nsnotification *) Notification {     //Respond to changes in device orientation}-(void) view diddisappear {     //Request to stop receiving accelerometer events and turn off accelerometer     [[Nsnotificationcente R Defaultcenter] removeobserver:self];     [[Uidevice Currentdevice] endgeneratingdeviceorientationnotifications];}

when the user shakes the device, the system notifies each of the devices in use and can make itself a first responder:

-(BOOL) Canbecomefirstresponder {    return YES;}-(void) Viewdidappear: (bool) animated {    [self Becomefirstresponder];}

There are three ways to handle motion events, start (Motionbegan), End (motionended), Cancel (motioncancelled):

-(void) Motionbegan: (uieventsubtype) Motion withevent: (uievent *) event Ns_available_ios (3_0);-(void) motionended: ( Uieventsubtype) Motion withevent: (uievent *) event Ns_available_ios (3_0);-(void) motioncancelled: (Uieventsubtype) Motion withevent: (uievent *) event Ns_available_ios (3_0);

The Motionended method handles:

-(void) motionended: (uieventsubtype) Motion withevent: (uievent *) Event {    if (motion = = Uieventsubtypemotionshake)    {        //flyelephant  Http://        [[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Flyelephant" object:self];    }

Coremotion is a very important framework when dealing with accelerometer data and gyroscope data, the framework itself integrates many algorithms to obtain native data, and it can be well demonstrated that coremotion is different from Uikit, and is connected uievent rather than event response chains. Coremotion is simply a simpler distribution of motion events than receiving data.

The Cmmotionmanager class is able to use all of the mobile data for the device (motion data), and the Core motion Framework provides two ways to manipulate motion data:

Pull mode: Can be Coremotionmanager read-only method to obtain the current status of any sensor or combination of data;

Push mode: is to collect the desired data in blocks or closures and get real-time updates in a specific cycle;

Pull processing mode:

    Determine if the accelerometer is available    if ([_motionmanager isaccelerometeravailable]) {        //Set the accelerometer sampling frequency        [_motionmanager Setaccelerometerupdateinterval:1/40.0];        [_motionmanager startaccelerometerupdates];    } else {        NSLog (@ "blog Park-flyelephant");    }

Touch End:

-(void) touchesended: (Nsset *) touches withevent: (uievent *) event{     cmacceleration acceleration=_ motionManager.accelerometerData.acceleration;    NSLog (@ "%f---%f---%f", acceleration.x,acceleration.y,acceleration.z);}

Push processing mode:

@property (strong,nonatomic) Cmmotionmanager  *motionmanager; @property (strong,nonatomic) Nsoperationqueue * Quene;
     _motionmanager=[[cmmotionmanager Alloc]init];    Determine if the accelerometer is available    if ([_motionmanager isaccelerometeravailable]) {        //Set the accelerometer frequency        [_motionmanager Setaccelerometerupdateinterval:1/40.0];        Start sampling Data        [_motionmanager startaccelerometerupdatestoqueue:_quene withhandler:^ (Cmaccelerometerdata * Accelerometerdata, Nserror *error) {            NSLog (@ "%f---%f", accelerometerdata.acceleration.x, ACCELEROMETERDATA.ACCELERATION.Y);}        ];    } else {        NSLog (@ "blog Park-flyelephant");    }

Time Setting Frequency:


Gyroscope actually main method and way and accelerometer no difference, first look at the gyroscope rotation angle Picture:

Gyroscope Update data is also available in two ways, pull mode (startgyroupdates), push mode (startgyroupdatestoqueue) :

static const Nstimeinterval gyromin = 0.01; -(void) Startupdateswithslidervalue: (int) Slidervalue {//Determine the update interval nstimeinterval delta = 0.     005;      Nstimeinterval updateinterval = gyromin + Delta * slidervalue; Create a cmmotionmanager Cmmotionmanager *mmanager = [(Aplappdelegate *) [[uiapplication Sharedapplication] Delegate     ] Sharedmanager];      Aplgyrographviewcontroller * __weak weakself = self; Check whether the gyroscope is available if ([mmanager isgyroavailable] = = YES) {//Assign the update int          Erval to the Motion manager [Mmanager Setgyroupdateinterval:updateinterval]; [Mmanager startgyroupdatestoqueue:[nsoperationqueue Mainqueue] withhandler:^ (cmgyrodata *gyroData, NSError *error)               {[Weakself.graphview addx:gyrodata.rotationrate.x y:gyrodata.rotationrate.y z:gyrodata.rotationrate.z]; [Weakself setlabelvaluex:gyrodata.rotationrate.x y:gyrodata.rotationrate.y Z:gyrodata.rotaTIONRATE.Z];     }]; } self.updateIntervalLabel.text = [NSString stringwithformat:@ "%f", UpdateInterval];} -(void) stopupdates{Cmmotionmanager *mmanager = [(Aplappdelegate *) [[uiapplication Sharedapplication] delegate] Share     Dmanager];     if ([mmanager isgyroactive] = = YES) {[Mmanager stopgyroupdates]; }}

Very late, first to go to bed ~ have time to add a bit ~

iOS Development-coremotion Framework (accelerometer and gyroscope)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.