10.12 Sensor Special (3) — Accelerometer/Gyroscope Sensor
Category Android Basic Tutorial
Introduction to This Section:
This section continues to explore the sensors in Android, focusing on the accelerometer sensor and the gyroscope sensor, which, like the orientation sensor from the previous section, have x, y, and z axes. It's important to note: the coordinates of the x and y axes must be distinguished from those in the drawing! The sensor's origin is at the lower left corner! x to the right, y upward! Alright, let's learn about the sensors in this section with our usual approach!
Additionally, I'd like to point out that we are not professionals in this field; we just write and play around, and have a look, so don't take many things too seriously!
PS: The orientation sensor actually uses the accelerometer and magnetic field sensor to obtain the direction, which has been deprecated since version 2.2~
1. Accelerometer Sensor
1) Concept:
>
The unit of the accelerometer sensor: acceleration (m/s^2)
The acceleration obtained by the orientation sensor is: the combined acceleration of the phone's motion and the gravitational acceleration (9.81m/s^2)
Additionally, gravitational acceleration is vertically downward!
The calculation of the combined acceleration in different directions seems quite complicated, so we won't dwell on it here! Let's first take a look at the three values in the value array of the accelerometer, which correspond to the accelerations on the X, Y, and Z axes, respectively! Alright, let's get a rough idea and write a simple pedometer to get familiar with its usage!
2). Implementation of a Simple Pedometer
Running Effect Picture :
Code Implementation :
Layout code: activity_main.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:text="Simple Pedometer"
android:textSize="25sp" />
<TextView
android:id="@+id/tv_step"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:text="0"
android:textColor="#DE5347"
android:textSize="100sp"
android:textStyle="bold" />
<Button
android:id="@+id/btn_start"
android:layout_width="match_parent"
android:layout_height="64dp"
android:text="Start"
android:textSize="25sp" />
</LinearLayout>
MainActivity.java :
public class MainActivity extends AppCompatActivity implements View.OnClickListener, SensorEventListener {
private SensorManager sManager;
private Sensor mSensorAccelerometer;
private TextView tv_step;
private Button btn_start;
private int step = 0; //Step count
private double oriValue = 0; //Original value
private double lstValue = 0; //Previous value
private double curValue = 0; //Current value
private boolean motiveState = true; //Whether in motion state
private boolean processState = false; //Flag to mark whether it is currently counting steps
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensorAccelerometer = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sManager.registerListener(this, mSensorAccelerometer, SensorManager.SENSOR_DELAY_UI);
bindViews();
}
private void bindViews() {
tv_step = (TextView) findViewById(R.id.tv_step);
btn_start = (Button) findViewById(R.id.btn_start);
btn_start.setOnClickListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
double range = 1; //Set an accuracy range
float[] value = event.values;
curValue = magnitude(value[0], value[1], value[2]); //Calculate the current magnitude
//Accelerating upward state
if (motiveState == true) {
if (curValue >= lstValue) lstValue = curValue;
else {
His three values are the angular velocities of rotation along the X-axis, Y-axis, and Z-axis, respectively. When the phone rotates counterclockwise, the angular velocity is positive; when it rotates clockwise, it is negative!
This is often used to calculate the angle the phone has rotated! This is a piece of code from the internet~
private static final float NS2S = 1.0f / 1000000000.0f; private float timestamp;
public void onSensorChanged(SensorEvent event) { if (timestamp != 0) { // event.timestamp represents the current time, in nanoseconds (one-millionth of a millisecond) final float dT = (event.timestamp - timestamp) * NS2S; angle[0] += event.values[0] * dT; angle[1] += event.values[1] * dT; angle[2] += event.values[2] * dT; } timestamp = event.timestamp; } ```
By using the time difference (dT) between two adjacent data acquisitions from the gyroscope sensor, the angles at which the phone rotates along the X, Y, and Z axes during this period are calculated separately, and the values are accumulated into different elements of the angle array.
3. Download the example code for this section:
Summary of this section:
>
Well, in this section, I briefly introduced the accelerometer and gyroscope to everyone and wrote a simple pedometer. I feel that I haven't played much with sensors and have nothing to write about, so let's just introduce the remaining sensors in the next section. Let's consider it as popular science, and delve into it later when needed.
-1.0.1 Latest Android Basic Tutorial Catalogue for 2015
-1.1 Background and System Architecture Analysis
-1.2 Setting up the Development Environment
-1.2.1 Developing Android Apps with Eclipse + ADT + SDK
-1.2.2 Developing Android Apps with Android Studio
-1.3 Solving SDK Update Issues
-1.4 Installing Genymotion Emulator
-1.5.1 Basic Operations of Git Local Repository
-1.5.2 Using GitHub with Git to Set Up a Remote Repository
-1.6 How to Play with 9 (Nine Sister) Images
-1.7 Interface Prototype Design
-1.8 Project-Related Analysis (Various Files, Resource Access)
-1.9 Android App Signing and Packaging
-1.11 Decompiling APK to Retrieve Code & Resources
-2.1 The Concept of View and ViewGroup
-2.2.1 LinearLayout (Linear Layout)
-2.2.2 RelativeLayout (Relative Layout)
-2.2.3 TableLayout (Table Layout)
-2.2.4 FrameLayout (Frame Layout)
-2.2.5 GridLayout (Grid Layout)
-2.2.6 AbsoluteLayout (Absolute Layout)
-2.3.1 TextView (Text Box) Detailed Explanation
-2.3.2 EditText (Input Box) Detailed Explanation
-2.3.3 Button (Button) and ImageButton (Image Button)
-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton (Toggle Button) and Switch (Switch)
-[2.3.7 ProgressBar (Progress Bar)](android-tutorial-
4.4.2 Further Exploration of ContentProvider - Document Provider
5.2.1 Detailed Explanation of Fragment Example - Implementation of Bottom Navigation Bar (Method 1)
5.2.2 Detailed Explanation of Fragment Example - Implementation of Bottom Navigation Bar (Method 2)
5.2.3 Detailed Explanation of Fragment Example - Implementation of Bottom Navigation Bar (Method 3)
5.2.4 Detailed Explanation of Fragment Example - Bottom Navigation Bar + ViewPager Page Switching
6.2 Data Storage and Access - Saving User Preferences with SharedPreferences
7.1.1 Things to Learn in Android Network Programming and Http Protocol Study
[8.2.2 OOM Issues Caused by Bitmap
10.12 Sensor Special (3) — Accelerometer/Gyroscope Sensors
11.0 "2015 Latest Android Basic Tutorial" Concludes with Fireworks~
12.2 DrySister Beauty Viewing App (First Edition) — 2. Parsing Backend Data
12.4 DrySister Beauty Viewing App (First Edition) — 4. Adding Data Caching (Integrating SQLite)