




下載本文檔
版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
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
提交評論