【问题标题】:Read serialport and store it in a String Variable C#读取串行端口并将其存储在字符串变量 C#
【发布时间】:2018-12-29 09:02:21
【问题描述】:

我必须读取串行端口并将响应存储为字符串变量中的六个字节序列。我试图通过连接响应将响应存储在字符串变量中。但只有响应的最后一个字节被存储。

        int response = port.ReadByte();
        string responseString = "";
        responseString  += response.ToString();
        Console.WriteLine(responseString);

【问题讨论】:

  • 您从串口读取的方式似乎不对。试试这里提到的方法stackoverflow.com/questions/13754694/…
  • 请发布真实的minimal reproducible example,以便人们可以帮助您解决您的问题(即当前发布的代码只读取一个字节并且始终将responseString 设置为该单个字节的空)。否则@HaBom 提供的链接就足够了 - 也许问题应该作为它的副本关闭stackoverflow.com/questions/13754694/…
  • 该代码是否在 DataReceived() 事件中?如果是这样,请将string responseString = ""; 行移出类/表单级别,以免每次都重置。

标签: c# c#-4.0 serial-port port c#-3.0


【解决方案1】:
Port.ReadByte()  

从 SerialPort 输入缓冲区同步读取一个字节。

所以你可能想使用:

Port.ReadExisting()

根据编码在 SerialPort 对象的流和输入缓冲区中读取所有立即可用的字节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    相关资源
    最近更新 更多