标签:串口 rs232 com口 初始化
C# 串口初始化要领之一。完整例程中界说了多个串口,措施运行初始会从配置文件加载串口设置并批量初始化串口。
... using System.Text.RegularExpressions; ... //Example, InitPort(gdmPort, 2, "115200,N,8,1") private void InitPort( System.IO.Ports.SerialPort _seriPort, int _com, string _setting) { string strBuf = string.Empty; _seriPort.PortName = "COM" + _com; //设置 COM 口 strBuf = Regex.Match(_setting, @"^\d+(?=,)").ToString().Trim(); if (strBuf != string.Empty) { _seriPort.BaudRate = Convert.ToInt32(strBuf); //设置 BaudRate } strBuf = Regex.Match(_setting, @"(?<=^\d+,)[a-z A-Z]+").ToString().ToUpper().Trim(); if (strBuf != string.Empty) //设置 Parity { switch (strBuf) { case "E": _seriPort.Parity = System.IO.Ports.Parity.Even; break; case "M": _seriPort.Parity = System.IO.Ports.Parity.Mark; break; case "N": _seriPort.Parity = System.IO.Ports.Parity.None; break; case "O": _seriPort.Parity = System.IO.Ports.Parity.Odd; break; case "S": _seriPort.Parity = System.IO.Ports.Parity.Space; break; default: break; } } strBuf = Regex.Match(_setting, @"(?<=[a-z A-Z]+,)\d+").ToString().Trim(); if (strBuf != string.Empty) { _seriPort.DataBits = Convert.ToInt32(strBuf); //设置 DataBits } strBuf = Regex.Match(_setting, @"(?<=,)[0-9 \.]+$").ToString().Trim(); if (strBuf != string.Empty) //设置 StopBits { switch (strBuf) { case "0": _seriPort.StopBits = System.IO.Ports.StopBits.None; break; case "1": _seriPort.StopBits = System.IO.Ports.StopBits.One; break; case "1.5": _seriPort.StopBits = System.IO.Ports.StopBits.OnePointFive; break; case "2": _seriPort.StopBits = System.IO.Ports.StopBits.Two; break; default: //SerPort.StopBits = System.IO.Ports.StopBits.One; break; } } }