如何向外部设备发送数据
我有一个串行设备通过 com 端口连接到我的计算机。我想将十六进制数据发送到该设备,向该设备发送数据的最佳方法是什么。
例如,我有这个数据 -
String hexStr = "02303033434333d3037313131303131323639393130333131303139033f";
我现在正在做的是 -
byte[] unsignedByte = HexUtil.convertToBytes(hexStr);
serialPort.getOutputStream().write(unsignedByte);
我面临的问题是 - 串行设备没有响应? 当我通过软件发送相同的十六进制字符串时,终端正在响应。我做错了什么吗?
这是代码的一部分 -
mOutputToPort.write(unsignedByte);
logger.info("Byte Sent");
mOutputToPort.flush();
logger.info("Waiting for response");
Thread.sleep(10000);
byte mBytesIn [] = new byte[2000];
int num = mInputFromPort.read(mBytesIn);
System.out.println("Number of bytes read -"+ num);
for(byte b : mBytesIn){
System.out.print(b);
System.out.print(" ");
}
System.out.println();
大家好,我终于自己找到了如何正确执行的方法。 我没有以正确的格式发送数据。我在使用其他软件监控串行数据交换时发现了这一点。
将数据发送到串行设备的最佳方式是 - ASCII 数据 -->十六进制字符串 -->无符号字节
I have a serial device connected to my computer at com port. I want to send Hex data to this device, what is the best approach to send data to the device.
For example I have this data-
String hexStr = "02303033434333d3037313131303131323639393130333131303139033f";
What I am doing right now is-
byte[] unsignedByte = HexUtil.convertToBytes(hexStr);
serialPort.getOutputStream().write(unsignedByte);
The problem I am facing is - Serial device is not responding ?
When i m sending the same hex string via a software, terminal is responding. Am I doing something wrong?
This is some part of the code-
mOutputToPort.write(unsignedByte);
logger.info("Byte Sent");
mOutputToPort.flush();
logger.info("Waiting for response");
Thread.sleep(10000);
byte mBytesIn [] = new byte[2000];
int num = mInputFromPort.read(mBytesIn);
System.out.println("Number of bytes read -"+ num);
for(byte b : mBytesIn){
System.out.print(b);
System.out.print(" ");
}
System.out.println();
Hi Guys, I finally found out by myself how to do it properly.
I was not sending data in correct format. I found out while i monitor the serial data exchange using other software.
the best way to send data to serial device is -
ASCII DATA --> HEX STRING --> UNSIGNED BYTE
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能希望在写入操作后
flush()
输出流。尝试一下是否有帮助:You may want to
flush()
the outputstream after write operations. Try if this helps: