반응형




게임 플레이시 안드로이드에 있는 센서를 이용하여 플레이하는 것이 어떻게 동작하는지 알아보기 위해..태스트 앱을 만들었습니다. 향후 로봇 제어용으로 사용하려고 구현해놓았는데 제대로 동작했으면 좋겠습니다...


안드로이드폰을  수평으로 놓아서  pitch 값이 0이되거나 안드로이드폰 상단을 아래로 향하게 해서 pitch값이 양수가 되면 로봇에 STOP신호를 주도록 작성할 계획입니다.







안드로이 폰을 들어서 보면 상단이 위로 향하게 되어  pitch값은 음수가 되고 이때 로봇에게 GO 명령을 줄 계획입니다..




이제 스마트폰을 게임플레이하던거 처럼 좌우로 기울이면 로봇에게 해당 방향으로 전진하도록 할 계획입니다...






AndroidManifest.xml파일에 다음 퍼미션 두 가지를 추가해주어야 합니다..


  1. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
  2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  




그리고 다음은 메인 레이아웃 XML파일입니다. 여기에서 사용한 img.png 파일은  res/drawable폴더에 넣어주셔야 합니다..아래 있는 삼각형 이미지입니다.




  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:padding="100dp"  
  7.     tools:context=".MainActivity" >  
  8.   
  9.     <LinearLayout  
  10.         android:orientation="vertical"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="match_parent">  
  13.   
  14.         <ImageView  
  15.             android:id="@+id/pointer"  
  16.             android:layout_width="match_parent"  
  17.             android:layout_height="100dp"  
  18.             android:src="@drawable/img" />  
  19.   
  20.         <TextView  
  21.             android:layout_width="match_parent"  
  22.             android:layout_height="wrap_content"  
  23.             android:text=""  
  24.             android:textSize="40sp"  
  25.             android:gravity="center"  
  26.             android:id="@+id/textView" />  
  27.   
  28.   
  29.         <TextView  
  30.             android:layout_width="wrap_content"  
  31.             android:layout_height="wrap_content"  
  32.             android:text="New Text"  
  33.             android:id="@+id/pitch" />  
  34.   
  35.         <TextView  
  36.             android:layout_width="wrap_content"  
  37.             android:layout_height="wrap_content"  
  38.             android:text="New Text"  
  39.             android:id="@+id/roll" />  
  40.   
  41.   
  42.   
  43.     </LinearLayout>  
  44.   
  45. </RelativeLayout>  




