当前位置: 首页 > 编程笔记 >

C#串口通信实现方法

穆俊名
2023-03-14
本文向大家介绍C#串口通信实现方法,包括了C#串口通信实现方法的使用技巧和注意事项,需要的朋友参考一下

本文实例讲述了C#串口通信实现方法。分享给大家供大家参考。具体方法如下:

通过COM1发送数据,COM2接收数据。当COM2接收完本次发送的数据后,向COM1发送信息通知COM1本次数据已发完,COM1接到通知后,再发下一段数据。这样可以确保每次发送的数据都可以被正确接收。

代码如下:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO.Ports;

using System.Threading;

using Utils;

namespace 串口通信 {     public partial class Form1 : Form     {         #region 变量         /// <summary>         /// 启动还是停止,true起动,false停止         /// </summary>         public static bool start = true;         /// <summary>         /// 串口资源         /// </summary>         private static SerialPort serialPort1 = null;         /// <summary>         /// 串口资源         /// </summary>         private static SerialPort serialPort2 = null;         /// <summary>         /// 成功次数         /// </summary>         private static int successCount = 0;         /// <summary>         /// 失败次数         /// </summary>         private static int errorCount = 0;         /// <summary>         /// 上次计算的总次数         /// </summary>         private static int lastCount = 0;         /// <summary>         /// 定时器         /// </summary>         private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();         #endregion

        #region Form1         public Form1()         {             InitializeComponent();         }         #endregion

        #region Form1_Load         private void Form1_Load(object sender, EventArgs e)         {             serialPort1 = new SerialPort("COM1");             serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived1);             serialPort1.Open();             serialPort2 = new SerialPort("COM2");             serialPort2.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived2);             serialPort2.Open();         }         #endregion

        #region Form1_FormClosed         private void Form1_FormClosed(object sender, FormClosedEventArgs e)         {             serialPort1.Close();             serialPort1.Dispose();             serialPort2.Close();             serialPort2.Dispose();         }         #endregion

        #region btnStart_Click         private void btnStart_Click(object sender, EventArgs e)         {             start = true;             SendData();

            timer.Interval = 500;             timer.Tick += new EventHandler(delegate(object obj, EventArgs eventArgs)             {                 if (lastCount == 0)                 {                     lastCount = successCount + errorCount;                 }                 else                 {                     int cnt = successCount + errorCount - lastCount;                     cnt = Data.Length * cnt / 1024 * (1000 / timer.Interval);                     double total = (successCount + errorCount) * Data.Length / 1024.0;

                    InvokeDelegate invokeDelegate = delegate()                     {                         label3.Text = cnt.ToString() + "KB/S " + total.ToString("#.0") + "KB";                     };                     InvokeUtil.Invoke(this, invokeDelegate);                     lastCount = successCount + errorCount;                 }             });             timer.Start();         }         #endregion

        #region btnStop_Click         private void btnStop_Click(object sender, EventArgs e)         {             start = false;             timer.Stop();             timer.Dispose();             timer = new System.Windows.Forms.Timer();         }         #endregion

        #region 接收串口数据事件         /// <summary>         /// 接收串口数据事件         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         public void serialPort_DataReceived1(object sender, SerialDataReceivedEventArgs e)         {             if (serialPort1.ReadLine() != null)             {                 successCount++;                 SendData();             }         }

        /// <summary>         /// 接收串口数据事件         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         public void serialPort_DataReceived2(object sender, SerialDataReceivedEventArgs e)         {             List<byte> bList = new List<byte>();             int i = 0;             while (serialPort2.BytesToRead > 0)             {                 byte[] bArr = new byte[serialPort2.BytesToRead];                 i += serialPort2.Read(bArr, 0, bArr.Length);                 bList.AddRange(bArr);             }             serialPort2.WriteLine("success");

            string s = ASCIIEncoding.UTF8.GetString(bList.ToArray());             InvokeDelegate invokeDelegate = delegate()             {                 textBox2.Text = s;             };             InvokeUtil.Invoke(this, invokeDelegate);

            if (s != Str)             {                 errorCount++;                 invokeDelegate = delegate()                 {                     label2.Text = errorCount + "次不相等(失败)";                 };                 InvokeUtil.Invoke(this, invokeDelegate);             }             else             {                 invokeDelegate = delegate()                 {                     label1.Text = successCount + "次相等(成功)";                 };                 InvokeUtil.Invoke(this, invokeDelegate);             }         }         #endregion

        #region 发送数据         private void SendData()         {             if (start)             {                 Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)                 {                     InvokeDelegate invokeDelegate = delegate()                     {                         textBox1.Text = Str;                     };                     InvokeUtil.Invoke(this, invokeDelegate);

                    serialPort1.Write(Data, 0, Data.Length);                 }));                 thread.Start();             }         }         #endregion

        #region 数据         private static byte[] data = null;         /// <summary>         /// 数据         /// </summary>         private static byte[] Data         {             get             {                 if (data == null)                 {                     data = ASCIIEncoding.UTF8.GetBytes(Str);                 }

                return data;             }         }         #endregion

        #region 获取字符串         private static string str = null;         /// <summary>         /// 字符串         /// </summary>         private static string Str         {             get             {                 if (str == null)                 {                     StringBuilder sb = new StringBuilder();                     for (int i = 0; i < 270; i++)                     {                         sb.Append("计算机程序");                     }                     str = sb.ToString();                 }

                return str;             }         }         #endregion

    } }

