串口接收
private long receive_count = 0;//接收字节计数
public static SerialPort serialPort1 = new SerialPort();
public static StringBuilder sb = new StringBuilder(); //为了避免在接收处理函数中反复调用,依然声明为一个全局变量
public Form1()
{
InitializeComponent();
serialPort1.DataReceived += SerialPort1_DataReceived;//在当前窗体中运行serialport串口接收事件
}
///
/// 数据接收事件
///
///
///
public void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int num = 0,tempnum=0;
Thread.Sleep(25);//延迟接收-- 嵌入式mcu在发送时可能出现一段数据分多个包发送 需要一定的延迟
byte[] receive_buf = new byte[tempnum];
byte[] full=new byte[tempnum];
while (serialPort1.BytesToRead>0)
{
tempnum = 0;
tempnum = serialPort1.BytesToRead;
receive_buf = new byte[tempnum];
serialPort1.Read(receive_buf, 0, tempnum);
num += tempnum;
receive_count += num;
full = new byte[full.Length + receive_buf.Length];
}
// throw new NotImplementedException();
//int num = serialPort1.BytesToRead;//获取接收缓冲区的字节数
//byte[] receive_buf = new byte[num];//声明一个大小为num的字节数据用于存放读出的byte型数据
//serialPort1.Read(receive_buf, 0, num);//读取接收缓存区num的字节数
sb.Clear(); //防止出错,首先清空字符串构造器
if (checkBoxshowtime.Checked)
{
BeginInvoke(new Action(() =>
{
textBoxreceive.AppendText("["+DateTime.Now.TimeOfDay.ToString()+"]收:");
}));
}
if (radioButtonreceiveASCII.Checked)
{
sb.Append(Encoding.ASCII.GetString(receive_buf)); //将整个数组解码为ASCII数组
//科学计数法
// sb.Append(Convert.ToDecimal(Convert.ToDouble(Encoding.ASCII.GetString(receive_buf))));
}
else if (radioButtonreceiveHEX.Checked)
{
sb.Append(Conversion.byteToHex(receive_buf));
}
try
{
this.Invoke((EventHandler)(delegate
{
textBoxreceive.AppendText(sb.ToString());
textBoxreceive.AppendText("\r\n");
label8.Text = "RX:" + receive_count.ToString() + "Bytes";
}
)
);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show(ex.Message);
}
}
///
/// 打开/关闭串口
///
///
///
private void buttonopen_Click(object sender, EventArgs e)
{
if (comboBoxpart.Text.Equals(""))
{
MessageBox.Show("选择COM口");
}
else
{
try
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonopen.Text = "打开串口";
}
else
{
serialPort1.PortName = comboBoxpart.Text; //配置COM XX
serialPort1.BaudRate = Convert.ToInt32(comboBoxbaudrate.Text); //波特率
serialPort1.DataBits = Convert.ToInt32(comboBoxdatabits.Text); //数据位长度
//配置校验{
if (comboBoxparity.Text.Equals("None"))
serialPort1.Parity = Parity.None;
else if (comboBoxparity.Text.Equals("Odd"))
serialPort1.Parity = Parity.Odd;
else if (comboBoxparity.Text.Equals("Even"))
serialPort1.Parity = Parity.Even;
else if (comboBoxparity.Text.Equals("Mark"))
serialPort1.Parity = Parity.Mark;
else if (comboBoxparity.Text.Equals("Space"))
serialPort1.Parity = Parity.Space;
if (comboBoxstopbits.Text.Equals("0"))
serialPort1.StopBits = StopBits.None;
if (comboBoxstopbits.Text.Equals("1"))
serialPort1.StopBits = StopBits.One;
if (comboBoxstopbits.Text.Equals("1.5"))
serialPort1.StopBits = StopBits.OnePointFive;
if (comboBoxstopbits.Text.Equals("2"))
serialPort1.StopBits = StopBits.Two;
//}
serialPort1.Open();
}
}
catch (Exception ex)
{
serialPort1 = new SerialPort();
comboBoxpart.Items.Clear();
comboBoxpart.Items.AddRange(SerialPort.GetPortNames());
System.Media.SystemSounds.Beep.Play();
}
}
}
串口发送
public void Send(TextBox textbox)
{
string text= textbox.Text.Replace(" ", "");
StringBuilder showtext = new StringBuilder();
try
{
if (serialPort1.IsOpen)
{
if (radioButtonsendASCII.Checked)
{//ASCII发送
if (checkBoxnewline.Checked)
{//发送新行
if(checkBoxreturn.Checked)//回车
serialPort1.Write(text + "\r\n");
else serialPort1.Write(text + "\n");
}
else serialPort1.WriteLine(text);
showtext.Append(text);
}
else if (radioButtonsendHEX.Checked)
{//HEX发送
byte[] BytesHex = Conversion.StringsToHexbytes(text);
if (checkBoxnewline.Checked)
{//换行
if (checkBoxreturn.Checked)
{
serialPort1.Write(BytesHex, 0, BytesHex.Length);
serialPort1.Write("\r\n");
}
else {
serialPort1.Write(BytesHex, 0, BytesHex.Length);
serialPort1.Write("\n");
}
}
else
{
serialPort1.Write(BytesHex, 0, BytesHex.Length);
}
foreach (byte b in BytesHex)
{
showtext.Append(b.ToString("X2") + " ");
}
//if (textBoxsend1.Text.Length % 2 != 0)//输入的是奇数需单独处理
//{
// byte[] temp = new byte[1];
// temp[0] = Convert.ToByte(textBoxsend1.Text.Substring(textBoxsend1.Text.Length - 1, 1), 16);
// serialPort1.Write(temp, 0, 1);
// showtext.Append(temp[0]);
//}
}
if (checkBoxshowtime.Checked)
{
textBoxreceive.AppendText("[" + DateTime.Now.TimeOfDay.ToString() + "]发:");
}
textBoxreceive.AppendText(showtext + "\r\n");
}
}
catch (Exception ex)
{
serialPort1.Close();
comboBoxpart.Items.Clear();
comboBoxpart.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
System.Media.SystemSounds.Beep.Play();
MessageBox.Show(ex.Message);
}
}
以前做的,有删减所以不知道会不会有奇怪的bug
https://download.csdn.net/download/qq_39097092/12642274