【问题标题】:How to send data to external device如何向外部设备发送数据
【发布时间】:2010-08-12 04:18:09
【问题描述】:

我有一个串行设备通过 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 数据 --> 十六进制字符串 --> 无符号字节

【问题讨论】:

  • 能否请您发送 ASCII DATA --> HEX STRING --> UNSIGNED BYTE 代码中的意思?据我了解,您的旧代码正在这样做(ascii 字符串到十六进制字节)

标签: java serial-port hexdump


【解决方案1】:

您可能希望在写操作后flush() 输出流。试试看是否有帮助:

byte[] unsignedByte = HexUtil.convertToBytes(hexStr);
serialPort.getOutputStream().write(unsignedByte);
serialPort.getOutputStream().flush();   // <- new line added here

【讨论】:

  • 大家好,我终于自己找到了正确的方法。我没有以正确的格式发送数据。我在使用其他软件监控串行数据交换时发现。向串行设备发送数据的最佳方式是 - ASCII DATA --> HEX STRING --> UNSIGNED BYTE
猜你喜欢
  • 2019-05-09
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多