辅助代码如下:

using System;

using System.Collections.Generic;

using System.Text;

using System.Windows.Forms;

namespace Utils {     /// <summary>     /// 跨线程访问控件的委托     /// </summary>     public delegate void InvokeDelegate();

    /// <summary>     /// 跨线程访问控件类     /// </summary>     public class InvokeUtil     {         /// <summary>         /// 跨线程访问控件         /// </summary>         /// <param name="ctrl">Form对象</param>         /// <param name="de">委托</param>         public static void Invoke(Control ctrl, Delegate de)         {             if (ctrl.IsHandleCreated)             {                 ctrl.BeginInvoke(de);             }         }     } }

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.Win32;

using System.Security.Permissions;

using System.IO.Ports;

using System.Security;

namespace Utils {     /// <summary>     /// 串口资源工具类     /// </summary>     public class SerialPortUtil     {         #region 获取本机串口列表,包括虚拟串口         /// <summary>         /// 获取本机串口列表,包括虚拟串口         /// </summary>         public static string[] GetCOMList()         {             List<string> list = new List<string>();

            foreach (string portName in SerialPort.GetPortNames())             {                 list.Add(portName);             }

            return list.ToArray();         }         #endregion

        #region 从注册表获取本机串口列表         /// <summary>         /// 从注册表获取本机串口列表         /// </summary>         public static string[] GetPortNames()         {             RegistryKey localMachine = null;             RegistryKey key2 = null;             string[] textArray = null;

            //这里有个断言,判断该注册表项是否存在             new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM").Assert();

            try             {                 localMachine = Registry.LocalMachine;                 key2 = localMachine.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM", false);                 if (key2 != null)                 {                     string[] valueNames = key2.GetValueNames();                     textArray = new string[valueNames.Length];                     for (int i = 0; i < valueNames.Length; i++)                     {                         textArray[i] = (string)key2.GetValue(valueNames[i]);                     }                 }             }             finally             {                 if (localMachine != null)                 {                     localMachine.Close();                 }                 if (key2 != null)                 {                     key2.Close();                 }                 CodeAccessPermission.RevertAssert();             }             if (textArray == null)             {                 textArray = new string[0];             }             return textArray;         }         #endregion

    } }

希望本文所述对大家的C#程序设计有所帮助。

 类似资料:
  • 本文向大家介绍C#实现Socket通信的解决方法,包括了C#实现Socket通信的解决方法的使用技巧和注意事项,需要的朋友参考一下 本文以实例详述了C#实现Socket通信的解决方法,具体实现步骤如下: 1、首先打开VS新建两个控制台应用程序: ConsoleApplication_socketServer和ConsoleApplication_socketClient。   2、在Console

  • 本文向大家介绍Android串口通信之串口读写实例,包括了Android串口通信之串口读写实例的使用技巧和注意事项,需要的朋友参考一下 在Android串口通信:基本知识梳理的基础上,我结合我项目中使用串口的实例,进行总结; Android使用jni直接进行串口设备的读写网上已经有开源项目了,本文是基于网上的开源项目在实际项目中的使用做的调整和优化; Google串口开源项目 下面是我项目中的相关

  • 通过serial接口可以使Chrome应用进行串口通信。使用serial接口需要在Manifest中声明serial权限: "permissions": [ "serial" ] 本章内容参考自https://crxdoc-zh.appspot.com/apps/serial。

  • 3.1.2 action通信自定义action文件调用A(C++) 需求: 创建两个ROS 节点,服务器和客户端,客户端可以向服务器发送目标数据N(一个整型数据)服务器会计算 1 到 N 之间所有整数的和,这是一个循环累加的过程,返回给客户端,这是基于请求响应模式的,又已知服务器从接收到请求到产生响应是一个耗时操作,每累加一次耗时0.1s,为了良好的用户体验,需要服务器在计算过程中,每累加一次,就

  • 设备通过串口RX,TX和OBLOQ进行通信,因为波特率的不同,发送的数据可能会乱码或者丢包,设备通过发送这条指令,检测设备串口和OBLOQ串口是否已经正常通信。建议设备通信之前先通过这条指令检查串口连接状态。 请求方式: "|1|1|\r" 返回值: "|1|1|\r"表示已经建立串口通信 Arduino样例: softSerial.print("|1|1|\r");

  • 本文向大家介绍java使用Rxtx实现串口通信调试工具,包括了java使用Rxtx实现串口通信调试工具的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了java使用Rxtx实现串口通信调试工具的具体代码,供大家参考,具体内容如下 最终效果如下图: 1、把rxtxParallel.dll、rxtxSerial.dll拷贝到:C:\WINDOWS\system32下。 2、RXTXcomm