Android Sensor applications

Source: Internet
Author: User
Tags cos sin

This chapter describes the knowledge points that are relevant to sensor applications in Android development.

1. Functional Requirements
    • Make a sensor-based horizontal ruler application.
2. Software implementation

Figure 1

Figure 2

As shown: When running on a mobile phone, you can test the function of the level ruler and compass by flipping the phone.

3. Related knowledge points (1) Introduction to Sensors

Basic knowledge of Android sensor programming, including accelerometer (accelerometer), gyroscope (gyroscope), ambient light sensor, magnetic sensor (magnetic field), Direction sensor (orientation), pressure sensor (pressure), distance sensor (proximity), and temperature sensor (temperature).

  • Define Sensor_type_accelerometer 1//acceleration
  • Define Sensor_type_magnetic_field 2//Magnetic
  • Define Sensor_type_orientation 3//direction
  • Define Sensor_type_gyroscope 4//Gyroscope
  • Define Sensor_type_light 5//Light Sensing
  • Define Sensor_type_pressure 6//pressure
  • Define Sensor_type_temperature 7//temperature
  • Define Sensor_type_proximity 8//Close
  • Define Sensor_type_gravity 9//Gravity
  • Define Sensor_type_linear_acceleration 10//Linear acceleration
  • Define Sensor_type_rotation_vector 11//rotation vector
1 Acceleration Sensor

The accelerometer is also called G-sensor, which returns the acceleration values for the X, y, and Z axes.

This value contains the effect of gravity, in units of m/s^2.

Put your phone flat on the desktop, the X axis defaults to the 0,y axis default 0,z axis default 9.81.

Place your phone face down on the desktop with a Z axis of-9.81.

Tilt the phone to the left and the x-axis as positive.

Tilt the phone to the right and negative x-axis.

Tilt the phone upward and the y-axis is negative.

Tilt the phone downward and the y-axis is positive.

The accelerometer is probably the most sophisticated MEMS product, with a wide range of accelerometer sensors on the market.

The commonly used accelerometer in mobile phones is Bosch's BMA series, AMK 897X series, St's LIS3X series, etc.

These sensors typically provide an acceleration measurement range from ±2g to ±16g with an I²C or SPI interface connected to the MCU with a data accuracy of less than 16bit.

2 Magnetic Sensor

The magnetic sensor is referred to as m-sensor and returns the environmental magnetic field data of the X, y, and Z axes.

The unit of the value is micro-Tesla (Micro-tesla), expressed in UT.

The unit can also be Gauss (Gauss), 1tesla=10000gauss.

There is generally no independent magnetic sensor on the hardware, and the magnetic data is provided by the electronic Compass Sensor (E-COMPASS).

The Electronic Compass sensor also provides direction sensor data for the following.

3 Direction Sensor

The direction sensor is abbreviated as O-SENSOR, which returns the angle data of the three axes, and the unit of the direction data is the angle.

To get accurate angular data, e-compass needs to get g-sensor data,

The production o-sensor data is calculated, otherwise only the horizontal angle can be obtained.

The direction sensor provides three data, azimuth, pitch, and roll respectively.

Azimuth: Azimuth, returns the angle of the magnetic north and Y axes at horizontal time, ranging from 0° to 360°.

0°= North, 90°= East, 180°= South, 270°= West.

The angle between the pitch:x axis and the horizontal plane, ranging from -180° to 180°.

When the z axis rotates toward the y axis, the angle is positive.

The angle between the roll:y axis and the horizontal plane, for historical reasons, ranges from -90° to 90°.

When the x-axis moves toward the z-axis, the angle is positive.

The electronic compass needs to be calibrated before it can get the correct data, usually with a 8-word calibration method.

8-word calibration requires the user to do 8-word shaking in the air using a device that needs to be calibrated,

In principle, as much as possible, the device normal direction points to all 8 quadrants of space.

The electronic compass chip used in the mobile phone has the AKM company's 897X series, St company's LSM series as well as Yamaha company and so on.

