C#开发记录如何建立虚拟串口,进行串口通信,以及通信模板

devtools/2024/9/21 12:14:03/

记录时间;2024年4月

记录如何开启虚拟串口以及进行基础串口通信。

建立虚拟串口

使用的软件是vspd,建立虚拟串口之后就可以将他们当成实际物理连接的两个串口进行通信。

之后使用我们之前给出的通信模板,建立一个稍微规矩一点的界面。

界面建立

 

 其中添加对用户输入的检查。

配合之前打开串口的逻辑就可以开始串口应用的调试和开发了。

代码

  public partial class Form1 : Form{//串口参数和串口工具类public System.IO.Ports.SerialPort _serialPort = new System.IO.Ports.SerialPort();string[] baud = { "43000", "56000", "57600", "115200", "128000", "230400", "256000", "460800" };private void displaytext(object sender, EventArgs e){string str = _serialPort.ReadExisting();rtxreceive.AppendText(str);}//串口接收事件private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e){//串口接收事件try{//串口接收数据//if(serialPort1.IsOpen){this.Invoke(new EventHandler(displaytext));}}catch (Exception ex){//捕获到异常,创建一个新的对象,之前的不可以再用_serialPort = new System.IO.Ports.SerialPort();//刷新COM口选项comboBox1.Items.Clear();comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());//响铃并显示异常给用户System.Media.SystemSounds.Beep.Play();button4.Text = "打开串口";MessageBox.Show(ex.Message);hintrtx.Text += "\n串口接收失败";comboBox1.Enabled = true;comboBox2.Enabled = true;comboBox3.Enabled = true;comboBox4.Enabled = true;comboBox5.Enabled = true;}}public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){//检测try{string[] ports = SerialPort.GetPortNames();if (ports.Length == 0){MessageBox.Show("没有找到串口");hintrtx.Text += "没有找到串口";return;}comboBox1.Items.Clear();comboBox1.Items.AddRange(ports);comboBox1.SelectedIndex = 0;comboBox2.SelectedIndex = 0;comboBox3.SelectedIndex = 0;comboBox4.SelectedIndex = 0;comboBox5.SelectedIndex = 0;//检测到串口后,使能串口参数设置comboBox1.Enabled = true;comboBox2.Enabled = true;comboBox3.Enabled = true;comboBox4.Enabled = true;comboBox5.Enabled = true;}catch (Exception ex){MessageBox.Show(ex.Message);}}private void Form1_Load(object sender, EventArgs e){//界面初始化int i;for (i = 300; i <= 38400; i = i * 2){comboBox2.Items.Add(i.ToString());  //添加波特率列表}comboBox2.Items.AddRange(baud);comboBox1.Enabled = false;comboBox2.Enabled = false;comboBox3.Enabled = false;comboBox4.Enabled = false;comboBox5.Enabled = false;hintrtx.Text += "欢迎使用";}private void button4_Click(object sender, EventArgs e){//开启串口try{if (_serialPort.IsOpen){//如果串口已经处于打开状态,则关闭串口_serialPort.Close();button4.Text = "打开串口";hintrtx.Text += "\n串口已经关闭";//关闭串口后,使能串口参数设置comboBox1.Enabled = true;comboBox2.Enabled = true;comboBox3.Enabled = true;comboBox4.Enabled = true;comboBox5.Enabled = true;//取消串口接收事件注册_serialPort.DataReceived -= new SerialDataReceivedEventHandler(_serialPort_DataReceived);return;}else{//串口已经处于关闭状态,则设置好串口属性后打开comboBox1.Enabled = false;comboBox2.Enabled = false;comboBox3.Enabled = false;comboBox4.Enabled = false;comboBox5.Enabled = false;_serialPort.PortName = comboBox1.Text;_serialPort.BaudRate = Convert.ToInt32(comboBox2.Text);_serialPort.DataBits = Convert.ToInt16(comboBox3.Text);_serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox4.Text);if (comboBox5.Text.Equals("1"))_serialPort.StopBits = System.IO.Ports.StopBits.One;else if (comboBox5.Text.Equals("1.5"))_serialPort.StopBits = System.IO.Ports.StopBits.OnePointFive;else if (comboBox5.Text.Equals("2"))_serialPort.StopBits = System.IO.Ports.StopBits.Two;//_serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.Text);_serialPort.Open();//注册串口接收事件_serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);button4.Text = "关闭串口";hintrtx.Text += "\n串口已经打开";}}catch (Exception ex){MessageBox.Show(ex.Message);hintrtx.Text += "\n串口打开失败";}}private void button3_Click(object sender, EventArgs e){//try{//首先判断串口是否开启if (_serialPort.IsOpen){//串口处于开启状态,将发送区文本发送_serialPort.Write(rtx_send.Text);}}catch (Exception ex){//捕获到异常,创建一个新的对象,之前的不可以再用_serialPort = new System.IO.Ports.SerialPort();//刷新COM口选项comboBox1.Items.Clear();comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());//响铃并显示异常给用户System.Media.SystemSounds.Beep.Play();button4.Text = "打开串口";MessageBox.Show(ex.Message);hintrtx.Text += "\n串口发送失败";comboBox1.Enabled = true;comboBox2.Enabled = true;comboBox3.Enabled = true;comboBox4.Enabled = true;comboBox5.Enabled = true;}}}

代码解释:

扫描串口:

我们使用serialport类进行串口的扫描,能够给到一个串口名称的列表。展示的中间修改页面元素的可用性,允许用户修改串口配置。

private void button1_Click(object sender, EventArgs e){//检测try{string[] ports = SerialPort.GetPortNames();if (ports.Length == 0){MessageBox.Show("没有找到串口");hintrtx.Text += "没有找到串口";return;}comboBox1.Items.Clear();comboBox1.Items.AddRange(ports);comboBox1.SelectedIndex = 0;comboBox2.SelectedIndex = 0;comboBox3.SelectedIndex = 0;comboBox4.SelectedIndex = 0;comboBox5.SelectedIndex = 0;//检测到串口后,使能串口参数设置comboBox1.Enabled = true;comboBox2.Enabled = true;comboBox3.Enabled = true;comboBox4.Enabled = true;comboBox5.Enabled = true;}catch (Exception ex){MessageBox.Show(ex.Message);}}

打开/关闭串口

逻辑非常简单,判断是否已经打开,如果已经打开就关闭。

打开的逻辑是:

读取用户设置之前先锁定配置,防止调试中用户修改。

接着就是打开串口,注册串口接收事件用于执行接收指定的逻辑。

关闭串口更加简单,重新给予用户修改配置的机会,同时关闭串口,取消事件的注册。

事件机制是串口收发的核心:

C#笔记4 详细解释事件及其原型、匿名方法和委托的关系-CSDN博客

c#笔记5 详解事件的内置类型EventHandler、windows事件在winform中的运用_c# eventhandler用法-CSDN博客

 private void button4_Click(object sender, EventArgs e){//开启串口try{if (_serialPort.IsOpen){//如果串口已经处于打开状态,则关闭串口_serialPort.Close();button4.Text = "打开串口";hintrtx.Text += "\n串口已经关闭";//关闭串口后,使能串口参数设置comboBox1.Enabled = true;comboBox2.Enabled = true;comboBox3.Enabled = true;comboBox4.Enabled = true;comboBox5.Enabled = true;//取消串口接收事件注册_serialPort.DataReceived -= new SerialDataReceivedEventHandler(_serialPort_DataReceived);return;}else{//串口已经处于关闭状态,则设置好串口属性后打开comboBox1.Enabled = false;comboBox2.Enabled = false;comboBox3.Enabled = false;comboBox4.Enabled = false;comboBox5.Enabled = false;_serialPort.PortName = comboBox1.Text;_serialPort.BaudRate = Convert.ToInt32(comboBox2.Text);_serialPort.DataBits = Convert.ToInt16(comboBox3.Text);_serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox4.Text);if (comboBox5.Text.Equals("1"))_serialPort.StopBits = System.IO.Ports.StopBits.One;else if (comboBox5.Text.Equals("1.5"))_serialPort.StopBits = System.IO.Ports.StopBits.OnePointFive;else if (comboBox5.Text.Equals("2"))_serialPort.StopBits = System.IO.Ports.StopBits.Two;//_serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.Text);_serialPort.Open();//注册串口接收事件_serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);button4.Text = "关闭串口";hintrtx.Text += "\n串口已经打开";}}catch (Exception ex){MessageBox.Show(ex.Message);hintrtx.Text += "\n串口打开失败";}}

串口接收事件:

这里主要是做了一个串口的错误处理和调用界面元素显示的方法。从不是创建这个元素的线程调用改变元素的方法需要使用invoke。

//串口接收事件private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e){//串口接收事件try{//串口接收数据//if(serialPort1.IsOpen){this.Invoke(new EventHandler(displaytext));}}catch (Exception ex){//捕获到异常,创建一个新的对象,之前的不可以再用_serialPort = new System.IO.Ports.SerialPort();//刷新COM口选项comboBox1.Items.Clear();comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());//响铃并显示异常给用户System.Media.SystemSounds.Beep.Play();button4.Text = "打开串口";MessageBox.Show(ex.Message);hintrtx.Text += "\n串口接收失败";comboBox1.Enabled = true;comboBox2.Enabled = true;comboBox3.Enabled = true;comboBox4.Enabled = true;comboBox5.Enabled = true;}}

display方法 

这里就可以写你自己的方法了。串口的数据经过怎么处理展示到哪里。 

private void displaytext(object sender, EventArgs e){string str = _serialPort.ReadExisting();rtxreceive.AppendText(str);}


http://www.ppmy.cn/devtools/114988.html

相关文章

如何在安卓設備上更換IP地址?

IP地址是設備在網路中的唯一標識&#xff0c;通過IP地址&#xff0c;網路能夠識別並與設備進行通信。本文將詳細介紹在安卓設備上更換IP地址的幾種方法。 在安卓設備上更換IP地址的方法 1. 使用Wi-Fi網路更換IP地址 最簡單的方法是通過Wi-Fi網路更換IP地址。步驟如下&#x…

渗透测试入门学习——php文件上传与文件包含

最终效果&#xff1a; 提前在网站根目录创建upload目录&#xff1a; 主页面&#xff08;文件名为file.php&#xff09;&#xff1a; <html> <head><meta charset"utf-8"><title>php文件相关练习</title> </head><h1>php文…

Zookeeper学习

文章目录 学习第 1 章 Zookeeper 入门1.1 概述Zookeeper工作机制 1.2 特点1.3 数据结构1.4 应用场景统一命名服务统一配置管理统一集群管理服务器动态上下线软负载均衡 1.5 下载zookeeper 第 2 章 Zookeeper 本地安装2.1 本地模式安装安装前准备配置修改操作 Zookeeper本地安装…

IO流体系(FiletOutputStream)

书写步骤&#xff1a; 1.创建字节输出流对象 细节1:参数是字符串表示的路径或者是File对象都是可以的 细节2:如果文件不存在会创建一个新的文件&#xff0c;但是要保证父级路径是存在的。 细节3:如果文件已经存在&#xff0c;则会清空文件 2.写数据 细节:write方法的参数…

数据结构-2.9.双链表

一.双链表与单链表的对比&#xff1a; 二.双链表的初始化(带头结点)&#xff1a; 1.图解&#xff1a; 2.代码演示&#xff1a; #include<stdio.h> #include<stdlib.h> ​ //定义双链表结构体 typedef struct DNode {int data;struct DNode *prior;//前驱指针即指…

Iterative Regularized Policy Optimization with Imperfect Demonstrations

ICML 2024 paper code Intro 利用基于次优专家数据的专家策略&#xff0c;通过policy constraint的形式引导智能体的在线优化&#xff0c;同时通过利用在线高质量数据扩展专家数据&#xff0c;并有监督得对专家策略进行矫正。二者交替优化实现目标策略的迭代更新 Method 上述…

【RabbitMQ 项目】项目概述

项目概述 一.角色划分二.服务器模块概述1.本地模块2.网络模块3.服务器模块 三.模块详细划分1.服务端2.客户端 一.角色划分 该项目的模型是一个跨主机的生产消费模型&#xff0c;有三种角色&#xff1a;生产者&#xff0c;消费者&#xff0c;中间人。对应就要实现三个大模块&…

PTA L1-062 幸运彩票

L1-062 幸运彩票&#xff08;15分&#xff09; 彩票的号码有 6 位数字&#xff0c;若一张彩票的前 3 位上的数之和等于后 3 位上的数之和&#xff0c;则称这张彩票是幸运的。本题就请你判断给定的彩票是不是幸运的。 输入格式&#xff1a; 输入在第一行中给出一个正整数 N&a…