首页 > 编程语言 >C#结合串口通信类实现串口通信源代码(原创)

C#结合串口通信类实现串口通信源代码(原创)

时间:2024-01-15 10:35:51浏览次数:18  
标签:Windows System 通信 Forms 串口 new 源代码 Drawing Size

C#结合串口通信类实现串口通信源代码(原创)

 

mycom是串口通信类,在本blog前一篇中有完整代码。( C#串口通信编程类(修改版) )
下面是串口通讯测试程序的源代码,将mycom类放在此项目中
可以实现简单的串口通信,希望读者能通过这个程序对串口通信过程有一个初步的了解:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
namespace BusApp
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Label label1;
  private System.Windows.Forms.Label label2;
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.GroupBox groupBox1;
  private System.Windows.Forms.Label label3;
  private System.Windows.Forms.Label label4;
  private System.Windows.Forms.Label label5;
  private System.Windows.Forms.Label label6;
  private System.Windows.Forms.Button button2;
  private System.Windows.Forms.Button button3;
  private System.Windows.Forms.Button button4;
  private System.Windows.Forms.TextBox textBox8;
  private System.Windows.Forms.Label label7;

  public int iPort=1; //1,2,3,4
  public int iRate=9600; //1200,2400,4800,9600
  public byte bSize=8; //8 bits
  public byte bParity=0; // 0-4=no,odd,even,mark,space
  public byte bStopBits=1; // 0,1,2 = 1, 1.5, 2
  public int iTimeout=1000;
  public mycom mycom1=new mycom();
  public byte[] recb;

  private System.Windows.Forms.TextBox msg;
  private System.Windows.Forms.TextBox t_port;
  private System.Windows.Forms.TextBox t_rate;
  private System.Windows.Forms.TextBox t_bytesize;
  private System.Windows.Forms.TextBox t_stopbyte;
  private System.Windows.Forms.TextBox t_parity;
  private System.Windows.Forms.TextBox t_send;
  private System.Windows.Forms.Button button5; //readTimeOut
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   InitializeComponent();
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.msg = new System.Windows.Forms.TextBox();
   this.label1 = new System.Windows.Forms.Label();
   this.label2 = new System.Windows.Forms.Label();
   this.t_send = new System.Windows.Forms.TextBox();
   this.button1 = new System.Windows.Forms.Button();
   this.groupBox1 = new System.Windows.Forms.GroupBox();
   this.button2 = new System.Windows.Forms.Button();
   this.t_port = new System.Windows.Forms.TextBox();
   this.label3 = new System.Windows.Forms.Label();
   this.t_rate = new System.Windows.Forms.TextBox();
   this.label4 = new System.Windows.Forms.Label();
   this.t_bytesize = new System.Windows.Forms.TextBox();
   this.label5 = new System.Windows.Forms.Label();
   this.t_stopbyte = new System.Windows.Forms.TextBox();
   this.label6 = new System.Windows.Forms.Label();
   this.t_parity = new System.Windows.Forms.TextBox();
   this.button3 = new System.Windows.Forms.Button();
   this.button4 = new System.Windows.Forms.Button();
   this.textBox8 = new System.Windows.Forms.TextBox();
   this.label7 = new System.Windows.Forms.Label();
   this.button5 = new System.Windows.Forms.Button();
   this.groupBox1.SuspendLayout();
   this.SuspendLayout();
   //
   // msg
   //
   this.msg.ForeColor = System.Drawing.Color.Green;
   this.msg.Location = new System.Drawing.Point(0, 0);
   this.msg.Multiline = true;
   this.msg.Name = "msg";
   this.msg.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
   this.msg.Size = new System.Drawing.Size(512, 264);
   this.msg.TabIndex = 0;
   this.msg.Text = "";
   //
   // label1
   //
   this.label1.Location = new System.Drawing.Point(16, 24);
   this.label1.Name = "label1";
   this.label1.Size = new System.Drawing.Size(56, 16);
   this.label1.TabIndex = 1;
   this.label1.Text = "串口号:";
   //
   // label2
   //
   this.label2.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(64)), ((System.Byte)(0)));
   this.label2.Location = new System.Drawing.Point(8, 280);
   this.label2.Name = "label2";
   this.label2.Size = new System.Drawing.Size(80, 16);
   this.label2.TabIndex = 1;
   this.label2.Text = "设置数据包:";
   //
   // t_send
   //
   this.t_send.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_send.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(128)), ((System.Byte)(0)));
   this.t_send.Location = new System.Drawing.Point(80, 272);
   this.t_send.Name = "t_send";
   this.t_send.Size = new System.Drawing.Size(344, 21);
   this.t_send.TabIndex = 2;
   this.t_send.Text = "";
   //
   // button1
   //
   this.button1.Location = new System.Drawing.Point(432, 272);
   this.button1.Name = "button1";
   this.button1.Size = new System.Drawing.Size(40, 23);
   this.button1.TabIndex = 3;
   this.button1.Text = "发送";
   this.button1.Click += new System.EventHandler(this.button1_Click);
   //
   // groupBox1
   //
   this.groupBox1.Controls.Add(this.button2);
   this.groupBox1.Controls.Add(this.t_port);
   this.groupBox1.Controls.Add(this.label1);
   this.groupBox1.Controls.Add(this.label3);
   this.groupBox1.Controls.Add(this.t_rate);
   this.groupBox1.Controls.Add(this.label4);
   this.groupBox1.Controls.Add(this.t_bytesize);
   this.groupBox1.Controls.Add(this.label5);
   this.groupBox1.Controls.Add(this.t_stopbyte);
   this.groupBox1.Controls.Add(this.label6);
   this.groupBox1.Controls.Add(this.t_parity);
   this.groupBox1.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(64)), ((System.Byte)(0)));
   this.groupBox1.Location = new System.Drawing.Point(8, 304);
   this.groupBox1.Name = "groupBox1";
   this.groupBox1.Size = new System.Drawing.Size(176, 216);
   this.groupBox1.TabIndex = 4;
   this.groupBox1.TabStop = false;
   this.groupBox1.Text = "参数设置";
   //
   // button2
   //
   this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
   this.button2.Location = new System.Drawing.Point(80, 184);
   this.button2.Name = "button2";
   this.button2.TabIndex = 3;
   this.button2.Text = "应用设置";
   this.button2.Click += new System.EventHandler(this.button2_Click);
   //
   // t_port
   //
   this.t_port.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_port.Location = new System.Drawing.Point(80, 16);
   this.t_port.Name = "t_port";
   this.t_port.Size = new System.Drawing.Size(80, 21);
   this.t_port.TabIndex = 2;
   this.t_port.Text = "1";
   //
   // label3
   //
   this.label3.Location = new System.Drawing.Point(16, 58);
   this.label3.Name = "label3";
   this.label3.Size = new System.Drawing.Size(56, 16);
   this.label3.TabIndex = 1;
   this.label3.Text = "波特率:";
   //
   // t_rate
   //
   this.t_rate.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_rate.Location = new System.Drawing.Point(80, 50);
   this.t_rate.Name = "t_rate";
   this.t_rate.Size = new System.Drawing.Size(80, 21);
   this.t_rate.TabIndex = 2;
   this.t_rate.Text = "9600";
   //
   // label4
   //
   this.label4.Location = new System.Drawing.Point(16, 92);
   this.label4.Name = "label4";
   this.label4.Size = new System.Drawing.Size(56, 16);
   this.label4.TabIndex = 1;
   this.label4.Text = "数据位:";
   //
   // t_bytesize
   //
   this.t_bytesize.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_bytesize.Location = new System.Drawing.Point(80, 84);
   this.t_bytesize.Name = "t_bytesize";
   this.t_bytesize.Size = new System.Drawing.Size(80, 21);
   this.t_bytesize.TabIndex = 2;
   this.t_bytesize.Text = "8";
   //
   // label5
   //
   this.label5.Location = new System.Drawing.Point(16, 126);
   this.label5.Name = "label5";
   this.label5.Size = new System.Drawing.Size(56, 16);
   this.label5.TabIndex = 1;
   this.label5.Text = "停止位:";
   //
   // t_stopbyte
   //
   this.t_stopbyte.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_stopbyte.Location = new System.Drawing.Point(80, 118);
   this.t_stopbyte.Name = "t_stopbyte";
   this.t_stopbyte.Size = new System.Drawing.Size(80, 21);
   this.t_stopbyte.TabIndex = 2;
   this.t_stopbyte.Text = "1";
   //
   // label6
   //
   this.label6.Location = new System.Drawing.Point(16, 160);
   this.label6.Name = "label6";
   this.label6.Size = new System.Drawing.Size(56, 16);
   this.label6.TabIndex = 1;
   this.label6.Text = "校验位:";
   //
   // t_parity
   //
   this.t_parity.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_parity.Enabled = false;
   this.t_parity.Location = new System.Drawing.Point(80, 152);
   this.t_parity.Name = "t_parity";
   this.t_parity.Size = new System.Drawing.Size(80, 21);
   this.t_parity.TabIndex = 2;
   this.t_parity.Text = "0";
   //
   // button3
   //
   this.button3.Location = new System.Drawing.Point(472, 272);
   this.button3.Name = "button3";
   this.button3.Size = new System.Drawing.Size(40, 23);
   this.button3.TabIndex = 3;
   this.button3.Text = "清空";
   this.button3.Click += new System.EventHandler(this.button3_Click);
   //
   // button4
   //
   this.button4.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
   this.button4.Location = new System.Drawing.Point(432, 312);
   this.button4.Name = "button4";
   this.button4.Size = new System.Drawing.Size(72, 23);
   this.button4.TabIndex = 6;
   this.button4.Text = "初始化";
   //
   // textBox8
   //
   this.textBox8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.textBox8.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(128)), ((System.Byte)(0)));
   this.textBox8.Location = new System.Drawing.Point(288, 312);
   this.textBox8.Name = "textBox8";
   this.textBox8.Size = new System.Drawing.Size(136, 21);
   this.textBox8.TabIndex = 7;
   this.textBox8.Text = "";
   //
   // label7
   //
   this.label7.Location = new System.Drawing.Point(200, 320);
   this.label7.Name = "label7";
   this.label7.Size = new System.Drawing.Size(100, 16);
   this.label7.TabIndex = 8;
   this.label7.Text = "设置本机地址:";
   //
   // button5
   //
   this.button5.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
   this.button5.Location = new System.Drawing.Point(440, 504);
   this.button5.Name = "button5";
   this.button5.Size = new System.Drawing.Size(64, 23);
   this.button5.TabIndex = 9;
   this.button5.Text = "关闭串口";
   this.button5.Click += new System.EventHandler(this.button5_Click);
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(512, 533);
   this.Controls.Add(this.button5);
   this.Controls.Add(this.textBox8);
   this.Controls.Add(this.label7);
   this.Controls.Add(this.button4);
   this.Controls.Add(this.groupBox1);
   this.Controls.Add(this.button1);
   this.Controls.Add(this.t_send);
   this.Controls.Add(this.msg);
   this.Controls.Add(this.label2);
   this.Controls.Add(this.button3);
   this.Name = "Form1";
   this.Text = "串口通讯(小y设计)";
   this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
   this.Load += new System.EventHandler(this.Form1_Load);
   this.groupBox1.ResumeLayout(false);
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }
//程序开启,串口初始化
  private void Form1_Load(object sender, System.EventArgs e)
  {
   mycom1.PortNum=iPort;
   mycom1.BaudRate=iRate;
   mycom1.ByteSize=bSize;
   mycom1.Parity=bParity;
   mycom1.StopBits=bStopBits;
   mycom1.ReadTimeout=iTimeout;
   if(this.OpenCom())
    msg.AppendText("串口初始化成功……\r\n");
   else
    msg.AppendText("串口初始化失败!\r\n");
  }
