0

我的 EV3 和我的 Android 设备之间的连接有一些问题。我可以用我的 EV3 接收数据,但我不能发送。如果您想查看该应用程序,我已使用我的 Github 帐户注册。

这是我的代码:

public class Bluetooth {
    public static int speed = 100;
    public static BTConnector connector;
    public static NXTConnection connection;

    public static void main(String[] args) throws IOException {    
        openConnection();
        Thread moveWithBluetoothThread = new Thread(new moveWithBluetooth());
        moveWithBluetoothThread.start();    
    }

    public static void openConnection() {
        connector = new BTConnector();
        LCD.drawString("Waiting for Connecrion", 3, 1);
        connection = connector.waitForConnection(0, NXTConnection.RAW);
        LCD.clear();
        LCD.drawString("Connected", 3, 5);    
    }    
}

class moveWithBluetooth implements Runnable {
    @Override
    public void run() {
        while (true) {    
            InputStream is = Bluetooth.connection.openInputStream();
            BufferedReader dis = new BufferedReader(new InputStreamReader(is), 1);
            OutputStream os = Bluetooth.connection.openOutputStream();
            BufferedWriter dos = new BufferedWriter(new OutputStreamWriter(os), 1);
            try {
                byte[] b;
                for (int i = 0; i < 100; i++) {
                    String n = dis.readLine();
                    System.out.println(n);
                    b = n.getBytes();
                    Bluetooth.connection.write(b, b.length);
                    Thread.sleep(10);
                    dos.write(n);
                    dos.flush();
                }
                dis.close();
                dos.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }    
    }
}
4

1 回答 1

0

我发现,我的 EV3 没有问题。这意味着,您可以使用此代码。如果你有同样的问题,这是我的解决方案:

问题是我在我的应用程序中使用的库。在 Github 的“Tssues”-Tab 是我的问题。库会一直等到传输完成,但 EV3 会发送一个永久流,所以我只需要\r\n在传输结束时添加即可。我的最终代码如下所示:

byte[] b = (n + "\r\n").getBytes();
Bluetooth.connection.write(b, b.length);
于 2020-01-15T11:49:12.870 回答