该文中使用的串口接收数据方法不会造成cpu占用过高等问题
源码地址:https://download.csdn.net/download/horseroll/10756130
demo效果图:
1.首先声明一个Serial变量
SerialPort serialPort1 = new SerialPort();
2.进行串口连接
public void opencom()
{
try
{
//波特率
serialPort1.BaudRate = 9600;
//数据位
serialPort1.DataBits = 8;
serialPort1.PortName = comboBox1.Text;
//两个停止位
serialPort1.StopBits = System.IO.Ports.StopBits.One;
//无奇偶校验位
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.ReadTimeout = 100;
serialPort1.Open();
if (!serialPort1.IsOpen)
{
MessageBox.Show("端口打开失败");
return;
}
else
{
richTextBox1.AppendText("端口" + comboBox1.Text + "打开成功\r\n");
}
serialPort1.DataReceived += serialPort1_DataReceived;
}
catch (Exception ex)
{
serialPort1.Dispose();
richTextBox1.AppendText(ex.Message);
}
}
3.串口接收数据事件
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(50); //(毫秒)等待一定时间,确保数据的完整性 int len
int len = serialPort1.BytesToRead;
string receivedata = string.Empty;
if (len != 0)
{
byte[] buff = new byte[len];
serialPort1.Read(buff, 0, len);
receivedata = Encoding.Default.GetString(buff);
}
richTextBox1.AppendText(receivedata + "\r\n");
}
4.串口发送数据
serialPort1.Write(textBox1.Text);
5.附赠方法,得到可用串口号
String[] portnames = SerialPort.GetPortNames();
foreach (var item in portnames)
{
comboBox1.Items.Add(item);
}