//显示包信息
  public string dis_package(byte[] reb)
  {
   string temp="";
   foreach(byte b in reb)
    temp+=b.ToString("X2")+" ";
   return temp;
  }
//开串口
  public bool OpenCom()
  {
   try
   {
     if (mycom1.Opened)
     {
      mycom1.Close();
      mycom1.Open(); //打开串口
     }
     else
     {
      mycom1.Open();//打开串口
     }
     return true;
   }
   catch(Exception e)
   {
     MessageBox.Show("错误:" + e.Message);
     return false;
   }

  }
//发送按钮
  private void button1_Click(object sender, System.EventArgs e)
  {
   if(t_send.Text=="")
   {MessageBox.Show("发送数据为空!");return;}
   byte[] temp1=mysendb();
   int sendnumb=0;
   try
   {
    sendnumb=mycom1.Write(temp1);
     msg.AppendText("\r\n发送数据("+sendnumb+"):"+dis_package(temp1));
    recb=mycom1.Read(50);
    //if(recb.Length!=0)
     msg.AppendText("\r\n接收到数据包:"+dis_package(recb));
   }
   catch
   {msg.AppendText("\r\n发送失败!");return;}
   
   //OpenCom();
  }
//去掉发送数组中的空格
  public string delspace(string putin)
  {
   string putout="";
   for(int i=0;i<putin.Length;i++)
   {
    if(putin[i]!=' ')
     putout+=putin[i];
   }
   return putout;
  }
