查看: 4116|回复: 0

[ASP.NET教程] C# 串口初始化

发表于 2018-3-11 16:06:56

C# 串口初始化方法之一。完整例程中定义了多个串口,程序运行初始会从配置文件加载串口设置并批量初始化串口。

  1. ...
  2. using System.Text.RegularExpressions;
  3. ...
  4. //Example, InitPort(gdmPort, 2, "115200,N,8,1")
  5. private void InitPort( System.IO.Ports.SerialPort _seriPort, int _com, string _setting)
  6. {
  7. string strBuf = string.Empty;
  8. _seriPort.PortName = "COM" + _com; //设置 COM 口
  9. strBuf = Regex.Match(_setting, @"^\d+(?=,)").ToString().Trim();
  10. if (strBuf != string.Empty)
  11. {
  12. _seriPort.BaudRate = Convert.ToInt32(strBuf); //设置 BaudRate
  13. }
  14. strBuf = Regex.Match(_setting, @"(?<=^\d+,)[a-z A-Z]+").ToString().ToUpper().Trim();
  15. if (strBuf != string.Empty) //设置 Parity
  16. {
  17. switch (strBuf)
  18. {
  19. case "E":
  20. _seriPort.Parity = System.IO.Ports.Parity.Even;
  21. break;
  22. case "M":
  23. _seriPort.Parity = System.IO.Ports.Parity.Mark;
  24. break;
  25. case "N":
  26. _seriPort.Parity = System.IO.Ports.Parity.None;
  27. break;
  28. case "O":
  29. _seriPort.Parity = System.IO.Ports.Parity.Odd;
  30. break;
  31. case "S":
  32. _seriPort.Parity = System.IO.Ports.Parity.Space;
  33. break;
  34. default:
  35. break;
  36. }
  37. }
  38. strBuf = Regex.Match(_setting, @"(?<=[a-z A-Z]+,)\d+").ToString().Trim();
  39. if (strBuf != string.Empty)
  40. {
  41. _seriPort.DataBits = Convert.ToInt32(strBuf); //设置 DataBits
  42. }
  43. strBuf = Regex.Match(_setting, @"(?<=,)[0-9 \.]+$").ToString().Trim();
  44. if (strBuf != string.Empty) //设置 StopBits
  45. {
  46. switch (strBuf)
  47. {
  48. case "0":
  49. _seriPort.StopBits = System.IO.Ports.StopBits.None;
  50. break;
  51. case "1":
  52. _seriPort.StopBits = System.IO.Ports.StopBits.One;
  53. break;
  54. case "1.5":
  55. _seriPort.StopBits = System.IO.Ports.StopBits.OnePointFive;
  56. break;
  57. case "2":
  58. _seriPort.StopBits = System.IO.Ports.StopBits.Two;
  59. break;
  60. default:
  61. //SerPort.StopBits = System.IO.Ports.StopBits.One;
  62. break;
  63. }
  64. }
  65. }
复制代码








回复

使用道具 举报