连接 蓝牙HC - 05 模块 读写操作

连接 蓝牙HC - 05 模块 进行读写操作


1. 开启蓝牙进行连接

    //藍牙
    private BluetoothAdapter bluetoothAdapter;
    private Set<BluetoothDevice> pairedDevices;
    private static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    
    private OutputStream mmOutStream;
    private InputStream mmInStream;
    private BluetoothSocket mmSocket;
    private byte[] mmBuffer; // mmBuffer store for the stream
 //建立蓝牙连接
    public void on() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mmSocket = null;

        if (!bluetoothAdapter.isEnabled()) {
            Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOn, 0);
            Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
        }
    }

2. 建立sockat通道

 
        try {
            String name = "CONNECTED";
            byte[] bytes = name.getBytes();
            mmOutStream.write(bytes);
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "Connecting...", Toast.LENGTH_LONG).show();
            connector();
        }
  

connector方法


    /**
     * 初始化文件流 开启Socket连接
     */
    public void connector() {

        OutputStream tmpOut = null;
        InputStream tmpIn = null;

        // Get list of paired devices

        BluetoothSocket tmp = null;

        String dname;


        pairedDevices = bluetoothAdapter.getBondedDevices();
        BluetoothDevice device = null;
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice bt : pairedDevices) {
                Log.d("TAG name", "已连接:" + bt.getName());
                dname = bt.getName();
                if (dname.equals("HC-05")) {
                    textinfo1.setText("设备名:" + dname);
                    textinfo2.setText("地址:" + bt.getAddress());
                    device = bt;
                    Log.d("TAG", "HC-05设备已读取到!!!");
                    Toast.makeText(getApplicationContext(), "HC-05设备已读取到!!!" + device.getName(), Toast.LENGTH_LONG).show();
                } else {
                    Log.d("TAG", "HC-05 设备未读取到");
                }

            }

            try {
                // MY_UUID is the app's UUID string, also used by the client code.
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);

            } catch (IOException e) {
                Log.d("TAG", "Socket's listen() method failed", e);
                Toast.makeText(getApplicationContext(), "Error 1 Socket连接失败", Toast.LENGTH_LONG).show();
            }
            mmSocket = tmp;

            bluetoothAdapter.cancelDiscovery();

            try {
                // Connect to the remote device through the socket. This call blocks
                // until it succeeds or throws an exception.
                mmSocket.connect();

                Log.d("TAG", "Socket connected!!!!!");
                Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
            } catch (IOException connectException) {

            }

            try {
                tmpIn = mmSocket.getInputStream();
            } catch (IOException e) {
                Log.e(TAG, "Error occurred when creating input stream", e);
            }


            try {
                tmpOut = mmSocket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "Error occurred when creating output stream", e);
                Toast.makeText(getApplicationContext(), "Error 2", Toast.LENGTH_LONG).show();
            }

            mmOutStream = tmpOut;
            mmInStream = tmpIn;


        } else {
            Log.d("TAG", "No devices");
            Toast.makeText(getApplicationContext(), "HC-05 is not pared", Toast.LENGTH_LONG).show();
        }


    }

3. 写入数据

/**
     * 写入数据
     *
     * @param v
     */
    public void write(View v) {

        String name =“要发送的数据”; 
        byte[] bytes = name.getBytes();
        Log.e("TAG", "bytes : " + name);
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
             Toast.makeText(getApplicationContext(), "发送失败", Toast.LENGTH_LONG).show();
        }

    }

4. 接受数据

/**
     * 接受数据
     */
    Thread th = new Thread(new Runnable() {
        public void run() {


            mmBuffer = new byte[4096];
            int numBytes;

             while (true) {
                try {
                    if (mmInStream.available() > 2) {
                        Log.d("TAG", "数据正常:" + "mmInStream.available()>2 ");
                        // Read from the InputStream.
                        numBytes = mmInStream.read(mmBuffer);

                        final String readMessage = new String(mmBuffer, 0, numBytes);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textViewInfo.setText(readMessage);
                            }
                        });
                        Log.d("TAG", "readMessage:" + readMessage);
                    } else {
                        SystemClock.sleep(100);
                        Log.d("TAG", "No Data");
                    }

                } catch (IOException e) {
                    Log.d("TAG", "连接中断,流断开", e);
                    break;
                }
            }

        }
    });


5. 关闭连接

    public void off(View v) {
        bluetoothAdapter.disable();
        Toast.makeText(getApplicationContext(), "关闭连接", Toast.LENGTH_LONG).show();
    }

PS:蓝牙权限自己处理

在Android Studio中连接HC-05蓝牙模块,需要使用Android的蓝牙API和串口通信协议,具体步骤如下: 1. 在AndroidManifest.xml文件中添加蓝牙权限: ```xml <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> ``` 2. 在应用程序中使用BluetoothAdapter类来获取本地蓝牙适配器: ```java BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); ``` 3. 使用BluetoothAdapter对象来搜索HC-05蓝牙模块: ```java bluetoothAdapter.startDiscovery(); ``` 4. 连接HC-05蓝牙模块。首先需要获取HC-05蓝牙模块的MAC地址,然后使用BluetoothDevice类来连接蓝牙模块: ```java String mac = "00:11:22:33:44:55"; // HC-05蓝牙模块的MAC地址 BluetoothDevice device = bluetoothAdapter.getRemoteDevice(mac); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); socket.connect(); ``` 其中,uuidHC-05蓝牙模块服务的UUID,可以在HC-05模块的说明书中找到。 5. 使用IO流进行数据的传输和通信。可以使用InputStream和OutputStream来进行数据的读写操作: ```java InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); byte[] buffer = new byte[1024]; int bytes; bytes = inputStream.read(buffer); outputStream.write(buffer, 0, bytes); ``` 6. 最后,在应用程序退出时需要关闭蓝牙连接: ```java socket.close(); ``` 以上是Android Studio连接HC-05蓝牙模块的基本步骤,具体的实现过程需要根据应用程序的需求和实际情况进行相应的调整和修改。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值