//提取数据包
  public byte[] mysendb()
  {
   string temps=delspace(t_send.Text);
   byte[] tempb=new byte[50];
   int j=0;
   for(int i=0;i<temps.Length;i=i+2,j++)
    tempb[j]=Convert.ToByte(temps.Substring(i,2),16);
   byte[] send=new byte[j];
   Array.Copy(tempb,send,j);
   return send;
  }
//清空按钮
  private void button3_Click(object sender, System.EventArgs e)
  {
   t_send.Text=string.Empty;
   msg.Text=string.Empty;
  }

//参数设置
  private void button2_Click(object sender, System.EventArgs e)
  {
    mycom1.PortNum=Convert.ToInt16(t_port.Text); //1,2,3,4
   mycom1.BaudRate=Convert.ToInt16(t_rate.Text); //1200,2400,4800,9600
   mycom1.ByteSize=Convert.ToByte(t_bytesize.Text,10); //8 bits
   mycom1.Parity=Convert.ToByte(t_parity.Text,10); // 0-4=no,odd,even,mark,space
   mycom1.StopBits=Convert.ToByte(t_stopbyte.Text,10); // 0,1,2 = 1, 1.5, 2
   //iTimeout=3;
   if(this.OpenCom())
    msg.AppendText("串口初始化成功……\r\n");
   else
    msg.AppendText("串口初始化失败!\r\n");
  }
