如何从串口读取二进制数据而不进行任何编码? [英] How to read Binary Data from Serial Port without any Encoding?

查看:121
本文介绍了如何从串口读取二进制数据而不进行任何编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



我开发了一个应用程序,用于从C#中的SerialPort读取数据。它的工作正常。但从SerialPort读取的数据与我预期的不同。



当我使用XCTU或Matlab读取端口时,它将提供如下数据,

Hello,

I have developed an application to read data from SerialPort in C#. Its working fine. But the data read from SerialPort is different than I expected.

When I read the port using XCTU or Matlab it will gives the data like the following,

00 00 e2 00 40 74 95 07 02 25 14 00 8a 92 00 77 ff



但是当我正在阅读来自C#应用程序的相同数据,


But When I am reading the same data from C# application it gives,

8C3F275A483F



我期待C#应用程序的结果数据如来自Matlab和XCTU的结果。我尝试过使用SerialPort编码(ASCIIEncoding,Unicode,Latin)。但没有任何作用。帮我。这是我的代码,


I am expecting the result data of C# application like the result from Matlab and XCTU. I have tried with SerialPort encodings(ASCIIEncoding, Unicode, Latin). But nothing works. Help me. this is my code,

//DataReceived event handler
public event EventHandler<SerialDataEventArgs> NewSerialDataRecieved;
//Serial Port Initialization
SerialPort _serialPort = new SerialPort("COM3",9600,Parity.None,8,StopBits.One);
_serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
_serialPort.Open();

//DataReceived event
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    int dataLength = _serialPort.BytesToRead;
    byte[] data = new byte[dataLength];
    int nbrDataRead = _serialPort.Read(data, 0, dataLength);
    if (nbrDataRead == 0)
        return;
    
    if (NewSerialDataRecieved != null)
        NewSerialDataRecieved(this, new SerialDataEventArgs(data));
}

//class SerialDataEventArgs
public class SerialDataEventArgs : EventArgs
{
    public byte[] Data;
    public SerialDataEventArgs(byte[] dataInByteArray)
    {
        Data = dataInByteArray;
    }
    
}

//printing the read data
string str = BitConverter.ToString(e.Data);
txtData.AppendText(str);//txtData is a TextBox

推荐答案

引用:

我期待C#应用程序的结果数据喜欢Matlab和XCTU的结果。我尝试过使用SerialPort编码(ASCIIEncoding,Unicode,Latin)。但没有任何作用。帮我。这是我的代码,

I am expecting the result data of C# application like the result from Matlab and XCTU. I have tried with SerialPort encodings(ASCIIEncoding, Unicode, Latin). But nothing works. Help me. this is my code,

技巧很简单,你从串口接收二进制数据,不要转换它。

你的数据包含一些字节在任何编码方案中都没有转换,它们只是二进制值(00 07 02 14),都取决于发送数据的设备。如果不是特定于设备,唯一的可能是数据包含以二进制形式发送的一些浮点值。



所以,直到你知道数据是什么,将它作为一系列字节处理,并显示数据,只需将每个字节显示为十六进制值。

The trick is simple, you receive binary data from serial port, don't convert it.
Your data contain some bytes that do not convert in any coding scheme, they are just binary values (00 07 02 14), all depend on the device that send the data. If not device specific, the only possibility is that the data contain some floating point value sent in its binary form.

So until you have clue of what is the data, handle it as a series of bytes, and to display the data, just display each byte as an hexadecimal value.


这部分 VR Karthikeyan 的代码:

This part of VR Karthikeyan's code:
//printing the read data
string str = BitConverter.ToString(e.Data);
txtData.AppendText(str);//txtData is a TextBox

要获得理想的输出 00 00 e2 00 ...... ,请将上面的块更改为使用字符串格式化程序X,如下所示:

To get the desirable output 00 00 e2 00 ......, change the above block to use string formatter "X" like this:

foreach (byte i in e.Data)
{
    // i is byte value, two hexadecimal digit is enough
    // to hold its value (max 255, hex FF). For illustration
    // space is appended after each byte printout. 
    string str2 = i.ToString("X2").Append(" ");
    txtData.AppendText(str2);
}

然而,由于将文本附加到 txtData (这是一个textBox),这会执行得很慢。当byte []很大时,速度差异显示。在这种情况下,使用此技术来提高感知性能,主要是通过在循环外移动 .AppendText()操作:

Yet this executes slowly due to appending text to txtData which is a textBox. When byte[] is large the speed difference shows. In that case use this technique to improve perceived performance, mainly by moving the .AppendText() operation outside of the loop:

using System.Text;

StringBuilder s = new StringBuilder();
foreach (byte i in e.Data)
{
    s.Append(i.ToString("X2")).Append(" ");
}
txtData.AppendText(s.ToString());

该技术采用 StringBuilder 来收集数组中所有字节的转换结果< b> e.Data 的。 foreach循环完成后,一次性附加 txtData 。为此, VR Karthikeyan 的代码可以这样写:

The technique employed StringBuilder to collect conversion results of all the bytes in the array e.Data. When the foreach loop finishes, txtData is appended in one go. To wrap this up, VR Karthikeyan's code can be written like this:

//-----------------------------------------------------------------
// StringBuilder class use this name space to import
//-----------------------------------------------------------------
using System.Text;

//-----------------------------------------------------------------
// The code snapshot, portion to print out the byte array fast
//-----------------------------------------------------------------
txtData.AppendText(OurOwnConverter(e.Data)); //txtData is a TextBox

//-----------------------------------------------------------------
// A formatter function is used to wrap up the converstion
//-----------------------------------------------------------------
string OurOwnConverter(byte[] byteArray)
{
    StringBuilder s = new StringBuilder();
    foreach (byte i in byteArray)
    {
        s.Append(i.ToString("X2")).Append(" ");
    }
    return s.ToString();
}


这篇关于如何从串口读取二进制数据而不进行任何编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