C#串口问题:接收事件触发的问题
最近做了个循环向串口发送数据的例子,要求获取返回值,并显示在同一txtBox中。功能是实现了,但是显示结果是却是所有发送数据显示完才显示接收数据,我想要的结果是发一条数据显示一条返回结果,有没有做过这类功能的大神提示一下。
代码附上:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace LoopPort_send_received
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
SerialPort serp =new SerialPort();
//定义事件处理函数
private void serialport_DataReceived(Object sender, SerialDataReceivedEventArgs e)
{
try
{
Thread.Sleep(100); //(毫秒)等待一定时间,确保数据的完整性 int len
int len = serp.BytesToRead;
if (len != 0)
{
byte[] buff = new byte[len];
serp.Read(buff, 0, len);
//try some other functions to read? do yourself if intersted
//processing data in buff
this.textBox1.BeginInvoke(
new MethodInvoker(()=>
{
this.textBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+" "+ buff[0]+"\r\n");
}));
}
}
catch(Exception)
{
}
}
private void Form2_Load(object sender, EventArgs e)
{
//设置接收超时。一旦超时,将抛出Exception
serp.ReadTimeout = 90 * 1000;
serp = new SerialPort("COM7", 9600, Parity.Even, 7, StopBits.One);
//注册事件处理函数
serp.DataReceived += new SerialDataReceivedEventHandler(serialport_DataReceived);
}
private void button1_Click(object sender, EventArgs e)
{
List<byte[]> list = new List<byte[]>();
list.Add(new byte[] { 0x02, 0x31, 0x31, 0x34, 0x30, 0x34, 0x30, 0x32, 0x31, 0x45, 0x30, 0x30, 0x03, 0x33, 0x35 });
list.Add(new byte[] { 0x02, 0x31, 0x31, 0x34, 0x30, 0x38, 0x30, 0x32, 0x31, 0x45, 0x30, 0x30, 0x03, 0x33, 0x39 });
for (int i = 0; i < 2; i++)
{
if (serp.IsOpen)
serp.Close();
serp.Open();
serp.Write(list[i], 0, 15);
this.textBox1.Text +=string.Format("第{0}个",i+1) + "\r\n";
Thread.Sleep(5000);
}
}
}
}