Java串口问题

标签 java serial-port macos

我正在尝试打开/关闭继电器,但到目前为止我无法成功。我尝试了 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/

相关文章:

macos - 在 CentOS 上启动 selenium 服务器

python - Jupyter Notebook 未从 Anaconda Navigator 启动

java - Gradle 派生出多次 war

java - 如何在 Java Apache POI 库中使用嵌入式方程?

C++:带 D2XX 驱动程序的 Bit-banging(USB 到串行 UART)FTDI 模块

c - 将 rs232 编程为 lcd (Linux)

macos - 在 MacOS 中使用鼠标和热键 move 窗口

java - 如何将不同类型的对象包装在一个包装对象中

java - 如何捕获pcap4j中的域?

java - 我可以使用 jssc 与虚拟串行设备通信吗? ttyS0 配置问题 (Ubuntu)