我是靠谱客的博主 虚拟白云,这篇文章主要介绍c#串口模拟互发数据(COM1-COM2),现在分享给大家,希望可以做个参考。

比如:通过COM1发送数据,COM2接收数据。当COM2接收完本次发送的数据后,向COM1发送信息通知COM1本次数据已发完,COM1接到通知后,再发下一段数据。这样可以确保每次发送的数据都可以被正确接收。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.Threading; using Utils; namespace com1_com2 { public partial class Form1 : Form { #region 变量 /// <summary> /// 启动还是停止,true起动,false停止 /// </summary> public static bool start = true; /// <summary> /// 串口资源 /// </summary> private static SerialPort serialPort1 = null; /// <summary> /// 串口资源 /// </summary> private static SerialPort serialPort2 = null; /// <summary> /// 成功次数 /// </summary> private static int successCount = 0; /// <summary> /// 失败次数 /// </summary> private static int errorCount = 0; /// <summary> /// 上次计算的总次数 /// </summary> private static int lastCount = 0; /// <summary> /// 定时器 /// </summary> private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); #endregion #region Form1 public Form1() { InitializeComponent(); } #endregion #region Form1_Load private void Form1_Load(object sender, EventArgs e) { serialPort1 = new SerialPort("COM1"); serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived1); serialPort1.Open(); serialPort2 = new SerialPort("COM2"); serialPort2.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived2); serialPort2.Open(); } #endregion #region Form1_FormClosed private void Form1_FormClosed(object sender, FormClosedEventArgs e) { serialPort1.Close(); serialPort1.Dispose(); serialPort2.Close(); serialPort2.Dispose(); } #endregion #region btnStart_Click private void btnStart_Click(object sender, EventArgs e) { start = true; SendData(); timer.Interval = 500; timer.Tick += new EventHandler(delegate(object obj, EventArgs eventArgs) { if (lastCount == 0) { lastCount = successCount + errorCount; } else { int cnt = successCount + errorCount - lastCount; cnt = Data.Length * cnt / 1024 * (1000 / timer.Interval); double total = (successCount + errorCount) * Data.Length / 1024.0; InvokeDelegate invokeDelegate = delegate() { label3.Text = cnt.ToString() + "KB/S " + total.ToString("#.0") + "KB"; }; InvokeUtil.Invoke(this, invokeDelegate); lastCount = successCount + errorCount; } }); timer.Start(); } #endregion #region btnStop_Click private void btnStop_Click(object sender, EventArgs e) { start = false; timer.Stop(); timer.Dispose(); timer = new System.Windows.Forms.Timer(); } #endregion #region 接收串口数据事件 /// <summary> /// 接收串口数据事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void serialPort_DataReceived1(object sender, SerialDataReceivedEventArgs e) { if (serialPort1.ReadLine() != null) { successCount++; SendData(); } } /// <summary> /// 接收串口数据事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void serialPort_DataReceived2(object sender, SerialDataReceivedEventArgs e) { List<byte> bList = new List<byte>(); int i = 0; while (serialPort2.BytesToRead > 0) { byte[] bArr = new byte[serialPort2.BytesToRead]; i += serialPort2.Read(bArr, 0, bArr.Length); bList.AddRange(bArr); } serialPort2.WriteLine("success"); string s = ASCIIEncoding.UTF8.GetString(bList.ToArray()); InvokeDelegate invokeDelegate = delegate() { textBox2.Text = s; }; InvokeUtil.Invoke(this, invokeDelegate); if (s != Str) { errorCount++; invokeDelegate = delegate() { label2.Text = errorCount + "次不相等(失败)"; }; InvokeUtil.Invoke(this, invokeDelegate); } else { invokeDelegate = delegate() { label1.Text = successCount + "次相等(成功)"; }; InvokeUtil.Invoke(this, invokeDelegate); } } #endregion #region 发送数据 private void SendData() { if (start) { Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj) { InvokeDelegate invokeDelegate = delegate() { textBox1.Text = Str; }; InvokeUtil.Invoke(this, invokeDelegate); serialPort1.Write(Data, 0, Data.Length); })); thread.Start(); } } #endregion #region 数据 private static byte[] data = null; /// <summary> /// 数据 /// </summary> private static byte[] Data { get { if (data == null) { data = ASCIIEncoding.UTF8.GetBytes(Str); } return data; } } #endregion #region 获取字符串 private static string str = null; /// <summary> /// 字符串 /// </summary> private static string Str { get { if (str == null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 270; i++) { sb.Append("计算机程序"); } str = sb.ToString(); } return str; } } #endregion } }

关于跨线程委托的问题

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace Utils { /// <summary> /// 跨线程访问控件的委托 /// </summary> public delegate void InvokeDelegate(); /// <summary> /// 跨线程访问控件类 /// </summary> public class InvokeUtil { /// <summary> /// 跨线程访问控件 /// </summary> /// <param name="ctrl">Form对象</param> /// <param name="de">委托</param> public static void Invoke(Control ctrl, Delegate de) { if (ctrl.IsHandleCreated) { ctrl.BeginInvoke(de); } } } }

相关类Uitls.Ports:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Win32; using System.Security.Permissions; using System.IO.Ports; using System.Security; namespace Utils { /// <summary> /// 串口资源工具类 /// </summary> public class SerialPortUtil { #region 获取本机串口列表,包括虚拟串口 /// <summary> /// 获取本机串口列表,包括虚拟串口 /// </summary> public static string[] GetCOMList() { List<string> list = new List<string>(); foreach (string portName in SerialPort.GetPortNames()) { list.Add(portName); } return list.ToArray(); } #endregion #region 从注册表获取本机串口列表 /// <summary> /// 从注册表获取本机串口列表 /// </summary> public static string[] GetPortNames() { RegistryKey localMachine = null; RegistryKey key2 = null; string[] textArray = null; //这里有个断言,判断该注册表项是否存在 new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINEHARDWAREDEVICEMAPSERIALCOMM").Assert(); try { localMachine = Registry.LocalMachine; key2 = localMachine.OpenSubKey(@"HARDWAREDEVICEMAPSERIALCOMM", false); if (key2 != null) { string[] valueNames = key2.GetValueNames(); textArray = new string[valueNames.Length]; for (int i = 0; i < valueNames.Length; i++) { textArray[i] = (string)key2.GetValue(valueNames[i]); } } } finally { if (localMachine != null) { localMachine.Close(); } if (key2 != null) { key2.Close(); } CodeAccessPermission.RevertAssert(); } if (textArray == null) { textArray = new string[0]; } return textArray; } #endregion } }

 

最后

以上就是虚拟白云最近收集整理的关于c#串口模拟互发数据(COM1-COM2)的全部内容,更多相关c#串口模拟互发数据(COM1-COM2)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(76)

评论列表共有 0 条评论

立即
投稿
返回
顶部