简体   繁体   中英

Communication Bluetooth android-arduino

I have modified the android app "Bluetooth Chat" that you can find in android sdk examples version 2.1 The app estabilished a bluetooth connection with arduino, and, when with the app I send 0 or 1, arduino send a simple message "You have pressed 0 or 1". It works if I test with eclipse's debug, but when I test with my smartphone, the result in the display is different, arduino's string is fragmented

example: smartphone: 0 -> arduino "You have pressed 0 or 1" smartphone display: "y" "ou pr"

The rest of the string was lost or not shown in the display. Can you help me? No error in logcat, only this bug.

This is the code:

public class BluetoothLampService {
    // Debugging
    private static final String TAG = "BluetoothLampService";
    private static final boolean D = true;

    // Name for the SDP record when creating server socket
    private static final String NAME = "BluetoothLamp";

    // Unique UUID for this application - Standard SerialPortService ID
   private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");



    // Member fields
    private final BluetoothAdapter Adapter;
    private final Handler Handler;
 //   private AcceptThread AcceptThread;
    private ConnectThread ConnectThread;
    private ConnectedThread ConnectedThread;
    private int State;

    // Constants that indicate the current connection state
    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device

    /**
     * Constructor. Prepares a new BluetoothChat session.
     * @param context  The UI Activity Context
     * @param handler  A Handler to  messages back to the UI Activity
     */
    public BluetoothLampService(Context context, Handler handler) {
        Adapter = BluetoothAdapter.getDefaultAdapter();
        State = STATE_NONE;
        Handler = handler;
    }

    /**
     * Set the current state of the chat connection
     * @param state  An integer defining the current connection state
     */
    private synchronized void setState(int state) {
         State = state;

        // Give the new state to the Handler so the UI Activity can update
        Handler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }

    /**
     * Return the current connection state. */
    public synchronized int getState() {
        return State;
    }

    /**
     * Start the chat service. Specifically start AcceptThread to begin a
     * session in listening (server) mode. Called by the Activity onResume() */
    public synchronized void start() {

        // Cancel any thread attempting to make a connection
        if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}

