Java串行端口问题

Java串行端口问题,java,serial-port,macos,Java,Serial Port,Macos,我正试图打开/关闭继电器,但到目前为止我没有成功。我尝试了Coolterm程序,看看驱动程序是否安装正确,是的,它工作正常,我能够通过GUI打开/关闭它。但是,我无法通过java发送打开继电器的命令 通信参数: 8个数据,1个停止,无奇偶校验 波特率:9600 命令: 关闭命令:FF 01 00(十六进制)或255 1 0(十二进制) ON命令:FF 01 01(十六进制)或255 11(十二进制) 我的代码如下: public class Application { InputStream

我正试图打开/关闭继电器,但到目前为止我没有成功。我尝试了Coolterm程序,看看驱动程序是否安装正确,是的,它工作正常,我能够通过GUI打开/关闭它。但是,我无法通过java发送打开继电器的命令

通信参数: 8个数据,1个停止,无奇偶校验 波特率:9600

命令: 关闭命令:FF 01 00(十六进制)或255 1 0(十二进制)

ON命令:FF 01 01(十六进制)或255 11(十二进制)

我的代码如下:

public class Application {

InputStream in;
OutputStream out;
String dataHex = "FF 01 01";

void connect(String portName) throws Exception {

CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
System.out.println(portIdentifier);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
System.out.println(commPort);
SerialPort serialPort = (SerialPort) commPort;
System.out.println(serialPort);
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

this.in = serialPort.getInputStream();
this.out = serialPort.getOutputStream();

System.out.println(dataHex.getBytes());
out.write(dataHex.getBytes());

System.out.println("end");


}

InputStream getIn() {
return this.in;
}

OutputStream getOut() {
return this.out;
}

public static void main(String args[]) throws QTException, FileNotFoundException, IOException {
Application app = new Application();
try {

app.connect("/dev/tty.usbserial-A400953X");

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
}

提前感谢…

您的程序正在发送字符串“FF 01 01”,该字符串采用ascii兼容编码,长度为8字节。这似乎很不寻常,我猜您的小工具需要3个字节,如下代码所示:

byte[] data = new byte[] {(byte)0xFF, (byte)0x01, (byte)0x01};

out.write(data);
byte[] array = { -1, 1, 1 };
out.write(array);
请尝试以下代码:

byte[] data = new byte[] {(byte)0xFF, (byte)0x01, (byte)0x01};

out.write(data);
byte[] array = { -1, 1, 1 };
out.write(array);
而不是

out.write(dataHex.getBytes());

您正在使用哪些Java库?导入Java.io.FileNotFoundException;导入java.io.IOException;导入quicktime.QTException;输入gnu.io.*;导入java.io.InputStream;导入java.io.OutputStream;忽略Qt库,我忘了删除它,因为我以前在使用它。上次我做串口开发时,我删除了与之通信的设备,对我的应用程序进行了一些简单的测试。因此,不要通过等待继电器跳闸来测试你的应用程序,而是让另一个应用程序在同一TTY上监听,看看你的应用程序是否发送了正确的命令来测试你的应用程序。在你证明你的应用程序发送了正确的命令之后,然后介绍实际的串行设备。