手机通过蓝牙连接Matlab-数据互传

手机通过蓝牙连接Matlab-数据互传

测试使用的是手机端蓝牙串口模式与电脑端Matlab连接。
使用串口可实现数据透传,方便自行设计更上层的协议。
Matlab端底层使用了BlueCove-2.1.1-SNAPSHOT.jar这个jar包,作为整个socket连接的client端,主动去连接手机蓝牙;手机端,配置Android开发环境,编写了整个socket连接的server端,等待电脑端连接。
但使用BlueCove-2.1.1-SNAPSHOT.jar时,主动连接时需要输入channel端口号(可能是这个jar包太久远了,又没新的jar包出现),而安卓手机端现在用UUID来标识每个连接了。通过测试,串口UUID=“00001101-0000-1000-8000-00805F9B34FB”时,channel端口号为8(手机设备状态不同,channel号可能也不相同。通过不完全的蓝牙协议阅读,不同channel上运行不同服务,比如channel 2上是连个设备配对的服务,从channel 0试到channel 8后连接成功)双方连接成功。

Matlab端配置:

先手动打开电脑端蓝牙

  1. 1、 使用instrhwinfo(‘Bluetooth’)命令查看周围可查找到的蓝牙设备。比较新的蓝牙有低功耗模式,开启时间长后容易搜索不到,建议重启下蓝牙再搜索。该命令返回周围蓝牙设备信息。同时使用instrhwinfo(‘Bluetooth’,DeviceName),加入想要连接的设备名称后可以看相应名称的蓝牙设备信息。
    Fig1.蓝牙设备信息

  2. Bluetooth()函数:
    B = Bluetooth(‘RemoteName’, Channel)
    B = Bluetooth(‘RemoteID’, Channel)
    B = Bluetooth(‘RemoteID’, Channel, ‘P1’,V1,‘P2’,V2,…)
    该函数返回一个bluetooth对象,'RemoteName’为要连接的手机端蓝牙名称,'RemoteID’与手机端的蓝牙MAC地址相关。

  3. fopen(B)传入得到的Bluetooth对象,打开连接。相应fclose(B)为关掉相应连接。

  4. fwrite(B,data,‘uchar’)打开连接后,可使用fwrite()向手机端发送信息,B为Bluetooth对象,data为待发送数据,‘uchar’数据格式。使用fgets(B)函数,可以从手机端接收数据,B为相应Bluetooth对象,fgets()函数阻塞相应线程,一直等到一次数据传送到来。

测试

Matlab端代码:
B=Bluetooth(‘LCK’,8);
fopen(B);
fgets(B)
Matlab端代码
手机端
手机端

手机端主要代码

展出主要代码,仅供参考。后续将整个工程放在CSDN上以供下载。

// An highlighted block
package com.example.lck.test;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {
   

    public BluetoothAdapter mBluetoothAdapter = null;
    AcceptThread acceptThread;
    ConnectThread connectThread;
    TextView textView;
    Button button;
    EditText editText;
    public boolean is_bluetooth_opened = 
  • 3
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值