        // Cancel any thread currently running a connection
        if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}

        // Start the thread to listen on a BluetoothServerSocket
 //       if (AcceptThread == null) {
 //           AcceptThread = new AcceptThread();
 //           AcceptThread.start();
  //      }
        setState(STATE_LISTEN);
    }

    /**
     * Start the ConnectThread to initiate a connection to a remote device.
     * @param device  The BluetoothDevice to connect
     */
    public synchronized void connect(BluetoothDevice device) {

        // Cancel any thread attempting to make a connection
        if (State == STATE_CONNECTING) {
            if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
        }

        // Cancel any thread currently running a connection
        if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}

        // Start the thread to connect with the given device
        ConnectThread = new ConnectThread(device);
        ConnectThread.start();
        setState(STATE_CONNECTING);
    }

    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {

        // Cancel the thread that completed the connection
        if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}

        // Cancel any thread currently running a connection
        if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}

        // Cancel the accept thread because we only want to connect to one device
 //       if (AcceptThread != null) {AcceptThread.cancel(); AcceptThread = null;}

        // Start the thread to manage the connection and perform transmissions
        ConnectedThread = new ConnectedThread(socket);
        ConnectedThread.start();

        // Send the name of the connected device back to the UI Activity
        Message msg = Handler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(MainActivity.DEVICE_NAME, device.getName());
        msg.setData(bundle);
        Handler.sendMessage(msg);

        setState(STATE_CONNECTED);
    }

    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
        if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
   //     if (AcceptThread != null) {AcceptThread.cancel(); AcceptThread = null;}
        setState(STATE_NONE);
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (State != STATE_CONNECTED) return;
            r = ConnectedThread;
        }
        // Perform the write unsynchronized
         r.write(out);
    }

    /**
     * Indicate that the connection attempt failed and notify the UI Activity.
     */
    private void connectionFailed() {
        setState(STATE_LISTEN);

        // Send a failure message back to the Activity
        Message msg = Handler.obtainMessage(MainActivity.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(MainActivity.TOAST, "Unable to connect device");
        msg.setData(bundle);
        Handler.sendMessage(msg);
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
        setState(STATE_LISTEN);

        // Send a failure message back to the Activity
        Message msg = Handler.obtainMessage(MainActivity.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(MainActivity.TOAST, "Device connection was lost");
        msg.setData(bundle);
        Handler.sendMessage(msg);
    }

    /**
     * This thread runs while listening for incoming connections. It behaves
     * like a server-side client. It runs until a connection is accepted
     * (or until cancelled).
     */
    /*
    private class AcceptThread extends Thread {
        // The local server socket
        private final BluetoothServerSocket ServerSocket;

        public AcceptThread() {
            BluetoothServerSocket tmp = null;

            // Create a new listening server socket
            try {
                tmp = Adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (IOException e) {
                }
            ServerSocket = tmp;
        }

        public void run() {
            //Looper.prepare();

            setName("AcceptThread");
            BluetoothSocket socket = null;

            // Listen to the server socket if we're not connected
            while (State != STATE_CONNECTED) {
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    socket = ServerSocket.accept();
                } catch (IOException e) {
                     break;
                   }

                // If a connection was accepted
                if (socket != null) {
                    synchronized (BluetoothLampService.this) {
                        switch (State) {
                                        case STATE_LISTEN:
                                        case STATE_CONNECTING:
                                        // Situation normal. Start the connected thread.
                                        connected(socket, socket.getRemoteDevice());
                                        break;
                                        case STATE_NONE:
                                        case STATE_CONNECTED:
                                            // Either not ready or already connected. Terminate new socket.
                                            try {
                                                    socket.close();
                                            } catch (IOException e) {
                                                }
                            break;
                        }
                    }
                }
            }
         //   Looper.loop();
        }

        public void cancel() {
             try {
               ServerSocket.close();
            } catch (IOException e) {
             }
        }
    }
*/

    /**
     * This thread runs while attempting to make an outgoing connection
     * with a device. It runs straight through; the connection either
     * succeeds or fails.
     */
    private class ConnectThread extends Thread {
        private final BluetoothSocket Socket;
        private final BluetoothDevice Device;

        public ConnectThread(BluetoothDevice device) {
            Device = device;
            BluetoothSocket tmp = null;

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
             }
            Socket = tmp;
        }

        public void run() {
            Looper.prepare();
             setName("ConnectThread");

            // Always cancel discovery because it will slow down a connection
            Adapter.cancelDiscovery();

            // Make a connection to the BluetoothSocket
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                Socket.connect();
            } catch (IOException e) {
                connectionFailed();
                // Close the socket
                    try {
                        Socket.close();
                    } catch (IOException e2) {}

                    // Start the service over to restart listening mode
                    BluetoothLampService.this.start();
                    return;
                }

                // Reset the ConnectThread because we're done
                synchronized (BluetoothLampService.this) {
                    ConnectThread = null;
                }
                // Start the connected thread


                connected(Socket, Device);
                Looper.loop();
        }

        public void cancel() {
            try {
                Socket.close();
            } catch (IOException e) {
         }
        }
    }

    /**
     * This thread runs during a connection with a remote device.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket Socket;
        private final InputStream InStream;
        private final OutputStream OutStream;

        public ConnectedThread(BluetoothSocket socket) {
            Socket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }

            InStream = tmpIn;
            OutStream = tmpOut;
        }

        public void run() {
            Looper.prepare();
             byte[] buffer = new byte[1024];
             int bytes;

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    // FUNZIONANTE 
                    bytes = InStream.read(buffer);
                    Log.i("BYTES", Integer.toString(bytes));

                    //String dati = new String(buffer);
                    //fine aggiunto da me


                    // Send the obtained bytes to the UI Activity
         Handler.obtainMessage(MainActivity.MESSAGE_READ, 27, -1, buffer).sendToTarget();//buffer
                } catch (IOException e) {
                   connectionLost();
                    break;
                  }
            }
            Looper.loop();
        }

        /**
         * Write to the connected OutStream.
         * @param buffer  The bytes to write
         */
        public void write(byte[] buffer) {
            try {
                OutStream.write(buffer);

                // Share the sent message back to the UI Activity
         Handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();


            } catch (IOException e) {
                }
        }

        public void cancel() {
            try {
                Socket.close();
            } catch (IOException e) {
             }
        }
    }
}

Have you already gived permission to your android app on your Manifest file?

uses-permission android:name="android.permission.BLUETOOTH" /

uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /

Then check the serial baude rate on your arduino serial connection too.

Kindly try by first pairing the device explicitly from your Android phone's settings. Usually the pair code is 1234

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM