Android 蓝牙实时数据流慢

Android Bluetooth real time data stream slow

我有一个连接到 Arduino Uno 的 ECG 模块和 HC-06 蓝牙模块以 100 Hz 的频率测量 ECG 信号,并每 10 毫秒向 Android 应用程序发送数据 6 个字节的数据。但是,我无法实现每秒接收 100 个样本。

这是我的 Arduino 代码:

#include <SoftwareSerial.h>
SoftwareSerial myBT(2, 3);
void setup() {
  myBT.begin(115200);
  Serial.begin(115200);
  pinMode(A0, OUTPUT);
}
char cmd;
int ECG;
void loop() 
{
  if(myBT.available()>0)
  {
    cmd = myBT.read();

    while(cmd = 'r')
    {
    ECG = ((ECG+1)%1023);
    float Volt = (float)ECG*5.0/1023.0;
    myBT.print("s"+String(Volt,2));
    delay(10);
    }
  }
}

这是我的 Android Java 代码:

package com.example.mscale;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.icu.text.UnicodeSetSpanner;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.Series;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;


public class MonitorActivity extends AppCompatActivity {
    private final String TAG = "MonitorActivity";
    //Stuffs
    GraphView graphx;
    Button recordButton;
    TextView statusBtTxt, KilogramTxt;
    //Bluetooth Stuffs
    private static final int REQUEST_ENABLE_BT = 1;
    BluetoothAdapter bluetoothAdapter;
    private ArrayList<String> mDeviceList;
    private String pairedAddres;
    ArrayAdapter<String> adapter;
    private BluetoothSocket mBluetoothSocket;
    public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    protected static final int SUCESS_CONNECT = 0;
    protected static final int MESSAGE_READ = 1;
    protected static final int MESSAGE_WRITE = 2;
    private boolean recording = false;

