gpt4 book ai didi

java - 串口双向通信 Java Comm API

转载 作者:太空宇宙 更新时间:2023-11-04 14:08:14 25 4
gpt4 key购买 nike

大家好,我遇到了以下问题。我有一台扫描仪,我正在使用命令对其进行寻址并接收一些行。目前我尝试使用 super 终端,效果非常好。但现在我的程序中需要这些行,因此我设置了 Java Comm API 和 RXTX(只是因为我无法将其与 Comm API 一起使用)。

我已经在论坛上阅读了很多内容,但无法将其付诸实践。

我的意思是只有 3 部分。首先,我设置了端口、输入流和输出流,它们工作得很好。

    portList = CommPortIdentifier.getPortIdentifiers();
int i;
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM3")) {
// if (portId.getName().equals("/dev/term/a")) {

try {
serialPort = (SerialPort)
portId.open("SimpleWriteApp", 2000);
} catch (PortInUseException e) {System.out.println(e);}
try {
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
} catch (IOException e) {System.out.println(e);}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_XONXOFF_IN);

} catch (UnsupportedCommOperationException e) {System.out.println(e);}

然后我想用outputStream.write("xYZ".getByteS());发送命令我认为这也应该有效。但后来我无法得到回复。

响应应该如下所示02349234235883挪威克朗但它只是卡住了。代码如下所示

                            try {               
System.out.println(messageString);
outputStream.write(messageString.getBytes());
BufferedReader portReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
String line = portReader.readLine();
System.out.println(line);


if (inputStream != null) inputStream.close();
if (outputStream != null) outputStream.close();
if (serialPort != null) serialPort.close();
} catch (IOException e) {System.out.println(e);}

有人可以帮助我吗?非常感谢你的努力

最佳答案

谢谢你的帮助。问题在于添加串行事件和发送命令之间没有足够的时间。在我将线程设置为 sleep 几秒钟后,我毫无问题地得到了响应。

关于java - 串口双向通信 Java Comm API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28631108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com