Because of the need to read g-sensor data and calculate m-sensor and o-sensor data,

So vendors will generally provide a background daemon to complete the work, electronic compass algorithm is generally the company's private property rights.

4 Gyro Sensor

The gyroscope sensor is called gyro-sensor and returns the angular acceleration data for the X, y, and Z axes.

The unit of angular acceleration is radians/second.

Measured by Nexus S mobile:

Rotate horizontally counterclockwise and the z axis is positive.

The horizontal counterclockwise rotation, the z axis is negative.

Rotate to the left and negative on the Y axis.

Rotates to the right and the y-axis is positive.

Rotate up and the x axis is negative.

Rotate downward and the x axis is positive.

ST's L3G series of gyroscope sensors are more popular, iphone4 and Google's Nexus S use this kind of sensor.

5 Light Sensing Sensor

The light sensor detects real-time light intensity, the unit of light is lux, and its physical meaning is luminous flux on the unit area.

The light sensor is mainly used for the LCD auto-brightness function of Android system.

The brightness of the LCD can be adjusted in real time according to the light intensity sampled.

6 Pressure sensor

The pressure sensor returns the current pressure in the unit of Hectopascal (HPa).

7 Temperature Sensor

The temperature sensor returns the current temperature.

8 Proximity Sensor

The proximity sensor detects the distance between the object and the phone, in centimeters.

Some proximity sensors can only return far and near two states,

Therefore, the proximity sensor returns the maximum distance to the far state, which is less than the maximum distance to return to the near state.

Proximity sensors can be used to automatically turn off the LCD screen when answering a phone to conserve power.

Some chips have integrated proximity sensors and light sensors for both functions.

The following three sensors are the new sensor types proposed by ANDROID2, and it is not yet clear which applications are available.

9 Gravity Sensor

The gravity sensor is referred to as gv-sensor and outputs gravity data.

On Earth, the value of gravity is 9.8, the unit is m/s^2.

The coordinate system is the same as the accelerometer sensor.

When the device is reset, the output of the gravity sensor is the same as the accelerometer sensor.

10 Linear acceleration Sensor

Linear accelerometer is referred to as la-sensor.

The linear accelerometer is the data obtained by the acceleration sensor minus the gravity effect.

The unit is m/s^2 and the coordinate system is the same as the accelerometer sensor.

The formula for acceleration sensors, gravity sensors and linear accelerometer is as follows:

Acceleration = gravity + linear acceleration

11 Rotation Vector Sensor

Rotary vector sensor for short rv-sensor.

The rotation vector represents the direction of the device, which is a mix of axes and angles to calculate the data.

Rv-sensor output of three data:

X*sin (THETA/2)

Y*sin (THETA/2)

Z*sin (THETA/2)

Sin (THETA/2) is an order of magnitude for RV.

The RV is in the same direction as the Axis rotation.

The three values of the RV, together with the Cos (THETA/2), constitute a four-tuple.

RV data has no units, and the coordinate system used is the same as acceleration.

Example:

Sensors_event_t.data[0] = X*sin (THETA/2)

SENSORS_EVENT_T.DATA[1] = Y*sin (THETA/2)

SENSORS_EVENT_T.DATA[2] = Z*sin (THETA/2)

SENSORS_EVENT_T.DATA[3] = cos (THETA/2)

The values for GV, LA, and RV are not available in the physical sensor directly,

G-sensor, O-sensor, and gyro-sensor are required to be calculated by the algorithm.

(2) Sensor operation

Get a Sensormanager Object

Sensormanager Msensormanager = (sensormanager) getsystemservice (sensor_service);

Get sensor list

list<sensor> sensors = msensormanager.getsensorlist (Sensor. Type_orientation);

Registering sensors

Boolean result = Msensormanager.registerlistener (this, sensors, Sensormanager. Sensor_delay_fastest);

Sersormanager provides a method for registering the sensor as Registerlistener (Sensorlistener Listener, sensor sensor, int rate) The three parameters in this method are described below:

