Android端 同 单片机 利用蓝牙模块的通信实现_第1页
Android端 同 单片机 利用蓝牙模块的通信实现_第2页
Android端 同 单片机 利用蓝牙模块的通信实现_第3页
Android端 同 单片机 利用蓝牙模块的通信实现_第4页
Android端 同 单片机 利用蓝牙模块的通信实现_第5页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Android端同单片机利用蓝牙模块的通信实现这次期末的课程设计做了一个智能灯光控制系统,系统整体的功能不在此赘述,系统主要是要实现下位机同上位机的通信,上位机选用的是Android手机端,下位机是52单片机,通过蓝牙模块实现通信。虽然系统很简单,但还是第一次完成的走完从下位机数据采集,数据传输,再到上位机的处理这个流程,故在这里做一个记录,也希望能够帮到有需要的人。一、下位机通信下位机选用的是52单片机,数据来自几个传感器,传感器采集到数据后通过串口发送到蓝牙模块,然后蓝牙模块发送到上位机。因代码量较大,所以只在这里贴出传输有关的函数。//利用串口发送一个字符voidSendOneByte(unsignedcharc){SBUF=c;while(!TI);TI=0;}//重写putchar函数,就可以直接调用printf()函数向串口发送数据,程序自动将printf()中的数据转换成char调用putchar发送charputchar(charch){ES=0;SBUF=ch;while(!TI);TI=0;ES=1;return0;}//初始化串口voidInitUART(){TMOD=0x20;PCON=0x00;SCON=0x50;TH1=0xFD;TL1=0xFD;TR1=1;ES=1;EA=1;}//串口中断voidUARTInterrupt()interrupt4{//RI为1则表示串口接收到数据if(RI){RI=0;r_buf=SBUF;//价格SBUF中的数据赋给r_buf,然后就可以对数据进行处理}}voidmain(){InitUART();while(1){}}二、蓝牙模块蓝牙模块我选用的是HC-05,这个模块我之前也没用使用过,查询了一些资料后就能够上手了,感觉还是很好用。模块有六个引脚,如果用的是带一个小按钮的HC-05,EN就不用接;然后VCC和GND分别接电源和地;TXD和RXD在配置AT指令的时候分别接单片机的TXD和RXD,但是在正常使用时,HC-05的TXD和RXD分别接单片机的RXD和TXD,这个需要注意;还有一个引脚是state,当有蓝牙连接的时候会置1,将其随意连接到单片机的引脚上。使用前先利用AT指令集配置模块,设置波特率和主从模式等,然后就可以连线使用。连接后蓝牙模块会进入快闪模式,进入AT指令集后会进入慢闪模式,当有蓝牙设备连接后会进入双闪模式。三、Android端程序Android端主要就是接受数据,做出一定处理,还需发送指令给单片机。我用的代码也是在网上找的然后又做了一些修改,源代码出处找不到了。主要代码如下:1、DeveiceListActivity类publicclassDeviceListActivityextendsActivity{//调试用privatestaticfinalStringTAG="DeviceListActivity";privatestaticfinalbooleanD=true;//返回时数据标签publicstaticStringEXTRA_DEVICE_ADDRESS="设备地址";//成员域privateBluetoothAdaptermBtAdapter;privateArrayAdapter<String>mPairedDevicesArrayAdapter;privateArrayAdapter<String>mNewDevicesArrayAdapter;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);//创建并显示窗口requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//设置窗口显示模式为窗口方式setContentView(R.layout.device_list);//设定默认返回值为取消setResult(Activity.RESULT_CANCELED);//设定扫描按键响应ButtonscanButton=(Button)findViewById(R.id.button_scan);scanButton.setOnClickListener(newOnClickListener(){publicvoidonClick(Viewv){doDiscovery();v.setVisibility(View.GONE);}});//初使化设备存储数组mPairedDevicesArrayAdapter=newArrayAdapter<String>(this,R.layout.device_name);mNewDevicesArrayAdapter=newArrayAdapter<String>(this,R.layout.device_name);//设置已配队设备列表ListViewpairedListView=(ListView)findViewById(R.id.paired_devices);pairedListView.setAdapter(mPairedDevicesArrayAdapter);pairedListView.setOnItemClickListener(mDeviceClickListener);//设置新查找设备列表ListViewnewDevicesListView=(ListView)findViewById(R.id.new_devices);newDevicesListView.setAdapter(mNewDevicesArrayAdapter);newDevicesListView.setOnItemClickListener(mDeviceClickListener);//注册接收查找到设备action接收器IntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);this.registerReceiver(mReceiver,filter);//注册查找结束action接收器filter=newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);this.registerReceiver(mReceiver,filter);//得到本地蓝牙mBtAdapter=BluetoothAdapter.getDefaultAdapter();}@OverrideprotectedvoidonDestroy(){super.onDestroy();//关闭服务查找if(mBtAdapter!=null){mBtAdapter.cancelDiscovery();}//注销action接收器this.unregisterReceiver(mReceiver);}publicvoidOnCancel(Viewv){finish();}/***开始服务和设备查找*/privatevoiddoDiscovery(){if(D)Log.d(TAG,"doDiscovery()");//在窗口显示查找中信息setProgressBarIndeterminateVisibility(true);setTitle("查找设备中...");//显示其它设备(未配对设备)列表findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);//关闭再进行的服务查找if(mBtAdapter.isDiscovering()){mBtAdapter.cancelDiscovery();}//并重新开始mBtAdapter.startDiscovery();}//选择设备响应函数privateOnItemClickListenermDeviceClickListener=newOnItemClickListener(){publicvoidonItemClick(AdapterView<?>av,Viewv,intarg2,longarg3){//准备连接设备,关闭服务查找mBtAdapter.cancelDiscovery();//得到mac地址Stringinfo=((TextView)v).getText().toString();Stringaddress=info.substring(info.length()-17);//设置返回数据Intentintent=newIntent();intent.putExtra(EXTRA_DEVICE_ADDRESS,address);//设置返回值并结束程序setResult(Activity.RESULT_OK,intent);finish();}};//查找到设备和搜索完成action监听器privatefinalBroadcastReceivermReceiver=newBroadcastReceiver(){@OverridepublicvoidonReceive(Contextcontext,Intentintent){Stringaction=intent.getAction();//查找到设备actionif(BluetoothDevice.ACTION_FOUND.equals(action)){//得到蓝牙设备BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//如果是已配对的则略过,已得到显示,其余的在添加到列表中进行显示if(device.getBondState()!=BluetoothDevice.BOND_BONDED){mNewDevicesArrayAdapter.add(device.getName()+"\n"+device.getAddress());}else{//添加到已配对设备列表mPairedDevicesArrayAdapter.add(device.getName()+"\n"+device.getAddress());}//搜索完成action}elseif(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){setProgressBarIndeterminateVisibility(false);setTitle("选择要连接的设备");if(mNewDevicesArrayAdapter.getCount()==0){StringnoDevices="没有找到新设备";mNewDevicesArrayAdapter.add(noDevices);}}}};}

