Android和放大器;蓝牙放大器; Arduino的 [英] Android & Bluetooth & Arduino

查看:194
本文介绍了Android和放大器;蓝牙放大器; Arduino的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的(目标4.3)从发射的Arduino类型设备接收的Andr​​oid手机上显示的传感器数据。传输通过蓝牙发生。我能够但是连接到Arduino类型的设备,甚至分享数据,我有同步问题某些原因。

I am trying to display sensor data on my Android phone (target 4.3) received from a transmitting arduino type device. 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是设置,现在,连接成功后,它等待从我的手机(无符号字节值255),当它通过发送一个数据包(3个字节)接收该字节它响应包含接收的字节从三个不同的传感器的信息,即

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 i.e.

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

所有我需要做的,直到用户终止Android手机上的连接反复显示此数据(这是实时更新)。

All I have to do is display this data(which is updating live) repeatedly until the user terminates the connection on the android phone.

下面是我的code,我觉得我在我的逻辑地方做一个小错误。

Here is my code I feel I am making a minor error somewhere in my logic.

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

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

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

字节INT方法

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.

推荐答案

检查是否可以在邮件中发送给处理器克隆阵列。
它应该是类似buffer.clone或buffer.clone(),而不是简单的缓冲。
如果是这样,这意味着不克隆缓冲器被复制为参照处理程序。虽然处理器正在尽自己的东西,连接的线程可能会重新定义数组,并重新分配给它不同的值。
为了验证这一点,你也可以定义缓冲广告字节[],而不是为byte []。
这样,我在我的应用固定的类似的问题。

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". 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[]. In this way I fixed similar problem in my application.

这篇关于Android和放大器;蓝牙放大器; Arduino的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