简体   繁体   English

Android,蓝牙和Arduino

[英]Android & Bluetooth & Arduino

I am trying to display sensor data on my Android phone (target 4.3) received from a transmitting arduino type device. 我试图在从传输的arduino类型的设备接收到的Android手机(目标4.3)上显示传感器数据。 The transmission takes place via Bluetooth. 传输通过蓝牙进行。 I am able to connect to the arduino type device and even share data, however for some reason I am having synchronization issues. 我能够连接到arduino类型的设备,甚至可以共享数据,但是由于某些原因,我遇到了同步问题。

The way the arduino is setup right now, after a successful connection it waits for a byte to be received from my phone (unsigned byte value 255), when it receives this byte it responds by sending a packet (3 bytes) containing information from three different sensors ie 现在设置arduino的方式,成功连接后,它等待从我的手机接收一个字节(无符号字节值255),当它收到此字节时,它会通过发送一个包含三个信息的数据包(3个字节)来做出响应不同的传感器,即

packet:
byte 1: temperature data
byte 2: cadence data
byte 3: speed data

All I have to do is display this data(which is updating live) repeatedly until the user terminates the connection on the android phone. 我要做的就是重复显示此数据(实时更新),直到用户终止android手机上的连接。

Here is my code I feel I am making a minor error somewhere in my logic. 这是我的代码,我觉得自己在逻辑中的某个地方犯了一个小错误。

MessageHandler 的MessageHandler

Handler mHandler = new Handler(){           
            public void handleMessage(Message msg){
                super.handleMessage(msg);
                switch(msg.what){
                    case SUCCESS_CONNECT:
                        // Do Something;
                        ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
                        Toast.makeText(getActivity(),"CONNECTED",Toast.LENGTH_SHORT).show();
                        /*
                         * Could send test string here
                         */
                        /*
                         * String connect_string = "test";
                         * connectedThread.write(connect_string.getBytes());
                         */
                        connectedThread.start();
                        break;
                    case MESSAGE_READ:
                        byte[] readBuf = (byte[])msg.obj;
                        int tempInt = byteToInt(readBuf[0]);
                        int cadenceInt = byteToInt(readBuf[1]);
                        int speedInt = byteToInt(readBuf[2]);
                        EditText temperatureData = (EditText)getActivity().findViewById(R.id.temperatureData);
                        temperatureData.setText(Integer.toString(tempInt));
                        EditText cadenceData = (EditText)getActivity().findViewById(R.id.cadence);
                        cadenceData.setText(Integer.toString(cadenceInt));
                        EditText speedData = (EditText)getActivity().findViewById(R.id.speed_data);
                        speedData.setText(Integer.toString(speedInt));

                }
            }       
        };

ConnectThread ConnectThread

public class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    public ConnectThread(BluetoothDevice device) {

        /*
         *  Use a temporary object that is later assigned to mmSocket,
         *  because mmSocket is final                
         */

        BluetoothSocket tmp = null;

        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();

        try {
        // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) {
                Toast.makeText(getActivity(), "Connecting to device failed!", Toast.LENGTH_LONG).show();
            }
                return;
        }

            // Do work to manage the connection (in a separate thread)
            mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
           } catch (IOException e) { }
    }

}

ConnectedThread ConnectedThread

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

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

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer; // buffer store for the stream
        int bytes; // bytes returned from read()
        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                buffer = new byte[3];
                byte maxByte = (byte) 1;
                mmOutStream.write(255);
                bytes = mmInStream.read(buffer,0,buffer.length);
                // Send the obtained bytes to the message handler

                mHandler.obtainMessage(MESSAGE_READ,buffer).sendToTarget();
                }
             catch (IOException e) {
                 break;
             }
        }
     }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }
}

Byte To Int Method 字节到整数方法

public static int byteToInt(byte b){
    int value;
    value = b & 0xFF;
    return  value;
}

The data I receive is being displayed but often ends up wrong mostly because the byte array sequence is off which causes the wrong values to be displayed. 正在显示我收到的数据,但通常最终会出错,这主要是因为字节数组序列已关闭,导致显示了错误的值。 I have been trying to figure this out for a while and any input would be helpful. 我一直试图弄清楚这一点,任何输入都会有所帮助。

Check if you can send in the message to the handler a cloned array. 检查是否可以将消息发送给处理程序克隆的数组。 It should be something like "buffer.clone" or "buffer.clone()" instead of simply "buffer". 它应该类似于“ buffer.clone”或“ buffer.clone()”,而不是简单的“ buffer”。 If it is so, it means that the not-cloned buffer is copied as reference to the handler. 如果是这样,则意味着将未克隆的缓冲区复制为对处理程序的引用。 While the handler is doing its stuff, the connected thread may redefine the array and reassign to it different values. 在处理程序执行其工作时,连接的线程可能会重新定义该数组并为其分配不同的值。 To test this you can also define the buffer ad Byte[] instead of byte[]. 要对此进行测试,您还可以定义缓冲区ad Byte []而不是byte []。 In this way I fixed similar problem in my application. 这样,我在应用程序中解决了类似的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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