-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
305 lines (268 loc) · 11.4 KB
/
Copy pathForm1.cs
File metadata and controls
305 lines (268 loc) · 11.4 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
namespace Serial
{
public partial class Form1 : Form
{
SerialPort serialPort1 = null;
public Form1()
{
InitializeComponent();
}
/**************************************************************************/
#region 初始化窗体
private void Form1_Load(object sender, EventArgs e) //加载界面程序
{
try
{
string[] str = SerialPort.GetPortNames(); //获取连接到电脑的串口号并存进数组
comboBox_PortNames.Items.Clear(); //清除串口号下拉框的内容
comboBox_PortNames.Items.AddRange(str); //将串口号添加到下拉框
if (str.Length > 0)
{
comboBox_PortNames.SelectedIndex = 0; //设置ComboBox框的初始值
comboBox_BaudRate.SelectedIndex = 7;
comboBox_DataBit.SelectedIndex = 3;
comboBox_StopBit.SelectedIndex = 0;
comboBox_Parity.SelectedIndex = 2;
}
else
{
MessageBox.Show("当前无串口连接!");
}
}
catch
{
MessageBox.Show("无串口设备!/r/n请检查是否连接设备!/r/n请检查设备驱动!");
}
}
#endregion
/**************************************************************************/
/**************************************************************************/
#region 搜索串口(与初始化函数一样)
private void button_Serach_Click(object sender, EventArgs e)
{
try
{
string[] str = SerialPort.GetPortNames();
comboBox_PortNames.Items.Clear();
comboBox_PortNames.Items.AddRange(str);
if (str.Length > 0)
{
comboBox_PortNames.SelectedIndex = 0;
comboBox_BaudRate.SelectedIndex = 7;
comboBox_DataBit.SelectedIndex = 3;
comboBox_StopBit.SelectedIndex = 0;
comboBox_Parity.SelectedIndex = 2;
}
else
{
MessageBox.Show("当前无串口连接!");
}
}
catch
{
MessageBox.Show("无串口设备!/r/n请检查是否连接设备!/r/n请检查设备驱动!");
}
}
#endregion
/**************************************************************************/
/**************************************************************************/
#region 打开串口
private void button_OpenOrClose_Click(object sender, EventArgs e)
{
serialPort1 = new SerialPort();
if (!serialPort1.IsOpen)
{
if (comboBox_PortNames.SelectedItem == null)
{
MessageBox.Show("请选择正确的串口", "提示");
return;
}
//设置串口参数
serialPort1.PortName = comboBox_PortNames.Text.ToString(); //serialPort1是serialPort组件的Name
serialPort1.BaudRate = Convert.ToInt32(comboBox_BaudRate.SelectedItem.ToString());
serialPort1.DataBits = Convert.ToInt32(comboBox_DataBit.SelectedItem.ToString());
//设置停止位
if (comboBox_StopBit.Text == "One")
{
serialPort1.StopBits = StopBits.One;
}
else if (comboBox_StopBit.Text == "Two")
{
serialPort1.StopBits = StopBits.Two;
}
else if (comboBox_StopBit.Text == "OnePointFive")
{
serialPort1.StopBits = StopBits.OnePointFive;
}
else if (comboBox_StopBit.Text == "None")
{
serialPort1.StopBits = StopBits.None;
}
//设置奇偶校验位
if (comboBox_Parity.Text == "Odd")
{
serialPort1.Parity = Parity.Odd;
}
else if (comboBox_Parity.Text == "Even")
{
serialPort1.Parity = Parity.Even;
}
else if (comboBox_Parity.Text == "None")
{
serialPort1.Parity = Parity.None;
}
try
{
//禁止操作组件
comboBox_PortNames.Enabled = false;
comboBox_BaudRate.Enabled = false;
comboBox_DataBit.Enabled = false;
comboBox_StopBit.Enabled = false;
comboBox_Parity.Enabled = false;
button_Search.Enabled = false;
serialPort1.Open(); //设置完参数后打开串口
button_OpenOrClose.Text = "Close"; //更改Open按钮文本内容
}
catch
{
MessageBox.Show("串口打开失败!");
}
serialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialDataReceive); //打开串口后绑定数据接收
}
else if (button_OpenOrClose.Text == "Close")
{
try
{
//允许操作组件
comboBox_PortNames.Enabled = true;
comboBox_BaudRate.Enabled = true;
comboBox_DataBit.Enabled = true;
comboBox_StopBit.Enabled = true;
comboBox_Parity.Enabled = true;
button_Search.Enabled = true;
serialPort1.DiscardInBuffer(); //清除缓冲区的数据
serialPort1.Close();
button_OpenOrClose.Text = "Open"; //更改Close按钮文本内容
}
catch
{
MessageBox.Show("串口打开失败!");
}
}
}
#endregion
/**************************************************************************/
/**************************************************************************/
#region 接收串口数据
/*
开辟缓存区 根据具体协议内容获取一帧数据进行接收中断处理
*/
//变量
List<byte> sp_buffer = new List<byte>(4096); //串口缓存区
int sp_buffer_max = 4096; //串口缓存区最大缓存字节数
private void SerialDataReceive(object sender, SerialDataReceivedEventArgs e)
{
if (serialPort1.IsOpen == false)
{
serialPort1.Close();
return;
}
int Byte_len = serialPort1.BytesToRead; //读取缓存的数据长度
byte[] Rc_byte = new byte[Byte_len];
serialPort1.Read(Rc_byte, 0, Byte_len); //将缓存数据存储进字节数组里面
if (sp_buffer.Count > sp_buffer_max) //缓存超过字节数 先丢弃前面的字节
sp_buffer.RemoveRange(0, sp_buffer_max); //丢弃前面的字节0到sp_buffer_max
sp_buffer.AddRange(Rc_byte); //存入缓存区
byte[] ruffer = new byte[9192]; //用来存放缓冲区的数据流
//对数据流进行筛选,缓冲区每一组数据个数大于4则为我们想要的数据流
if (sp_buffer.Count > 4)
{
sp_buffer.CopyTo(0, ruffer, 0, sp_buffer.Count);
Task.Run(() => printf_data(ruffer, sp_buffer.Count, 1)); //打印数据流
}
}
#endregion
/**************************************************************************/
/**************************************************************************/
#region 打印数据流
void printf_data(byte[] Frame, int Length, int T_R) //打印串口数据
{
Int16 i_len;
StringBuilder s = new StringBuilder();
if (T_R == 0)
s.Append("发送:");
else
s.Append("接收:");
for (i_len = 0; i_len < Length; i_len++) //打印字符串
{
s.Append(Frame[i_len].ToString("X2"));
s.Append(" ");
}
s.Append("[" + DateTime.Now.ToString("HH:mm:ss fff") + "]");
s.Append("\r\n");
string str_show = s.ToString();
MethodInvoker mi = new MethodInvoker(() =>
{
if (richTextBox_Receive.Lines.Count() > 20)
richTextBox_Receive.Clear();
richTextBox_Receive.AppendText(str_show);
});
BeginInvoke(mi);
/*
textBox_com_data.Focus(); //获取焦点
textBox_com_data.Select(textBox_com_data.TextLength, 0);//光标
textBox_com_data.ScrollToCaret(); //滚动条*/
}
#endregion
/**************************************************************************/
/**************************************************************************/
#region 发送数据
private void button_Send_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
string[] sendbuff = richTextBox_Send.Text.Split(); //分割输入的字符串,判断有多少个字节需要发送
int Buff_Len = sendbuff.Length;
byte[] buff = new byte[Buff_Len];
for (int i = 0; i < sendbuff.Length; i++)
{
buff[i] = byte.Parse(sendbuff[i], System.Globalization.NumberStyles.HexNumber); //格式化字符串为十六进制数值
}
try
{
serialPort1.Write(buff, 0, buff.Length); //写数据
Task.Run(() => printf_data(buff, Buff_Len, 0));
}
catch
{
MessageBox.Show("发送失败!!");
}
}
else
{
MessageBox.Show("串口未打开!");
}
}
#endregion
/**************************************************************************/
/**************************************************************************/
#region 清除输出框
private void Clear_Click(object sender, EventArgs e)
{
richTextBox_Receive.Clear(); //清除数据接收框数据
}
#endregion
/**************************************************************************/
}
}