【问题标题】:Received data from SerialPort > 0x7F gets displayed as 0x3F从 SerialPort > 0x7F 接收的数据显示为 0x3F
【发布时间】:2018-11-18 19:43:32
【问题描述】:

我想将随机生成的数据从我的 PC 发送到 µC (ATmega328p),然后将其镜像回来。为此,我用 C# 编写了一个程序(我第一次使用它)。

PC 接收回的每个字节 >0xF7 都显示为 0x3F。

µController 正确接收和发送数据(我在 LCD 上显示 µC 接收和发送的所有数据)。 我还使用了两个串行终端工具(HTerm、Pololu Serial Transmitter)来验证 µC 工作正常。 当 PC 最后接收/显示数据时,一定有问题。

在 textBox1 中将接收到的数据显示为 .hex

  private  void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e){

        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        string outp = string.Empty;
        char[] value = indata.ToCharArray();
        foreach(char L in value){
        int V = Convert.ToInt32(L);
        outp+= string.Format("{0:x}",V);
        }

        if (outp != String.Empty)
            Invoke(new Action(() => textBox1.AppendText(outp)));
    }

编辑2//

我解决了这个问题。感谢kunifgunnerone 的提示! port.ReadExisting() 的编码似乎有问题。相反,我知道使用 port.Read()。

private  void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e){

        int bytesToRead = port.BytesToRead;
        byte[] value = new byte[bytesToRead];
        port.Read(value,0,bytesToRead);
        string indata = BitConverter.ToString(value);
        if (indata != String.Empty)
            Invoke(new Action(() => textBox1.AppendText(indata)));
    }

【问题讨论】:

  • 您的问题是由编码/解码字节的人引起的。 0x7F 以上的所有内容都更改为 0x3F(问号符号)。如果您的程序发送 0x08 0x09 0x10,那与发送“8910”不同。如果你向你的 uC 发送 0xFF 之类的东西,会得到什么回应?
  • 你是对的,>0x​​7F 的所有内容都会被回显为 0x3F。有点愚蠢,没看到,我会编辑我的帖子。

标签: c# serial-port hex


【解决方案1】:

正如本文ASCIIEncoding.ASCII.GetBytes() Returning Unexpected Value 中的那样,类似于 Encoding.ASCII.GetBytes() 或 ASCIIEncoding.ASCII.GetBytes() 的处理似乎在某处完成(可能是 indata.ToCharArray())。

请尝试将char[] value = indata.ToCharArray();更改为byte[] value = Encoding.GetEncoding("ISO-8859-1").GetBytes(indata);,同时将其他char[]更改为byte[]。

【讨论】:

  • 问题仍然存在,但你链接的文章是有道理的。我稍后会研究它。
猜你喜欢
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多