开发者

Android: Bluetooth Serial (Com Port) communication with Android Phone

I am trying to communicate with a Bluetooth programmable Microcontroller. The Bluetooth device on the microcontroller communicates (specifically) on Bluetooth Serial COM Port number 4.

QUESTION: How can I开发者_如何学C get the Android App to read data from this COM port (number 4)?

I know the UUID is a well known unique ID,that works for this device, but I don't think that it has anything to do with specifying the COM port.

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;
} }}


The COM port is something that exists only on the microcontroller, not the Bluetooth device attached to it. The Bluetooth device does not even know which COM port the microcontroller used to connect to it. The Bluetooth device's connection to the micro is via the TX and RX lines. The fact that they are attached to pins on the micro assigned to a specific COM port is irrelevant and unknown to the Bluetooth device.


I had this problem with a custom bluetooth device I built. Instead of using createRfcommSocketToServiceRecord in your connect thread, try something similar to the following:

    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));
    }

Where my mmDevice is your btDevice.

This forces a socket connection between the unknown device and the smartphone. From what I've heard, there's an issue in Android connecting "non-similar" devices. Worth a shot.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