先放上串口的一個類,本身編寫的,以爲這樣好用些。數組
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;緩存
namespace channel_ratio
{
public partial class Serial
{
private SerialPort comm = new SerialPort();
public StringBuilder builder = new StringBuilder();//避免在事件處理方法中反覆的建立,定義到外面。接收到的數據
private long receive_count = 0;//接收計數
private long send_count = 0;//發送計數
private bool saveflag = false;//保存報文標誌
public bool HexFlag = false;
private byte[] buffer = new byte[1024];
//private string[] ports;
//private int receive
public Serial()
{
//初始化SerialPort對象
comm.NewLine = "\r\n";
comm.RtsEnable = true;//根據實際狀況吧。
receive_count = 0;
send_count = 0;
string[] ports = SerialPort.GetPortNames();
Array.Sort(ports);
//添加事件註冊
comm.DataReceived += comm_DataReceived;
} ui
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int n = comm.BytesToRead;//先記錄下來,避免某種緣由,人爲的緣由,操做幾回之間時間長,緩存不一致
receive_count += n;
byte[] buf = new byte[n];//聲明一個臨時數組存儲當前來的串口數據
receive_count += n;//增長接收計數
comm.Read(buf, 0, n);//讀取緩衝數據
//builder.Clear();//清除字符串構造器的內容
if (HexFlag)
{
foreach (byte b in buf)
{
//依次的拼接出16進制字符串
builder.Append(b.ToString("X2") + "");
//Console.WriteLine(b.ToString("X2") + "");
}
}
else
{
//直接按ASCII規則轉換成字符串
builder.Append(Encoding.ASCII.GetString(buf));
}
}spa
public void removestr(int len)
{
builder.Remove(0, len);
}orm
public void Close()
{
//根據當前串口對象,來判斷操做
if (comm.IsOpen)
{
//打開時點擊,則關閉串口
comm.Close();
}
}
public void Open(string PortName,string BaudRate)
{
comm.PortName = PortName;
comm.BaudRate = int.Parse(BaudRate);
try
{
comm.Open();
}
catch (Exception ex)
{
//捕獲到異常信息,建立一個新的comm對象,以前的不能用了。
//comm = new SerialPort();
//現實異常信息給客戶。
writeLogFile(ex.Message);
}
}
public int Send(string sendstr,bool HexFlag)
{
int n=0;
if (!comm.IsOpen)
return 0;
byte[] buf = new byte[sendstr.Length / 2];
if(HexFlag)
{
buf = HexStringToByteArray(sendstr);
//轉換列表爲數組後發送
comm.Write(buf, 0, buf.Length);
//記錄發送的字節數
n = buf.Length;
}
else
{
comm.Write(sendstr);
n = sendstr.Length;
/*
byte[] buff = 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;
}rem
#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
}
}string
而後在主類中
Serial comm = new Serial();
在主窗體中增長計時器的類,一致讀取串口讀取的數據並處理便可。
串口發送
string s = "readinf"; //定義字符串要發送的內容 comm.Send(s, false); //發送