C#中实现串口通讯和网口通讯(使用SerialPort和Socket类)

仅作自己学习使用


1 准备部份

串口通讯需要两个调试软件commix和Virtual Serial Port Driver,分别用于监视串口和创造虚拟串口。网口通讯需要一个网口调试助手,网络上有很多资源,我在这里采用的是微软商店中的TCP/UDP网络调试助手,其中也有和commix一样功能的串口调试模块。

第一个软件是这样的:
commix 1.4
资源在这里:免费下载:Commix
也可以前往官网下载:Bwsensing— Attitude is everything
在这里插入图片描述
点击Download即可


第二个软件是这样的:
Virtual Serial Port Driver Pro
官方下载链接:Virtual Serial Port Driver


第三个软件是这样的:
TCP UDP网络调试工具
可以看到其实这个软件也有串口通讯调试的功能。
官方下载链接:TCP UDP网络调试助手

2 串口通讯

2.1 Xaml代码

界面做得很丑,能用就行,关键是原理:
在这里插入图片描述

<Window x:Class="WPF_ZhaoXi_0205.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WPF_ZhaoXi_0205"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><TextBox x:Name="textBox_receive" Grid.Row="0" Grid.Column="0" FontSize="15" Margin="10" Text="接收窗口"/><TextBox x:Name="textBox_send" Grid.Row="0" Grid.Column="1" FontSize="15" Margin="10" Text="发送窗口"/><Button x:Name="button_open" Grid.Row="1" Grid.Column="0" Content="打开串口" Margin="10" Click="button_open_Click"/><Button x:Name="button_recisive" Grid.Row="1" Grid.Column="1" Content="接收数据" Margin="10" Click="button_recisive_Click"/><Button x:Name="button_send" Grid.Row="2" Grid.Column="0" Content="发送数据" Margin="10" Click="button_send_Click"/></Grid>
</Window>

2.2 cs代码

using System.IO.Ports;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace WPF_ZhaoXi_0205
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{// 声明一个串口对象SerialPort sp = null;public MainWindow(){InitializeComponent();// 实例化串口对象//sp = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);sp = new SerialPort();// 设置通讯的属性sp.PortName = "COM2";       // 串口名称sp.BaudRate = 9600;         // 波特率sp.Parity = Parity.None;    // 校验位sp.DataBits = 8;            // 数据位  sp.StopBits = StopBits.One; // 停止位 // 第二种接收数据的方式,被动接收,如称重,扫码枪等 sp.DataReceived += Sp_DataReceived;}/// <summary>/// 第二种数据接收的方式/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e){byte[] bt1 = new byte[sp.BytesToRead];sp.Read(bt1, 0, bt1.Length);// 这里在异步线程处理了UI控件,而UI控件必须在主线程处理,因此要报错//textBox_recsive.Text = Encoding.ASCII.GetString(bt1);// 因此把这个语句放在UI线程(主线程进行)this.Dispatcher.Invoke(() =>{ textBox_receive.Text = Encoding.ASCII.GetString(bt1); });}/// <summary>/// 打开串口/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button_open_Click(object sender, RoutedEventArgs e){// 打开动作try{// 串口的一端只能同时被一个用户打开,否则报错,所以看是否串口已经被占用sp.Open();MessageBox.Show(sp.PortName+"串口已打开", "提示");}catch (Exception ex){MessageBox.Show(ex.Message,"提示");}}/// <summary>/// 发送数据/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button_send_Click(object sender, RoutedEventArgs e){// 发送动作(与打开动作操作同一个串口对象)// sp.Write();string str_send = textBox_send.Text;byte[] bt1 = Encoding.ASCII.GetBytes(str_send);byte[] bt2 = new byte[] { 0x01, 0x02, 0x03 };sp.Write(bt1, 0, bt1.Length);  // 在bytes中从位置0开始发送bytes.Length个字节}/// <summary>/// 接收数据(第一种接收方式,主动请求接收方式)/// 我要你再给/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button_recisive_Click(object sender, RoutedEventArgs e){// 长度是串口能够读到的最大的字节数量byte[] bt1 = new byte[sp.BytesToRead];sp.Read(bt1, 0, bt1.Length); // 从当前串口中的位置0处开始读取bt1.Length个字节到bt1中textBox_receive.Text = Encoding.ASCII.GetString(bt1);}}
}

3 网口通讯

3.1 Xaml代码

<Window x:Class="WPF_ZhaoXi_0205.window1"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WPF_ZhaoXi_0205"mc:Ignorable="d"Title="window1" Height="450" Width="800"><Grid><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><TextBox x:Name="textBox_receive" Grid.Row="0" Grid.Column="0" FontSize="15" Margin="10" Text="接收窗口"/><TextBox x:Name="textBox_send" Grid.Row="0" Grid.Column="1" FontSize="15" Margin="10" Text="发送窗口"/><Button x:Name="button_connect" Grid.Row="1" Grid.Column="0" Content="链接服务器" Margin="10" Click="button_connect_Click"/><Button x:Name="button_receive" Grid.Row="1" Grid.Column="1" Content="接收数据" Margin="10" Click="button_receive_Click"/><Button x:Name="button_send" Grid.Row="2" Grid.Column="0" Content="发送数据" Margin="10" Click="button_send_Click" /></Grid>
</Window>

