C# · 12月 19, 2021

C#串口通信

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

代码:

using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.IO.Ports; System.Threading; Utils;namespace 串口通信{ public partial class Form1 : Form { #region 变量 /// <summary> /// 启动还是停止,true起动,false停止 </summary> static bool start = true; 串口资源 private static SerialPort serialPort1 = nullstatic SerialPort serialPort2 = 成功次数 int successCount = 0 失败次数 int errorCount = 上次计算的总次数 int lastCount = 定时器 private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); #endregion #region Form1 public Form1() { InitializeComponent(); } #region Form1_Load void Form1_Load(object sender,EventArgs e) { serialPort1 = new SerialPort(“COM1″); serialPort1.DataReceived += SerialDataReceivedEventHandler(serialPort_DataReceived1); serialPort1.open(); serialPort2 = COM2); serialPort2.DataReceived += SerialDataReceivedEventHandler(serialPort_DataReceived2); serialPort2.open(); } #region Form1_FormClosed void Form1_FormClosed(#region btnStart_Click void btnStart_Click(= ; SendData(); timer.Interval = 500; timer.Tick += new EventHandler(delegate( obj,EventArgs eventArgs) { if (lastCount == ) { 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(); } #region btnStop_Click void btnStop_Click(false; timer.Stop(); timer.Dispose(); timer = System.Windows.Forms.Timer(); } #region 接收串口数据事件 接收串口数据事件 </summary> <param name=”sender”></param> <param name=”e”></param> void serialPort_DataReceived1(if (serialPort1.ReadLine() != ) { successCount++; SendData(); } } void serialPort_DataReceived2(<byte> bList = new List<byte>(); int i = ; while (serialPort2.BytesToRead > ) { byte[] bArr = new byte[serialPort2.BytesToRead]; i += serialPort2.Read(bArr,success); string s = ASCIIEncoding.UTF8.GetString(bList.ToArray()); InvokeDelegate invokeDelegate = () { text@R_106_2419@2.Text = s; }; InvokeUtil.Invoke(if (s != Str) { errorCount++; invokeDelegate = () { label2.Text = errorCount + 次不相等(失败); }; InvokeUtil.Invoke( { invokeDelegate = () { label1.Text = successCount + 次相等(成功)#region 发送数据 void SendData() { if (start) { Thread thread = new Thread(new ParameterizedThreadStart( obj) { InvokeDelegate invokeDelegate = () { text@R_106_2419@1.Text = Str; }; InvokeUtil.Invoke(#region 数据 byte[] data = 数据 [] Data { get { if (data == ) { data = ASCIIEncoding.UTF8.GetBytes(Str); } return data; } } #region 获取字符串 string str = 字符串 string Str { if (str == ) { StringBuilder sb = StringBuilder(); for (0; i < 270; i++) { sb.Append(计算机程序); } str = sb.ToString(); } str; } } #endregion }}View Code

辅助代码:

System.Windows.Forms; Utils{ <summary> 跨线程访问控件的委托 </summary> delegate InvokeDelegate(); 跨线程访问控件类 InvokeUtil { 跨线程访问控件 <param name=”ctrl”>Form对象</param> <param name=”de”>委托</param> Invoke(Control ctrl,Delegate de) { (ctrl.IsHandleCreated) { ctrl.BeginInvoke(de); } } }}View Code

 

Microsoft.Win32; System.Security.Permissions; System.Security; 串口资源工具类 SerialPortUtil { #region 获取本机串口列表,包括虚拟串口 获取本机串口列表,包括虚拟串口 [] GetCOMList() { List<string> list = string>(); foreach (string portName in SerialPort.GetPortNames()) { list.Add(portName); } list.ToArray(); } #region 从注册表获取本机串口列表 从注册表获取本机串口列表 [] GetPortNames() { RegistryKey localMachine = ; RegistryKey key2 = string[] textArray = ; //这里有个断言,判断该注册表项是否存在 new RegistryPermission(RegistryPermissionAccess.Read,1)”>@”HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM).Assert(); try { localMachine = Registry.LocalMachine; key2 = localMachine.OpenSubKey(HARDWARE\DEVICEMAP\SERIALCOMM”,); if (key2 != ) { string[] valueNames = key2.GetValueNames(); textArray = [valueNames.Length]; 0; i < valueNames.Length; i++) { textArray[i] = ()key2.GetValue(valueNames[i]); } } } finallyif (localMachine != ) { localMachine.Close(); } ) { key2.Close(); } CodeAccessPermission.RevertAssert(); } if (textArray == ) { textArray = string[]; } textArray; } }}View Code