分享

android Motion Senor API 简介

 linux_android 2015-05-29

作者:裘德超

        目前,大多数Android手机手机都内置了很多传感器,大家熟知的有重力传感器,亮度传感器,加速度传感器等。本文将为大家介绍Android系统中的运动传感器。

        Android系统为用户提供了多个运动传感器,其中,加速度传感器和陀螺仪传感器经常是由硬件实现,而重力传感器,线形加速度传感器,旋转向量传感器一般是由软件实现出来的,由软件实现的模拟传感器从一个或多个硬件传感器中获取数据来模拟该虚拟传感器。对于每一个传感器事件,运动传感器都返回一个多维数组,其中包含了传感器感知的数据。下表总结了Android平台中的所有运动传感器:




与传感器有关的类主要包含在android.hardware包中。

SensorManager:可以用来管理Android设备中指出的所有的传感器。

Sensor:具体的传感器,例如重力传感器,陀螺仪传感器。

通过SensorManager类的registerListener方法可以监听某一个传感器,当被监测的传感器的检测到数据变化时就会产生一个事件,回调该传感器的监听器,我们可以在回调方法中执行相应的操作应对数据的变化。

下面是测试程序的布局:首先是一个用于显示当前机器包含的所有硬件传感器和软件传感器的列表。然后分别是重力传感器,加速度传感器(包括重力),线性加速度传感器(不包括重力),陀螺仪传感器,旋转向量传感器的检测到的数据的显示窗口。


res/layout/main.xml


  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <ScrollView xmlns:android="http://schemas./apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:fadingEdge="vertical"  
  6.     android:scrollbars="vertical" >  
  7.   
  8.     <LinearLayout  
  9.         xmlns:android="http://schemas./apk/res/android"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:orientation="vertical" >  
  13.   
  14.         <TextView  
  15.             android:id="@+id/metaPromt"  
  16.             android:layout_width="fill_parent"  
  17.             android:layout_height="wrap_content"  
  18.             android:text="metaPromt" />  
  19.   
  20.         <TextView  
  21.             android:id="@+id/gravityPromt"  
  22.             android:layout_width="fill_parent"  
  23.             android:layout_height="wrap_content"  
  24.             android:text="gravityPromt" />  
  25.   
  26.         <TextView  
  27.             android:id="@+id/accelerometerPromt"  
  28.             android:layout_width="fill_parent"  
  29.             android:layout_height="wrap_content"  
  30.             android:text="accelerometerPromt" />  
  31.   
  32.         <TextView  
  33.             android:id="@+id/linearAccelerometerPromt"  
  34.             android:layout_width="fill_parent"  
  35.             android:layout_height="wrap_content"  
  36.             android:text="linearAccelerometerPromt" />  
  37.   
  38.         <TextView  
  39.             android:id="@+id/gyroscopePromt"  
  40.             android:layout_width="fill_parent"  
  41.             android:layout_height="wrap_content"  
  42.             android:text="gyroscopePromt" />  
  43.   
  44.         <TextView  
  45.             android:id="@+id/rotationVectorPromt"  
  46.             android:layout_width="fill_parent"  
  47.             android:layout_height="wrap_content"  
  48.             android:text="rotationVectorPromt" />  
  49.     </LinearLayout>  
  50. </ScrollView>  


