日期:2014-05-17 浏览次数:21169 次
//定义串口
private SerialPort comm;
private long received_count = 0;//接收计数
private long send_count = 0;//发送计数
byte c = 51;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comm = new SerialPort("COM4", 1200);
//添加事件注册
comm.DataReceived += comm_DataReceived;
comm.ReceivedBytesThreshold = 1;
}
//数据接收
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int n = comm.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致
byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据
received_count += n;//增加接收计数
comm.Read(buf, 0, n);//读取缓冲数据
//因为要访问ui资源,所以需要使用invoke方式同步ui。
this.Invoke((EventHandler)(delegate
{
//依次的拼接出16进制字符串
string ReceivedStr = GetHexStrFromByte(buf);
this.label1.Text = GetAm(ReceivedStr);
}));
&n