无法通过蓝牙将Arduino传输的消息接收到android应用中

问题描述

我试图通过来回发送简单的字符串,通过我的android应用程序与ESP 32芯片进行通信。我能够成功地将数据发送到ESP32串行监视器,但无法将数据重新接收到我的套接 InputStream 中。到目前为止,这是我在Arduino中针对ESP32和Android的实现。

Arduino代码

#include "BluetoothSerial.h" //Header File for Serial Bluetooth,will be added default into Arduino
#include <SoftwareSerial.h>  
BluetoothSerial ESP_BT;
int incoming;

void setup() {

ESP_BT.begin("ESP32_IRegained"); //Name of your Bluetooth Signal
Serial.begin(9600); //Start Serial monitor in 9600

//  pinMode (13,OUTPUT);//Specify that LED pin is output
}

void loop() {

if (ESP_BT.available()) //Check if we receive anything from Bluetooth
{
  incoming = ESP_BT.read(); //Read what we recevive 
  Serial.print((char)incoming);
}

if(ESP_BT.available())  // If stuff was typed in the serial monitor
{
   char c = (char) Serial.write();
   // Send any characters the Serial monitor prints to the bluetooth
  Serial.print(c); 
}
 delay(20); 
}

MainActivity.java

public class MessageActivity extends AppCompatActivity {

private static final String TAG = MessageActivity.class.getName();
private EditText etText;
private Button btnSend,btnClear;
private TextView tvSent;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
public BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
String s;
String data;

OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    address = "24:0A:C4:00:21:06"; //receive the address of the bluetooth device

    //view of the LightControl
    setContentView(R.layout.activity_message);

    //call the widgets
    etText = (EditText) findViewById(R.id.editText);
    btnSend = (Button) findViewById(R.id.buttonSend);
    btnClear = (Button) findViewById(R.id.buttonReceive);
    tvSent = findViewById(R.id.tvMessageSent);
    //disconnect();
    new MessageActivity.ConnectBT().execute(); //Call the class to connect

    new Thread(new ClientThread()).start();
}

class ClientThread implements Runnable {
    @SuppressWarnings("deprecation")
    @Override
    public void run() {
        try {
            receiveData();
        } catch (UnkNownHostException e1) {
            e1.printstacktrace();
        } catch (IOException e1) {
            e1.printstacktrace();
        }
    }
}

@SuppressLint("SetTextI18n")
public void onSend(View view) {
    if (TextUtils.isEmpty(etText.getText().toString())) {
        Toast.makeText(MessageActivity.this,"Enter text",Toast.LENGTH_SHORT).show();
        etText.requestFocus();
    } else {
        s = etText.getText().toString();
        s.concat("\n");
        try {
            btSocket.getoutputStream().write(etText.getText().toString().getBytes());
            etText.setText("");
        } catch (IOException e) {
            msg("Error");
        }
        tvSent.append("\nSent Data: " + s + "\n");
    }
}

public void onReceive(View v) {
    try {
        data = String.valueOf(btSocket.getInputStream().read());
        Log.d(TAG,"Message Received: " + data);
    } catch (IOException e) {
        msg("Error" + e.getMessage());
    }
}

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

private void disconnect() {
    if (btSocket != null) //If the btSocket is busy
    {
        try {
            btSocket.close(); //close connection
        } catch (IOException e) {
            msg("Error");
        }
    }
    finish(); //return to the first layout

}

public void receiveData() throws IOException {

}

// fast way to call Toast
private void msg(String s) {
    Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}

@SuppressLint("StaticFieldLeak")
private class ConnectBT extends AsyncTask<Void,Void,Void>  // UI thread
{
    private boolean ConnectSuccess = true; //if it's here,it's almost connected

    @Override
    protected void onPreExecute() {
        progress = ProgressDialog.show(MessageActivity.this,"Connecting...","Please wait!!!");  //show a progress dialog
    }

    @Override
    protected Void doInBackground(Void... devices) //while the progress dialog is shown,the connection is done in background
    {
        try {
            if (btSocket == null || !isBtConnected) {
                myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
                BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
                btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
                BluetoothAdapter.getDefaultAdapter().canceldiscovery();
                mmOutputStream = btSocket.getoutputStream();
                mmInputStream = btSocket.getInputStream();
                btSocket.connect();//start connection
            }

        } catch (IOException e) {
            ConnectSuccess = false;//if the try Failed,you can check the exception here
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) //after the doInBackground,it checks if everything went fine
    {
        super.onPostExecute(result);

        if (!ConnectSuccess) {
            msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
            finish();
        } else {
            msg("Connected.");
            isBtConnected = true;
        }
        progress.dismiss();
    }
}

void beginListenForData() {
    final Handler handler = new Handler(this.getMainLooper());
    final byte delimiter = 10; // This is the ASCII code for a newline
    // character
    readBufferPosition = 0;
    readBuffer = new byte[1024];
    workerThread = new Thread(new Runnable() {
        public void run() {
            Looper.prepare();
            while (!Thread.currentThread().isInterrupted()) {
                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,encodedBytes,encodedBytes.length);
                                final String data = new String(
                                        encodedBytes,"US-ASCII");
                                readBufferPosition = 0;

                                handler.post(new Runnable() {
                                    public void run() {
                                        tvSent.setText("\nReceived Data: " + data);
                                    }
                                });
                            } else {
                                readBuffer[readBufferPosition++] = b;
                            }
                        }
                    }
                } catch (IOException ex) {
                    Log.d(TAG,"run: " + ex.getMessage());
                }
            }
            Looper.loop();
        }
    });
    workerThread.start();
}

@Override
protected void onPause() {
    progress.dismiss();
    super.onPause();
}

@Override
protected void onStop() {
    progress.dismiss();
    super.onStop();
 }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)