我试图打开/关闭继电器,但到目前为止我无法成功。我尝试了Coolterm程序,看看驱动程序是否安装正确,是否有效,我可以通过GUI打开/关闭它。但是我有问题通过java发送命令来打开继电器..
通讯参数: 8个数据,1个停止,没有奇偶校验 波特率:9600
命令: OFF命令:FF 01 00(HEX)或255 1 0(DEC)
ON命令:FF 01 01(HEX)或255 1 1(DEC)
我的代码如下:
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();
}
}
}
提前致谢...
答案 0 :(得分:3)
您的程序当前正在以ascii兼容编码发送字符串“FF 01 01”,该字符串长度为8个字节。这似乎很不寻常,我猜你的小工具真的需要3个字节,如下面的代码所示:
byte[] data = new byte[] {(byte)0xFF, (byte)0x01, (byte)0x01};
out.write(data);
答案 1 :(得分:0)
请尝试以下代码:
byte[] array = { -1, 1, 1 };
out.write(array);
而不是
out.write(dataHex.getBytes());