   /* @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        if (Bluetooth.connectedThread != null) {
            Bluetooth.connectedThread.write("Q");}//Stop streaming
        super.onBackPressed();
    }*/

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCESS_CONNECT:
                    statusBtTxt.setText("Connected");
                    recording = true;
                    break;
                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, 5);                 // create string from bytes array
                    statusBtTxt.setText(strIncom);
                    Log.d(TAG, strIncom);
                    /*if (strIncom.indexOf("s") == 3) {
                        Log.d(TAG, strIncom);
                        strIncom = strIncom.replace("s", "");
                        if(isFloatNumber(strIncom)){
                        }
                    }else Log.d(TAG, "The s is not where it should be!");*/
                    break;
                case MESSAGE_WRITE:
                    ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket) msg.obj);
                    connectedThread.write("r");
                    break;
            }
        }
    };

    public boolean isFloatNumber(String num) {
        //Log.d("checkfloatNum", num);
        try {
            Double.parseDouble(num);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideStatusbar();
        setContentView(R.layout.activity_monitor);
        findIDStuff();
        plotting();
        System.gc();
        recordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recording == false) {
                    bluetoothManagement();
                } else {
                    ConnectedThread connectedThread = new ConnectedThread(mBluetoothSocket);
                    connectedThread.write("r");
                    connectedThread.start();
                }
            }
        });
    }

    //Find ID of Stuffs
    private void findIDStuff() {
        recordButton = findViewById(R.id.recordBtn);
        //graphx = (GraphView) findViewById(R.id.graph);
        statusBtTxt = findViewById(R.id.btStatusTxt);
        KilogramTxt = findViewById(R.id.kiloTxt);
    }

    //Bluetooth management
    private void bluetoothManagement() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        } else {
            //Do sth
            pairedBtDevices();
        }
    }

    //Graph plotting
    private void plotting() {


    }

    //Hide status bar
    private void hideStatusbar() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    //Paired Bluetooth device
    private void pairedBtDevices() {
        // Register for broadcasts when a device is discovered.
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter);
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                String module = "ECG_Module";
                if (device.getName().equals(module)) {
                    pairedAddres = device.getAddress();
                }
            }
            bluetoothAdapter.startDiscovery();
            //Log.d(TAG, String.valueOf(mPairedDeviceList));
        } else {
            statusBtTxt.setText("No paired");
        }
    }

    // Create a BroadcastReceiver for ACTION_FOUND.
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
            mDeviceList = new ArrayList<String>();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Discovery has found a device. Get the BluetoothDevice
                // object and its info from the Intent.
                String module = "ECG_Module";
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getName() != null && device.getName().equalsIgnoreCase(module) && device.getAddress() != null && device.getAddress().equalsIgnoreCase(pairedAddres)) {
                    mDeviceList.add(device.getName() + "\n" + device.getAddress());
                    bluetoothAdapter.cancelDiscovery();
                    open_dialog();
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                statusBtTxt.setText("Start Discovery...");
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                statusBtTxt.setText("End Discovery....");
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }

    //Open dialog
    public void open_dialog() {

        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        final View row = getLayoutInflater().inflate(R.layout.rowitem, null);
        ListView mlistView = (ListView) row.findViewById(R.id.listviewBt);
        final Button mBtnConnect = (Button) row.findViewById(R.id.conBtn);
        Button mBtnCancel = (Button) row.findViewById(R.id.canBtn);

        mlistView.setClickable(true);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mDeviceList);
        mlistView.setAdapter(adapter);
        alertDialog.setView(row);
        final AlertDialog dialog = alertDialog.create();
        dialog.show();

        mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String mNames = (String) parent.getItemAtPosition(position);
                final String[] mMacAddress = mNames.split("\r?\n");

                mBtnConnect.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(mMacAddress[1]);
                            ConnectThread connectThread = new ConnectThread(bluetoothDevice);
                            connectThread.start();
                            Context context = getApplicationContext();
                            Toast toast = Toast.makeText(context, "Connnecting to " + mMacAddress[1], Toast.LENGTH_SHORT);
                            toast.show();
                            dialog.hide();
                        } catch (Exception e) {
                            Context context = getApplicationContext();
                            Toast toast = Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT);
                            toast.show();
                            return;
                        }
                    }
                });
            }
        });

        mBtnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.hide();
            }
        });
    }

    //Connection Bluetooth
    private 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;

            try {
                // Get a BluetoothSocket to connect with the given BluetoothDevice.
                // MY_UUID is the app's UUID string, also used in the server code.
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "Socket's create() method failed", e);
            }
            mBluetoothSocket = tmp;
            mmSocket = tmp;
        }

        public void run() {
            // Cancel discovery because it otherwise slows down the connection.
            bluetoothAdapter.cancelDiscovery();
            try {
                // Connect to the remote device through the socket. This call blocks
                // until it succeeds or throws an exception.
                mmSocket.connect();
            } catch (IOException connectException) {
                // Unable to connect; close the socket and return.
                try {
                    mmSocket.close();
                    Log.d(TAG, "Failed connection");
                } catch (IOException closeException) {
                    Log.e(TAG, "Could not close the client socket", closeException);
                }
                return;
            }

            // The connection attempt succeeded. Perform work associated with
            // the connection in a separate thread.
            mHandler.obtainMessage(SUCESS_CONNECT, mmSocket).sendToTarget();
        }

        // Closes the client socket and causes the thread to finish.
        public void cancel() {
            try {
                statusBtTxt.setText("Failed Connection");
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "Could not close the client socket", e);
            }
        }
    }


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

        StringBuffer sbb = new StringBuffer();

        public void run() {
            // Keep listening to the InputStream until an exception occurs
            byte[] buffer;
            int bytes = 0;
            try {
                while(mmInStream.read() != (byte) 's')
                {}
                //Since we already read out the "s", we need to read 4 more bytes, to regain alignment.
                mmInStream.read();
                mmInStream.read();
                mmInStream.read();
                mmInStream.read();
                //Now, the next byte read should be an "s".
            } catch (IOException e) {
                return;
            }
            while (true) {
                try {
                    buffer = new byte[1024];
                    // Read from the InputStream
                    int totalRead = 0;
                    while(totalRead < 5)
                    {
                        bytes = mmInStream.read(buffer,totalRead,5-totalRead);
                        if(bytes==-1)
                            throw new IOException("EOS reached");
                        totalRead += bytes;
                    }
                    //Log.d("Obtain: ", String.valueOf(totalRead));
                    mHandler.obtainMessage(MESSAGE_READ, totalRead, -1, buffer).sendToTarget();
                } catch (IOException e) {
                    break;
                }
            }
        }
            /* Call this from the main activity to send data to the remote device */
            public void write (String income){

                try {
                    mmOutStream.write(income.getBytes());
                } catch (IOException e) {
                }
            }

            /* Call this from the main activity to shutdown the connection */
            public void cancel () {
                try {
                    mmSocket.close();
                } catch (IOException e) {
                }
            }
        }
    }

