Android的蓝牙串口(Bluetooth SPP)使用

while (1)
{
     GPIOB_ODR &= 0xFFFFFFF0;
     Delay_Ms(500);
     USART1_Send_String( "Hello\n" );
     GPIOB_ODR |= 0x1;
     Delay_Ms(500);
     USART1_Send_String( "World\n" );
  }

USART1_Send_String是向串口发数据的函数,这段程序在做的是,每隔500ms发一次Hello和World,发的时候PB0上的LED toggle一下,十分简单。蓝牙透传模块用的是HC-06,单片机是STM32。
以下是Android上的代码,主要来自anddev.org的网友,注释很详细,就不再多解释了。原来的代码只演示了发送数据,增加了接受数据的演示代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package com.bt_spp;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
 
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class BT_sppActivity extends Activity {
     private static final String TAG = "THINBTCLIENT" ;
     private static final boolean D = true ;
     private BluetoothAdapter mBluetoothAdapter = null ;
     private BluetoothSocket btSocket = null ;
     private OutputStream outStream = null ;
     private InputStream inStream = null ;
     private Button btn_read = null ;
     // Well known SPP UUID (will *probably* map to
     // RFCOMM channel 1 (default) if not in use);
     // see comments in onResume().
     private static final UUID MY_UUID =
             UUID.fromString( "00001101-0000-1000-8000-00805F9B34FB" );
 
     // ==> hardcode your server's MAC address here
     private static String address = "00:11:09:18:00:54" ;
 
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.main);
         if (D)
             Log.e(TAG, "+++ ON CREATE +++" );
 
         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
         if (mBluetoothAdapter == null ) {
             Toast.makeText( this ,
                 "Bluetooth is not available." ,
                 Toast.LENGTH_LONG).show();
             finish();
             return ;
         }
 
         if (!mBluetoothAdapter.isEnabled()) {
             Toast.makeText( this ,
                 "Please enable your BT and re-run this program." ,
                 Toast.LENGTH_LONG).show();
             finish();
             return ;
         }
 
         if (D)
             Log.e(TAG, "+++ DONE IN ON CREATE, GOT LOCAL BT ADAPTER +++" );
         btn_read = (Button)findViewById(R.id.btn_read);
         btn_read.setOnClickListener( new Button.OnClickListener(){
 
             @Override
             public void onClick(View arg0) {
                 // TODO Auto-generated method stub
                 Log.i(TAG, "Reading" );
                 if (inStream!= null )
                 {
                     byte [] buff= new byte [ 1024 ];
                     try {
                         inStream.read(buff);
                         String str = new String(buff);
                         Log.i(TAG,str);
                     } catch (IOException e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                     }
 
                 }
             }});
     }
 
     @Override
     public void onStart() {
         super .onStart();
         if (D)
             Log.e(TAG, "++ ON START ++" );
     }
 
     @Override
     public void onResume() {
         super .onResume();
 
         if (D) {
             Log.e(TAG, "+ ON RESUME +" );
             Log.e(TAG, "+ ABOUT TO ATTEMPT CLIENT CONNECT +" );
         }
 
         // When this returns, it will 'know' about the server,
         // via it's MAC address.
         BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
 
         // We need two things before we can successfully connect
         // (authentication issues aside): a MAC address, which we
         // already have, and an RFCOMM channel.
         // Because RFCOMM channels (aka ports) are limited in
         // number, Android doesn't allow you to use them directly;
         // instead you request a RFCOMM mapping based on a service
         // ID. In our case, we will use the well-known SPP Service
         // ID. This ID is in UUID (GUID to you Microsofties)
         // format. Given the UUID, Android will handle the
         // mapping for you. Generally, this will return RFCOMM 1,
         // but not always; it depends what other BlueTooth services
         // are in use on your Android device.
         try {
             btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
         } catch (IOException e) {
             Log.e(TAG, "ON RESUME: Socket creation failed." , e);
         }
 
         // Discovery may be going on, e.g., if you're running a
         // 'scan for devices' search from your handset's Bluetooth
         // settings, so we call cancelDiscovery(). It doesn't hurt
         // to call it, but it might hurt not to... discovery is a
         // heavyweight process; you don't want it in progress when
         // a connection attempt is made.
         mBluetoothAdapter.cancelDiscovery();
 
         // Blocking connect, for a simple client nothing else can
         // happen until a successful connection is made, so we
         // don't care if it blocks.
         try {
             btSocket.connect();
             Log.e(TAG, "ON RESUME: BT connection established, data transfer link open." );
         } catch (IOException e) {
             try {
                 btSocket.close();
             } catch (IOException e2) {
                 Log.e(TAG,
                     "ON RESUME: Unable to close socket during connection failure" , e2);
             }
         }
 
         // Create a data stream so we can talk to server.
         if (D)
             Log.e(TAG, "+ ABOUT TO SAY SOMETHING TO SERVER +" );
 
         try {
             outStream = btSocket.getOutputStream();
             inStream = btSocket.getInputStream();
         } catch (IOException e) {
             Log.e(TAG, "ON RESUME: stream creation failed." , e);
         }
 
         String message = "Hello message from client to server." ;
         byte [] msgBuffer = message.getBytes();
         try {
             outStream.write(msgBuffer);
         } catch (IOException e) {
             Log.e(TAG, "ON RESUME: Exception during write." , e);
         }
     }
     @Override
     public void onPause() {
         super .onPause();
 
         if (D)
             Log.e(TAG, "- ON PAUSE -" );
 
         if (outStream != null ) {
             try {
                 outStream.flush();
             } catch (IOException e) {
                 Log.e(TAG, "ON PAUSE: Couldn't flush output stream." , e);
             }
         }
 
         try {
             btSocket.close();
         } catch (IOException e2) {
             Log.e(TAG, "ON PAUSE: Unable to close socket." , e2);
         }
     }
 
     @Override
     public void onStop() {
         super .onStop();
         if (D)
             Log.e(TAG, "-- ON STOP --" );
     }
 
     @Override
     public void onDestroy() {
         super .onDestroy();
         if (D)
             Log.e(TAG, "--- ON DESTROY ---" );
     }
}

http://billhsu.me/?p=118




你可能感兴趣的:(Android通信)