src/org/reno/ MotionSensorsActivity.java

  1. package org.reno;  
  2.   
  3. import java.util.List;  
  4.   
  5. import android.app.Activity;  
  6. import android.content.Context;  
  7. import android.hardware.Sensor;  
  8. import android.hardware.SensorEvent;  
  9. import android.hardware.SensorEventListener;  
  10. import android.hardware.SensorManager;  
  11. import android.os.Bundle;  
  12. import android.widget.TextView;  
  13.   
  14. public class MotionSensorsActivity extends Activity {  
  15.     private SensorManager mSensorManager;  
  16.     private Sensor gravitySensor;  
  17.     private Sensor accelerometerSensor;  
  18.     private Sensor gyroscopeSensor;  
  19.     private Sensor linearAccelerometeSensor;  
  20.     private Sensor rotationVectorSensor;  
  21.     private TextView metaPromt;  
  22.     private TextView gravityPromt;  
  23.     private TextView accelerometerPromt;  
  24.     private TextView linearAccelerometerPromt;  
  25.     private TextView gyroscopePromt;  
  26.     private TextView rotationVectorPromt;  
  27.   
  28.     /** Called when the activity is first created. */  
  29.     @Override  
  30.     public void onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32.         setContentView(R.layout.main);  
  33.         mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);  
  34.         metaPromt = (TextView) findViewById(R.id.metaPromt);  
  35.         // 从传感器管理器中获得全部的传感器列表  
  36.         List<Sensor> allSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);  
  37.         // 显示有多少个传感器  
  38.         metaPromt.setText("经检测该手机有" + allSensors.size() + "个传感器,他们分别是:\n");  
  39.         // 显示每个传感器的具体信息  
  40.         for (Sensor s : allSensors) {  
  41.             String tempString = "\n" + "  设备名称:" + s.getName() + "\n"  
  42.                     + "  设备版本:" + s.getVersion() + "\n" + "  供应商:"  
  43.                     + s.getVendor() + "\n";  
  44.             switch (s.getType()) {  
  45.             case Sensor.TYPE_ACCELEROMETER:  
  46.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  47.                         + " 加速度传感器accelerometer" + tempString);  
  48.                 break;  
  49.             case Sensor.TYPE_MAGNETIC_FIELD:  
  50.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  51.                         + " 电磁场传感器magnetic field" + tempString);  
  52.                 break;  
  53.             case Sensor.TYPE_ORIENTATION:  
  54.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  55.                         + " 方向传感器orientation" + tempString);  
  56.                 break;  
  57.             case Sensor.TYPE_GYROSCOPE:  
  58.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  59.                         + " 陀螺仪传感器gyroscope" + tempString);  
  60.                 break;  
  61.             case Sensor.TYPE_LIGHT:  
  62.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  63.                         + " 环境光线传感器light" + tempString);  
  64.                 break;  
  65.             case Sensor.TYPE_PRESSURE:  
  66.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  67.                         + " 压力传感器pressure" + tempString);  
  68.                 break;  
  69.             case Sensor.TYPE_TEMPERATURE:  
  70.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  71.                         + " 温度传感器temperature" + tempString);  
  72.                 break;  
  73.             case Sensor.TYPE_PROXIMITY:  
  74.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  75.                         + " 距离传感器proximity" + tempString);  
  76.                 break;  
  77.             case Sensor.TYPE_GRAVITY:  
  78.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  79.                         + " 重力传感器gravity" + tempString);  
  80.                 break;  
  81.             case Sensor.TYPE_ROTATION_VECTOR:  
  82.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  83.                         + " 旋转向量传感器:RotationVector" + tempString);  
  84.                 break;  
  85.             default:  
  86.                 metaPromt.setText(metaPromt.getText().toString() + s.getType()  
  87.                         + " 未知传感器" + tempString);  
  88.                 break;  
  89.             }  
  90.         }  
  91.         gravitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);  
  92.         linearAccelerometeSensor = mSensorManager  
  93.                 .getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);  
  94.         accelerometerSensor = mSensorManager  
  95.                 .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);  
  96.         gyroscopeSensor = mSensorManager  
  97.                 .getDefaultSensor(Sensor.TYPE_GYROSCOPE);  
  98.         rotationVectorSensor = mSensorManager  
  99.                 .getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);  
  100.         gravityPromt = (TextView) findViewById(R.id.gravityPromt);  
  101.         accelerometerPromt = (TextView) findViewById(R.id.accelerometerPromt);  
  102.         linearAccelerometerPromt = (TextView) findViewById(R.id.linearAccelerometerPromt);  
  103.         gyroscopePromt = (TextView) findViewById(R.id.gyroscopePromt);  
  104.         rotationVectorPromt = (TextView) findViewById(R.id.rotationVectorPromt);  
  105.         mSensorManager.registerListener(new SensorEventListener() {  
  106.             float[] gravity = new float[3];  
  107.             float[] linear_acceleration = new float[3];  
  108.   
  109.             @Override  
  110.             public void onAccuracyChanged(Sensor sensor, int accuracy) {  
  111.   
  112.             }  
  113.   
  114.             @Override  
  115.             public void onSensorChanged(SensorEvent event) {  
  116.                 // In this example, alpha is calculated as t / (t + dT),  
  117.                 // where t is the low-pass filter's time-constant and  
  118.                 // dT is the event delivery rate.  
  119.   
  120.                 final float alpha = 0.8f;  
  121.   
  122.                 // Isolate the force of gravity with the low-pass filter.  
  123.                 gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];  
  124.                 gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];  
  125.                 gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];  
  126.   
  127.                 // Remove the gravity contribution with the high-pass filter.  
  128.                 linear_acceleration[0] = event.values[0] - gravity[0];  
  129.                 linear_acceleration[1] = event.values[1] - gravity[1];  
  130.                 linear_acceleration[2] = event.values[2] - gravity[2];  
  131.                 gravityPromt.setText("gravityPromt: x="  
  132.                         + (int) linear_acceleration[0] + "," + "y="  
  133.                         + (int) linear_acceleration[1] + "," + "z="  
  134.                         + (int) linear_acceleration[2]);  
  135.             }  
  136.         }, gravitySensor, SensorManager.SENSOR_DELAY_GAME);  
  137.         mSensorManager.registerListener(new SensorEventListener() {  
  138.             float[] gravity = new float[3];  
  139.             float[] linear_acceleration = new float[3];  
  140.   
  141.             @Override  
  142.             public void onAccuracyChanged(Sensor sensor, int accuracy) {  
  143.   
  144.             }  
  145.   
  146.             @Override  
  147.             public void onSensorChanged(SensorEvent event) {  
  148.                 // In this example, alpha is calculated as t / (t + dT),  
  149.                 // where t is the low-pass filter's time-constant and  
  150.                 // dT is the event delivery rate.  
  151.   
  152.                 final float alpha = 0.8f;  
  153.   
  154.                 // Isolate the force of gravity with the low-pass filter.  
  155.                 gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];  
  156.                 gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];  
  157.                 gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];  
  158.   
  159.                 // Remove the gravity contribution with the high-pass filter.  
  160.                 linear_acceleration[0] = event.values[0] - gravity[0];  
  161.                 linear_acceleration[1] = event.values[1] - gravity[1];  
  162.                 linear_acceleration[2] = event.values[2] - gravity[2];  
  163.                 accelerometerPromt.setText("accelerometerPromt: x="  
  164.                         + (int) linear_acceleration[0] + "," + "y="  
  165.                         + (int) linear_acceleration[1] + "," + "z="  
  166.                         + (int) linear_acceleration[2]);  
  167.             }  
  168.         }, accelerometerSensor, SensorManager.SENSOR_DELAY_GAME);  
  169.   
  170.         mSensorManager.registerListener(new SensorEventListener() {  
  171.             @Override  
  172.             public void onAccuracyChanged(Sensor sensor, int accuracy) {  
  173.   
  174.             }  
  175.   
  176.             @Override  
  177.             public void onSensorChanged(SensorEvent event) {  
  178.                 linearAccelerometerPromt.setText("linearAccelerometerPromt: x="  
  179.                         + (int) event.values[0] + "," + "y="  
  180.                         + (int) event.values[1] + "," + "z="  
  181.                         + (int) event.values[2]);  
  182.             }  
  183.         }, linearAccelerometeSensor, SensorManager.SENSOR_DELAY_GAME);  
  184.         mSensorManager.registerListener(new SensorEventListener() {  
  185.             // Create a constant to convert nanoseconds to seconds.  
  186.             private static final float NS2S = 1.0f / 1000000000.0f;  
  187.             private final float[] deltaRotationVector = new float[4];  
  188.             private float timestamp;  
  189.   
  190.             @Override  
  191.             public void onAccuracyChanged(Sensor sensor, int accuracy) {  
  192.                 // TODO Auto-generated method stub  
  193.             }  
  194.   
  195.             @Override  
  196.             public void onSensorChanged(SensorEvent event) {  
  197.                 // This timestep's delta rotation to be multiplied by the  
  198.                 // current rotation  
  199.                 // after computing it from the gyro sample data.  
  200.                 if (timestamp != 0) {  
  201.                     final float dT = (event.timestamp - timestamp) * NS2S;  
  202.                     // Axis of the rotation sample, not normalized yet.  
  203.                     float axisX = event.values[0];  
  204.                     float axisY = event.values[1];  
  205.                     float axisZ = event.values[2];  
  206.                     // Calculate the angular speed of the sample  
  207.                     float omegaMagnitude = (float) Math.sqrt(axisX * axisX  
  208.                             + axisY * axisY + axisZ * axisZ);  
  209.                     // Integrate around this axis with the angular speed by the  
  210.                     // timestep  
  211.                     // in order to get a delta rotation from this sample over  
  212.                     // the timestep  
  213.                     // We will convert this axis-angle representation of the  
  214.                     // delta rotation  
  215.                     // into a quaternion before turning it into the rotation  
  216.                     // matrix.  
  217.                     float thetaOverTwo = omegaMagnitude * dT / 2.0f;  
  218.                     float sinThetaOverTwo = (float) Math.sin(thetaOverTwo);  
  219.                     float cosThetaOverTwo = (float) Math.cos(thetaOverTwo);  
  220.                     deltaRotationVector[0] = sinThetaOverTwo * axisX;  
  221.                     deltaRotationVector[1] = sinThetaOverTwo * axisY;  
  222.                     deltaRotationVector[2] = sinThetaOverTwo * axisZ;  
  223.                     deltaRotationVector[3] = cosThetaOverTwo;  
  224.                 }  
  225.                 timestamp = event.timestamp;  
  226.                 float[] deltaRotationMatrix = new float[9];  
  227.                 SensorManager.getRotationMatrixFromVector(deltaRotationMatrix,  
  228.                         deltaRotationVector);  
  229.                 String promt = "";  
  230.                 for (int i = 0; i < deltaRotationMatrix.length; i++) {  
  231.                     promt += deltaRotationMatrix[i] + "\n";  
  232.                 }  
  233.                 gyroscopePromt.setText("gyroscopePromt: \n" + promt);  
  234.                 // User code should concatenate the delta rotation we computed  
  235.                 // with the current rotation  
  236.                 // in order to get the updated rotation.  
  237.                 // rotationCurrent = rotationCurrent * deltaRotationMatrix;  
  238.             }  
  239.         }, gyroscopeSensor, SensorManager.SENSOR_DELAY_GAME);  
  240.         mSensorManager.registerListener(new SensorEventListener() {  
  241.             private final float[] deltaRotationVector = new float[4];  
  242.   
  243.             @Override  
  244.             public void onAccuracyChanged(Sensor sensor, int accuracy) {  
  245.   
  246.             }  
  247.   
  248.             @Override  
  249.             public void onSensorChanged(SensorEvent event) {  
  250.                 deltaRotationVector[0] = event.values[0];  
  251.                 deltaRotationVector[1] = event.values[1];  
  252.                 deltaRotationVector[2] = event.values[2];  
  253.                 // deltaRotationVector[3] = event.values[3];  
  254.                 float[] deltaRotationMatrix = new float[9];  
  255.                 SensorManager.getRotationMatrixFromVector(deltaRotationMatrix,  
  256.                         deltaRotationVector);  
  257.                 String promt = "";  
  258.                 for (int i = 0; i < deltaRotationMatrix.length; i++) {  
  259.                     promt += deltaRotationMatrix[i] + "\n";  
  260.                 }  
  261.                 rotationVectorPromt.setText("rotationVectorPromt: \n" + promt);  
  262.             }  
  263.         }, rotationVectorSensor, SensorManager.SENSOR_DELAY_GAME);  
  264.     }  
  265. }  


