c # serial operation type

Placed first in a class of serial port, I have written, some think this is easy to use.

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.Collections;
using System.IO;
using System.Text.RegularExpressions;

channel_ratio namespace
{
public partial class Serial
{
Private the SerialPort the SerialPort new new COMM = ();
public new new = the StringBuilder the StringBuilder Builder (); // Create event to avoid repeated processing method is defined to the outside. Received data
private long receive_count = 0; // count the received
private long send_count = 0; // count transmitting
private bool saveflag = false; // save message flag
public BOOL = HexFlag to false;
Private byte [] = new new byte Buffer [1024];
// Private String [] the ports;
// int Private the receive
public Serial ()
{
// initialization SerialPort objects
comm.NewLine = "\ R & lt \ n-";
comm.RtsEnable = to true; // the actual situation it .
= 0 receive_count How;
send_count How many = 0;
String [] = the SerialPort.GetPortNames the ports ();
Array.Sort (the ports);
// add event registration
comm.DataReceived + = comm_DataReceived;
}

comm_DataReceived void (Object SENDER, SerialDataReceivedEventArgs E)
{
int = n-comm.BytesToRead; // record to avoid some reason, human reason, a long time between the operation several times, the cache inconsistency
receive_count How n-+ =;
byte [] buf = new byte [n]; // declare a temporary array to store the current serial data
receive_count + = n; // reception count increases
comm.Read (buf, 0, n) ; // read buffer data
// builder .Clear (); // clear the contents of the string constructor
IF (HexFlag)
{
the foreach (B in buf byte)
{
// out sequentially stitching hexadecimal string
builder.Append (b.ToString ( "X2") + "");
//Console.WriteLine(b.ToString("X2 ") +" ");
}
}
the else
{
// directly converted into a string in ASCII rules
builder.Append (Encoding.ASCII.GetString (buf) );
}
}

public void removestr(int len)
{
builder.Remove(0, len);
}

void the Close public ()
{
// The current port object to determine if the operation
IF (comm.IsOpen)
{
// When clicking to open, then close the serial port
comm.Close ();
}
}
public void the Open (the PortName String, String the BaudRate)
{
comm.PortName = the PortName;
comm.BaudRate the int.Parse = (the BaudRate);
the try
{
comm.Open ();
}
the catch (exception EX)
{
// capture abnormality information, creating a new comm objects, not before used.
the SerialPort new new COMM = // ();
// reality exception information to the customer.
writeLogFile (ex.Message);
}
}

public int the Send (String sendstr, BOOL HexFlag)
{
int n-= 0;
IF (comm.IsOpen!)
return 0;
byte [] = buf new new byte [sendstr.Length / 2];
IF (HexFlag)
{
buf = HexStringToByteArray (sendstr);
// array after converting the transmission list
comm.Write (buf, 0, buf.length);
// recording the number of bytes sent
n-buf.length =;
}
the else
{
comm.Write (sendstr);
n-sendstr.Length =;
/ *
byte [] = BUFF new new byte [sendstr.Length]; //
BUFF = Encoding.ASCII .GetBytes (sendstr);
comm.Write (BUFF, 0, buff.Length);
n-= sendstr.Length;
* /
}

return n;
}

private byte[] HexStringToByteArray(string strHexString)
{
strHexString.Replace(" ", "");
int len = strHexString.Length;
if ((len % 2) != 0)
writeLogFile("");

int byteLen = len / 2;
byte[] bytes = new byte[byteLen];
for (int i = 0; i < byteLen; i++)
{
bytes[i] = Convert.ToByte(strHexString.Substring(i * 2, 2), 16);
}
return bytes;
}


#region 写log文件
public int writeLogFile(string str)
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + @"\run.log";
if (File.Exists(filePath))
{
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.Length > 2000000)
File.Delete(filePath);
}

FileStream aFile = new FileStream(filePath, FileMode.OpenOrCreate | FileMode.Append);
StreamWriter sw = new StreamWriter(aFile);
DateTime tt = DateTime.Now;
str = "["+tt.ToString()+"] " + str;
sw.WriteLine(str);
sw.Close();
aFile.Close();
return 1;
}
#endregion
}
}

 

Then in the main class

Serial comm = new Serial();

Increasing the timer class in the main form, consistent read serial data can be read and processed.

 Serial port 

string s = "readinf"; // define the content of the string to be sent
comm.Send (s, false); // send

 

Guess you like

Origin www.cnblogs.com/mainmaster/p/12002679.html