Подключение H C -05 к Android для получения данных от Arduino - PullRequest
0 голосов
/ 04 августа 2020

05 и arduino Uno для отправки строки в мое приложение android. Но я не могу получить данные. Я не уверен, что делаю неправильно. Я следил за учебником в Интернете. Единственное, что я отредактировал, - это функция отправки данных, поскольку я просто хочу слушать данные, поступающие в приложение android. Приложение работает без ошибок, но ничего не делает.

 TextView myLabel;
TextView temperatureData;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
String selectedBt;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth_test);

    selectedBt = getIntent().getStringExtra("btName");

    Button openButton = (Button)findViewById(R.id.open);
    Button closeButton = (Button)findViewById(R.id.close);
    myLabel = (TextView)findViewById(R.id.label);
    temperatureData = (TextView)findViewById(R.id.tempSensorDataLabel);


    try
    {
        findBT();
        openBT();
    }
    catch (IOException ex) { }

    //Open Button
    openButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try
            {
                findBT();
                openBT();
            }
            catch (IOException ex) { }
        }
    });

    //Send Button


    //Close button
    closeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                closeBT();
            } catch (IOException ex) {
            }
        }
    });
}

void findBT()
{
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(mBluetoothAdapter == null)
    {
        myLabel.setText("No bluetooth adapter available");
    }

    if(!mBluetoothAdapter.isEnabled())
    {
        Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBluetooth, 0);
    }

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    mmDevice = mBluetoothAdapter.getRemoteDevice("E0:F8:47:43:68:E2");
    if (pairedDevices.contains(mmDevice))
    {

        Log.d("ArduinoBT","Bluetooth Device Found, address: " + mmDevice.getAddress() );
        Log.d("ArduinoBT", "BT is paired");
    }
    myLabel.setText("Bluetooth Device Found");
}

void openBT() throws IOException
{
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
    mmSocket.connect();
    mmOutputStream = mmSocket.getOutputStream();
    mmInputStream = mmSocket.getInputStream();

    beginListenForData();

    myLabel.setText("Bluetooth Opened");
}

void beginListenForData()
{
    final Handler handler = new Handler();
    final byte delimiter = 10; //This is the ASCII code for a newline character

    stopWorker = false;
    readBufferPosition = 0;
    readBuffer = new byte[1024];
    workerThread = new Thread(new Runnable()
    {
        public void run()
        {
            while(!Thread.currentThread().isInterrupted() && !stopWorker)
            {
                try
                {
                    int bytesAvailable = mmInputStream.available();
                    if(bytesAvailable > 0)
                    {
                        byte[] packetBytes = new byte[bytesAvailable];
                        mmInputStream.read(packetBytes);
                        for(int i=0;i<bytesAvailable;i++)
                        {
                            byte b = packetBytes[i];
                            if(b == delimiter)
                            {
                                byte[] encodedBytes = new byte[readBufferPosition];
                                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                final String data = new String(encodedBytes, "US-ASCII");
                                try {
                                    final JSONObject dataObj = new JSONObject(data);

                                    readBufferPosition = 0;

                                    handler.post(new Runnable()
                                    {
                                        public void run()
                                        {
                                            //myLabel.setText(data);
                                            //temperatureData.setText(data);
                                            try {
                                                temperatureData.append("\n Temperature: "+dataObj.getString("temperature"));
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                                } catch (JSONException e){}

                            }
                            else
                            {
                                readBuffer[readBufferPosition++] = b;
                            }
                        }
                    }
                }
                catch (IOException ex)
                {
                    stopWorker = true;
                }
            }
        }
    });

    workerThread.start();
}



void closeBT() throws IOException
{
    stopWorker = true;
    mmOutputStream.close();
    mmInputStream.close();
    mmSocket.close();
    myLabel.setText("Bluetooth Closed");
}

Это xml код

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/open"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="47dp"
    android:layout_marginTop="145dp"
    android:layout_marginBottom="147dp"
    android:text="open"
    app:layout_constraintBottom_toBottomOf="@+id/close"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="90dp"
    android:text="send"
    app:layout_constraintBaseline_toBaselineOf="@+id/open"
    app:layout_constraintEnd_toEndOf="parent" />

<Button
    android:id="@+id/close"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="60dp"
    android:layout_marginTop="292dp"
    android:text="close"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/label"
    android:layout_width="233dp"
    android:layout_height="66dp"
    android:layout_marginStart="66dp"
    android:layout_marginTop="118dp"
    android:layout_marginBottom="117dp"
    android:text="label"
    app:layout_constraintBottom_toBottomOf="@+id/tempSensorDataLabel"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/close" />

<TextView
    android:id="@+id/tempSensorDataLabel"
    android:layout_width="233dp"
    android:layout_height="36dp"
    android:layout_marginStart="79dp"
    android:layout_marginBottom="138dp"
    android:text="tempSensorDataLabel"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>

Любая помощь приветствуется. спасибо

...