通过串口将字节数组 - Passing byte array through serialport

- 此内容更新于:2016-02-15
主题:

我想通过以下字节数组通过串行端口。我通过了字节数组一样遵循但串口接收信件像B,B等。我怎么能接受它作为数字??

原文:

I want to pass the following byte array through serial port.

array[j].abc = 2;
array[j].def = 4;
array[j].gh = 6;
array[j].ij = 0;
array[j].jl = 1;
array[j].fg= 1;
array[j].bh = 2;

I passed the byte array as follow

byte[] wtbin = TestSerializer.StructureToByteArray(array[j]);
byte[] bharr = new byte[1];
bharr[0] = wtbin[i];

serialPort1.Write(bharr, 0, 1);

But serialport receives it as letters like B,B etc. How can I receive it as numbers??

网友:你是什么意思“串口接收”吗?串口不处理数据。

(原文:What do you mean with "the serialport receives"? The serial port doesn't handle data.)

网友:@CommuSoft:我使用的腻子。Exe”来查看数据。我意味着值显示在腻子是B等

(原文:@CommuSoft: I used 'PUTTY.Exe' to see the data.. Here i meant that values shows in putty is like B etc)

解决方案:
你可以通过一个字节数组(通常叫缓冲区)方法。你在做什么而不是单个字节传递给方法。在你的情况下,调用的方法是类似的:你可以在MSDN阅读更多关于串口,串口写。另外请记住,你是发送字节,不是ASCII文本。根据你发送的腻子可能显示不同的东西。为了将ASCII字节数组(缓冲区),您可以使用希望这有助于:)
原文:

You can pass a whole byte array (generally named buffer) into the serialPort.Write() method. What you are doing instead is passing a single byte to the method. In your case the call to the method would be something like:

serialport1.Write(wtbin, 0, wtbin.Length);

You can read more about SerialPort on MSDN - SerialPort Write. Additionally keep in mind that you are sending bytes, not ASCII text. Depending on what you are sending PUTTY may display different things. In order to convert a byte array(buffer) back to ASCII, you can use

Encoding.ASCII.GetString(buffer);

Hope this helps :)