传输的可变值和 Logcat 在 Android 接收到的数据(没有 myBT.print("\n") 和传感器输入):

2020-01-22 13:12:22.369 28250-28250/com.example.mscale D/MonitorActivity: s0.01
2020-01-22 13:12:22.401 28250-28250/com.example.mscale D/MonitorActivity: s0.01
2020-01-22 13:12:22.421 28250-28250/com.example.mscale D/MonitorActivity: s0.02
2020-01-22 13:12:22.421 28250-28250/com.example.mscale D/MonitorActivity: s0.02
2020-01-22 13:12:22.422 28250-28250/com.example.mscale D/MonitorActivity: s0.03
2020-01-22 13:12:22.444 28250-28250/com.example.mscale D/MonitorActivity: s0.03
2020-01-22 13:12:22.454 28250-28250/com.example.mscale D/MonitorActivity: s0.04
2020-01-22 13:12:22.454 28250-28250/com.example.mscale D/MonitorActivity: s0.04
2020-01-22 13:12:22.454 28250-28250/com.example.mscale D/MonitorActivity: s0.05
2020-01-22 13:12:22.478 28250-28250/com.example.mscale D/MonitorActivity: s0.05
2020-01-22 13:12:22.488 28250-28250/com.example.mscale D/MonitorActivity: s0.06
2020-01-22 13:12:22.488 28250-28250/com.example.mscale D/MonitorActivity: s0.06
2020-01-22 13:12:22.514 28250-28250/com.example.mscale D/MonitorActivity: s0.07
2020-01-22 13:12:22.522 28250-28250/com.example.mscale D/MonitorActivity: s0.07
2020-01-22 13:12:22.522 28250-28250/com.example.mscale D/MonitorActivity: s0.08
2020-01-22 13:12:22.548 28250-28250/com.example.mscale D/MonitorActivity: s0.08
2020-01-22 13:12:22.555 28250-28250/com.example.mscale D/MonitorActivity: s0.09
2020-01-22 13:12:22.555 28250-28250/com.example.mscale D/MonitorActivity: s0.09
2020-01-22 13:12:22.572 28250-28250/com.example.mscale D/MonitorActivity: s0.10
2020-01-22 13:12:22.589 28250-28250/com.example.mscale D/MonitorActivity: s0.10
2020-01-22 13:12:22.589 28250-28250/com.example.mscale D/MonitorActivity: s0.11
2020-01-22 13:12:22.606 28250-28250/com.example.mscale D/MonitorActivity: s0.11
2020-01-22 13:12:22.623 28250-28250/com.example.mscale D/MonitorActivity: s0.12
2020-01-22 13:12:22.640 28250-28250/com.example.mscale D/MonitorActivity: s0.12
2020-01-22 13:12:22.641 28250-28250/com.example.mscale D/MonitorActivity: s0.13
2020-01-22 13:12:22.659 28250-28250/com.example.mscale D/MonitorActivity: s0.13
2020-01-22 13:12:22.673 28250-28250/com.example.mscale D/MonitorActivity: s0.14
2020-01-22 13:12:22.673 28250-28250/com.example.mscale D/MonitorActivity: s0.14
2020-01-22 13:12:22.674 28250-28250/com.example.mscale D/MonitorActivity: s0.15
2020-01-22 13:12:22.700 28250-28250/com.example.mscale D/MonitorActivity: s0.15
2020-01-22 13:12:22.707 28250-28250/com.example.mscale D/MonitorActivity: s0.16
2020-01-22 13:12:22.707 28250-28250/com.example.mscale D/MonitorActivity: s0.16
2020-01-22 13:12:22.724 28250-28250/com.example.mscale D/MonitorActivity: s0.17
2020-01-22 13:12:22.724 28250-28250/com.example.mscale D/MonitorActivity: s0.17
2020-01-22 13:12:22.743 28250-28250/com.example.mscale D/MonitorActivity: s0.18
2020-01-22 13:12:22.758 28250-28250/com.example.mscale D/MonitorActivity: s0.18
2020-01-22 13:12:22.758 28250-28250/com.example.mscale D/MonitorActivity: s0.19
2020-01-22 13:12:22.778 28250-28250/com.example.mscale D/MonitorActivity: s0.19
2020-01-22 13:12:22.793 28250-28250/com.example.mscale D/MonitorActivity: s0.20
2020-01-22 13:12:22.794 28250-28250/com.example.mscale D/MonitorActivity: s0.20
2020-01-22 13:12:22.815 28250-28250/com.example.mscale D/MonitorActivity: s0.21
2020-01-22 13:12:22.828 28250-28250/com.example.mscale D/MonitorActivity: s0.21
2020-01-22 13:12:22.828 28250-28250/com.example.mscale D/MonitorActivity: s0.22
2020-01-22 13:12:22.829 28250-28250/com.example.mscale D/MonitorActivity: s0.22
2020-01-22 13:12:22.858 28250-28250/com.example.mscale D/MonitorActivity: s0.22
2020-01-22 13:12:22.877 28250-28250/com.example.mscale D/MonitorActivity: s0.23
2020-01-22 13:12:22.878 28250-28250/com.example.mscale D/MonitorActivity: s0.23
2020-01-22 13:12:22.878 28250-28250/com.example.mscale D/MonitorActivity: s0.24
2020-01-22 13:12:22.897 28250-28250/com.example.mscale D/MonitorActivity: s0.24
2020-01-22 13:12:22.911 28250-28250/com.example.mscale D/MonitorActivity: s0.25
2020-01-22 13:12:22.912 28250-28250/com.example.mscale D/MonitorActivity: s0.25
2020-01-22 13:12:22.929 28250-28250/com.example.mscale D/MonitorActivity: s0.26
2020-01-22 13:12:22.929 28250-28250/com.example.mscale D/MonitorActivity: s0.26
2020-01-22 13:12:22.945 28250-28250/com.example.mscale D/MonitorActivity: s0.27
2020-01-22 13:12:22.964 28250-28250/com.example.mscale D/MonitorActivity: s0.27
2020-01-22 13:12:22.965 28250-28250/com.example.mscale D/MonitorActivity: s0.28
2020-01-22 13:12:22.980 28250-28250/com.example.mscale D/MonitorActivity: s0.28
2020-01-22 13:12:22.998 28250-28250/com.example.mscale D/MonitorActivity: s0.29
2020-01-22 13:12:23.013 28250-28250/com.example.mscale D/MonitorActivity: s0.29
2020-01-22 13:12:23.013 28250-28250/com.example.mscale D/MonitorActivity: s0.30
2020-01-22 13:12:23.033 28250-28250/com.example.mscale D/MonitorActivity: s0.30
2020-01-22 13:12:23.046 28250-28250/com.example.mscale D/MonitorActivity: s0.31
2020-01-22 13:12:23.046 28250-28250/com.example.mscale D/MonitorActivity: s0.31
2020-01-22 13:12:23.047 28250-28250/com.example.mscale D/MonitorActivity: s0.32
2020-01-22 13:12:23.069 28250-28250/com.example.mscale D/MonitorActivity: s0.32
2020-01-22 13:12:23.079 28250-28250/com.example.mscale D/MonitorActivity: s0.33
2020-01-22 13:12:23.080 28250-28250/com.example.mscale D/MonitorActivity: s0.33
2020-01-22 13:12:23.104 28250-28250/com.example.mscale D/MonitorActivity: s0.34
2020-01-22 13:12:23.115 28250-28250/com.example.mscale D/MonitorActivity: s0.34
2020-01-22 13:12:23.115 28250-28250/com.example.mscale D/MonitorActivity: s0.35
2020-01-22 13:12:23.116 28250-28250/com.example.mscale D/MonitorActivity: s0.35
2020-01-22 13:12:23.139 28250-28250/com.example.mscale D/MonitorActivity: s0.36
2020-01-22 13:12:23.149 28250-28250/com.example.mscale D/MonitorActivity: s0.36
2020-01-22 13:12:23.149 28250-28250/com.example.mscale D/MonitorActivity: s0.37
2020-01-22 13:12:23.178 28250-28250/com.example.mscale D/MonitorActivity: s0.37
2020-01-22 13:12:23.198 28250-28250/com.example.mscale D/MonitorActivity: s0.38
2020-01-22 13:12:23.198 28250-28250/com.example.mscale D/MonitorActivity: s0.38
2020-01-22 13:12:23.215 28250-28250/com.example.mscale D/MonitorActivity: s0.39
2020-01-22 13:12:23.216 28250-28250/com.example.mscale D/MonitorActivity: s0.39
2020-01-22 13:12:23.216 28250-28250/com.example.mscale D/MonitorActivity: s0.40
2020-01-22 13:12:23.235 28250-28250/com.example.mscale D/MonitorActivity: s0.40
2020-01-22 13:12:23.248 28250-28250/com.example.mscale D/MonitorActivity: s0.41
2020-01-22 13:12:23.249 28250-28250/com.example.mscale D/MonitorActivity: s0.41
2020-01-22 13:12:23.266 28250-28250/com.example.mscale D/MonitorActivity: s0.42
2020-01-22 13:12:23.284 28250-28250/com.example.mscale D/MonitorActivity: s0.42
2020-01-22 13:12:23.299 28250-28250/com.example.mscale D/MonitorActivity: s0.43
2020-01-22 13:12:23.299 28250-28250/com.example.mscale D/MonitorActivity: s0.43
2020-01-22 13:12:23.319 28250-28250/com.example.mscale D/MonitorActivity: s0.43
2020-01-22 13:12:23.336 28250-28250/com.example.mscale D/MonitorActivity: s0.44
2020-01-22 13:12:23.336 28250-28250/com.example.mscale D/MonitorActivity: s0.44
2020-01-22 13:12:23.355 28250-28250/com.example.mscale D/MonitorActivity: s0.45
2020-01-22 13:12:23.367 28250-28250/com.example.mscale D/MonitorActivity: s0.45
2020-01-22 13:12:23.386 28250-28250/com.example.mscale D/MonitorActivity: s0.46
2020-01-22 13:12:23.386 28250-28250/com.example.mscale D/MonitorActivity: s0.46
2020-01-22 13:12:23.387 28250-28250/com.example.mscale D/MonitorActivity: s0.47
2020-01-22 13:12:23.387 28250-28250/com.example.mscale D/MonitorActivity: s0.47
2020-01-22 13:12:23.417 28250-28250/com.example.mscale D/MonitorActivity: s0.48
2020-01-22 13:12:23.435 28250-28250/com.example.mscale D/MonitorActivity: s0.48
2020-01-22 13:12:23.436 28250-28250/com.example.mscale D/MonitorActivity: s0.49
2020-01-22 13:12:23.436 28250-28250/com.example.mscale D/MonitorActivity: s0.49
2020-01-22 13:12:23.457 28250-28250/com.example.mscale D/MonitorActivity: s0.50
2020-01-22 13:12:23.474 28250-28250/com.example.mscale D/MonitorActivity: s0.50
2020-01-22 13:12:23.474 28250-28250/com.example.mscale D/MonitorActivity: s0.51
2020-01-22 13:12:23.474 28250-28250/com.example.mscale D/MonitorActivity: s0.51
2020-01-22 13:12:23.501 28250-28250/com.example.mscale D/MonitorActivity: s0.52
2020-01-22 13:12:23.501 28250-28250/com.example.mscale D/MonitorActivity: s0.52
2020-01-22 13:12:23.519 28250-28250/com.example.mscale D/MonitorActivity: s0.53
2020-01-22 13:12:23.540 28250-28250/com.example.mscale D/MonitorActivity: s0.53
2020-01-22 13:12:23.541 28250-28250/com.example.mscale D/MonitorActivity: s0.54
2020-01-22 13:12:23.541 28250-28250/com.example.mscale D/MonitorActivity: s0.54
2020-01-22 13:12:23.553 28250-28250/com.example.mscale D/MonitorActivity: s0.55
2020-01-22 13:12:23.573 28250-28250/com.example.mscale D/MonitorActivity: s0.55
2020-01-22 13:12:23.587 28250-28250/com.example.mscale D/MonitorActivity: s0.56
2020-01-22 13:12:23.587 28250-28250/com.example.mscale D/MonitorActivity: s0.56

您的蓝牙模块可能没问题。您看到的性能问题更可能是您的协议实现存在问题:即 s 字符不在您期望的位置。造成这种情况的原因有很多,让我们一一分析:

心电图值

注意analogRead()的return取值范围是0到1023(docs),对应的范围是0V到Vref。假设您的 Vref 是 5V,那么 ECG 的 3.3V 输出将导致 analogRead() 到 return 675。因此,在实践中,ECG 可能在 0675 之间。这就是为什么你有这个缩放逻辑:

float Volt = (float)ECG*5.0/1023.0;

将 ADC 读数转换回电压。

缩放逻辑精度

如果 ECG5,那么 Volt 将是 0.024437929。这违反了 Volt 始终是四字符浮点数的假设,并且导致 s 字符未对齐。

Logcat 问题

  • 跳过消息:这不是因为您的 BT 连接有问题。这是因为您将比计划更多的消息放入一个缓冲区。 mmInStream.read(buffer) 将尝试读取最多 1024 个字节;这意味着它可能会抓取多条消息。但是如果您在缓冲区中收到多条消息,那么您只会处理第一条。

  • 损坏的消息:例如,s0.����。这是因为 mmInStream.read(buffer) 只读取了 3 个字节,但您假设它读取了 5 个字节。您看,read() return 只要有至少 1 个新字节可用,它就是一个值。这并不意味着它已阅读所有内容。在这种情况下,最后 2 个字节被单元化 (0),但您还是尝试将它们转换为 String

  • 未对齐的消息:这与损坏的消息具有相同的根本原因。请注意 logcat 中的下一行是 15s0.。那是因为第 15 条消息 (s0.15) 在中间被拆分了。然后第 16 条消息的一部分 (s0.) 被附加到末尾,因为现在您的对齐已关闭。由于套接字计时中的一个怪癖,重新对齐才重新获得(在下一行)。

