无法从arduino发送数据

时间:2019-04-13 18:18:53

标签: java android bluetooth

我已经成功地将android应用程序连接到了arduino,但是即使使用输入流,我似乎也无法获取数据...我不知道几天来一直在尝试其他解决方案的原因。

Android Studio代码:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bluetooth = new BluetoothSPP(this);
    text = (TextView) findViewById(R.id.textView2);
    connect = (Button) findViewById(R.id.connect);
    on = (Button) findViewById(R.id.on);
    BluetoothSocket socket = null;
    mAdapter = BluetoothAdapter.getDefaultAdapter();

    if (!bluetooth.isBluetoothAvailable()) {
        Toast.makeText(getApplicationContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();
        finish();
    }

    bluetooth.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
        public void onDeviceConnected(String name, String address) {
            connect.setText("Connected to " + name);
        }

        public void onDeviceDisconnected() {
            connect.setText("Connection lost");
        }

        public void onDeviceConnectionFailed() {
            connect.setText("Unable to connect");
        }
    });

    connect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (bluetooth.getServiceState() == BluetoothState.STATE_CONNECTED) {
                bluetooth.disconnect();
            } else {
                Intent intent = new Intent(getApplicationContext(), DeviceList.class);
                startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
            }


        }
    });


    on.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


        }


    });

    /*off.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bluetooth.send(OFF, true);
        }
    });*/




}






 public void onStart() {
    super.onStart();
    if (!bluetooth.isBluetoothEnabled()) {
        bluetooth.enable();
    } else {
        if (!bluetooth.isServiceAvailable()) {
            bluetooth.setupService();
            bluetooth.startService(BluetoothState.DEVICE_OTHER);
        }
    }
}

< /* class ConnectedThread extends Thread {
        private InputStream mInStream;

public ConnectedThread(BluetoothSocket socket) throws IOException { InputStream tmpIn = null; // Get the input and output streams, using temp objects because // member streams are final try { tmpIn = socket.getInputStream(); } catch (IOException e) { } mInStream = tmpIn; } } public void run() { BufferedReader r = new BufferedReader(new InputStreamReader(mInStream)); while (true) { try { int a = r.read(); Log.d(TAG, Integer.toString(a)); } catch (IOException e) { break; } } } }*/ 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"); readBufferPosition = 0; handler.post(new Runnable() { public void run() { text.setText(data); } }); } else { readBuffer[readBufferPosition++] = b; } } } } catch (IOException ex) { stopWorker = true; } } } }); workerThread.start(); } void closeBT() throws IOException { stopWorker = true; mmOutputStream.close(); mmInputStream.close(); text.setText("Bluetooth Closed"); } public void onDestroy() { super.onDestroy(); bluetooth.stopService(); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) { if (resultCode == Activity.RESULT_OK) bluetooth.connect(data); } else if (requestCode == BluetoothState.REQUEST_ENABLE_BT) { if (resultCode == Activity.RESULT_OK) { bluetooth.setupService(); } else { Toast.makeText(getApplicationContext() , "Bluetooth was not enabled." , Toast.LENGTH_SHORT).show(); finish(); } } }

Arduino代码:

enter image description here

1 个答案:

答案 0 :(得分:1)

您不需要InputStream和OutputStream,因为您没有使用本地android RFCOMM蓝牙API。我在BluetoothSPP类上进行了搜索,发现您正在使用此github库进行蓝牙spp通信:akexorcist/Android-BluetoothSPPLibrary

您的代码似乎可以用于连接/断开与arduino设备的连接。因此,我认为您恰当地集成了该库。缺少的是发送/接收蓝牙数据的代码。我更新了您的代码,如下所示:

on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    bluetooth.send("ON", true);
}
});

off.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        bluetooth.send("OFF", true);
    }
});

bluetooth.setOnDataReceivedListener(new OnDataReceivedListener() {
    public void onDataReceived(byte[] data, String message) {
         Toast.makeText(getApplicationContext(), String.format("Data Received: %s", message), Toast.LENGTH_SHORT).show();
    }
});