C#語言的串口通信類,有問題及時回帖
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO.Ports;
- using System.Threading.Tasks;
- //串口進行操作的類,其中包括寫和讀操作,類可設(shè)置串口參數(shù)、設(shè)置接收函數(shù)、打開串口資源、關(guān)閉串口資源,操作完成后,
- //一定要關(guān)閉串口、接收串口數(shù)據(jù)事件、接收數(shù)據(jù)出錯事件、獲取當(dāng)前全部串口、
- //把字節(jié)型轉(zhuǎn)換成十六進制字符串等功能。這個串口類已經(jīng)過了調(diào)試,可以使用:
- namespace 串口接收發(fā)送
- {
- public class SerialClass
- {
- public SerialClass1 sc3 = new SerialClass1();
- SerialPort _serialPort = null;
- public string strRec {get;set; }
- public int RecCount;
- public int replaceCount;
-
- //定義委托
- public delegate void SerialPortDataReceiveEventArgs(object sender, SerialDataReceivedEventArgs e, byte[] bits);
- //定義接收數(shù)據(jù)事件
- public event SerialPortDataReceiveEventArgs DataReceived;
- //定義接收錯誤事件
- //public event SerialErrorReceivedEventHandler Error;
- //接收事件是否有效 false表示有效
- public bool ReceiveEventFlag = false;
- #region 獲取串口名
- private string protName;
- public string PortName
- {
- get { return _serialPort.PortName; }
- set
- {
- _serialPort.PortName = value;
- protName = value;
- }
- }
- #endregion
- #region 獲取比特率
- private int baudRate;
- public int BaudRate
- {
- get { return _serialPort.BaudRate; }
- set
- {
- _serialPort.BaudRate = value;
- baudRate = value;
- }
- }
- #endregion
- #region 默認(rèn)構(gòu)造函數(shù)
- /// <summary>
- /// 默認(rèn)構(gòu)造函數(shù),操作COM1,速度為9600,沒有奇偶校驗,8位字節(jié),停止位為1 "COM1", 9600, Parity.None, 8, StopBits.One
- /// </summary>
- public SerialClass()
- {
- _serialPort = new SerialPort();
- }
- #endregion
- #region 構(gòu)造函數(shù)
- /// <summary>
- /// 構(gòu)造函數(shù),
- /// </summary>
- /// <param name="comPortName"></param>
- public SerialClass(string comPortName)
- {
- _serialPort = new SerialPort(comPortName);
- _serialPort.BaudRate = 9600;
- _serialPort.Parity = Parity.Even;
- _serialPort.DataBits = 8;
- _serialPort.StopBits = StopBits.One;
- _serialPort.Handshake = Handshake.None;
- _serialPort.RtsEnable = true;
- _serialPort.ReadTimeout = 2000;
- setSerialPort();
- }
- #endregion
- #region 構(gòu)造函數(shù),可以自定義串口的初始化參數(shù)
- /// <summary>
- /// 構(gòu)造函數(shù),可以自定義串口的初始化參數(shù)
- /// </summary>
- /// <param name="comPortName">需要操作的COM口名稱</param>
- /// <param name="baudRate">COM的速度</param>
- /// <param name="parity">奇偶校驗位</param>
- /// <param name="dataBits">數(shù)據(jù)長度</param>
- /// <param name="stopBits">停止位</param>
- public SerialClass(string comPortName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
- {
- _serialPort = new SerialPort(comPortName, baudRate, parity, dataBits, stopBits);
- _serialPort.RtsEnable = true; //自動請求
- _serialPort.ReadTimeout = 3000;//超時
- setSerialPort();
- }
- #endregion
- #region 析構(gòu)函數(shù)
- /// <summary>
- /// 析構(gòu)函數(shù),關(guān)閉串口
- /// </summary>
- ~SerialClass()
- {
- if (_serialPort.IsOpen)
- _serialPort.Close();
- }
- #endregion
- #region 設(shè)置串口參數(shù)
- /// <summary>
- /// 設(shè)置串口參數(shù)
- /// </summary>
- /// <param name="comPortName">需要操作的COM口名稱</param>
- /// <param name="baudRate">COM的速度</param>
- /// <param name="dataBits">數(shù)據(jù)長度</param>
- /// <param name="stopBits">停止位</param>
- public void setSerialPort(string comPortName, int baudRate, int dataBits, int stopBits )
- {
- if (_serialPort.IsOpen)
- {
- _serialPort.Close();
- }
- _serialPort.PortName = comPortName;
- _serialPort.BaudRate = baudRate;
- _serialPort.Parity = Parity.None;
- _serialPort.DataBits = dataBits;
- _serialPort.StopBits = (StopBits)stopBits;
- _serialPort.Handshake = Handshake.None;
- _serialPort.RtsEnable = false;
- _serialPort.ReadTimeout = 3000;
- _serialPort.ReadBufferSize = 31 * 1024;
- _serialPort.NewLine = "/r/n";
- setSerialPort();
- }
- #endregion
- #region 設(shè)置接收函數(shù)
- /// <summary>
- /// 設(shè)置串口資源,還需重載多個設(shè)置串口的函數(shù)
- /// </summary>
- void setSerialPort()
- {
- if (_serialPort != null)
- {
- //設(shè)置觸發(fā)DataReceived事件的字節(jié)數(shù)為1
- _serialPort.ReceivedBytesThreshold = 1;
- //接收到一個字節(jié)時,也會觸發(fā)DataReceived事件
- _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
- //接收數(shù)據(jù)出錯,觸發(fā)事件
- _serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(_serialPort_ErrorReceived);
- //打開串口
- //openPort();
- }
- }
- #endregion
- #region 打開串口資源
- /// <summary>
- /// 打開串口資源
- /// <returns>返回bool類型</returns>
- /// </summary>
- public bool openPort()
- {
- bool ok = false;
- //如果串口是打開的,先關(guān)閉
- if (_serialPort.IsOpen)
- _serialPort.Close();
- try
- {
- //打開串口
- _serialPort.Open();
- ok = true;
- }
- catch (Exception Ex)
- {
- throw Ex;
- }
- return ok;
- }
- #endregion
- #region 關(guān)閉串口
- /// <summary>
- /// 關(guān)閉串口資源,操作完成后,一定要關(guān)閉串口
- /// </summary>
- public void closePort()
- {
- //如果串口處于打開狀態(tài),則關(guān)閉
- if (_serialPort.IsOpen)
- {
- _serialPort.Close();
- }
- }
- #endregion
- #region 接收串口數(shù)據(jù)事件
- /// <summary>
- /// 接收串口數(shù)據(jù)事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- //禁止接收事件時直接退出
- if (ReceiveEventFlag)
- {
- return;
- }
- try
- {
- //System.Threading.Thread.Sleep(5);
- byte[] _data = new byte[_serialPort.BytesToRead];
- _serialPort.Read(_data, 0, _data.Length);
- string strRecBuffer = Encoding.Default.GetString(_data);
- RecCount = RecCount + 1;
- if (RecCount == 1)
- {
- replaceCount = 0;
- }
- if (strRecBuffer.Contains("^PON^") && replaceCount == 0)
- {
- replaceCount = replaceCount + 1;
- strRecBuffer = strRecBuffer.Replace("^PON^", "^RON^");
- }
- sc3.SendData(strRecBuffer);
- strRec = strRec + strRecBuffer;
-
- if (_data.Length == 0) { return; }
- if (DataReceived != null)
- {
- DataReceived(sender, e, _data);
- }
- //_serialPort.DiscardInBuffer(); //清空接收緩沖區(qū)
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- #endregion
- #region 接收數(shù)據(jù)出錯事件
- /// <summary>
- /// 接收數(shù)據(jù)出錯事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void _serialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
- {
- }
- #endregion
- #region 發(fā)送數(shù)據(jù)string類型
- public void SendData(string data)
- {
- //發(fā)送數(shù)據(jù)
- //禁止接收事件時直接退出
- if (ReceiveEventFlag)
- {
- return;
- }
- if (_serialPort.IsOpen)
- {
- _serialPort.Write(data);
- }
- }
- #endregion
- #region 發(fā)送數(shù)據(jù)byte類型
- /// <summary>
- /// 數(shù)據(jù)發(fā)送
- /// </summary>
- /// <param name="data">要發(fā)送的數(shù)據(jù)字節(jié)</param>
- public void SendData(byte[] data, int offset, int count)
- {
- //禁止接收事件時直接退出
- if (ReceiveEventFlag)
- {
- return;
- }
- try
- {
- if (_serialPort.IsOpen)
- {
- //_serialPort.DiscardInBuffer();//清空接收緩沖區(qū)
- _serialPort.Write(data, offset, count);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- #endregion
- #region 發(fā)送命令
- /// <summary>
- /// 發(fā)送命令
- /// </summary>
- /// <param name="SendData">發(fā)送數(shù)據(jù)</param>
- /// <param name="ReceiveData">接收數(shù)據(jù)</param>
- /// <param name="Overtime">超時時間</param>
- /// <returns></returns>
- public int SendCommand(byte[] SendData, ref byte[] ReceiveData, int Overtime)
- {
- if (_serialPort.IsOpen)
- {
- try
- {
- ReceiveEventFlag = true; //關(guān)閉接收事件
- _serialPort.DiscardInBuffer(); //清空接收緩沖區(qū)
- _serialPort.Write(SendData, 0, SendData.Length);
- int num = 0, ret = 0;
- System.Threading.Thread.Sleep(10);
- ReceiveEventFlag = false; //打開事件
- while (num++ < Overtime)
- {
- if (_serialPort.BytesToRead >= ReceiveData.Length)
- break;
- System.Threading.Thread.Sleep(10);
- }
- if (_serialPort.BytesToRead >= ReceiveData.Length)
- {
- ret = _serialPort.Read(ReceiveData, 0, ReceiveData.Length);
- }
- else
- {
- ret = _serialPort.Read(ReceiveData, 0, _serialPort.BytesToRead);
- }
- ReceiveEventFlag = false; //打開事件
- return ret;
- }
- catch (Exception ex)
- {
- ReceiveEventFlag = false;
- throw ex;
- }
- }
- return -1;
- }
- #endregion
- #region 獲取串口
- /// <summary>
- /// 獲取所有已連接短信貓設(shè)備的串口
- /// </summary>
- /// <returns></returns>
- public string[] serialsIsConnected()
- {
- List<string> lists = new List<string>();
- string[] seriallist = getSerials();
- foreach (string s in seriallist)
- {
- }
- return lists.ToArray();
- }
- #endregion
- #region 獲取當(dāng)前全部串口資源
- /// <summary>
- /// 獲得當(dāng)前電腦上的所有串口資源
- /// </summary>
- /// <returns></returns>
- public string[] getSerials()
- {
- return SerialPort.GetPortNames();
- }
- #endregion
- #region 字節(jié)型轉(zhuǎn)換16
- /// <summary>
- /// 把字節(jié)型轉(zhuǎn)換成十六進制字符串
- /// </summary>
- /// <param name="InBytes"></param>
- /// <returns></returns>
- public static string ByteToString(byte[] InBytes)
- {
- string StringOut = "";
- foreach (byte InByte in InBytes)
- {
- StringOut = StringOut + String.Format("{0:X2} ", InByte);
- }
- return StringOut;
- }
- #endregion
- #region 十六進制字符串轉(zhuǎn)字節(jié)型
- /// <summary>
- /// 把十六進制字符串轉(zhuǎn)換成字節(jié)型(方法1)
- /// </summary>
- /// <param name="InString"></param>
- /// <returns></returns>
- public static byte[] StringToByte(string InString)
- {
- string[] ByteStrings;
- ByteStrings = InString.Split(" ".ToCharArray());
- byte[] ByteOut;
- ByteOut = new byte[ByteStrings.Length];
- for (int i = 0; i <= ByteStrings.Length-1 ; i++)
- {
- //ByteOut[i] = System.Text.Encoding.ASCII.GetBytes(ByteStrings[i]);
- ByteOut[i] = Byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);
- //ByteOut[i] =Convert.ToByte("0x" + ByteStrings[i]);
- }
- return ByteOut;
- }
- #endregion
- #region 十六進制字符串轉(zhuǎn)字節(jié)型
- /// <summary>
- /// 字符串轉(zhuǎn)16進制字節(jié)數(shù)組(方法2)
- /// </summary>
- /// <param name="hexString"></param>
- /// <returns></returns>
- public static byte[] strToToHexByte(string hexString)
- {
- hexString = hexString.Replace(" ", "");
- if ((hexString.Length % 2) != 0)
- hexString += " ";
- byte[] returnBytes = new byte[hexString.Length / 2];
- for (int i = 0; i < returnBytes.Length; i++)
- returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
- return returnBytes;
- }
- #endregion
- #region 字節(jié)型轉(zhuǎn)十六進制字符串
- /// <summary>
- /// 字節(jié)數(shù)組轉(zhuǎn)16進制字符串
- /// </summary>
- /// <param name="bytes"></param>
- /// <returns></returns>
- public static string byteToHexStr(byte[] bytes)
- {
- string returnStr = "";
- if (bytes != null)
- {
- for (int i = 0; i < bytes.Length; i++)
- {
- returnStr += bytes[i].ToString("X2");
- }
- }
- return returnStr;
- }
- #endregion
- }
- }
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.IO.Ports;
- using System.IO;
- using System.Threading;
- namespace 串口發(fā)送
- {
- public partial class Form1 : Form
- {
- SerialClass sc1 = new SerialClass();
- public Form1()
- {
- InitializeComponent();
-
- }
- private void btn_OpenSerialPort_Click(object sender, EventArgs e)
- {
-
- sc1.setSerialPort("COM1", 115200, 8, 1);
- sc1.openPort();
- }
- private void btn_CloseSerialPort_Click(object sender, EventArgs e)
- {
- sc1.closePort();
- }
- private void btn_ReadFile_Click(object sender, EventArgs e)
- {
- string path = "E:\\SF.txt";
- StreamReader sr = new StreamReader(path, Encoding.Default);
- string line;
- while ((line = sr.ReadLine()) != null)
- {
- textBox1.Text = textBox1.Text + line;
- }
- }
- private void btn_Clear_Click(object sender, EventArgs e)
- {
- textBox1.Text = "";
- }
- private void btn_SendMessage_Click(object sender, EventArgs e)
- {
- //Thread sendThread = new Thread(SendData);
- //sendThread.IsBackground = true;
- //sendThread.Start();
- sc1.SendData(textBox1.Text);
- }
- public void SendData()
- {
- string path = "E:\\SF.txt";
- StreamReader sr = new StreamReader(path, Encoding.Default);
- string line = "";
- while ((line = sr.ReadLine()) != null)
- {
- //textBox1.Text = textBox1.Text + line;
- sc1.SendData(line);
- Thread.Sleep(5);
- }
- }
- }
- }
復(fù)制代碼
【必讀】版權(quán)免責(zé)聲明
1、本主題所有言論和內(nèi)容純屬會員個人意見,與本論壇立場無關(guān)。2、本站對所發(fā)內(nèi)容真實性、客觀性、可用性不做任何保證也不負(fù)任何責(zé)任,網(wǎng)友之間僅出于學(xué)習(xí)目的進行交流。3、對提供的數(shù)字內(nèi)容不擁有任何權(quán)利,其版權(quán)歸原著者擁有。請勿將該數(shù)字內(nèi)容進行商業(yè)交易、轉(zhuǎn)載等行為,該內(nèi)容只為學(xué)習(xí)所提供,使用后發(fā)生的一切問題與本站無關(guān)。 4、本網(wǎng)站不保證本站提供的下載資源的準(zhǔn)確性、安全性和完整性;同時本網(wǎng)站也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的損失或傷害。 5、本網(wǎng)站所有軟件和資料均為網(wǎng)友推薦收集整理而來,僅供學(xué)習(xí)用途使用,請務(wù)必下載后兩小時內(nèi)刪除,禁止商用。6、如有侵犯你版權(quán)的,請及時聯(lián)系我們(電子郵箱1370723259@qq.com)指出,本站將立即改正。
|