您好,
会员登录 快速注册
退出 ( 条未读消息)
关于本站 意见反馈 首页

公告:小宅博客网可以开发票了,需要发票的,去群里找群主哈!!
全部文章分类
  • 人工智能 >

  • 编程语言 >

  • WPF系列 >

  • ASP.NET系列 >

  • Linux >

  • 数据库 >

  • 嵌入式 >

  • WEB技术 >

  • PLC系列 >

  • 微服务与框架 >

  • 小宅DIY >

  • 学习资料 >

OpenCv基础 ANN车牌识别 yolov5车牌识别 指针式仪表识别 ROS系列 YOLO Halcon Detectron2 昇腾AI ChatGPT在线体验 英伟达JETSON ChatGLM ChatTTS FunASR 地平线 ByteTrack 魔搭社区 LangChain
C C# C++ Python Java Go
WPF
ASP.NET小功能 GPS定位系统-MVC GPS定位系统-VUE ASP.NET WebRTC
Linux Linux内核 Shell MakeFile
MySql SqlServer Oracle
STM8 STM32 51单片机
VUE入门 HTML JavaScript CSS layui镜像网站 ElementUi中文官网 element-plus 图标
三菱 欧姆龙 西门子 施耐德 松下 台达
IOTSharp IOTGateway ABP FRAMEWORK Docker
亚克力音响 编程仙途:智驭万法
面试题与技巧 Python入门技能树 微软C#教程
首页 编程之美 工具下载 全国就业 流量地图 文心一言
C#
内容简介 1、C#环境下使用EF操作MySql 2、实现串口通信 3、TCP通信 4、读写SqlServer数据库 5、读写ini配置文件 6、实现远程升级 7、调用打印机 8、AES数据加密与解密 AES加解密(RijndaelManaged版) 9、FTP的上传和下载 10、封装dll到exe 11、重写Button控件 12、重写Labeld控件 13、重写DataGridView控件 14、重写TabControl控件 15、重写ProgressBar控件 16、加载状态弹窗设计 17、模拟按键精灵 18、24种数据校验算法 19、C#如何调用opencv 20、地图上显示GPS坐标 21、使用EPPlus导出/导入xlsx格式的Excel报表和曲线图 22、exe程序生成安装包 23、DataGridView控件列控制 24、json解析 25、自定义委托事件 26、xml文件的生成与读取 27、DataGridView实现翻页效果 28、如何实现CAD dxf文件的读取 29、StopWatch的使用 30、Async与Await 同步与异步操作 31、关闭登录窗体打开主窗体的方法 32、SQLite数据库的操作 33、MD5数据加密 34、DES数据加密与解密 35、获取本地IP地址 36、打开与保存文件 37、静态图表显示(曲线图) 38、动态图表显示(曲线图) 39、根据公网IP获取地址信息 40、List转DataTable 41、C#下实现Ping操作 42、父窗体中嵌入子窗体 43、获取MySql数据库列表 44、WebSocket通讯 45、Mqtt客户端与服务端通讯 46、使用QRCode生成二维码 47、AForge调用摄像头 48、Emgu.CV调用摄像头 49、获取以太网网卡IP 50、DataGridView全选与定位 51、如何获取系统中所有程序的句柄 遍历指定目录下的所有文件 ​NPOI Excel报表的导入与导出 常用正则表达式字符串格式判断 Task和Thread的启停操作 C# 一些常用小功能1 C# 一些常用小功能2 如何使用C#来发送QQ邮件 Aspose.Slides文档格式转换 C# GDI+ 画心形 跳动动画 使用Remoting实现RPC RabbitMQ.消息发布与订阅 .Net Core 微信/支付宝 官方Demo C# OCR图片文字识别 Quartz 计划任务 文字语音播报 winform基于百度地图的电子围栏、路径规划、小车导航实现 Visual Studio C盘数据迁移,解决C盘空间不足的问题 Kafka通讯(Kafka-Net版) Kafka通讯(Confluent.Kafka版) 获取变量Description描述 C# 将PDF文档转换为Word文档 C# MVC 多图片上传预览
1、C#环境下使用EF操作MySql
3、TCP通信
激萌の小宅 小宅博客网 C#

文章作者:激萌の小宅

促销:¥0

价格:¥0

配送方式: 购买后立即生效(如购买异常,请联系站长)
付款之后一定要等待自动跳转结束,否则购买可能会失败
  • 0 天

    有效期

  • 0

    总销量

  • 7

    累计评价

