1. 程式人生 > >開發手機與單片機通過藍牙模塊

開發手機與單片機通過藍牙模塊

out write bluetooth transfer local .com mission sta info

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.效果
技術分享圖片

 

開發手機與單片機通過藍牙模塊