一个小项目中应用到的串口通信,把核心源码整理一下.
C#实现串口通信其实非常简单,用到的类 SerialPort ,引用的命名空间System.IO.Ports.SerialPort类中主要用到的属性,有一下几个:
PortName 通信端口名称
BaudRate 串行波特率
DataBits 每个字节的标准数据位长度
Parity 奇偶校验检查协议
StopBits 每个字节的标准停止位数
HandShaking 串行端口数据传输的握手协议
SerialPort方法:
Open 打开一个新的串行端口连接
Write 将数据写入串行端口输出缓冲区
WriteLine 将指定的字符串和NewLine值输出缓冲区
Read 从缓冲区读取数据
ReadLine 一直读取到输入缓冲区中的NewLine值
将SerialPort的类操作封装了一下,呵呵,见下类SerialPortCommunication
下面代码主要为 SerialPortCommunication 事件的参数
XML配置类
SerialPortSetting 代码略,可以见前一篇文章...
PS.1.通信双放设置必须一致;2.计算机与计算机串口通信时候记得用交叉线。
C#实现串口通信其实非常简单,用到的类 SerialPort ,引用的命名空间System.IO.Ports.SerialPort类中主要用到的属性,有一下几个:
PortName 通信端口名称
BaudRate 串行波特率
DataBits 每个字节的标准数据位长度
Parity 奇偶校验检查协议
StopBits 每个字节的标准停止位数
HandShaking 串行端口数据传输的握手协议
SerialPort方法:
Open 打开一个新的串行端口连接
Write 将数据写入串行端口输出缓冲区
WriteLine 将指定的字符串和NewLine值输出缓冲区
Read 从缓冲区读取数据
ReadLine 一直读取到输入缓冲区中的NewLine值
将SerialPort的类操作封装了一下,呵呵,见下类SerialPortCommunication
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.IO.Ports;
- using System.Threading;
- namespace SerialPortComm
- {
- public class SerialPortCommunication
- {
- #region SerialPort 基本设置
- /// <summary>
- /// 端口号
- /// </summary>
- public string PortName = "COM1";
- /// <summary>
- /// 波特率
- /// </summary>
- public Int32 BaudRate = 9600;
- /// <summary>
- /// 数据位
- /// </summary>
- public int DataBits = 8;
- /// <summary>
- /// 校验位
- /// </summary>
- public string Paritys = "None";
- /// <summary>
- /// 停止位
- /// </summary>
- public string StopBits = "One";
- /// <summary>
- /// 握手协议
- /// </summary>
- public string HandShaking = "None";
- #endregion
- private Thread thread = null;
- SerialPort serialPort = new SerialPort();
- public bool KeepRead = true;
- /// <summary>
- /// 接受数据
- /// </summary>
- public event SerialPortEventHandler ReceivedData;
- /// <summary>
- /// 异常处理
- /// </summary>
- public event SerialPortEventHandler SerialPortException;
- public SerialPortCommunication(string portName)
- {
- PortName = portName;
- //构造函数初始化
- SerialPortSetting spSetting = new SerialPortSetting("config.xml");
- PortConfig pConfig = spSetting.GetSerialPortName(PortName);
- if (pConfig == null)
- {
- pConfig = new PortConfig();
- pConfig.PortName = this.PortName;
- spSetting.AddSerialPort(pConfig);//不存在则添加默认配置
- }
- //加载配置信息
- this.BaudRate = Int32.Parse(pConfig.BaudRate);
- this.DataBits = int.Parse(pConfig.DataBits);
- this.Paritys = pConfig.Paritys;
- this.StopBits = pConfig.StopBits;
- this.HandShaking = pConfig.HandShaking;
- }
- /// <summary>
- /// 打开端口
- /// </summary>
- public void Open()
- {
- serialPort.Encoding = Encoding.UTF8;//编码
- serialPort.PortName = PortName;
- serialPort.BaudRate = BaudRate;
- serialPort.DataBits = DataBits;
- serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), Paritys);
- serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), StopBits);
- serialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), HandShaking);
- serialPort.WriteTimeout = 100;
- serialPort.ReadTimeout = 100;
- if (serialPort.IsOpen)
- {
- serialPort.Close();
- }
- try
- {
- serialPort.Open();
- Start();
- }
- catch
- {
- SerialPortException(this, new SerialPortEventArgs(serialPort.PortName, "打开异常,端口已经存在或已经占用!"));
- }
- }
- /// <summary>
- /// 返回端口打开状态
- /// </summary>
- public bool IsOpen
- {
- get { return serialPort.IsOpen; }
- }
- /// <summary>
- /// 发送字符串
- /// </summary>
- /// <param name="sendStrings"></param>
- public void SendLine(string sendStrings)
- {
- serialPort.WriteLine(sendStrings);
- }
- /// <summary>
- /// 发送字符串
- /// </summary>
- /// <param name="sendStrings"></param>
- public void Send(string sendStrings)
- {
- serialPort.Write(sendStrings);
- }
- /// <summary>
- /// 发送字符串(开始和结束的字符串)
- /// </summary>
- /// <param name="sendStrings">发送的字符串</param>
- /// <param name="StartStrings">开始字符串</param>
- /// <param name="EndStrings">结束字符串</param>
- public void Send(string sendStrings, string StartStrings, string EndStrings)
- {
- serialPort.Write(StartStrings + sendStrings + EndStrings);
- }
- /// <summary>
- /// 关闭端口
- /// </summary>
- public void Close()
- {
- if (thread != null && serialPort != null)
- {
- KeepRead = false;
- thread.Join();
- thread = null;
- serialPort.Close();
- serialPort = null;
- }
- }
- //接受数据处理
- public void ReceiveProcess()
- {
- while (KeepRead)
- {
- if (serialPort.IsOpen)
- {
- try
- {
- string ReceiveLine = serialPort.ReadLine();
- ReceivedData(this, new SerialPortEventArgs(serialPort.PortName, ReceiveLine));
- }
- catch
- {
- //超时
- }
- }
- }
- }
- private void Start()
- {
- if (KeepRead)
- {
- thread = new Thread(new ThreadStart(ReceiveProcess));
- thread.Start();
- }
- }
- }
- }
下面代码主要为 SerialPortCommunication 事件的参数
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace SerialPortComm
- {
- /// <summary>
- /// SerialPort事件处理委托
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public delegate void SerialPortEventHandler(object sender, SerialPortEventArgs e);
- /// <summary>
- /// 事件参数
- /// </summary>
- public class SerialPortEventArgs : EventArgs
- {
- private string _Message;
- private string _PortName;
- /// <summary>
- /// 消息
- /// </summary>
- public string Message
- {
- set { _Message = value; }
- get { return _Message; }
- }
- /// <summary>
- /// 端口名
- /// </summary>
- public string PortName
- {
- set { _PortName = value; }
- get { return _PortName; }
- }
- /// <summary>
- /// 构造函数
- /// </summary>
- /// <param name="portName">端口名称</param>
- /// <param name="message">消息内容</param>
- public SerialPortEventArgs(string portName, string message)
- {
- this.PortName = portName;
- this.Message = message;
- }
- }
- }
PS.1.通信双放设置必须一致;2.计算机与计算机串口通信时候记得用交叉线。