2、Client类publicclassBTClientextendsActivity{privatefinalstaticintREQUEST_CONNECT_DEVICE=1;//宏定义查询设备句柄privatefinalstaticStringMY_UUID="00001101-0000-1000-8000-00805F9B34FB";//SPP服务UUID号privateInputStreamis;//输入流,用来接收蓝牙数据privateEditTextedit0;//发送数据输入句柄privateTextViewlightSwitch;privateTextViewlightStrength;privateTextViewlightMode;privateTextViewlightPower;privateStringswitchMsg="";privateStringstrengthMsg="";privateStringmodeMsg="";BluetoothDevice_device=null;//蓝牙设备BluetoothSocket_socket=null;//蓝牙通信socketbooleanbRun=true;booleanbThread=false;booleantimesign=false;privateBluetoothAdapter_bluetooth=BluetoothAdapter.getDefaultAdapter();//获取本地蓝牙适配器,即蓝牙设备/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);//设置画面为主画面main.xmledit0=(EditText)findViewById(R.id.Edit0);//得到输入框句柄lightSwitch=(TextView)findViewById(R.id.lightSwitch);lightStrength=(TextView)findViewById(R.id.lightStrength);lightMode=(TextView)findViewById(R.id.lightMode);lightPower=(TextView)findViewById(R.id.lightpower);lightSwitch.setText("关闭");lightStrength.setText("8");lightMode.setText("时间调节模式");lightPower.setText("无数据");//如果打开本地蓝牙设备不成功,提示信息,结束程序if(_bluetooth==null){Toast.makeText(this,"无法打开手机蓝牙,请确认手机是否有蓝牙功能!",Toast.LENGTH_LONG).show();finish();return;}//设置设备可以被搜索newThread(){publicvoidrun(){if(_bluetooth.isEnabled()==false){_bluetooth.enable();}}}.start();}//发送按键响应publicvoidonSendButtonClicked(Viewv){try{OutputStreamos=_socket.getOutputStream();//蓝牙连接输出流modeMsg=edit0.getText().toString();if(modeMsg.equals("1")||modeMsg.equals("2")||modeMsg.equals("3")){if(modeMsg.equals("1")){lightMode.setText("手动调节模式");lightPower.setText("无数据");timesign=false;}elseif(modeMsg.equals("2")){lightMode.setText("自动调节模式");timesign=false;}elseif(modeMsg.equals("3")){lightMode.setText("时间调节模式");lightPower.setText("无数据");}}if(timesign){finalinttimec=Integer.valueOf(modeMsg).intValue()*1000;//CountDownTimercdt=newCountDownTimer(timec,timec){//@Override//publicvoidonTick(longmillisUntilFinished){//}////@Override//publicvoidonFinish(){//edit0.setText("3");//}//};//cdt.start();try{Thread.currentThread().sleep(timec);}catch(InterruptedExceptione){e.printStackTrace();}edit0.setText("3");}if(modeMsg.equals("3")&&!timesign)timesign=true;byte[]bos=edit0.getText().toString().getBytes();edit0.setText("");os.write(bos);}catch(IOExceptione){}}//接收活动结果,响应startActivityForResult()publicvoidonActivityResult(intrequestCode,intresultCode,Intentdata){switch(requestCode){caseREQUEST_CONNECT_DEVICE://连接结果,由DeviceListActivity设置返回//响应返回结果if(resultCode==Activity.RESULT_OK){//连接成功,由DeviceListActivity设置返回//MAC地址,由DeviceListActivity设置返回Stringaddress=data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);//得到蓝牙设备_device=_bluetooth.getRemoteDevice(address);//用服务号得到sockettry{_socket=_device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));}catch(IOExceptione){Toast.makeText(this,"连接失败!",Toast.LENGTH_SHORT).show();}//连接socketButtonbtn=(Button)findViewById(R.id.Button03);try{_socket.connect();Toast.makeText(this,"连接"+_device.getName()+"成功!",Toast.LENGTH_SHORT).show();btn.setText("断开");}catch(IOExceptione){try{Toast.makeText(this,"连接失败!",Toast.LENGTH_SHORT).show();_socket.close();_socket=null;}catch(IOExceptionee){Toast.makeText(this,"连接失败!",Toast.LENGTH_SHORT).show();}return;}//打开接收线程try{is=_socket.getInputStream();//得到蓝牙数据输入流}catch(IOExceptione){Toast.makeText(this,"接收数据失败!",Toast.LENGTH_SHORT).show();return;}if(bThread==false){ReadThread.start();bThread=true;}else{bRun=true;}}break;default:break;}}//接收数据线程ThreadReadThread=newThread(){publicvoidrun(){intnum=0;byte[]buffer=newbyte[1024];bRun=true;//接收线程while(true){try{while(is.available()==0){while(bRun==false){}}while(true){num=is.read(buffer);//读入数据Strings=newString(buffer,0,num);switchMsg=s;strengthMsg=s;if

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论