SerialPortMicrosoft

15 Сентябрь
Microsoft

SerialPort

Пример библиотеки работы с SerialPort.

  1. using System;
  2. using System.IO.Ports;
  3.  
  4. namespace AutoProtocolScanner
  5. {
  6. public interface IComPort
  7. {
  8. void SetPortBaudRate(int BaudRate);
  9. string Message { get; }
  10. bool IsOpen { get; }
  11. int ReadByte();
  12. bool BreakState { get; set; }
  13. int BytesToRead { get; }
  14. int Read(byte[] buffer, int offset, int count);
  15. }
  16. }
  1. using System;
  2. using System.IO.Ports;
  3.  
  4. namespace AutoProtocolScanner
  5. {
  6. public class ComPort:IComPort
  7. {
  8. SerialPort port;
  9. string message;
  10. public ComPort(string Name, int BaudRate)
  11. {
  12. port = new SerialPort(Name, BaudRate, Parity.None, 8, StopBits.One);
  13. try
  14. {
  15. port.Open();
  16. message = "порт открыт";
  17. }
  18. catch (Exception ex)
  19. {
  20. message=ex.Message;
  21. }
  22. }
  23.  
  24. public void SetPortBaudRate(int BaudRate)
  25. {
  26. if (port.IsOpen)
  27. {
  28. port.Close();
  29. }
  30. port.BaudRate = BaudRate;
  31. try
  32. {
  33. port.Open();
  34. message = "Порт открыт. BaudRate = "+port.BaudRate;
  35. }
  36. catch (Exception ex)
  37. {
  38. message = ex.Message;
  39. }
  40. }
  41.  
  42. public string Message
  43. {
  44. get
  45. {
  46. return message;
  47. }
  48. }
  49.  
  50. public bool IsOpen
  51. {
  52. get
  53. {
  54. return port.IsOpen;
  55. }
  56. }
  57. public int ReadByte()
  58. {
  59. return port.ReadByte();
  60. }
  61. public bool BreakState
  62. {
  63. set { port.BreakState = value; }
  64. get { return port.BreakState; }
  65. }
  66. public int BytesToRead
  67. {
  68. get { return port.BytesToRead; }
  69. }
  70. public int Read(byte[] buffer,int offset,int count)
  71. {
  72. return port.Read(buffer, offset, count);
  73. }
  74. }
  75. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO.Ports;
  5. using System.Timers;
  6.  
  7. namespace AutoProtocolScanner
  8. {
  9. public class ComPortReader
  10. {
  11. private string message;
  12. private int byteToRead;
  13. private int precentag;
  14. private IComPort port;
  15. private Timer timer;
  16. private bool timerFlag;
  17. private BackgroundWorker procReadPort;
  18.  
  19. public event MessgeChangedHandler MessageChanged;
  20. public delegate void MessgeChangedHandler(object seneder, EventArgs eventArgs);
  21.  
  22. public event PrecentageChangedHandler PrecentageChanged;
  23. public delegate void PrecentageChangedHandler(object seneder, EventArgs eventArgs);
  24. public int Precentag
  25. {
  26. get { return precentag; }
  27. set
  28. {
  29. precentag = value;
  30. if (PrecentageChanged != null)
  31. {
  32. EventArgs eventArgs = new EventArgs();
  33. PrecentageChanged(this, eventArgs);
  34. }
  35. }
  36. }
  37. public string Message
  38. {
  39. get { return message; }
  40. set
  41. {
  42. message = value;
  43.  
  44. }
  45. }
  46. public ComPortReader(IComPort Port)
  47. {
  48. port = Port;
  49. timer = new Timer();
  50. timer.Elapsed += timer_Elapsed;
  51. timerFlag = true;
  52. procReadPort = new BackgroundWorker();
  53. procReadPort.WorkerReportsProgress = true;
  54. procReadPort.DoWork += procReadPort_DoWork;
  55. procReadPort.ProgressChanged += procReadPort_ProgressChanged;
  56.  
  57. }
  58. void procReadPort_ProgressChanged(object sender, ProgressChangedEventArgs e)
  59. {
  60. }
  61. void procReadPort_DoWork(object sender, DoWorkEventArgs e)
  62. {
  63. Precentag = 0;
  64. if (port.IsOpen)
  65. {
  66. byteToRead = port.ReadByte();
  67. while (timerFlag)
  68. {
  69. message += string.Format("0x{0,2:X2}", byteToRead) + " ";
  70. byteToRead = port.ReadByte();
  71. procReadPort.ReportProgress(Precentag++);
  72. }
  73. }
  74. Update();
  75. }
  76. private void Update()
  77. {
  78. if (MessageChanged != null)
  79. {
  80. EventArgs eventArgs = new EventArgs();
  81. MessageChanged(this, eventArgs);
  82. }
  83. }
  84. private void timer_Elapsed(object sender, ElapsedEventArgs e)
  85. {
  86. timerFlag = false;
  87. }
  88. public string ReadPortToZero()
  89. {
  90.  
  91. message = string.Empty;
  92. if(port.IsOpen)
  93. {
  94. byteToRead = port.ReadByte();
  95. while (byteToRead != 0)
  96. {
  97. message += string.Format("0x{0,2:X2}", byteToRead) + " ";
  98. byteToRead = port.ReadByte();
  99. }
  100. }
  101. message += Environment.NewLine;
  102. return message;
  103. }
  104. public void ReadPort()
  105. {
  106. if (port.IsOpen)
  107. {
  108. byteToRead = port.ReadByte();
  109. while (timerFlag)
  110. {
  111. message += string.Format("0x{0,2:X2}", byteToRead) + " ";
  112. byteToRead = port.ReadByte();
  113. }
  114. }
  115. }
  116. public string ReadPortTimerOn(double interval)
  117. {
  118. timer.Interval = interval;
  119. timer.Enabled = true;
  120. if (port.IsOpen)
  121. {
  122. byteToRead = port.ReadByte();
  123. while (timerFlag)
  124. {
  125. message += string.Format("0x{0,2:X2}", byteToRead) + " ";
  126. byteToRead = port.ReadByte();
  127. }
  128. }
  129. timer.Enabled = false;
  130. timerFlag = true;
  131. return message;
  132. }
  133. public void RunReadPort(double time)
  134. {
  135. timer.Interval = time;
  136. timer.Enabled = true;
  137. procReadPort.RunWorkerAsync();
  138. }
  139. }
  140. }

Считываем в консоль

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using AutoProtocolScanner;
  7.  
  8. namespace TestsConsole
  9. {
  10. class Program
  11. {
  12. static IComPort port=null;
  13. static ComPortReader portReader=null;
  14. static void Main(string[] args)
  15. {
  16.  
  17. port = new ComPort("COM3", 115200);
  18. portReader = new ComPortReader(port);
  19.  
  20. portReader.MessageChanged += portReader_MessageChanged;
  21. portReader.PrecentageChanged += portReader_PrecentageChanged;
  22. portReader.RunReadPort(4000);
  23.  
  24. Console.ReadKey();
  25. }
  26.  
  27. static void portReader_PrecentageChanged(object seneder, EventArgs eventArgs)
  28. {
  29.  
  30. Console.Write(".");
  31. }
  32.  
  33. static void portReader_MessageChanged(object seneder, EventArgs eventArgs)
  34. {
  35. Console.WriteLine(portReader.Message);
  36. }
  37. }
  38. }
  39.  

Выводим на форму

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using AutoProtocolScanner;
  11.  
  12. namespace TestComPortToForm
  13. {
  14. public partial class Form1 : Form
  15. {
  16. IComPort port=null;
  17. ComPortReader portReader=null;
  18.  
  19. public Form1()
  20. {
  21. InitializeComponent();
  22. port = new ComPort("COM3", 115200);
  23. portReader = new ComPortReader(port);
  24. portReader.MessageChanged += portReader_MessageChanged;
  25. portReader.PrecentageChanged += portReader_PrecentageChanged;
  26. }
  27.  
  28. void portReader_PrecentageChanged(object seneder, EventArgs eventArgs)
  29. {
  30. Action action = () => progressBar1.Value++;
  31. if (InvokeRequired)
  32. Invoke(action);
  33. else
  34. action();
  35. }
  36.  
  37. void portReader_MessageChanged(object seneder, EventArgs eventArgs)
  38. {
  39. Action action = () => textBox1.Text += portReader.Message;
  40. if (InvokeRequired)
  41. Invoke(action);
  42. else
  43. action();
  44. }
  45.  
  46. private void button1_Click(object sender, EventArgs e)
  47. {
  48. // textBox1.Text += portReader.ReadPortTimerOn(1000);
  49. portReader.RunReadPort(10000);
  50.  
  51. }
  52. }
  53. }

Коментарии


Оставить коментарий