//程序关闭,结束串口
  private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  {
   mycom1.Close();
  }

  private void button5_Click(object sender, System.EventArgs e)
  {
   if(mycom1.Opened)
   {
    mycom1.Close();
    button5.Text="开启串口";
    msg.AppendText("\r\n串口被关闭……");
   }
   else
   {
    mycom1.Open();
    button5.Text="关闭串口";
    msg.AppendText("\r\n串口成功开启……");
   }
  }
 }
}

注意:发送数据包的格式是16进制数据如:02 45 66 FA  中间可以有或者没有空格,但要保证有偶数位

TO 大家:

   该程序源码已经放到本blog第一篇提供下载。

-----------------------------------------------------------------

标签:Windows,System,通信,Forms,串口,new,源代码,Drawing,Size
From: https://www.cnblogs.com/sexintercourse/p/17964875

相关文章

  • C#串口通信编程类(修改版)
    C#串口通信编程类(修改版) 这是从网上down下来的一个串口通信类,发现close函数忘记了设置Opened属性为false还有后面string转byte[]和byte[]转string的函数有错误,索性删掉了修改后的串口通信类如下:下一篇将把我的测试程序主程序部分全部代码贴出来可以坚强勇敢的用来实现串口......
  • APUE-网络socket通信
    网络通信​ 大部分网络应用系统可分为两部分:客户(Client)和服务器(Server),网路服务程序架构又两种:CS模式和BS模式。CS:Client/Server(客户机/服务器)结构,特点:交互性强,具有安全的存取模式,网络通信量低,响应速度快,利于处理大量数据。BS:Browser/Server(浏览器/服务器)结构,特点:分布性强,维护......
  • linux 内核和应用层之间的通信方式
    系统调用应用与内核通信的方式中,最常用的就是系统调用。如常见的open、write、read、ioctl等系统调用。当系统调用时,触发一个软中断,处理器进入内核模式。参数传递到内核空间,完成通信过程。内核完成服务之后,将数据返回给应用,并设置处理器为用户模式。copy_to_user()/copy_from_......
  • CAN通信配置过滤器和使用三个邮箱发送
    RM比赛用的电机基本都使用CAN通信,但是一条CAN线上只用一个发送邮箱在挂在设备多的情况可能会导致发送不完,但其实完全可以把三个发送邮箱都用上。这里贴一下自己的CAN筛选器,接收以及发送的代码。完整的工程可以看我开源的飞机云台程序~项目代码开源地址:https://github.com/ittuann......
  • 深入理解 Hadoop (一)网络通信架构与源码浅析
    HadoopRPC网络通信框架原理剖析YARNRPC服务端的工作大致可以分为四个阶段:第一个阶段:Server初始化和启动在Server初始化的时候,会初始化Listener组件(内部启动了一个AcceptSelector绑定了相应的端口,用来处理客户端的OP_ACCEPT事件),内部还初始化了一组Reader线程,其......
  • C#实现串口通讯的方法
    帖子只用于记录本人的学习记录,算是给未来的自己出一份傻瓜式教学。 在C#语言上,一般上位机是由Winform开发,也有WPF,但是我不会WPF上位机无非就是发送数据与接收数据,可以使用C#的SerialPort方法winform自带SerialPort控件,可以将此控件直接拖到页面上,然后实例化该控件,也可以直接实例化......
  • kepware关于U-CON的使用笔记 (串口_非主动问答式)
            8,新建两个变量t1,t2 (均为6字节的字符串)用来存储接收到的关键数据;   9,内容接收及解析逻辑     11 测试成功图片展示   ......
  • Java使用modbus4j通过串口modbus-rtu协议 连接设备 demo
    前言项目中需要使用串口来连接操控烟雾报警器且只能使用modbus-rtu协议在找了一堆资料后终于成功了在此呈上代码和资料链接【ModBus】modbus之modbus4j的使用和流程原理解析(5)-CSDN博客使用modbus4j通过串口解析modbus协议(java)_javamodbus4j-CSDN博客 串口通讯需要使用modbus4j......
  • 多种 React 组件通信方式实践
    使用ReactContext基于ReactContext实现跨组件通信的一个常见用例是创建一个能够在不同组件间共享和触发行为的上下文。以下是一个简化的例子,展示了如何在app.tsx中触发其他组件(例如,一个弹窗组件)中的方法。1.创建一个Context首先,我们创建一个新的Context。这个Context将......
  • UDP通信 [补档-2023-07-22]
    UDP通信6-1简介​UDP通信是面向无链接的,不稳定,不可靠,不安全的一种通信方式。TCP在通信前发送方会向接收方进行三次握手链接,然后确认双方链接后才会进行数据传输,最后四次挥手保证链接关闭。而UDP不会三次握手四次挥手,它会直接向发送方发送数据,无论接收方是否会收到,所以UDP更......