c#操作串口类

先放上串口的一个类,自己编写的,觉得这样好用些。

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;
}

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));
}
}

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

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;
}

#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
}
}

然后在主类中

Serial comm = new Serial();

在主窗体中增加计时器的类,一致读取串口读取的数据并处理即可。

串口发送

string s = "readinf";   //定义字符串要发送的内容
comm.Send(s, false);  //发送

原文地址:https://www.cnblogs.com/mainmaster/p/12002679.html

时间: 2024-08-10 17:41:47

c#操作串口类的相关文章

一个由印度人编写的VC串口类

软件介绍 一个由印度人编写的VC串口类(也是一种VC串口控件),他还配合这个类写了VC 串口通信方面的一些基础知识,如怎么用VC打开串口,如何对串口进行配置,读串口.写串口等. 这个类有点特别,它没有使用事件驱动原理,它是以查询方式工作的. 简介: 对没有接触过串口通信的VC程序员来说显得非常困难,很久以前我在 codeguru.com 上搜索过串口通信相关信息得到了非常大的帮助,从那时起能编写一个简单易用的VC 串口类是我的梦想. 经过七个月在串口通信编程方面实践经验后,我编写了一个基于API

Qt 串口类QSerialPort 使用笔记

Qt 串口类QSerialPort 使用笔记 虽然现在大多数的家用PC机上已经不提供RS232接口了.但是由于RS232串口操作简单.通讯可靠,在工业领域中仍然有大量的应用.Qt以前的版本中,没有提供官方的对RS232串口的支持,编写串口程序很不方便.现在好了,在 Qt5.1 中提供了QtSerialPort模块,方便编程人员快速的开发应用串口的应用程序. 本文就简单的讲讲QtSerialPort模块的使用. 当前的QtSerialPort模块中提供了两个C++类,分别是QSerialPort 

Remon Spekreijse CSerialPort串口类的修正版2014-01-10

转自:http://m.blog.csdn.net/blog/itas109/18358297# 2014-1-16阅读691 评论0 如需转载请标明出处:http://blog.csdn.net/itas109 这是一份优秀的类文件,好多的地方值得我们学习,具体在多线程,事件,自定义消息,类的封装方面等等.Remon提供的串口类网址为:http://codeguru.earthweb.com/network/serialport.shtml, 其他贡献者:http://blog.csdn.ne

.NET串口类(COM口),真正实际可用的串口类。

注:这是旧的代码,可用于生产环境,下面的校验码计算处,计算那里少取了一位,这个是用于永宏PLC的,如果是别的,只要改下校验码计算方式就行了.代码较乱,未整理. 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 //using System.Threading.Tasks; 6 using System.IO.Ports; 7 using System.Ti

CSerialPort串口类最新修正版2016-05-07

如需转载请标明出处:http://blog.csdn.net/itas109 QQ技术交流群:129518033 这是一份优秀的串口类文件,好多的地方值得我们学习,具体在多线程,事件,自定义消息,类的封装方面等等. Remon提供的串口类网址为:http://codeguru.earthweb.com/network/serialport.shtml, 由于已经运行十几年了,原文的问答部分列出来这么多年来的问题,经过网友们的总结,补充和修改原来代码后,整理出一份相对比较完美的代码. 2016-0

C++的继承操作---基类指针访问派生类问题---基类成员恢复访问属性问题

#include "stdafx.h" #include <iostream> #include <algorithm> using namespace std; class Base { public: int num; virtual void func() { cout<<"Do something in Base"<<endl; } }; class Derived:private Base { public:

Asp.Net 文件操作基类

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.T

一个印度人写的VC串口类CSerialCom(有串口基础介绍)

一个由印度人编写的VC串口类(也是一种VC串口控件),他还配合这个类写了VC 串口通信方面的一些基础知识,如怎么用VC打开串口,如何对串口进行配置,读串口.写串口等. 这个类有点特别,它没有使用事件驱动原理,它是以查询方式工作的. 简介: 对没有接触过串口通信的VC程序员来说显得非常困难,很久以前我在 codeguru.com 上搜索过串口通信相关信息得到了非常大的帮助,从那时起能编写一个简单易用的VC 串口类是我的梦想. 经过七个月在串口通信编程方面实践经验后,我编写了一个基于API实现的简单

一个串口类CSerialPort及其简单使用

一个挺好用的串口类:CnComm1.3.SerialPort.rar 简单用法: 1.定义成员:       CSerialPort m_SerialPort;          2.初始化:    m_SerialPort.SetBufferSize(1024,1024);   m_SerialPort.SetWnd(m_hWnd);  m_SerialPort.SetNotifyNum(DEF_IN_BYTE_SIZE);  if (m_SerialPort.IsOpen())  {