2011-02-19 100 views
2

我正在嘗試與藍牙可編程微控制器進行通信。微控制器上的藍牙設備與藍牙串行COM端口號4進行通信(具體)。Android:與Android手機進行藍牙串行(Com端口)通信

問題:如何讓Android應用程序從此COM端口(編號4)讀取數據?

我知道UUID是一個衆所周知的唯一ID,它適用於此設備,但我認爲它與指定COM端口沒有任何關係。

static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 
btSocket = btDevice.createRfcommSocketToServiceRecord(myUUID); 
btSocket.connect(); 
valid.append(btDevice.getName() + "\n" + btDevice.getAddress()); 
north.append("Socket Connected"); 
InputStream mmInStream = btSocket.getInputStream(); 
OutputStream mmOutStream = btSocket.getOutputStream(); 
byte[] buffer = new byte[10]; 
int bytes; 
StringBuffer str = new StringBuffer(); 
while (true)       {        
    try { 
    mmOutStream.write("a".getBytes()); 

     //Reads a # of bytes until the end of stream is reached 
     bytes = mmInStream.read(buffer); 
     //Transform to string 
       str.append(buffer.toString()+"\t");       //Clear the buffer 
     Log.e("DATA", "THE DATA: "+ str.toString()); 
     south.setText(str.toString()); 
     str.delete(0,str.length()); 
     } catch (IOException e) { 
     break; 
} }} 

回答

1

我有我自己的一個自定義藍牙設備的這個問題。相反,在你的連接線採用createRfcommSocketToServiceRecord,儘量類似以下的東西:

public ConnectThread(BluetoothDevice device) throws 
     SecurityException, NoSuchMethodException, IllegalArgumentException, 
      IllegalAccessException, InvocationTargetException { 
      mmDevice = device; 
      BluetoothSocket tmp = null; 

      // Force a BluetoothSocket for a connection with the 
      // given BluetoothDevice 

      Method m = mmDevice.getClass().getMethod("createRfcommSocket", 
          new Class[]{int.class}); 

     mmSocket = (BluetoothSocket)m.invoke(mmDevice, Integer.valueOf(1)); 
    } 

凡我mmDevice是你btDevice。

這會強制未知設備和智能手機之間的套接字連接。據我所知,Android在連接「非相似」設備時存在一個問題。值得一試。

3

COM端口只存在於微控制器上,而不是連接到它的藍牙設備。藍牙設備甚至不知道微控制器使用哪個COM端口連接它。藍牙設備與微型設備的連接通過TX和RX線路進行。它們連接到分配給特定COM端口的微引腳的事實對於藍牙設備來說是不相關的和未知的。

相關問題