Listener: Monitor listener for sensor events

Sensor: Transducer Object

Rate: Specify how often to get sensor data

Rate can get the frequency of sensor data, and it supports several frequency values as follows:

Sensor_delay_fastest: Fastest, least latency.

Sensor_delay_game: The frequency for the game.

Sensor_delay_normal: Normal frequency

SENSOR_DELAY_UI: Frequency for normal user interface.

Uninstalling the Sensor

Msensormanager.unregisterlistener (this);

Sensoreventlistener has two interface methods

Called when the sensor value changes

Onsensorchanged (Sensorevent event);

Sensorevent objects include a set of floating-point numbers

float x = Event.values[sensormanager. Data_x];

Float y = event.values[sensormanager. Data_y];

float z = event.values[sensormanager. Data_z];

Called when the accuracy of the sensor changes

Parameter accuracy represents the new accurate value of the sensor

Onaccuracychanged (sensor sensor, int accuracy)

(3) Sensor application precautions 1 Unregister a sensor listener

When you no longer use sensors or related activity pauses, be sure to log off the sensor listener in a timely manner. If the sensor listener is registered and the related activity is paused, the sensor will continue to measure data and consume battery resources unless you unregister the sensor. The following code shows how to use the OnPause () method to unregister the listener:

1 private sensormanager msensormanager;2 ...   3 @Override4 protected void OnPause () {5   super.onpause (); 6   Msensormanager.unregisterlistener (this); 7 8}
2 do not test your code on the simulator

Sensor-related code cannot be tested on the simulator at this time because the simulator cannot emulate the sensor. You must test the sensor-related code on the physical device. However, you can use the sensor simulator to simulate the sensor output.

3 do not block the Onsensorchanged () method

Sensor data changes at very high frequencies, which means that the system may call the Onsensorchanged (Sensorevent) method very frequently. The best implementation is that you should do as few things as possible in the onsensorchanged (sensorevent) method to prevent blocking. If your application requires filtering or culling of sensor data, it should be done outside of the onsensorchanged (Sensorevent) method.

4 avoid using outdated methods or sensor types

There are several methods and constants that are obsolete. In particular, the Type_orientation sensor type is obsolete. To get azimuth data, you should swap the Getorientation () method. Similarly, the Type_temperature sensor type is obsolete. On Android 4.0 devices, you should use the Type_ambient_temperature sensor type instead.

5 Verify the sensor before use

Before attempting to read data, be sure to verify that the sensor exists. Do not simply assume that it will exist because the sensor is very common. Manufacturers do not need to provide any sensors on their devices.

Detect sensors at run time and enable or disable appropriate functions of the application, as appropriate

1 Msensormanager = (Sensormanager) getsystemservice (Context.sensor_service); 2  3   if (Msensormanager.getdefaultsensor (sensor.type_pressure)! = null) {4  5   //success! There ' s a pressure sensor. 6  7   } 8  9   else {ten   ///failed! The sensor does not exist. *   

Use the Android Market filter to limit the target device to a specific sensor

If you want to publish your app on Android market, you can use the <uses-feature> element in the manifest file to filter out devices that do not provide the required sensor.

The <uses-feature> elements in the manifest file have many hardware descriptors that can be used to filter the application based on whether the sensor exists or not. The sensors listed include: accelerometer, barometer, compass (geomagnetic), gyroscope, light, and proximity distance. The following is a sample of the manifest of the filter without accelerometer:

<uses-feature android:name= "Android.hardware.sensor.accelerometer" android:required= "true"/>

If you add this element and descriptor to your manifest, only users with accelerometers on the device will be able to see your app on Android market.
6 careful selection of sensor delay

When registering a sensor with the Registerlistener () method, be sure to select the appropriate sending frequency for your app or usage scenario. The sensor can send data at very high frequencies. Make sure the system has the ability to send other data without wasting system resources and consuming battery power.

Android Sensor applications

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: info-contact@alibabacloud.com 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.