private void btnSend_Click(object sender, EventArgs e)
{
if (cbTimeSend.Checked)
{
tmSend.Enabled = true;
}
else
{
tmSend.Enabled = false;
}
if (!sp1.IsOpen) //如果没打开
{
MessageBox.Show("请先打开串口!", "Error");
return;
}
// string strSend = null;
String strSend = txtSend.Text.ToString();
if (radio1.Checked == true) //“HEX发送” 按钮
{
//处理数字转换
string sendBuf = strSend;
string sendnoNull = sendBuf.Trim();
string sendNOComma = sendnoNull.Replace(',', ' '); //去掉英文逗号
string sendNOComma1 = sendNOComma.Replace(',', ' '); //去掉中文逗号
string strSendNoComma2 = sendNOComma1.Replace("0x", ""); //去掉0x
strSendNoComma2.Replace("0X", ""); //去掉0X
string[] strArray = strSendNoComma2.Split(' ');
int byteBufferLength = strArray.Length;
for (int i = 0; i < strArray.Length; i++)
{
if (strArray[i] == "")
{
byteBufferLength--;
}
}
// int temp = 0;
byte[] byteBuffer = new byte[byteBufferLength];
int ii = 0;
for (int i = 0; i < strArray.Length; i++) //对获取的字符做相加运算
{
Byte[] bytesOfStr = Encoding.Default.GetBytes(strArray[i]);
int decNum = 0;
if (strArray[i] == "")
{
//ii--; //加上此句是错误的,下面的continue以延缓了一个ii,不与i同步
continue;
}
else
{
decNum = Convert.ToInt32(strArray[i], 16); //atrArray[i] == 12时,temp == 18
}
try //防止输错,使其只能输入一个字节的字符
{
byteBuffer[ii] = Convert.ToByte(decNum);
}
catch (System.Exception ex)
{
MessageBox.Show("字节越界,请逐个字节输入!", "Error");
tmSend.Enabled = false;
return;
}
ii++;
}
sp1.Write(byteBuffer, 0, byteBuffer.Length);
}
else //以字符串形式发送时
{
sp1.WriteLine(txtSend.Text); //写入数据
}
}
void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//输出当前时间
DateTime dt = DateTime.Now;
txtReceive.Text += dt.GetDateTimeFormats('f')[0].ToString() + "\r\n";
txtReceive.SelectAll();
txtReceive.SelectionColor = Color.Blue; //改变字体的颜色
try
{
byte[] receivedData = new byte[sp1.BytesToRead]; //创建接收字节数组
sp1.Read(receivedData, 0, receivedData.Length); //读取数据
if (receivedData.Length == 0)
return;
sp1.DiscardInBuffer(); //清空SerialPort控件的Buffer
if (receivedData.Length == 3 && receivedData[0] == 0xFF && receivedData[1] == _totalBytes[1] &&
receivedData[2] == 0x00)
{
//_totalBytes[1] = Convert.ToByte(_totalBytes[1] == 0xB5 ? 0xB6 : 0xB5);
_totalBytes[1] = Convert.ToByte(_totalBytes[1] == 0xB6 ? 0xB5 : 0xB6);
//_size += _totalBytes[1] == 0xB5 ? 512 : 0;
_size += _totalBytes[1] == 0xB6 ? 512 : 0;
SendBytes(false);
}
else
{
//发送失败
}
string strRcv = null;
if (rdSendStr.Checked)
{
strRcv = sp1.Encoding.GetString(receivedData);
}
else
{
//int decNum = 0;//存储十进制
for (int i = 0; i < receivedData.Length; i++) //窗体显示
{
strRcv += receivedData[i].ToString("X2"); //16进制显示
}
}
txtReceive.Text += strRcv + "\r\n";
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "出错提示");
txtSend.Text = "";
}
}
串口发送一段指定的字符串,串口接收,串口收到回复消息,提示出错。未将对象引用设置到对象的实例