转载请注明出处。
这次是一个课程设计,利用单片机开发一个物联网系统。我们利用了手机蓝牙与单片机板子上的蓝牙通信,通过 控制信号来控制单片机上led灯的亮灭和定时。
网上有很多的搜索蓝牙的例程,大家可以自己去看,由于本次我们是与特定的设备连接,因此直接使用Mac地址连接,不在使用搜索功能,当然如果大家采用搜索到设备后在连接也可以。我们将蓝牙连接和数据收发放在一个service中,由于蓝牙socket读是阻塞的,因此我们新开一个线程专门用于接收板子的信号。
在service的onCreate()方法中,我们连接指定的蓝牙,并获得其io流,在新开一个线程用于socket读。
记得在mk文件中给该service添加intent-filter。
/**
* 服务初始化
*/
@Override
public void onCreate() {
// TODO 自动生成的方法存根
initBluetooth();
super.onCreate();
}
/**
* 初始化蓝牙适配器
*/
public void initBluetooth(){
bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter==null){//等于null时通知主界面,设备不支持蓝牙
Intent intent = new Intent();
intent.setAction(Constants.ERROR);
sendBroadcast(intent);
}else {
if(!bluetoothAdapter.isEnabled())//蓝牙未开启时,开启蓝牙
{
bluetoothAdapter.enable();
}
connectDevice();
}
}
/**
* 链接设备
*/
private void connectDevice(){
device = bluetoothAdapter.getRemoteDevice(Constants.ADDRESS);//输入要连接的蓝牙的Mac地址,在说明书上可以查到
if(device==null){//为空,连接失败
Intent intent = new Intent();
intent.setAction(Constants.ERROR);
sendBroadcast(intent);
}else {
try {
socket = device.createRfcommSocketToServiceRecord(Constants.MY_UUID);//uuid,一般为00001101-0000-1000-8000-00805F9B34FB
socket.connect();//获得socket接口
inputStream = socket.getInputStream();//获得输入流,另起线程监听输入
receiveThread = new ReceiveThread(inputStream);
new Thread(receiveThread).start();