Serial port operation of the class, including write and read operations, class can set the serial port parameters, set the reception function, open the serial port resources, close the serial port resources, the operation is completed, must close the serial port, receive serial data events, receive data error events, get all the current serial port, the byte type into a hexadecimal string and other functions. This serial port class has been debugged, can be used: using system;using system.collections.generic;using system.text;using system.io.ports;using System.globalization;namespace serialclass{public class Serialclass {SerialPort _serialport = null;//define Delegate public Delega te void Serialportdatareceiveeventargs (object sender, Serialdatareceivedeventargs e, byte[] bits); Define receive data Events public event Serialportdatareceiveeventargs datareceived; Define receive error events//public event Serialerrorreceivedeventhandler error; Whether the receive event is valid false indicates a valid public bool Receiveeventflag = FALSE; #region get the serial name private string protname; public string PortName {get {return _serialport.portname;} set {_serialport.portname = value; protname = value;}} #e Ndregion #region Get bit rate private int baudrate; public int BaudRate {get {return _serialport.baudrate;} set {_serialport.baudrate = value; baudrate = value;}} #endr Egion #region Default constructor////// default constructor, Operation COM1, Speed 9600, no parity, 8 bit byte, stop bit 1 "COM1", 9600, Parity.none, 8, Stopbits.one //Public Serialclass () {_serialport = new SerialPort ();} #endregion #region Constructor////// constructor, //////Public Serialclass (String comportname) {_serialport = new SerialPort (comportname); _serialport.baudrate = 9600; _serialp Ort. Parity = Parity.even; _serialport.databits = 8; _serialport.stopbits = Stopbits.one; _serialport.handshake = Handshake.none; _serialport.rtsenable = true; _serialport.readtimeout = 2000; Setserialport (); } #endregion #region Constructor, you can customize the initialization parameters of the serial port////// constructor, you can customize the initialization parameters of the serial port //////The name of the COM port that needs to be manipulated///The speed of COM///Parity bit///Data length///Stop bitPublic Serialclass (string comportname, int baudrate, Parity Parity, int databits, stopbits stopbits) {_serialport = new S Erialport (Comportname, baudrate, parity, databits, stopbits); _serialport.rtsenable = true; Auto Request _serialport.readtimeout = 3000;//timeout setserialport (); } #endregion #region destructor////// destructor, close serial ///~serialclass () {if (_serialport.isopen) _serialport.close ()} #endregion #region Set the serial port parameters///// Set serial parameters //////The name of the COM port that needs to be manipulated///The speed of COM///Data length///Stop bitpublic void Setserialport (string comportname, int baudrate, int databits, int stopbits) {if (_serialport.isopen) _serial Port.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.newline = "/r/n"; Setserialport (); } #endregion #region Set the receive function///// set up serial port resources, also need to overload several functions to set the serial port //void Setserialport () {if (_serialport! = null) {//sets the number of bytes triggering the DataReceived event to 1 _serialport.receivedbytesthreshold = 1;//Received A byte will also trigger the datareceived event _serialport.datareceived + = new Serialdatareceivedeventhandler (_serialport_datareceived); Error receiving data, triggering event _serialport.errorreceived + = new Serialerrorreceivedeventhandler (_serialport_errorreceived); Open serial port//openport (); }} #endregion #region Open the serial resources///// Open Serial resources// return bool type //public bool Openport () {bool OK = false;//If the serial port is open, first close if (_serialport.isopen) _serialport.close (); try {//Open serial port _serial Port.open (); OK = true; } catch (Exception ex) {throw ex;} return OK; #endregion #region Close the serial port///// to close the serial port resources, after the operation is completed, be sure to close the serial //public void Closeport () {//If the serial port is open, close if (_serialport.isopen) _serialport.close ();} #endregion #region receive serial data events///// receive serial Data events /////////void _serialport_datareceived (object sender, Serialdatareceivedeventargs e) {//suppresses the receipt of an event when the direct exit if (Receiveeventflag) { Return } try {System.Threading.Thread.Sleep); byte[] _data = new Byte[_serialport.bytestoread]; _serialport.read (_data, 0, _ Data. Length); if (_data. Length = = 0) {return;} if (datareceived! = null) {datareceived (sender, E, _data);}//_serialport.discardinbuffer (); Empty receive buffer} catch (Exception ex) {throw ex;}} #endregion #region Receive data error events///// receive data Error event /////////void _serialport_errorreceived (object sender, Serialerrorreceivedeventargs e) {} #endregion #region send data string type public void SendData (String data) {//Send data//prohibit receive event directly exit if (Receiveeventflag) {return;} if (_serialport.isopen) {_serialport. Write (data); }} #endregion #region send data byte type///// data sent /////bytes of data to sendpublic void SendData (byte[] data, int offset, int count) {//suppresses the receipt of an event when the direct exit if (Receiveeventflag) {return;} try {if (_seri Alport.isopen) {//_serialport.discardinbuffer ();//empties the receive buffer _serialport.write (data, offset, count);}} catch (Exception ex) {throw ex;}} #endregion #region Send command////// Send command /////Send data///Receive data///Timeout period/// public int SendCommand (byte[] senddata, ref byte[] Receivedata, int overtime) {if (_serialport.isopen) {try {Receiveeve Ntflag = true; Turn off Receive event _serialport.discardinbuffer (); Empties the receive Buffer _serialport.write (senddata, 0, senddata.length); int num = 0, ret = 0; System.Threading.Thread.Sleep (10); Receiveeventflag = false; Open Event 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);} El SE {ret = _serialport.read (receivedata, 0, _serialport.bytestoread);} Receiveeventflag = false; Open event return ret; } catch (Exception ex) {Receiveeventflag = false; throw ex;}} return-1; } #endregion #region Get the serial///// access to the serial port of all connected SMS cat devices ///// Public string[] Serialsisconnected () {List Lists = new List (); string[] seriallist = Getserials (); foreach (string s in Seriallist) {} return lists. ToArray (); #endregion #region Get all the current serial port resources// /// get all the serial resources on the current computer ///// Public string[] Getserials () {return serialport.getportnames ();} #endregion #region byte-type conversion 16// /// convert byte type to hexadecimal string ////// /// public static string bytetostring (byte[] inbytes) {string stringout = ""; foreach (Byte inbyte in inbytes) {stringout = Stringout + String.Format ("{0:x2}", Inbyte);} return stringout; } #endregion #region hexadecimal string to byte type// ///convert hexadecimal string to byte type (Method 1)////// /// 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 hexadecimal string to byte type// ///String to 16 binary byte array (method 2)////// /// 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 byte-to-hexadecimal string// /// byte array to 16 binary string ///// /// 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}} Call method: Static Serialclass sc = new Serialclass (); static void Main (string[] Args) {SC. DataReceived + = new Serialclass.serialportdatareceiveeventargs (sc_datareceived); Sc.writedata ("at"); Console.ReadLine (); Sc.closeport (); }static void Sc_datareceived (object sender, Serialdatareceivedeventargs e, byte[] bits) {Console.WriteLine ( Encoding.Default.GetString (BITS));}
C # serial operation class, including serial read and write operation