C#利用SerialPort类对串口发送接收数据

1.连接串口方法

SerialPort ser = new SerialPort();//也可以在工具箱中直接拖SerialPort控件
public void OpenCom()
{
    try
    {
        //波特率
        ser.BaudRate = 9600;
        //数据位
        ser.DataBits = 8;
        ser.PortName = cbcomsmqB.Text;//端口几,例COM1
        //两个停止位
        ser.StopBits = System.IO.Ports.StopBits.One;
        //无奇偶校验位
        ser.Parity = System.IO.Ports.Parity.None;
        ser.ReadTimeout = 100;
        ser.Open();
        if (!ser.IsOpen)
        {
            MessageBox.Show("端口打开失败");
            return;
        }
        else
        {
            ToolData.WriteLog(lrtxtLog, "端口" + cbcomsmqB.Text + "打开成功", 0);
        }
        ser.DataReceived += ser_DataReceived;
    }
    catch (Exception ex)
    {
        //stop();
        ser.Dispose();
        ToolData.WriteLog(lrtxtLog, ex.Message + "-----------------------", 1);
    }
}

 

2.事件监听方法

 

private void ser_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string receive = "";//数据接收
            try
            {
                Thread.Sleep(50);  //(毫秒)等待一定时间,确保数据的完整性 int len        
                int len = ser.BytesToRead;
                if (len != 0)
                {
                    byte[] buff = new byte[len];
                    ser.Read(buff, 0, len);
                    receive = Encoding.Default.GetString(buff);//数据接收内容
                }
            }
            catch
            {
                ToolData.WriteLog(lrtxtLog, "接收数据出错", 1);
                return;
            }
        }

3.发送数据方法

public void comsendmessage(object message)
        {
            try
            {
                ser.Write(message.ToString());
                ToolData.WriteLog(lrtxtlog, "已发送字符串:" + message.ToString(), 0);
            }
            catch (Exception ex)
            {
                ToolData.WriteLog(lrtxtlog, "错误提示:" + ex.Message, 1);
            }
        }

4.断开连接方法

public void endconnect()
{
     ser.Dispose();
}

5.获取所有串口列表

String[] portnames = SerialPort.GetPortNames();
foreach (var item in portnames)
{
     cbcomname.Items.Add(item);
     cbcomsmqA.Items.Add(item);
     cbcomsmqB.Items.Add(item);
     cbtestcomname.Items.Add(item);
}

 

 

你可能感兴趣的:(TCP,Serial通讯)