110,545
社区成员
发帖
与我相关
我的任务
分享
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
int num = serialPort1.BytesToRead; //获取接收缓冲区中的字节数
byte[] received_buf = new byte[num]; //声明一个大小为num的字节数据用于存放读出的byte型数据
receive_count += num; //接收字节计数变量增加nun
serialPort1.Read(received_buf, 0, num); //读取接收缓冲区中num个字节到byte数组中
sb.Clear(); //防止出错,首先清空字符串构造器
//遍历数组进行字符串转化及拼接
foreach (byte b in received_buf)
{
sb.Append(b.ToString("X2")+' ');
}
//因为要访问UI资源,所以需要使用invoke方式同步ui
this.Invoke((EventHandler)(delegate
{
//label3.Text = serialPort1.ReadExisting() ;
textBox1.AppendText(sb.ToString());
}
)
);
}
catch (Exception ex)
{
//响铃并显示异常给用户
System.Media.SystemSounds.Beep.Play();
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//将可能产生异常的代码放置在try块中
//根据当前串口属性来判断是否打开
if (serialPort1.IsOpen)
{
//串口已经处于打开状态
serialPort1.Close(); //关闭串口
comboBox1.Enabled = true;
comboBox2.Enabled = true;
button1.Text = "连接";
}
else
{
//串口已经处于关闭状态,则设置好串口属性后打开
comboBox1.Enabled = false;
comboBox2.Enabled = false;
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.DataBits = 8;
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.Open(); //打开串口
button1.Text = "断开";
}
}
catch (Exception ex)
{
//捕获可能发生的异常并进行处理
//捕获到异常,创建一个新的对象,之前的不可以再用
serialPort1 = new System.IO.Ports.SerialPort();
//刷新COM口选项
comboBox1.Items.Clear();
comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
//响铃并显示异常给用户
System.Media.SystemSounds.Beep.Play();
button1.Text = "连接";
button1.BackColor = Color.ForestGreen;
MessageBox.Show(ex.Message);
comboBox1.Enabled = true;
comboBox2.Enabled = true;
}
}