private void button1USARTstart_Click(object sender, EventArgs e)
{
if(USARTstate)//默认启动
{
button1USARTstart.Text = "停止";
serialPort1.PortName = comboBox1PortName.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2BaudRate.Text);
try
{
serialPort1.Open();
USARTstate = false;//可以关闭
comboBox1PortName.Enabled = false;
comboBox2BaudRate.Enabled = false;
timer1.Enabled = true;
}
catch (System.Exception ex)
{
MessageBox.Show("打开串口失败! :"+ex.Message);
}
}
else
{
button1USARTstart.Text = "启动";
try
{
serialPort1.Close();
USARTstate = true;//可以启动
comboBox1PortName.Enabled = true;
comboBox2BaudRate.Enabled = true;
timer1.Enabled = false;
}
catch (System.Exception ex)
{
MessageBox.Show("关闭串口失败! :"+ex.Message);
}
}
}
//public static 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();
//}
public static string ByteArrayToString(byte[] data)//字节数组转为十六进制字符串
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToChar(b));
//return sb.ToString().ToUpper();
return sb.ToString();
}
public static byte[] HexStrToHexByte(string hexStr)
{
hexStr = hexStr.Replace(" ", "");//去掉字符串中所有的空格
if (hexStr.Length % 2 != 0) hexStr += " ";
byte[] returnBytes = new byte[hexStr.Length / 2];//新建一个byte数组,存放16进制byte
for (int i = 0; i < returnBytes.Length; i++)
{ returnBytes[i] = Convert.ToByte(hexStr.Substring(i * 2, 2).Trim(), 16); }
return returnBytes;
}
private void button2SendData_Click(object sender, EventArgs e)//发送数据
{
if (serialPort1.IsOpen)
{
if (checkBox.Checked)//send hex
{
//byte[] data = Encoding.ASCII.GetBytes(textBox1Tx.Text);
byte[] data = HexStrToHexByte(textBox1Tx.Text);
//string str = ByteArrayToHexString(data);
serialPort1.Write(data, 0, data.Length);
//serialPort1.Write(str);
TxNum += data.Length;
}
else
{
string str = textBox1Tx.Text.Trim();// 获得
serialPort1.Write(str);
TxNum += str.Length;
}
labelTxNum.Text = "TX:" + TxNum.ToString();
}
else
return;
}
private void timer1_Tick(object sender, EventArgs e)//定时器读取接受的数据,你想要的处理都可放在这里。
{
if (serialPort1.IsOpen == false) return;
int receiveNumber = serialPort1.BytesToRead;
if (receiveNumber == 0) return;
string str = null;
byte[] bs = new byte[receiveNumber];
serialPort1.Read(bs, 0, receiveNumber);
if (checkBox.Checked)
{
foreach (byte b in bs)
str += b.ToString("x2") + " ";
}
else
{
str = ByteArrayToString(bs);
}
textBox2Rx.AppendText(str);
RxNum += receiveNumber;
labelRxNum.Text = "RX:" + RxNum.ToString();
}
private void buttonClear_Click(object sender, EventArgs e)// 清除接收的textbox中的字符
{
textBox2Rx.Clear();
TxNum = 0;
RxNum = 0;
labelTxNum.Text = "TX:" + TxNum.ToString();
labelRxNum.Text = "RX:" + RxNum.ToString();
}
}
}

}