C# 串口类封装(串口通讯)RS232 示例代码分享

本文介绍了如何在C#中使用SerialPort类进行串口通讯,包括自动获取串口列表、打开关闭串口、数据发送与接收,以及事件处理机制。作者分享了一个自定义的串口类实例,用于学习交流。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 本文是对于串口通讯,普通串口RS232串口通讯分享。

通常电脑可以使用USB转TTL模块进行测试,只需两个USB转TTL模块,将两个模块的TX(输出端)和RX(输入端)交叉接入,在电脑上打开两个串口,就可以互相测试了。此部分如有不懂后期会出详细介绍。

头文件引用

using System.IO.Ports;

主要代码:

此代码为个人封装自用的串口类,可互相借鉴学习交流,不完善地方还有很多,主要用于学习目的。

using System;
using System.Collections.Generic;
using System.Data;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataCollectionSystem_attach
{
    class Port
    {
        //信息委托
        public delegate void TcpCommunicationData(string value);
        public event TcpCommunicationData CommunicationTexts;

        public delegate void TcpCommunicationData_buff(byte[] value);
        public event TcpCommunicationData_buff CommunicationTexts_buff;


        public SerialPort serialPort = new SerialPort();

        /// <summary>
        /// 自动获取串口的端口号
        /// </summary>
        /// <returns></returns>
        public DataTable GetComList(DataTable Port_DataTable)
        {
            Port_DataTable.Columns.Add("PortName", typeof(string));
            string[] names = SerialPort.GetPortNames();
            Port_DataTable.Clear();

            for (int i = 0; i < names.Length; i++)
            {
                Da
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值