메인 액티비티 자바파일입니다.. 

  1. package com.tistory.webnautes.sensorexample;  
  2.   
  3.   
  4. import android.app.Activity;  
  5. import android.graphics.Color;  
  6. import android.hardware.Sensor;  
  7. import android.hardware.SensorEvent;  
  8. import android.hardware.SensorEventListener;  
  9. import android.hardware.SensorManager;  
  10. import android.os.Bundle;  
  11. import android.view.animation.Animation;  
  12. import android.view.animation.RotateAnimation;  
  13. import android.widget.ImageView;  
  14. import android.widget.TextView;  
  15.   
  16.   
  17.   
  18. public class MainActivity extends Activity implements SensorEventListener {  
  19.   
  20.     private ImageView mPointer;  
  21.     private SensorManager mSensorManager;  
  22.     private Sensor mAccelerometer;  
  23.     private Sensor mMagnetometer;  
  24.     private float[] mLastAccelerometer = new float[3];  
  25.     private float[] mLastMagnetometer = new float[3];  
  26.     private boolean mLastAccelerometerSet = false;  
  27.     private boolean mLastMagnetometerSet = false;  
  28.     private float mCurrentDegree = 0f;  
  29.     TextView pitchValue, rollValue;  
  30.     private TextView view;  
  31.   
  32.   
  33.   
  34.   
  35.   
  36.     @Override  
  37.     protected void onCreate(Bundle savedInstanceState){  
  38.         super.onCreate(savedInstanceState);  
  39.         setContentView(R.layout.activity_main);  
  40.   
  41.         view = (TextView) findViewById(R.id.textView);  
  42.         view.setBackgroundColor(Color.GREEN);  
  43.   
  44.   
  45.         mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);  
  46.         mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);  
  47.         mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);  
  48.         mPointer = (ImageView) findViewById(R.id.pointer);  
  49.   
  50.         pitchValue=(TextView) findViewById(R.id.pitch);  
  51.         rollValue = (TextView) findViewById(R.id.roll);  
  52.   
  53.   
  54.   
  55.   
  56.     }  
  57.   
  58.     @Override  
  59.     protected void onResume() {  
  60.         super.onResume();  
  61.   
  62.         mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);  
  63.         mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_UI);  
  64.   
  65.   
  66.   
  67.     }  
  68.   
  69.     @Override  
  70.     protected void onPause() {  
  71.         super.onPause();  
  72.         mSensorManager.unregisterListener(this, mAccelerometer);  
  73.         mSensorManager.unregisterListener(this, mMagnetometer);  
  74.   
  75.   
  76.     }  
  77.   
  78.   
  79.     public static float[] computeOrientation(float[] accel, float[] magnetic){  
  80.         float[] inR = new float[16];  
  81.         float[] I = new float[16];  
  82.         float[] outR = new float[16];  
  83.         float[] values = new float[3];  
  84.   
  85.         SensorManager.getRotationMatrix(inR, I, accel, magnetic);  
  86.         SensorManager.remapCoordinateSystem(inR, SensorManager.AXIS_X, SensorManager.AXIS_Y, outR);  
  87.         SensorManager.getOrientation(outR, values);  
  88.         return values;  
  89.     }  
  90.   
  91.   


  92.   
  93.     @Override  
  94.     public void onSensorChanged(SensorEvent event) {  
  95.         long lastComputedTime = 0;  
  96.   
  97.         if (event.sensor == mAccelerometer) {  
  98.   
  99.             System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);  
  100.             mLastAccelerometerSet = true;  
  101.   
  102.         } else if (event.sensor == mMagnetometer) {  
  103.   
  104.             System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);  
  105.             mLastMagnetometerSet = true;  
  106.         }  
  107.   
  108.   
  109.   
  110.         if (mLastAccelerometerSet &&mLastMagnetometerSet) {  
  111.   
  112.             long tempTime = System.currentTimeMillis();  
  113.             if(tempTime - lastComputedTime > 1000){  
  114.                 float[] orientationValues = computeOrientation(mLastAccelerometer, mLastMagnetometer);  
  115.   
  116.   
  117.                 int pitch = (int)((360 * orientationValues[1]) / (2 * Math.PI));  
  118.                 int roll = (int) ((360 * orientationValues[2]) / (2 * Math.PI));  
  119.   
  120.   
  121.                 //경사도  
  122.                 pitchValue.setText("pitch="+String.valueOf(pitch));  
  123.                 //좌우회전  
  124.                 rollValue.setText("roll="+String.valueOf(roll));  
  125.   
  126.   
  127.   
  128.                 RotateAnimation ra = new RotateAnimation(  
  129.                         mCurrentDegree,  
  130.                         roll,  
  131.                         Animation.RELATIVE_TO_SELF, 0.5f,  
  132.                         Animation.RELATIVE_TO_SELF,  
  133.                         0.5f);  
  134.   
  135.                 ra.setDuration(250);  
  136.                 ra.setFillAfter(true);  
  137.   
  138.                 mPointer.startAnimation(ra);  
  139.                 mCurrentDegree =roll;  
  140.   
  141.   
  142.                 if (pitch<0) {  
  143.                     view.setBackgroundColor(Color.GREEN);  
  144.                     view.setText("GO");  
  145.                 } else {  
  146.                     view.setBackgroundColor(Color.RED);  
  147.                     view.setText("STOP");  
  148.                 }  
  149.   
  150.             }  
  151.         }  
  152.   
  153.   
  154.     }  
  155.   
  156.     @Override  
  157.     public void onAccuracyChanged(Sensor sensor, int accuracy) {  
  158.         // TODO Auto-generated method stub  
  159.   
  160.     }  
  161.   
  162. }  




반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts