如何从蓝牙读取传感器数据?

时间:2019-10-26 14:45:37

标签: java android arduino bluetooth

我正在尝试建立与Android设备和Arduino的连接。 目前,我已将多序列草图上传到arduino,在android方面,我遵循了本教程https://wingoodharry.wordpress.com/2014/04/15/android-sendreceive-data-with-arduino-using-bluetooth-part-2/ 现在我可以将数据发送到arduino并打开led了,但是我无法在Android设备上接收到arduino发送的数据。

我完全循序渐进地遵循了本教程(在此之前,我进行了一些更改,并认为可能引起任何问题)。

JAVA代码:

package com.codeyard.teleprompter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class TeleprompterActivity extends Activity {
    Button btnOn;
    Button btnOff;
    TextView txtArduino;
    TextView txtString;
    TextView txtStringLength;
    TextView sensorView0;
    TextView sensorView1;
    TextView sensorView2;
    TextView sensorView3;
    Handler bluetoothIn;
    final int handlerState = 0;
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private StringBuilder recDataString = new StringBuilder();
    private TeleprompterActivity.ConnectedThread mConnectedThread;
    private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static String address;

//    public TeleprompterActivity() {
//    }

    @SuppressLint("HandlerLeak")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_teleprompter);
        this.btnOn = (Button)this.findViewById(R.id.buttonOn);
        this.btnOff = (Button)this.findViewById(R.id.buttonOff);
        this.txtString = (TextView)this.findViewById(R.id.testView1);
        //Reading
        SharedPreferences sharedPreferences;
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(TeleprompterActivity.this);
        address=sharedPreferences.getString("ADDRESS","");
        this.txtStringLength = (TextView)this.findViewById(R.id.textView);
        this.sensorView0 = (TextView)this.findViewById(R.id.sensorView0);
        this.sensorView1 = (TextView)this.findViewById(R.id.sensorView1);
        this.sensorView2 = (TextView)this.findViewById(R.id.sensorView2);
        this.sensorView3 = (TextView)this.findViewById(R.id.sensorView3);
        this.bluetoothIn = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                int i = 0;
                if(msg.what == 0) {
                    String readMessage = (String)msg.obj;
                    TeleprompterActivity.this.recDataString.append(readMessage);
                    int endOfLineIndex = TeleprompterActivity.this.recDataString.indexOf("~");
                    if(endOfLineIndex > 0) {
                        String dataInPrint = TeleprompterActivity.this.recDataString.substring(0, endOfLineIndex);
                        TeleprompterActivity.this.txtString.setText("Data Received = " + dataInPrint);
                        int dataLength = dataInPrint.length();
                        TeleprompterActivity.this.txtStringLength.setText("String Length = " + String.valueOf(dataLength));
                        if(TeleprompterActivity.this.recDataString.charAt(0) == 35) {
                            String sensor0 = TeleprompterActivity.this.recDataString.substring(1, 5);
                            String sensor1 = TeleprompterActivity.this.recDataString.substring(6, 10);
                            String sensor2 = TeleprompterActivity.this.recDataString.substring(11, 15);
                            String sensor3 = TeleprompterActivity.this.recDataString.substring(16, 20);
                            TeleprompterActivity.this.sensorView0.setText(" Sensor 0 Voltage = " + sensor0 + "V");
                            TeleprompterActivity.this.sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
                            TeleprompterActivity.this.sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
                            TeleprompterActivity.this.sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
                        }

                        TeleprompterActivity.this.recDataString.delete(0, TeleprompterActivity.this.recDataString.length());
                        dataInPrint = " ";
                    }
                }

            }
        };
        this.btAdapter = BluetoothAdapter.getDefaultAdapter();
        this.checkBTState();
        this.btnOff.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                TeleprompterActivity.this.mConnectedThread.write("0");
                Toast.makeText(TeleprompterActivity.this.getBaseContext(), "Turn off LED", 0).show();
            }
        });
        this.btnOn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                TeleprompterActivity.this.mConnectedThread.write("1");
                Toast.makeText(TeleprompterActivity.this.getBaseContext(), "Turn on LED", 0).show();
            }
        });
    }

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
    }

    public void onResume() {
        super.onResume();

        BluetoothDevice device = this.btAdapter.getRemoteDevice(address);

        try {
            this.btSocket = this.createBluetoothSocket(device);
        } catch (IOException var7) {
            Toast.makeText(this.getBaseContext(), "Socket creation failed", 1).show();
        }

        try {
            this.btSocket.connect();
        } catch (IOException var6) {
            try {
                this.btSocket.close();
            } catch (IOException var5) {
                ;
            }
        }

        this.mConnectedThread = new TeleprompterActivity.ConnectedThread(this.btSocket);
        this.mConnectedThread.start();
        this.mConnectedThread.write("x");
    }

    public void onPause() {
        super.onPause();

        try {
            this.btSocket.close();
        } catch (IOException var2) {
            ;
        }

    }

    private void checkBTState() {
        if(this.btAdapter == null) {
            Toast.makeText(this.getBaseContext(), "Device does not support bluetooth", 1).show();
        } else if(!this.btAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE");
            this.startActivityForResult(enableBtIntent, 1);
        }

    }

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

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

            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException var6) {
                ;
            }

            this.mmInStream = tmpIn;
            this.mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[256];

            while(true) {
                try {
                    int bytes = this.mmInStream.read(buffer);
                    String readMessage = new String(buffer, 0, bytes);
                    TeleprompterActivity.this.bluetoothIn.obtainMessage(0, bytes, -1, readMessage).sendToTarget();
                } catch (IOException var4) {
                    return;
                }
            }
        }

        public void write(String input) {
            byte[] msgBuffer = input.getBytes();

            try {
                this.mmOutStream.write(msgBuffer);
            } catch (IOException var4) {
                Toast.makeText(TeleprompterActivity.this.getBaseContext(), "Connection Failure", 1).show();
                TeleprompterActivity.this.finish();
            }

        }
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.codeyard.teleprompter.TeleprompterActivity">
    <TextView
        android:id="@+id/testView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/txtString"
        android:text=""
        android:textSize="15sp" />

    <TextView
        android:id="@+id/txtString"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_alignLeft="@+id/testView1"
        android:layout_alignParentBottom="true"
        android:text=""
        android:textSize="15sp" />

    <Button
        android:id="@+id/buttonOn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="LED ON" />

    <Button
        android:id="@+id/buttonOff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/buttonOn"
        android:layout_alignParentRight="true"
        android:text="LED OFF" />

    <TextView
        android:id="@+id/sensorView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/sensorView0"
        android:layout_centerHorizontal="true"
        android:text="Sensor 1 Voltage = ????"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/sensorView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/sensorView1"
        android:layout_centerHorizontal="true"
        android:text="Sensor 2 Voltage = ????"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/sensorView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/sensorView2"
        android:layout_centerHorizontal="true"
        android:text="Sensor 3 Voltage = ????"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/sensorView0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="196dp"
        android:text="Sensor 0 Voltage = ????"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

通过我的调试,似乎根本没有运行该处理程序。

0 个答案:

没有答案