我正在尝试打开/关闭继电器,但到目前为止我无法成功。我尝试了 Coolterm 程序来查看驱动程序是否安装正确,是的,它工作正常,我能够通过 GUI 打开/关闭它。但是我在通过 java 发送命令以打开继电器时遇到问题..
通讯参数: 8 数据,1 停止,无奇偶校验 波特率:9600
命令: OFF 命令:FF 01 00 (HEX) 或 255 1 0 (DEC)
ON 命令:FF 01 01(十六进制)或 255 1 1(十进制)
我的代码如下:
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”,它是 8 个字节长的 ascii 兼容编码。这看起来很不寻常,我猜你的小工具真的需要 3 个字节,如下面的代码所示:
byte[] data = new byte[] {(byte)0xFF, (byte)0x01, (byte)0x01};
out.write(data);
关于Java串口问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7162297/