C# 串口初始化
阿新 • • 發佈:2017-11-22
串口 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; } } }
本文出自 “firswof” 博客,請務必保留此出處http://firswof.blog.51cto.com/9362961/1983941
C# 串口初始化