I learned a lot of knowledge and got to know a lot of people while writing an animation series. Like being invited into some mysterious kinesiological organization, all the gods on the front line. There are UI, UED, iOS. To join an organization, you can read here: Join CRAnimation.

I really discovered that writing is actually a process of forcing myself to keep learning. So, here we go again, starsea. For this series, I’m calling it iOS Sensor Brothers. We’ll call it that for now until we think of something better to call it.

The following directoriesModified at any timeFor reference only.

Article 1: Acceleration sensor

Chapter two: Gyroscopes

Chapter three: magnetometer

Distance sensor

Chapter five: Fingerprint identification sensor

MultipeerConnectivity of bluetooth

Core Bluetooth

Think of a fun example and put everything together.

This series of content emulators are basically not supported and require real machine testing. So pull out your phone, and let’s do something about it. In order to be able to record the mobile phone effect, also tip a lot of trouble.

Let’s see how the accelerometer works by implementing an image that rotates with the screen. Below is a screenshot of the finished video, and the GIF image is just compressed. Please ignore my little vest:

Some apps have special features in addition to a gorgeous interface. Such as wechat shake shake, a variety of health software pedometer, compass and so on. All of these apps actually use a CoreMotion framework in iOS called CoreMotion.

CoreMotion pulls data from built-in sensors, including gyroscopes, accelerometers and magnetometers. Even more impressive is apple’s integration of algorithms that directly output acceleration information stripped of gravity acceleration. A good example of a bad practice.

1. Introduction of accelerometer

The iPhone, iPad and iWatch can all measure acceleration forces along the X, Y and X axes. Acceleration force is the force acting on a body as it accelerates. Use a picture to illustrate:

2. Use of accelerometers

Since the accelerometer is managed through the CoreMotion framework, and Apple inherits many algorithms, CoreMotion must also have a Manager. CMMotionManager:

A CMMotionManager object is the gateway to the motion services provided by iOS. These services provide an app with accelerometer data, rotation-rate data, magnetometer data, And other device-motion data such as attitude. These types of data originate with a device’s accelerometers and (on some models) its magnetometer and gyroscope.

So whenever we use Motion services, we definitely need to use CMMotionManager. The steps are as follows:

  1. Initialize the CMMotionManager managed object.
  2. Call the object method of the managed object to get the data;
  3. Processing data;
  4. Stop fetching data when it is no longer needed.
// Initialize the global managed object - (CMMotionManager *)manager{if(! _manager) { _manager = [[CMMotionManager alloc] init]; }return _manager;
}

Copy the code
// Stop getting accelerometer data. Determine if you are still active before you stopif ( self.manager.accelerometerActive) {
        [self.manager stopAccelerometerUpdates];
        NSLog(@"Closed.");
    }

Copy the code

3. Two ways to obtain accelerometer data

There are two ways to get data in CoreMotion, one called PUSH and one called PULL. As the name implies, PUSH is passive acquisition. Once set, the thread periodically pushes the data back. It is conceivable that the consumption of resources will be slightly greater.

PULL is to take. You have to pull it to get the data. Don’t refuse.

3.1 Method of PULL

- (void)useAccelerometerPull{// Check whether the accelerometer is availableif(self, manager accelerometerAvailable) {/ / set the accelerometer how long sampling time self. Manager. AccelerometerUpdateInterval = 0.1; // Update starts, background thread starts running. This is Pull. [self.manager startAccelerometerUpdates]; } // Get and process accelerometer data. So here we're just simply printing. NSLog(@"X = %f,Y = %f,Z = %f",self.manager.accelerometerData.acceleration.x,self.manager.accelerometerData.acceleration.y,self.manager.accelerometerD ata.acceleration.z); }Copy the code

3.2 PUSH mode

- (void)useAccelerometerPush{// Check whether the accelerometer is available and whether the accelerometer is enabledif(self, manager accelerometerAvailable) {/ / set the accelerometer how long sampling time self. Manager. AccelerometerUpdateInterval = 0.1; // Get and process data in Push mode, here we just do simple printing again. Put the sampling work in the main thread. [self.manager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error){ NSLog(@"X = %f,Y = %f,Z = %f",self.manager.accelerometerData.acceleration.x,self.manager.accelerometerData.acceleration.y,self.manager.accelerometerD ata.acceleration.z); }]; }else{
        NSLog(@"Not available"); }}Copy the code

3.3 Printing Results

It’s nice to see the XYZ axis changing wildly. My phone’s screen was shaking the whole time.

4. Make the picture always horizontal

4.1 train of thought

STEP1: in order to be able to keep the image level no matter how tilted the device is, you must first capture the rotation of the screen.

STEP2: Rotate the picture after obtaining this value at a high frequency. STEP 3: That’s it. What? !!!!!!!!!! Just kidding. In fact, it can be found in this process, the picture will have some wobble when rotating. What to do? We can mitigate this by averaging data acquired over a period of time. After using the gyroscope described in the next article, the jitter effect will also be significantly improved. This part of the code is not implemented by the nerdy, try it yourself? ! La la la la la la.

4.2 implementation

- (void)keepBalance{
        if(self, manager accelerometerAvailable) {/ / set the accelerometer sampling frequency self. The manager. AccelerometerUpdateInterval = 0.01 f; [self.manager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {// Calculate the horizontal tilt Angle of the image. Interested in children's shoes realize the Z axis is good? Double rotation = atan2 (accelerometerData. Acceleration. X, accelerometerData. Acceleration. The y) - M_PI;  self.imageView.transform = CGAffineTransformMakeRotation(rotation); }]; }}Copy the code

4.3 Explanation of deformation Angle ATan2

/ / computing rotation Angle double rotation = atan2 (accelerometerData. Acceleration. X, accelerometerData. Acceleration. The y) - M_PI;Copy the code

This one uses a C function. Atan2 returns the azimuth from the origin to the point (x,y), that is, the Angle with the X-axis.

You’ve probably never used atan2. It’s similar to atan, but atan returns values in the range (-pi /2,PI/2), atan2 returns values in the range (-pi,PI), and it takes two arguments.

Atan2 is a function we can actually see in many places, Android, JS, PHP, etc. If you want to further understand, you can move to Baidu Encyclopedia, feel very clear. Baidu Encyclopedia about atan2 link; Wikipedia link about ATan2.

Ok ~ manual ~~ next time let’s use gyroscope to make a horizontal rolling ball game play ~

Thank you for your comments, likes and tips.


Source code download address: OC+Swift two versions. Download address