串行端口中收到的字节数永远不会超过127

问题描述

| 我有一个程序可以将流字节发送到另一台PC。 值的范围是0到255。我这样设置串行端口
sp.Baudrate = 115200;
sp.PortName = \"COM53\";
sp.DataBits = 8;
sp.StopBits = System.IO.Ports.StopBits.One;
sp.Parity = System.IO.Ports.Parity.None;
sp.ReadTimeout = 0;
sp.open();
sp.DataReceived += new
System.IO.Ports.SerialDataReceivedEventHandler(sp_ DataReceived);
然后我有这个
void sp_DataReceived(object sender,System.IO.Ports.SerialDataReceivedEventArgs e)
{

string Mystring = sp.ReadExisting();
byte testbyte = 254;
// Gather all the bytes until 102 is reached
foreach (byte c in Mystring)
{
if(pixelcount<102)
pixel[pixelcount] = c;
pixelcount++;
if (c 126)
Console.WriteLine(\"big number {0}\",c);// biggest number ever printed is 127
}
//got all the bytes,Now draw them
if (pixelcount == 102)
{
Console.WriteLine(\"testbyte = {0}\",testbyte);
oldx = 0;
pixelcount = 0;
pictureBox_rawData.Invalidate();
}
}
我的问题是\ c永远不会超过127。 我在这里想念什么? 我已经测试了所有编码,但无法解决此问题。请帮忙。 谢谢 int91h     

解决方法

如果要获取原始字节,则应使用SerialPort.Read将其读入字节数组。使用
SerialPort.ReadExisting
将数据读入字符串将强制进行某种转换(即编码会将字节转换为char)。     ,在SerialPort.Write的文档中(“备注”部分):   默认情况下,SerialPort使用ASCIIEncoding编码字符。 ASCIIEncoding将大于127的所有字符编码为(char)63或\'?\'。要支持该范围内的其他字符,请将Encoding设置为UTF8Encoding,UTF32Encoding或UnicodeEncoding。 也许ReadExisting的行为类似,并且将每个大于127的字节转换为63。     ,您不是在读取字节,而是在阅读文本。这是通过根据SerialPort.Encoding属性值转换端口接收的字节而产生的。默认为Encoding.ASCII,这是一种仅包含字节值0到127的字符的编码。超出该范围的字节值将替换为\“?\”字符。 这解释了您所看到的。在您的情况下,选择其他编码是不太可能的解决方案,请改用SerialPort.Read()。相当于ReadExisting的方法是使用足够大的count参数调用Read()。您将获得任何合适的值,复制到缓冲区中的实际字节数就是方法的返回值。当输入缓冲区为空时,它将阻塞。仅当e.EventType不等于SerialData.Chars时,这才可能在DataReceived事件处理程序中发生。通常不是问题。 请注意,对pict​​ureBox_rawData.Invalidate()的调用无效。 DataReceived在线程池线程上运行。您只能触摸UI线程上的控件成员。您将需要使用Control.BeginInvoke()。     ,就像Hans Passant所说的那样,您需要使用SerialPort.Read()。 这样的事情会起作用
\'retrieve number of bytes in the buffer
Dim bytes1 As Integer = ComPort.BytesToRead

\'create a byte array to hold the awaiting data
Dim comBuffer As Byte() = New Byte(bytes1 - 1) {}

\'read the data and store it to comBuffer
ComPort.Read(comBuffer,bytes1)