程序首先调用

(SensorManager)getSystemService(Context.SENSOR_SERVICE);

获取系统的传感器服务并且赋值给传感器管理器,然后通过调用

mSensorManager.getSensorList(Sensor.TYPE_ALL);

获取系统中所有类型的传感器。然后遍历所有的传感器,并且显示传感器的名称,制造商等信息。

然后调用mSensorManager.registerListener()方法监听某个传感器,当传感器检测到变化时会自动调用所注册的监听器的onSensorChanged(SensorEvent event)方法,其中event变量中包含了传感器检测到的数据,关于各个数据的作用见上文中的表一。

关于坐标系:

手机放桌面上,把手机往左边移动,那么x轴上的加速度为正,把手机往前移动,那么y轴的加速度为正,把手机往空中向上移动,那么z轴的加速度为正。

 

故对于加速度传感器,由于传感器默认当做自由落体运动时的加速度为0,所以手机静止时,加速度传感器返回的数据为0 –(-9.8)(即重力加速度g)。当手机以a的加速度向上移动时,加速度返回的数据为a-(-9.8)。然而由于我们的意识中当手机静止时的加速度应该为0。所以我们需要从系统返回的数据中过滤掉重力的作用。

 

关于陀螺仪传感器,由于传感器返回的event变量中的event.values数组中返回的分别是x, y, z轴中的角速度。所以我们需要算出这三个角速度的算数平方和的根,从而得出整体的角速度。然后把这个角速度乘以上次测量和本次测量之间的时间,算出手机总共旋转的角度,然后通过公式:

x*sin(θ/2)

y*sin(θ/2)

z*sin(θ/2)

算出手机在各个轴上旋转的角度。

执行效果:

由于本程序中同时监听的传感器过多,并且陀螺仪传感器和旋转向量传感器中涉及到了复杂的浮点数运算,所以会比较卡。




SourceCode下载链接:

https://github.com/renoqiu/MotionSensorTest

 

参考链接:

http://developer./guide/topics/sensors/sensors_motion.html

http:///2011/02/21/android-sensor-programming-1/



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多