所有这 3 个问题的解决方案是确保 read() 阻塞直到它正好读取 5 个字节(参见 "Fix #2")。

修复#1

强制所有字符串转换只生成 4 个字符 (docs):

myBT.print("s"+String(Volt,2));   //2 decimal places works out to 4 characters total, for your input range.

修复 #2

确保所有 BT 套接字读取的长度正好为 5 个字节。

buffer = new byte[1024];
// Read from the InputStream
int totalRead = 0;
while(totalRead < 5)
{
    bytes = mmInStream.read(buffer,totalRead,5-totalRead);
    if(bytes==-1)
        throw new IOException("EOS reached");
    totalRead += bytes;
}

或者,您可以使用为此目的设计的函数,例如 DataInputStream.readFully()

修复 #3

由于不完全清楚的原因,您发送的消息相对于您接收的消息有一个固定的偏移量。可能是因为启动条件有问题;您的 Arduino 可能在不知道它是否已连接的情况下向 BT 模块发送数据。因此,在实际发生 BT 连接时,它会在消息中间而不是开始时开始发送。要解决此问题并重新对齐,我建议使用如下代码:

// Keep listening to the InputStream until an exception occurs
byte[] buffer;
int bytes = 0;
try {
    while(mmInStream.read() != (byte) 's')    //TODO: Handle "-1" case
    {}
    //Since we already read out the "s", we need to read 4 more bytes, to regain alignment.
    mmInStream.read();
    mmInStream.read();
    mmInStream.read();
    mmInStream.read();
    //Now, the next byte read should be an "s".
} catch (IOException e) {
    return;
}
while (true) {
(...)

一旦实施了这些修复,您就可以摆脱接收循环中的 sleep(),因为 read() 逻辑 会阻塞,直到收到必要的数据.此外,如果不满足该条件(因为这表明您的对等方出现故障),您应该 关闭连接 ,而不是仅在第一个字节为 s 时才处理消息。

注意:我还没有测试过这段代码,但它应该可以工作。为避免将来出现此类问题,添加逻辑来验证您的更多假设。例如,在您的 Arduino 上,您可以点亮 LED if(strlen(String(Volt))!=4)。如果 s 不在您期望的位置,请不要忽略该问题;找出 为什么 .