3.2 cs代码

using System.IO;
using System.IO.Ports;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace WPF_ZhaoXi_0205
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class window1 : Window{// 声明一个对象Socket socket = null;public window1(){InitializeComponent();socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);}/// <summary>/// 链接数据库/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button_connect_Click(object sender, RoutedEventArgs e){try{socket.Connect("127.0.0.1", 6666);Task.Run(() =>{// 异步线程while (true){byte[] datb = new byte[50];socket.Receive(datb);this.Dispatcher.Invoke(() => {textBox_receive.Text = Encoding.UTF8.GetString(datb);});    }});MessageBox.Show("服务器已链接", "提示");}catch (Exception ex){MessageBox.Show(ex.Message, "提示");}}/// <summary>/// 发送数据/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button_send_Click(object sender, RoutedEventArgs e){// byte[] data = new byte[] { 0x32 };byte[] data = Encoding.UTF8.GetBytes("[abc] hello 牛犇!123");socket.Send(data);// 接收数据(主动响应)//byte[] datb = new byte[50];//socket.Receive(datb);//textBox_receive.Text = Encoding.UTF8.GetString(datb);}/// <summary>/// 接收数据/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button_receive_Click(object sender, RoutedEventArgs e){byte[] datb = new byte[50];socket.Receive(datb);textBox_receive.Text = Encoding.UTF8.GetString(datb);}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/674024.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【leetcode热题100】删除排序链表中的重复元素

难度&#xff1a; 简单通过率&#xff1a; 41.5%题目链接&#xff1a;力扣&#xff08;LeetCode&#xff09;官网 - 全球极客挚爱的技术成长平台 题目描述 给定一个排序链表&#xff0c;删除所有重复的元素&#xff0c;使得每个元素只出现一次。 示例 1: 输入: 1->1->…

cleanmymacX和腾讯柠檬哪个好用

很多小伙伴在使用Mac时&#xff0c;会遇到硬盘空间不足的情况。遇到这种情况&#xff0c;我们能做的就是清理掉一些不需要的软件或者一些占用磁盘空间较大的文件来腾出空间。我们可以借助一些专门的清理工具&#xff0c;本文中我们来推荐几款好用的Mac知名的清理软件。并且将Cl…

C语言:亲密数对

题目描述 在自然数中有一种这样的数&#xff1a;它自身是一个完全平方数&#xff0c;加上1之后是一个素数&#xff0c;这一对数被称为亲密数对&#xff0c;请编程找出指定区域内的所有亲密数对。 例如在[10,100]之间的亲密数对有&#xff1a;&#xff08;16,17&#xff09;&am…

SQL在云计算中的新角色:重新定义数据分析

文章目录 1. 云计算与数据分析的融合2. SQL在云计算中的新角色3. 分布式SQL查询引擎4. SQL-on-Hadoop解决方案5. SQL与其他数据分析工具的集成6. 实时数据分析与SQL7. SQL在云数据仓库中的角色8. 安全性与隐私保护9. SQL的未来展望《SQL数据分析实战&#xff08;第2版&#xff…

SQL笔记-2024/01/31

cross join 两个表的笛卡尔积 例如&#xff1a; select s.name student_name,s.age student_age,s.class_id class_id,c.name class_name from student s cross join class c; 子查询 select s.name name,s.score score,s.class_id class_id from student s where s.class_id …

14.scala隐式转换

目录 概述实践代码执行结果 结束 概述 隐式转换&#xff1a;偷偷的(隐式)对现有功能进行增强(转换) 实践 代码 package com.fun.scalaimport java.io.File import scala.io.Sourceobject ImplicitApp {def main(args: Array[String]): Unit {// implicit 2 to 等价 &…

vuecli3 执行 npm run build 打包命令报错:TypeError: file.split is not a function

问题 今天有个项目在打包的时候遇到了一个问题&#xff0c;就是执行 npm run build 命令的时候报错了&#xff0c;如下&#xff1a; 解决 我排查了一下&#xff0c;模拟代码如下&#xff1a;在打包的时候用了 MinChunkSizePlugin const webpack require("webpack"…

LabVIEW多任务实时测控系统

LabVIEW多任务实时测控系统 面对现代化工业生产的复杂性和多变性&#xff0c;传统的测控系统已难以满足高效、精准、可靠的监控和控制需求。因此&#xff0c;开发一种基于LabVIEW的智能测控系统&#xff0c;能够提高生产效率&#xff0c;保证生产安全&#xff0c;是解决现代工…

ubuntu 没有屏幕安装QT(SSH远程登陆下)

1背景说明 需要在SSH登陆的ubuntu远程上安装QT&#xff0c;但是远程电脑没有屏幕&#xff0c;报了这个错误“QXcbConnection: Could not connect to display”。 2网上搜索有2种解决方案 由于远程服务器没有配置屏幕&#xff0c;都失败了 2.1配置屏幕关闭 vim ~/.bashrc …

打卡今天学习的命令 (linux

1.1 cp - 复制文件或目录 cp source destination cp -r source_directory destination # 递归复制目录及其内容1.2 rm - 删除文件或目录 rm file rm -r directory # 递归删除目录及其内容1.3 mv - 移动/重命名文件或目录 mv source destination mv old_name new_name # 重…

怎么清理电脑内存?详细图文教程分享!

“我的电脑用了才不到一年&#xff0c;现在内存总是不足。想问问大家平常遇到电脑内存不足的情况时有什么好用的清理方法吗&#xff1f;” 随着电脑使用时间的增长&#xff0c;内存占用可能会不断增加&#xff0c;导致电脑运行缓慢。为了保持电脑的良好性能&#xff0c;定期清理…

手把手教你实现Kmeans聚类,不使用MATLAB工具箱,纯手写matlab代码免费获取,UCI数据集为例...

K均值&#xff08;K-means&#xff09;是一种常用的聚类算法&#xff0c;用于将数据集划分为K个不同的组&#xff08;簇&#xff09;&#xff0c;使得每个数据点属于与其最近的均值点所代表的簇。K均值算法的基本思想是通过迭代优化&#xff0c;将数据点分配到K个簇中&#xff…

C语言的联合体:一种节省内存的数据结构

在C语言中&#xff0c;联合体&#xff08;union&#xff09;是一种特殊的数据结构&#xff0c;它允许我们在相同的内存位置存储不同的数据类型。这意味着联合体中的所有成员都共享同一块内存空间&#xff0c;因此它们不能同时存储其各自的值。联合体的主要目的是节省内存&#…

【RT-DETR有效改进】重参数化模块DiverseBranchBlock助力特征提取(附代码 + 修改教程)

&#x1f451;欢迎大家订阅本专栏&#xff0c;一起学习RT-DETR&#x1f451; 一、本文介绍 本文给大家带来的是改进机制是一种替换多元分支模块&#xff08;Diverse Branch Block&#xff09;&#xff0c;Diverse Branch Block (DBB) 是一种用于增强卷积神经网络性能的结构…

Duplicate entry ‘1xx-2xx-3xx-4xx‘ for key ‘uniq_index‘的解决方法

我在往sql数据库新增数据的时候&#xff0c;碰到报错类似标题。 意思大概是插入的数据重复了&#xff0c;下面分享两种解决办法。 第一种 找到某一节对应的字段&#xff0c;然后在原sql语句里改动这一节的数据&#xff0c;重新执行新增操作。 比如ABC20240208-aaa-yangguang-…

牛客网SQL进阶137:第二快/慢用时之差大于试卷时长一半的试卷

官网链接&#xff1a; 第二快慢用时之差大于试卷时长一半的试卷_牛客题霸_牛客网现有试卷信息表examination_info&#xff08;exam_id试卷ID, tag试卷类别,。题目来自【牛客题霸】https://www.nowcoder.com/practice/b1e2864271c14b63b0df9fc08b559166?tpId240 0 问题描述 试…

基于tomcat的https(ssl)双向认证

一、背景介绍 某个供应商服务需要部署到海外&#xff0c;如果海外多个地区需要部署多个服务&#xff0c;最好能实现统一登录&#xff0c;这样可以减轻用户的使用负担&#xff08;不用记录一堆密码&#xff09;。由于安全问题&#xff08;可能会泄露用户数据&#xff09;&#x…

【数据结构】二叉树的三种遍历(非递归讲解)

目录 1、前言 2、二叉树的非递归遍历 2.1、先序遍历 2.2、中序遍历 2.3、后序遍历 1、前言 学习二叉树的三种非递归遍历前&#xff0c;首先来了解一下递归序&#xff1a; 递归序就是按照先序遍历的顺序&#xff0c;遇到的所有结点按顺序排列&#xff0c;重复的结点也必须记…

Debian系统中挂载一个数据盘

如果你想在Debian系统中挂载一个名为sdb的数据盘&#xff0c;你可以按照以下步骤操作。请注意&#xff0c;这里假设sdb是整个磁盘的设备名&#xff0c;而不是特定的分区。如果你想要挂载磁盘上的特定分区&#xff0c;设备名可能会是sdb1、sdb2等。 如下是我执行成功得命令&…

深度学习(14)--x.view()详解

在torch中&#xff0c;常用view()函数来改变tensor的形状 查询官方文档&#xff1a; torch.Tensor.view — PyTorch 2.2 documentationhttps://pytorch.org/docs/stable/generated/torch.Tensor.view.html#torch.Tensor.view示例 1.创建一个4x4的二维数组进行测试 x torch.…