程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#串口通訊完成辦法

C#串口通訊完成辦法

編輯:C#入門知識

C#串口通訊完成辦法。本站提示廣大學習愛好者:(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#法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved