開發手機與單片機通過藍芽模組

來源:互聯網
上載者:User

標籤:length   margin   tag   mini   not   finish   字串   之間   return   

1.xml布局檔案

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">

<Button
android:id="@+id/btnF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="前進"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="119dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"></Button>

<Button
android:id="@+id/btnL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="左轉"
app:layout_constraintBaseline_toBaselineOf="@+id/btnS"
tools:layout_constraintBaseline_creator="1"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="16dp"></Button>

<Button
android:id="@+id/btnR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="右轉"
tools:layout_constraintRight_creator="1"
android:layout_marginEnd="6dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBaseline_toBaselineOf="@+id/btnS"
tools:layout_constraintBaseline_creator="1"
android:layout_marginRight="6dp"></Button>

<Button
android:id="@+id/btnB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="後退"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="@+id/btnS"
android:layout_marginTop="58dp"
app:layout_constraintTop_toBottomOf="@+id/btnS"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="@+id/btnS"></Button>

<Button
android:id="@+id/btnS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="@+id/btnF"
android:layout_marginTop="64dp"
app:layout_constraintTop_toBottomOf="@+id/btnF"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="@+id/btnF"></Button>
</android.support.constraint.ConstraintLayout>

2.MainActivity
package com.example.administrator.bluetooth_cmd;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "THINBTCLIENT";

private static final boolean D = true;

private BluetoothAdapter mBluetoothAdapter = null;

private BluetoothSocket btSocket = null; //手機藍芽與藍芽模組之間的socket

private OutputStream outStream = null; //發送指令的輸出資料流
Button mButtonF;


Button mButtonB;
Button mButtonL;
Button mButtonR;
Button mButtonS;

private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");


private static String address = "00:0C:BF:09:4A:4A"; // <==要串連的藍牙裝置MAC地址


/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

btn_function();
init_bluetooth();
}
private void btn_function() {
//前進
mButtonF = (Button) findViewById(R.id.btnF);
mButtonF.setOnTouchListener(new Button.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
String message;
byte[] msgBuffer;
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN: //按下了前進按鈕
try {
outStream = btSocket.getOutputStream(); //通過socket 得到輸出資料流

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}


message = "1"; //上位機與下位機約定的指令1表示前進

msgBuffer = message.getBytes(); //因為outputStream 只能傳輸位元組,所以要把字串指令編程位元組流

try {
outStream.write(msgBuffer); //將指令寫入輸出資料流中。也就是寫入socket中

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
break;

case MotionEvent.ACTION_UP: //鬆開了前進按鈕,與前面類似,只是指令不同。
try {
outStream = btSocket.getOutputStream();

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}


message = "0";

msgBuffer = message.getBytes();

try {
outStream.write(msgBuffer);

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
break;
}
return false;
}


});
//後退
mButtonB = (Button) findViewById(R.id.btnB);
mButtonB.setOnTouchListener(new Button.OnTouchListener() {


@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
String message;
byte[] msgBuffer;
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
try {
outStream = btSocket.getOutputStream();

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}


message = "3";

msgBuffer = message.getBytes();

try {
outStream.write(msgBuffer);

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
break;

case MotionEvent.ACTION_UP:
try {
outStream = btSocket.getOutputStream();

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}


message = "0";

msgBuffer = message.getBytes();

try {
outStream.write(msgBuffer);

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
break;
}

return false;
}


});
//左轉
mButtonL = (Button) findViewById(R.id.btnL);
mButtonL.setOnTouchListener(new Button.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
String message;
byte[] msgBuffer;
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
try {
outStream = btSocket.getOutputStream();

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}


message = "2";

msgBuffer = message.getBytes();

try {
outStream.write(msgBuffer);

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
break;

case MotionEvent.ACTION_UP:
try {
outStream = btSocket.getOutputStream();

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}


message = "0";

msgBuffer = message.getBytes();

try {
outStream.write(msgBuffer);

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
break;
}

return false;

}
});
//右轉
mButtonR = (Button) findViewById(R.id.btnR);
mButtonR.setOnTouchListener(new Button.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
String message;
byte[] msgBuffer;
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
try {
outStream = btSocket.getOutputStream();

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}


message = "4";

msgBuffer = message.getBytes();

try {
outStream.write(msgBuffer);

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
break;

case MotionEvent.ACTION_UP:
try {
outStream = btSocket.getOutputStream();

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}


message = "0";

msgBuffer = message.getBytes();

try {
outStream.write(msgBuffer);

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
break;
}

return false;

}


});

//停止
mButtonS = (Button) findViewById(R.id.btnS);
mButtonS.setOnTouchListener(new Button.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN)
try {
outStream = btSocket.getOutputStream();

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}


String message = "0";

byte[] msgBuffer = message.getBytes();

try {
outStream.write(msgBuffer);

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
return false;
}

});
}
private void init_bluetooth()
{
if (D)Log.e(TAG, "+++ ON CREATE +++");

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available.", Toast.LENGTH_LONG).show();
//finish();
return;
}


if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(this, "Please enable your Bluetooth and re-run this program.", Toast.LENGTH_LONG).show();
finish();
return;

}


if (D)
Log.e(TAG, "+++ DONE IN ON CREATE, GOT LOCAL BT ADAPTER +++");

}


@Override

public void onStart() {

super.onStart();

if (D) Log.e(TAG, "++ ON START ++");
}


@Override

public void onResume() {

super.onResume();
if (D) {
Log.e(TAG, "+ ON RESUME +");
Log.e(TAG, "+ ABOUT TO ATTEMPT CLIENT CONNECT +");

}

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

try {

btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);

} catch (IOException e) {

Log.e(TAG, "ON RESUME: Socket creation failed.", e);

}
mBluetoothAdapter.cancelDiscovery();
try {

btSocket.connect();

Log.e(TAG, "ON RESUME: BT connection established, data transfer link open.");

} catch (IOException e) {

try {
btSocket.close();

} catch (IOException e2) {

Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
}

}


// Create a data stream so we can talk to server.

if (D)
Log.e(TAG, "+ ABOUT TO SAY SOMETHING TO SERVER +");
/* try {
outStream = btSocket.getOutputStream();

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
}


String message = "1";

byte[] msgBuffer = message.getBytes();

try {
outStream.write(msgBuffer);

} catch (IOException e) {
Log.e(TAG, "ON RESUME: Exception during write.", e);
}
*/

}


@Override

public void onPause() {

super.onPause();


if (D)
Log.e(TAG, "- ON PAUSE -");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
Log.e(TAG, "ON PAUSE: Couldn‘t flush output stream.", e);
}

}


try {
btSocket.close();
} catch (IOException e2) {
Log.e(TAG, "ON PAUSE: Unable to close socket.", e2);
}

}


@Override

public void onStop() {

super.onStop();

if (D)Log.e(TAG, "-- ON STOP --");

}


@Override

public void onDestroy() {

super.onDestroy();

if (D) Log.e(TAG, "--- ON DESTROY ---");

}
}
3.修改手機許可權manifest.XML
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
4.效果

 

 

開發手機與單片機通過藍芽模組

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.