用Java RXTX库写入串口问题

时间:2017-03-25 04:11:29

标签: java bluetooth arduino serial-port rxtx

我试图将一些字节从java代码发送到连接到Arduino的蓝牙模块。这是我的代码。

repositories {
  mavenCentral()
}

dependencies {
  compile 'org.eclipse.jetty:jetty-webapp:9.4.0.v20161208'
}

import gnu.io.*; import java.io.IOException; import java.io.OutputStream; public class ArduinoSerialWriter { private static OutputStream arduinoOutputStream; public static void init() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException { SerialPort arduino = (SerialPort) CommPortIdentifier.getPortIdentifier("COM6") .open(ArduinoSerialWriter.class.getName(), 2000); arduino.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); arduinoOutputStream = arduino.getOutputStream(); } public static void writeToArduino(byte[] bytes) throws IOException { arduinoOutputStream.write(bytes); } public static void main(String[] args) { try { ArduinoSerialWriter.init(); } catch (Exception e) { e.printStackTrace(); } try { arduinoOutputStream.write(new byte[]{(byte) -1, (byte) 90, (byte) 40}); } catch (IOException e) { e.printStackTrace(); } } } 似乎正常工作并连接到蓝牙模块。问题是对init()的调用无限期阻塞。我还可以说因为Arduino没有做任何事情而没有发送字节。但是,没有抛出异常。

我读到某个地方可能是因为Arduino正在重置并且在准备接收数据之前需要时间,所以我尝试在写入端口之前添加arduinoOutputStream.write(),但这并没有改变任何东西

我还使用调试器来确定代码阻塞的位置,并使用RXTX库中RXTXPort.class的write(byte [])方法将其跟踪到这些行:

Thread.sleep(10000);

从我可以收集的信息中,在下一行实际发送字节之前调用RXTXPort.this.waitForTheNativeCodeSilly(); RXTXPort.this.writeArray(var1, 0, var1.length, RXTXPort.this.monThreadisInterrupted); ,这就是代码冻结的地方。

我也尝试在调用write方法之后添加waitForTheNativeCodeSilly();,但这并没有帮助,因为代码在该行甚至到达之前就冻结了。

任何帮助都将不胜感激。

更新

我尝试使用移除蓝牙模块并使用USB电缆代替Arduino,它完美无缺。我想我可能需要使用蓝牙模块进行设置。

这是一个HC-06蓝牙模块。这是我从哪里得到的: https://www.amazon.ca/JMT-Wireless-Bluetooth-Serial-Arduino/dp/B00HXAE0PQ/

我设置它的唯一方法是在我的Windows 10 pc上管理蓝牙设备并点击一对。它说配对在它下面,所以我不确定问题是什么。

再次更新:

我尝试使用Arduino IDE中的串行监视器将数据发送到蓝牙模块,整个IDE完全冻结。我可以关闭它的唯一方法是杀死任务管理器中的进程。我相当肯定Arduino IDE遇到了和我一样的问题,所以它肯定与蓝牙芯片有关,而不是我的代码本身。

1 个答案:

答案 0 :(得分:0)

原来我有完全错误的想法。与尝试将蓝牙芯片视为COM端口相比,我使用蓝牙连接要好得多。我想我只是因为我已经习惯了Arduino。

我使用了适用于java的bluecove库,它现在运行得很好!