上位机如何实现串口通信 - (第二讲)


开发环境为 Visual Studio 2019


视频讲解如下:


CSDN源码下载


源码下载,提取码:jwo1

https://pan.baidu.com/s/1EY3xI7cQo5Ea3iQDeYEWfQ


这里给大家讲解一下在winform环境下如何实现串口通信的。


界面设计效果如下:


Form1.cs 代码如下

using System;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace usb
{
    public partial class Form1 : Form
    {
        private MyCom mCom = new MyCom();

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 查找串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_SearchCom_Click(object sender, EventArgs e)
        {
            string[] names = SerialPort.GetPortNames();
            comboBox_com.Items.Clear();
            if (names.Length >= 1)
            {
                for (int i = 0; i < names.Length; i++)
                {
                    comboBox_com.Items.Add(names[i]);
                }
                comboBox_com.Text = names[0];
            }
            else
            {
                comboBox_com.Items.Add("COM0");
                comboBox_com.Text = "COM0";
            }
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_open_Click(object sender, EventArgs e)
        {
            Res.com_name = comboBox_com.Text; // 串口号
            Res.Box_Bound = int.Parse(comboBox1.Text); // 波特率
            Res.Box_DataBit = int.Parse(comboBox2.Text); // 数据位
            Res.Box_StopBit = comboBox3.Text;// 停止位
            Res.Box_Verify = comboBox4.Text;// 校验位
            mCom.ComOpen();
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_send_Click(object sender, EventArgs e)
        {
            mCom.ComWrite(Encoding.UTF8.GetBytes(textBox2.Text));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] names = SerialPort.GetPortNames();
            if (names.Length >= 1)
            {
                for (int i = 0; i < names.Length; i++)
                {
                    comboBox_com.Items.Add(names[i]);
                }
                comboBox_com.Text = names[0];
            }
            else
            {
                comboBox_com.Items.Add("COM0");
                comboBox_com.Text = "COM0";
            }
            comboBox1.SelectedIndex = 13;
            comboBox2.SelectedIndex = 2;
            comboBox3.SelectedIndex = 0;
            comboBox4.SelectedIndex = 0;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Res.logs.Count > 0)
            {
                textBox1.Text += Res.logs[0] + "\r\n";
                Res.logs.RemoveAt(0);
            }
        }
    }

    /// <summary>
    /// 在这里实现串口的数据接收和发送
    /// </summary>
    public class MyCom
    {
        /// <summary>
        /// 打开串口
        /// </summary>
        public void ComOpen()
        {
            if (Res.comm.IsOpen == false)
            {
                // 打开串口
                Res.comm.PortName = Res.com_name; // 串口
                Res.comm.BaudRate = Res.Box_Bound; // 波特率
                Res.comm.DataBits = Res.Box_DataBit; // 数据位

                // 停止位
                if (Res.Box_StopBit == "1") Res.comm.StopBits = System.IO.Ports.StopBits.One;
                if (Res.Box_StopBit == "1.5") Res.comm.StopBits = System.IO.Ports.StopBits.OnePointFive;
                if (Res.Box_StopBit == "2") Res.comm.StopBits = System.IO.Ports.StopBits.Two;

                // 校验位
                if (Res.Box_Verify == "None") Res.comm.Parity = System.IO.Ports.Parity.None;
                if (Res.Box_Verify == "Odd") Res.comm.Parity = System.IO.Ports.Parity.Odd;
                if (Res.Box_Verify == "Even") Res.comm.Parity = System.IO.Ports.Parity.Even;
                if (Res.Box_Verify == "Mark") Res.comm.Parity = System.IO.Ports.Parity.Mark;
                if (Res.Box_Verify == "Space") Res.comm.Parity = System.IO.Ports.Parity.Space;

                Res.comm.NewLine = "\r\n";
                Res.comm.RtsEnable = true;
                Res.comm.Handshake = System.IO.Ports.Handshake.None;
                linkCom();
            }
            else
            {
                // 关闭串口
                Res.logs.Add("关闭串口.");
                if (Res.comm.IsOpen)
                    Res.comm.Close();
            }
        }

        /// <summary>
        /// 开线程
        /// </summary>
        private void linkCom()
        {
            Res.comm.Open();
            Res.comm.Encoding = Encoding.GetEncoding("GB2312");
            new Thread(ComReadData) { IsBackground = true }.Start();
        }

        /// <summary>
        /// 数据接收
        /// </summary>
        private void ComReadData()
        {
            Res.logs.Add("打开串口完成.");

            while (Res.comm.IsOpen)
            {
                Thread.Sleep(50); // 以50ms一个周期,进行串口数据接收,不能太快,不然会出现拆包的现象
                try
                {
                    // 查询串口中目前保存了多少数据
                    int n = Res.comm.BytesToRead;

                    // 读取数据
                    byte[] buf = new byte[n];
                    Res.comm.Read(buf, 0, n);

                    // 打印数据
                    if (buf.Length > 0)
                    {
                        string str = Encoding.Default.GetString(buf).Replace("-", " ");
                        Res.logs.Add(str);
                    }
                }
                catch
                {
                    if (Res.comm.IsOpen)
                        Res.comm.Close();
                }
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        public void ComWrite(byte[] bytes)
        {
            try
            {
                if (Res.comm.IsOpen && bytes != null)
                {
                    Res.comm.Write(bytes, 0, bytes.Length);
                }
            }
            catch { }
        }
    }
}


Res.cs  代码如下

using System.Collections.Generic;
using System.IO.Ports;

namespace usb
{
    public static class Res
    {
        /// <summary>
        /// 这里保存串口的接收数据
        /// </summary>
        public static List<string> logs = new List<string>();

        /// <summary>
        /// 串口接口
        /// </summary>
        public static SerialPort comm { get; set; } = new SerialPort();

        /// <summary>
        /// 串口名字
        /// </summary>
        public static string com_name { get; set; }

        /// <summary>
        /// 波特率
        /// </summary>
        public static int Box_Bound { get; set; }

        /// <summary>
        /// 数据位
        /// </summary>
        public static int Box_DataBit { get; set; }

        /// <summary>
        /// 校验位
        /// </summary>
        public static string Box_Verify { get; set; }

        /// <summary>
        /// 停止位
        /// </summary>
        public static string Box_StopBit { get; set; }
    }
}
1、C#环境下使用EF操作MySql
3、TCP通信

友情链接: CSDN激萌の小宅 95知识库 自考题库 罗分明个人网络博客 精益编程leanboot

小宅博客  www.bilibili996.com All Rights Reserved. 备案号: 闽ICP备2024034575号

网站经营许可证  福建省福州市 Copyright©2021-2025 版权所有

小宅博客
首页 智能家居 地图定位
公告:小宅博客网可以开发票了,需要发票的,去群里找群主哈!!

文章作者:激萌の小宅

促销:¥0

价格:¥0

配送方式: 购买后立即生效(如购买异常,请联系站长)
付款之后一定要等待自动跳转结束,否则购买可能会失败
  • 0 天

    有效期

  • 0

    总销量

  • 7

    累计评价

上位机如何实现串口通信 - (第二讲)


开发环境为 Visual Studio 2019


视频讲解如下:


CSDN源码下载


源码下载,提取码:jwo1

https://pan.baidu.com/s/1EY3xI7cQo5Ea3iQDeYEWfQ


这里给大家讲解一下在winform环境下如何实现串口通信的。


界面设计效果如下:


Form1.cs 代码如下

using System;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace usb
{
    public partial class Form1 : Form
    {
        private MyCom mCom = new MyCom();

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 查找串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_SearchCom_Click(object sender, EventArgs e)
        {
            string[] names = SerialPort.GetPortNames();
            comboBox_com.Items.Clear();
            if (names.Length >= 1)
            {
                for (int i = 0; i < names.Length; i++)
                {
                    comboBox_com.Items.Add(names[i]);
                }
                comboBox_com.Text = names[0];
            }
            else
            {
                comboBox_com.Items.Add("COM0");
                comboBox_com.Text = "COM0";
            }
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_open_Click(object sender, EventArgs e)
        {
            Res.com_name = comboBox_com.Text; // 串口号
            Res.Box_Bound = int.Parse(comboBox1.Text); // 波特率
            Res.Box_DataBit = int.Parse(comboBox2.Text); // 数据位
            Res.Box_StopBit = comboBox3.Text;// 停止位
            Res.Box_Verify = comboBox4.Text;// 校验位
            mCom.ComOpen();
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_send_Click(object sender, EventArgs e)
        {
            mCom.ComWrite(Encoding.UTF8.GetBytes(textBox2.Text));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] names = SerialPort.GetPortNames();
            if (names.Length >= 1)
            {
                for (int i = 0; i < names.Length; i++)
                {
                    comboBox_com.Items.Add(names[i]);
                }
                comboBox_com.Text = names[0];
            }
            else
            {
                comboBox_com.Items.Add("COM0");
                comboBox_com.Text = "COM0";
            }
            comboBox1.SelectedIndex = 13;
            comboBox2.SelectedIndex = 2;
            comboBox3.SelectedIndex = 0;
            comboBox4.SelectedIndex = 0;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Res.logs.Count > 0)
            {
                textBox1.Text += Res.logs[0] + "\r\n";
                Res.logs.RemoveAt(0);
            }
        }
    }

    /// <summary>
    /// 在这里实现串口的数据接收和发送
    /// </summary>
    public class MyCom
    {
        /// <summary>
        /// 打开串口
        /// </summary>
        public void ComOpen()
        {
            if (Res.comm.IsOpen == false)
            {
                // 打开串口
                Res.comm.PortName = Res.com_name; // 串口
                Res.comm.BaudRate = Res.Box_Bound; // 波特率
                Res.comm.DataBits = Res.Box_DataBit; // 数据位

                // 停止位
                if (Res.Box_StopBit == "1") Res.comm.StopBits = System.IO.Ports.StopBits.One;
                if (Res.Box_StopBit == "1.5") Res.comm.StopBits = System.IO.Ports.StopBits.OnePointFive;
                if (Res.Box_StopBit == "2") Res.comm.StopBits = System.IO.Ports.StopBits.Two;

                // 校验位
                if (Res.Box_Verify == "None") Res.comm.Parity = System.IO.Ports.Parity.None;
                if (Res.Box_Verify == "Odd") Res.comm.Parity = System.IO.Ports.Parity.Odd;
                if (Res.Box_Verify == "Even") Res.comm.Parity = System.IO.Ports.Parity.Even;
                if (Res.Box_Verify == "Mark") Res.comm.Parity = System.IO.Ports.Parity.Mark;
                if (Res.Box_Verify == "Space") Res.comm.Parity = System.IO.Ports.Parity.Space;

                Res.comm.NewLine = "\r\n";
                Res.comm.RtsEnable = true;
                Res.comm.Handshake = System.IO.Ports.Handshake.None;
                linkCom();
            }
            else
            {
                // 关闭串口
                Res.logs.Add("关闭串口.");
                if (Res.comm.IsOpen)
                    Res.comm.Close();
            }
        }

        /// <summary>
        /// 开线程
        /// </summary>
        private void linkCom()
        {
            Res.comm.Open();
            Res.comm.Encoding = Encoding.GetEncoding("GB2312");
            new Thread(ComReadData) { IsBackground = true }.Start();
        }

        /// <summary>
        /// 数据接收
        /// </summary>
        private void ComReadData()
        {
            Res.logs.Add("打开串口完成.");

            while (Res.comm.IsOpen)
            {
                Thread.Sleep(50); // 以50ms一个周期,进行串口数据接收,不能太快,不然会出现拆包的现象
                try
                {
                    // 查询串口中目前保存了多少数据
                    int n = Res.comm.BytesToRead;

                    // 读取数据
                    byte[] buf = new byte[n];
                    Res.comm.Read(buf, 0, n);

                    // 打印数据
                    if (buf.Length > 0)
                    {
                        string str = Encoding.Default.GetString(buf).Replace("-", " ");
                        Res.logs.Add(str);
                    }
                }
                catch
                {
                    if (Res.comm.IsOpen)
                        Res.comm.Close();
                }
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        public void ComWrite(byte[] bytes)
        {
            try
            {
                if (Res.comm.IsOpen && bytes != null)
                {
                    Res.comm.Write(bytes, 0, bytes.Length);
                }
            }
            catch { }
        }
    }
}


Res.cs  代码如下

using System.Collections.Generic;
using System.IO.Ports;

namespace usb
{
    public static class Res
    {
        /// <summary>
        /// 这里保存串口的接收数据
        /// </summary>
        public static List<string> logs = new List<string>();

        /// <summary>
        /// 串口接口
        /// </summary>
        public static SerialPort comm { get; set; } = new SerialPort();

        /// <summary>
        /// 串口名字
        /// </summary>
        public static string com_name { get; set; }

        /// <summary>
        /// 波特率
        /// </summary>
        public static int Box_Bound { get; set; }

        /// <summary>
        /// 数据位
        /// </summary>
        public static int Box_DataBit { get; set; }

        /// <summary>
        /// 校验位
        /// </summary>
        public static string Box_Verify { get; set; }

        /// <summary>
        /// 停止位
        /// </summary>
        public static string Box_StopBit { get; set; }
    }
}