C# 串口控件 datareceive事件的问题 40
privatevoidserialPort1_DataReceived(objectsender,SerialDataReceivedEventArgse){string...
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string readString ="";
if (checkBox1.Checked == true)
{
int bytesize = serialPort1.BytesToRead;
byte[] buffer = new byte[bytesize];
serialPort1.Read(buffer, 0, bytesize);
readString = ByteArrayToHexString(buffer);
string[] sarray = readString.Split(' ');
int result = string.Compare("A7", sarray[1]);
if (result == 0)
{
string a_8 = "0F A8 30 31 03 7A 4E 9E F0 FF";
serialPort1.WriteLine(a_8);
}
this.Invoke(updateText, new string[] { readString });
}
else....
每次运行都说sarry[1]数组索引出错,我查看变量出错的时候bytesize是0,但是只要不加上这个判断字符串的几条语句,bytesize就不是0
string readString ="";
if (checkBox1.Checked == true)
{
int bytesize = serialPort1.BytesToRead;
byte[] buffer = new byte[bytesize];
serialPort1.Read(buffer, 0, bytesize);
readString = ByteArrayToHexString(buffer);
this.Invoke(updateText, new string[] { readString });
}
譬如这样,程序运行就没错,我跟踪变量,bytesize都是正常的,不知道是不是转换函数出错 转换函数如下private string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();
} 展开
{
string readString ="";
if (checkBox1.Checked == true)
{
int bytesize = serialPort1.BytesToRead;
byte[] buffer = new byte[bytesize];
serialPort1.Read(buffer, 0, bytesize);
readString = ByteArrayToHexString(buffer);
string[] sarray = readString.Split(' ');
int result = string.Compare("A7", sarray[1]);
if (result == 0)
{
string a_8 = "0F A8 30 31 03 7A 4E 9E F0 FF";
serialPort1.WriteLine(a_8);
}
this.Invoke(updateText, new string[] { readString });
}
else....
每次运行都说sarry[1]数组索引出错,我查看变量出错的时候bytesize是0,但是只要不加上这个判断字符串的几条语句,bytesize就不是0
string readString ="";
if (checkBox1.Checked == true)
{
int bytesize = serialPort1.BytesToRead;
byte[] buffer = new byte[bytesize];
serialPort1.Read(buffer, 0, bytesize);
readString = ByteArrayToHexString(buffer);
this.Invoke(updateText, new string[] { readString });
}
譬如这样,程序运行就没错,我跟踪变量,bytesize都是正常的,不知道是不是转换函数出错 转换函数如下private string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询