无法从arduino发送数据

问题描述 投票:6回答:1

我已成功将android应用程序连接到arduino但似乎我无法获取数据,即使我使用输入流...我不知道什么是wronge一直在寻找和尝试其他解决方案几天..

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

java android bluetooth
1个回答
1
投票

你不需要InputStream和OutputStream,因为你没有使用原生的android RFCOMM蓝牙api。我用Google搜索了BluetoothSPP类,发现你正在使用这个github库进行blutooth 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();
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.