日期:2014-05-18  浏览次数:20950 次

serialPort控件的问题
高手请进
我想用com1口接受数据
但是不知道怎么实现,谢谢高手帮忙!




------解决方案--------------------
先对seriport控件进行初始化:
serialPort1.Close();
serialPort1 .PortName ="COM1";
serialPort1.BaudRate = 4800;
serialPort1.Parity = Parity.Odd;
serialPort1.RtsEnable = true;
serialPort1.DataBits = 8;
serialPort1.ReceivedBytesThreshold = 1;
serialPort1.StopBits = StopBits.One;
serialPort1.Open();

再对sriport的DataReceived进行读取数据格式进行设置:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
intBytes = serialPort1.BytesToRead;
byte[] bytes = new byte[intBytes];
serialPort1.Read(bytes, 0, intBytes);
StringBuilder sb = new StringBuilder(bytes.Length * 3);
foreach (byte b in bytes )
{
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
}
str = sb.ToString().ToUpper() ;
dspy_count += 1;
if (dspy_count ==15)
{
dspy_count = 0;
this.Invoke(new EventHandler(delegate { ClearText(); }));
}
this.Invoke(new EventHandler(delegate { SetText(); }));
}


最后还有两个函数用来清楚文本内容和写入文本内容:
private void SetText()
{
seriport.Text += str;
}
private void ClearText()
{
seriport.Text = "";
}