Winform串口编程---接收数据demo(VSPD虚拟串口)

更新时间:2023-07-13 03:48:56 阅读: 评论:0

Winform串⼝编程---接收数据demo(VSPD虚拟串⼝)参考地址:blog.csdn/memgxingfeixiang/article/details/52513970
    blog.csdn/kevin_iot/article/details/53926599馒头的营养
⼀、需求概述
  应⽤场景:winform中能接收到串⼝发送的数据。
所需软件: Configure Virtual Serial Port Driver(虚拟串⼝模拟软件)、串⼝调试助⼿。
⼆、效果展⽰(很简陋,捂脸中......)
说明:cmbPort是电脑上所有串⼝的列表,txtReciveData是每次该串⼝接收的数据,btnOpenOrClo按钮是控制打开/关闭串⼝。
三、具体实现:
(1)先在Load事件⾥将comPort控件绑定电脑串⼝列表,代码如下:
1#region初始化电脑上的串⼝列表
2foreach (string sPort in SerialPort.GetPortNames())
3            {
4                cmbPort.Items.Add(sPort);
5            }
6
7//串⼝设置默认选项
8if (cmbPort.Items.Count>0)
9            {
10                cmbPort.SelectedIndex = 0;
11            }
12#endregion
(2)编写btnOpenOrClo点击事件
1///<summary>
2///打开/关闭串⼝
白云苍狗打一生肖
3///</summary>
4///<param name="nder"></param>
5///<param name="e"></param>
6private void btnOpenOrClo_Click(object nder, EventArgs e)
7        {
8try
9            {
10if (btnOpenOrClo.Text == "打开串⼝")
11                {
12                    btnOpenOrClo.Text = "关闭串⼝";
13//设置串⼝的基本属性
14                    rialPort.PortName = cmbPort.SelectedItem.ToString();
15                    rialPort.BaudRate = 9600;
16                    rialPort.Parity = Parity.None;
17                    rialPort.DataBits = 8;
18                    rialPort.StopBits = StopBits.One;
19                    rialPort.Open();
20                }
21el
22                {
小笨猪
23                    btnOpenOrClo.Text = "打开串⼝";
24                    rialPort.Clo();
25                }
26            }
27catch (Exception ex)
面部痣相图解男人28            {
29                MessageBox.Show(ex.Message, "错误提⽰", MessageBoxButtons.OK, MessageBoxIcon.Error);
30return;
31            }
32        }
(3)编写接收串⼝数据⽅法
1void Comm_DataReceived(object nder, SerialDataReceivedEventArgs e)
2        {
3try
4            {
5                Byte[] InputBuf = new Byte[128];
6                rialPort.Read(InputBuf, 0, rialPort.BytesToRead);
7
8                ASCIIEncoding encoding = new ASCIIEncoding();
9                data = encoding.GetString(InputBuf);
10new Thread(SetReceiveData).Start();
11//直接调⽤会报错-------从不是创建控件”txtContent”的线程访问它
12//SetReceiveData();
13            }
14catch (Exception ex)
15            {
16                MessageBox.Show(ex.Message, "错误提⽰", MessageBoxButtons.OK, MessageBoxIcon.Error);
17return;
18            }
19        }
接收数据成功,调⽤下⾯的⽅法,将发送的数据显⽰到⽂本框中。
1///<summary>
2/// (将接收的数据显⽰到⽂本框中)不懂这⼀块的实现逻辑,需要加深理解线程的相关概念
3///</summary>
4public void SetReceiveData()
5        {
6lock (this)
7
8                Invoke(new MethodInvoker(delegate ()
9
10                {
11
13
14                }));
15
16        }
在load事件中将订阅该事件
//为串⼝加上数据接收事件
rialPort.DataReceived += new SerialDataReceivedEventHandler(Comm_DataReceived);
四:模拟串⼝发送数据
(1)打开vspd软件,虚拟出两个COM1和COM2两个串⼝
(2)打开串⼝调试助⼿,⼀个是COM1,另外⼀个是COM2,将两个串⼝的波特率设置为⼀样。
测试⼀下,两个串⼝是否能正常通讯。
(3)关掉其中的⼀个串⼝调试助⼿,留下COM2的串⼝调试助⼿,我们在程序中⽤COM1⼝接收数据。(winform中要先点击“打开串⼝”按钮)
五、完整代码
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Linq;
7using System.Text;
8using System.Threading.Tasks;
9using System.Windows.Forms;
10using System.IO.Ports;
11using System.Threading;
12
13namespace ComDataTest
14 {
15public partial class ComData : Form
16    {
17private SerialPort rialPort=new SerialPort();
18string data = string.Empty;
19public ComData()
20        {
21            InitializeComponent();
22        }
23
24private void ComData_Load(object nder, EventArgs e)
25        {
26#region初始化电脑上的串⼝列表
27foreach (string sPort in SerialPort.GetPortNames())
28            {
29                cmbPort.Items.Add(sPort);
30            }
31
32//串⼝设置默认选项
33if (cmbPort.Items.Count>0)
34            {
知识竞赛题库35                cmbPort.SelectedIndex = 0;
36            }
37#endregion
38
39//为串⼝加上数据接收事件
40            rialPort.DataReceived += new SerialDataReceivedEventHandler(Comm_DataReceived);
41        }
42
43///<summary>
44///打开/关闭串⼝
45///</summary>
46///<param name="nder"></param>
47///<param name="e"></param>
48private void btnOpenOrClo_Click(object nder, EventArgs e)
49        {
50try
51            {
52if (btnOpenOrClo.Text == "打开串⼝")
53                {
54                    btnOpenOrClo.Text = "关闭串⼝";
55//设置串⼝的基本属性
有关劳动的手抄报56                    rialPort.PortName = cmbPort.SelectedItem.ToString();
57                    rialPort.BaudRate = 9600;蝴蝶谷风情网
58                    rialPort.Parity = Parity.None;
59                    rialPort.DataBits = 8;
60                    rialPort.StopBits = StopBits.One;
61                    rialPort.Open();
62                }
63el
64                {
65                    btnOpenOrClo.Text = "打开串⼝";
66                    rialPort.Clo();
67                }竞选副班长
68            }
69catch (Exception ex)
70            {
71                MessageBox.Show(ex.Message, "错误提⽰", MessageBoxButtons.OK, MessageBoxIcon.Error); 72return;
73            }
74        }
75
76///<summary>
77/// (将接收的数据显⽰到⽂本框中)不懂这⼀块的实现逻辑,需要加深理解线程的相关概念
78///</summary>
79public void SetReceiveData()
80        {
81lock (this)
82
83                Invoke(new MethodInvoker(delegate ()
84
85                {
86
88
89                }));
90
91        }
92
93void Comm_DataReceived(object nder, SerialDataReceivedEventArgs e)
94        {
95try
96            {
97                Byte[] InputBuf = new Byte[128];
98                rialPort.Read(InputBuf, 0, rialPort.BytesToRead);
99
100                ASCIIEncoding encoding = new ASCIIEncoding();
101                data = encoding.GetString(InputBuf);
102new Thread(SetReceiveData).Start();
103//直接调⽤会报错-------从不是创建控件”txtContent”的线程访问它
104//SetReceiveData();
105            }
106catch (Exception ex)
107            {
108                MessageBox.Show(ex.Message, "错误提⽰", MessageBoxButtons.OK, MessageBoxIcon.Error);
109return;
110            }
111        }
112    }
113 }
六、写在后⾯的话:
初次接触串⼝编程,作为码农多年,确实有些汗颜。从最初下载vspd和串⼝调试软件,根本不知如何⽤,到慢慢的了解⼀些,会简单的⼀些操作,着实也费了⼀点时间。⽬前对于串⼝编程,还是有⼀些云⾥雾⾥,似乎缺少⼀根主线把他们串起来⼀般,还是需要再进⾏摸索和探究,继续加油~

本文发布于:2023-07-13 03:48:56,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/1093680.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:事件   打开   数据   接收   虚拟   软件
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图