开发手机与单片机通过蓝牙模块

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.效果
 

原文地址:https://www.cnblogs.com/zengke556/p/9350187.html

时间: 2024-10-12 17:05:10

开发手机与单片机通过蓝牙模块的相关文章

Bluetooth篇 开发实例之九 和蓝牙模块通信

首先,我们要去连接蓝牙模块,那么,我们只要写客户端的程序就好了,蓝牙模块就相当于服务端. 连接就需要UUID. #蓝牙串口服务SerialPortServiceClass_UUID = ‘{00001101-0000-1000-8000-00805F9B34FB}’ 第一步: 首先要连接设备.这个参考Android Developer的例子来写:Android Developer -- Bluetooth篇 开发实例之二 连接设备 private class ConnectThread exte

【三星Cortex-A9开发板】iTOP-4412开发板暑期送WIFI/蓝牙模块

详情请进入淘宝官方网店了解:http://arm-board.taobao.com QQ咨询:2551456065 电话咨询:010-58957586

Android蓝牙实例(和单片机蓝牙模块通信)

最近做毕设,需要写一个简单的蓝牙APP进行交互,在网上也找了很多资料,终于给搞定了,这里分享一下^_^. 1.Android蓝牙编程 蓝牙3.0及以下版本编程需要使用UUID,UUID是通用唯一识别码(Universally Unique Identifier),这是一个软件构建的标准,也是被开源基金会组织应用在分布式计算环境领域的一部分.在蓝牙3.0及下一版本中,UUID被用于唯一标识一个服务,比如文件传输服务,串口服务.打印机服务等,如下: #蓝牙串口服务 SerialPortService

51单片机蓝牙模块

51单片机的蓝牙模块,是在蓝牙通讯的基础上,进行蓝牙51模块与外部蓝牙发射接收设备之间,相互收发数据.并且其引脚为VCC,GND,TXD,RXD,可以通过串口通信与外部上位机或单片机通信. 代码如下(注意蓝牙模块是5V供电) #include<reg52.h> void init();void delay(unsigned int ms); unsigned char input;void display(unsigned char num_decimal);unsigned char cod

BLK-MD-BC04-B蓝牙模块开发说明

BLK-MD-BC04-B蓝牙模块开发说明 日期:2011-9-24?浏览次数:4178 ? ? BLK-MD-BC04-B蓝牙通信模块, BLK-MD-BC04-B蓝牙通信模块?为本公司自主开发的智能型无线数据传输产品,高灵敏性接收,低成本,体积小巧,低功耗,用于蓝牙的数据传输领域. BlueCore4-Ext芯片,完全兼容蓝牙2.0规范 Uart接口,支持1200bps~2764800bps等多种波特率 支持SPP协议最高可支持3M调制模式 外围IO口通信 内建8M Flash可视及对等条件

【转】android蓝牙开发---与蓝牙模块进行通信--不错

原文网址:http://www.cnblogs.com/wenjiang/p/3200138.html 近半个月来一直在搞android蓝牙这方面,主要是项目需要与蓝牙模块进行通信.开头的进展很顺利,但因为蓝牙模块不在我这里,所以只能用手机测试.一开头就发现手机的蓝牙不能用,为了证明这点,我刷了四次不同不同系统的官方包,正式宣布手机的蓝牙报销了,于是和朋友换手机.在测试的过程中也是非常痛苦,放假了,同学都几乎回家了,剩下的同学中竟然80%都是用非android手机!我和我的小伙伴都吓呆了!!就算

微信小程序蓝牙模块BLE开发说明基础知识

微信小程序蓝牙模块说明 一.简介 微信小程序作为轻量级应用的载体,确实方便了很多的应用场景.传统的产品如果要和手机互联互通,那么必须要开发两套APP,即IOS和安卓.十分的麻烦和成本巨高.但是微信小程序的出现大大的提升了效果.因为微信小程序有两个巨大的特点和优势 1.跨平台    --- 不用单独的去开发安卓和IOS的APP,只用借助微信小程序的API即可 2.依托于微信--- 微信这个常驻手机的核心APP之一 这里我们主要是说明,微信小程序和蓝牙之间的关系: 二.微信小程序关于蓝牙API 1.

蓝牙模块与手机通信

1.通信前必须具备东西: (1)  蓝牙串口模块: (2)  安卓系统并带有蓝牙的手机: (3)  串口调试软件: (4)  蓝牙测试软件: 配置蓝牙串口模块: 这里把蓝牙串口模块配置成从机模式,具体设置过程如下: (1)  让蓝牙串口模块进入命令设置状态,具体操作是:按着模块上唯一的按键不放,用USB接口给模块上电,这时正确的情景是模块上的LED灯是长亮几秒后熄灭再循环的.如果出现灯快速闪烁的情况,证明模块并未进入命令设置状态,断电重复上述操作即可. (2)  将模块通过串口线与电脑连接:成功

Arduino使用HC05蓝牙模块与手机连接

Arduino使用HC05蓝牙模块与手机连接 一切都是最好的选择 首先是线路连接,一定不要接错了 Arduino 代码 #include <SoftwareSerial.h> // Pin10为RX,接HC05的TXD // Pin11为TX,接HC05的RXD SoftwareSerial BT(10, 11); char val; void setup() { Serial.begin(38400); Serial.println("BT is ready!"); //