首页 > 编程语言 >C#串口通信编程类(修改版)

C#串口通信编程类(修改版)

时间:2024-01-15 10:35:37浏览次数:37  
标签:C# hComm private int 修改版 串口 byte ref public

C#串口通信编程类(修改版)

 

这是从网上down下来的一个串口通信类,发现close函数忘记了设置Opened属性为false
还有后面string转byte[]和byte[]转string的函数有错误,索性删掉了
修改后的串口通信类如下:
下一篇将把我的测试程序主程序部分全部代码贴出来
可以坚强勇敢的用来实现串口通信。

using System;
using System.Runtime.InteropServices;

namespace BusApp
{
 /// <summary>
 ///
 /// </summary>
 public class mycom
 {
  public mycom()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }
  public int PortNum; //1,2,3,4
  public int BaudRate; //1200,2400,4800,9600
  public byte ByteSize; //8 bits
  public byte Parity; // 0-4=no,odd,even,mark,space
  public byte StopBits; // 0,1,2 = 1, 1.5, 2
  public int ReadTimeout; //10
 
  //comm port win32 file handle
  private int hComm = -1;
 
  public bool Opened = false;
  
  //win32 api constants
  private const uint GENERIC_READ = 0x80000000;
  private const uint GENERIC_WRITE = 0x40000000;
  private const int OPEN_EXISTING = 3; 
  private const int INVALID_HANDLE_VALUE = -1;
 
  [StructLayout(LayoutKind.Sequential)]
   private struct DCB
  {
   //taken from c struct in platform sdk
   public int DCBlength;           // sizeof(DCB)
   public int BaudRate;            // current baud rate
   public int fBinary;          // binary mode, no EOF check
   public int fParity;          // enable parity checking
   public int fOutxCtsFlow;      // CTS output flow control
   public int fOutxDsrFlow;      // DSR output flow control
   public int fDtrControl;       // DTR flow control type
   public int fDsrSensitivity;   // DSR sensitivity
   public int fTXContinueOnXoff; // XOFF continues Tx
   public int fOutX;          // XON/XOFF out flow control
   public int fInX;           // XON/XOFF in flow control
   public int fErrorChar;     // enable error replacement
   public int fNull;          // enable null stripping
   public int fRtsControl;     // RTS flow control
   public int fAbortOnError;   // abort on error
   public int fDummy2;        // reserved
   public ushort wReserved;          // not currently used
   public ushort XonLim;             // transmit XON threshold
   public ushort XoffLim;            // transmit XOFF threshold
   public byte ByteSize;           // number of bits/byte, 4-8
   public byte Parity;             // 0-4=no,odd,even,mark,space
   public byte StopBits;           // 0,1,2 = 1, 1.5, 2
   public char XonChar;            // Tx and Rx XON character
   public char XoffChar;           // Tx and Rx XOFF character
   public char ErrorChar;          // error replacement character
   public char EofChar;            // end of input character
   public char EvtChar;            // received event character
   public ushort wReserved1;         // reserved; do not use
  }

  [StructLayout(LayoutKind.Sequential)]
   private struct COMMTIMEOUTS
  { 
   public int ReadIntervalTimeout;
   public int ReadTotalTimeoutMultiplier;
   public int ReadTotalTimeoutConstant;
   public int WriteTotalTimeoutMultiplier;
   public int WriteTotalTimeoutConstant;
  } 

  [StructLayout(LayoutKind.Sequential)]
   private struct OVERLAPPED
  {
   public int  Internal;
   public int  InternalHigh;
   public int  Offset;
   public int  OffsetHigh;
   public int hEvent;
  } 
 
  [DllImport("kernel32.dll")]
  private static extern int CreateFile(
   string lpFileName,                         // file name
   uint dwDesiredAccess,                      // access mode
   int dwShareMode,                          // share mode
   int lpSecurityAttributes, // SD
   int dwCreationDisposition,                // how to create
   int dwFlagsAndAttributes,                 // file attributes
   int hTemplateFile                        // handle to template file
   );
  [DllImport("kernel32.dll")]
  private static extern bool GetCommState(
   int hFile,  // handle to communications device
   ref DCB lpDCB    // device-control block
   );
  [DllImport("kernel32.dll")]
  private static extern bool BuildCommDCB(
   string lpDef,  // device-control string
   ref DCB lpDCB     // device-control block
   );
  [DllImport("kernel32.dll")]
  private static extern bool SetCommState(
   int hFile,  // handle to communications device
   ref DCB lpDCB    // device-control block
   );
  [DllImport("kernel32.dll")]
  private static extern bool GetCommTimeouts(
   int hFile,                  // handle to comm device
   ref COMMTIMEOUTS lpCommTimeouts  // time-out values
   );
  [DllImport("kernel32.dll")]
  private static extern bool SetCommTimeouts(
   int hFile,                  // handle to comm device
   ref COMMTIMEOUTS lpCommTimeouts  // time-out values
   );
  [DllImport("kernel32.dll")]
  private static extern bool ReadFile(
   int hFile,                // handle to file
   byte[] lpBuffer,             // data buffer
   int nNumberOfBytesToRead,  // number of bytes to read
   ref int lpNumberOfBytesRead, // number of bytes read
   ref OVERLAPPED lpOverlapped    // overlapped buffer
   );
  [DllImport("kernel32.dll")]
  private static extern bool WriteFile(
   int hFile,                    // handle to file
   byte[] lpBuffer,                // data buffer
   int nNumberOfBytesToWrite,     // number of bytes to write
   ref int lpNumberOfBytesWritten,  // number of bytes written
   ref OVERLAPPED lpOverlapped        // overlapped buffer
   );
  [DllImport("kernel32.dll")]
  private static extern bool CloseHandle(
   int hObject   // handle to object
   );
 
  public void Open()
  {
  
   DCB dcbCommPort = new DCB();
   COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
  
  
   // OPEN THE COMM PORT.

   
   hComm = CreateFile("COM" + PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);
 
   // IF THE PORT CANNOT BE OPENED, BAIL OUT.
   if(hComm == INVALID_HANDLE_VALUE)
   {
    throw(new ApplicationException("Comm Port Can Not Be Opened"));
   }
 
   // SET THE COMM TIMEOUTS.
  
   GetCommTimeouts(hComm,ref ctoCommPort);
   ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
   ctoCommPort.ReadTotalTimeoutMultiplier = 0;
   ctoCommPort.WriteTotalTimeoutMultiplier = 0;
   ctoCommPort.WriteTotalTimeoutConstant = 0; 
   SetCommTimeouts(hComm,ref ctoCommPort);
 
   // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
   // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
   // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
   // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
   // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.
 
   dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
   GetCommState(hComm, ref dcbCommPort);
   dcbCommPort.BaudRate=BaudRate;
   dcbCommPort.Parity=Parity;
   dcbCommPort.ByteSize=ByteSize;
   dcbCommPort.StopBits=StopBits;
   SetCommState(hComm, ref dcbCommPort);
   
   Opened = true;
   
  }
 
  public void Close()
  {
   if (hComm!=INVALID_HANDLE_VALUE)
   {
    CloseHandle(hComm);
                Opened=false;
   }
  }
 
  public byte[] Read(int NumBytes)
  {
   byte[] BufBytes;
   byte[] OutBytes;
   BufBytes = new byte[NumBytes];
   if (hComm!=INVALID_HANDLE_VALUE)
   {
    OVERLAPPED ovlCommPort = new OVERLAPPED();
    int BytesRead=0;
    ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
    OutBytes = new byte[BytesRead];
    Array.Copy(BufBytes,OutBytes,BytesRead);
   }
   else
   {
    throw(new ApplicationException("Comm Port Not Open"));
   }
   return OutBytes;
  }
 
  public int Write(byte[] WriteBytes)
  {
   int BytesWritten = 0;
   if (hComm!=INVALID_HANDLE_VALUE)
   {
    OVERLAPPED ovlCommPort = new OVERLAPPED();
    WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
   }
   else
   {
    throw(new ApplicationException("Comm Port Not Open"));
   } 
   return BytesWritten;
  }
 }
}


敬告各位网友:



    该程序源码已经放到本blog第一篇



中提供下载!

-----------------------------------------------------------------

标签:C#,hComm,private,int,修改版,串口,byte,ref,public
From: https://www.cnblogs.com/sexintercourse/p/17964874

相关文章

  • 5.HTTP和TCP
    6.1http1.0和http1.1有什么区别。HTTP1.1相较于HTTP1.0增加了长连接、管道。长连接:为解决HTTP/1.0发送一次请求,建立一次TCP,因此HTTP/1.1新增了长连接,减少连接重复创建和断开管道:解决HTTP/1.0在一个TCP连接中每发送一个请求需等待一个响应的问题,HTTP/1.1新增管道,一个TCP中......
  • 使用Tesseract做文字识别(OCR)
    使用Tesseract做文字识别(OCR)小糊糊​哈尔滨工业大学计算机科学与技术硕士 39人赞同了该文章前言OCR(opticalcharacterrecognition,光学字符识别)是指直接将包含文本的图像识别为计算机文字(计算机黑白点阵)的技术。图像中的文本一般为印刷体文本。T......
  • TypeScript 中的 Export 和 Import
    TypeScript中的Export和ImportAUG 30TH, 2016 7:33AM在TypeScript中,经常要使用export和import两个关键字,这两个关键字和es6中的语法是一致的,因为TypeScript=es6+type!注意:目前没有任何浏览器实现export和import,要在浏览器中执行,必须借助TypeSc......
  • 用Scala采集出行平台机票价格信息
    年关将至,趁着过年,打算拖家带口的出去游玩一番,目前也没有什么计划,去哪里玩也比较随机。正好年底公司项目都已经完成差不多,利用空余时间,用爬虫爬取各大景点飞机票价格信息,选择景点不错机票便宜的,来场说走就走的旅行,犒劳一下自己。以下是一个简单的示例,用于抓取网页上的机票价格信息:im......
  • 喜报!思迈特荣获DCMM稳健级认证,数据管理能力达国家标准
    近日,经中国电子信息行业联合组织主办的数据管理能力成熟度评估(简称DCMM)专家评审会的严格审查,思迈特成功取得DCMM稳健级(乙方三级)证书。这一成就标志着在数据战略和执行方面,思迈特取得了显著的进展,其数据管理能力已达到行业领先水平。DCMM是我国数据管理领域的国家级评估标准,自2018年......
  • ElasticSearch降本增效常见的方法 | 京东云技术团队
    Elasticsearch在db_ranking的排名不断上升,其在存储领域已经蔚然成风且占有非常重要的地位。随着Elasticsearch越来越受欢迎,企业花费在ES建设上的成本自然也不少。那如何减少ES的成本呢?今天我们就特地来聊聊ES降本增效的常见方法:弹性伸缩分级存储其他:(1)数据压缩(2)offheap1弹性伸缩......
  • 外贸CRM系统有哪些特点和应用价值?外贸企业必看
    外贸企业在客户管理、业务管理方面有更高的追求。为了更好地发展全球业务,满足客户多元化的需求,外贸企业需要通过CRM管理系统实现智能管理。接下来,让我们来谈谈外贸CRM的概念、特点和应用。什么是外贸CRM?外贸CRM是指针对外贸行业的客户关系管理系统,它可以帮助外贸企业管理客户......
  • Elasticserch核心概念
    索引一个索引就是一个拥有几分相似特征的文档的集合。比如说,你可以有一个客户数据的索引,另一个产品目录的索引,还有一个订单数据的索引。一个索引由一个名字来标识(必须全部是小写字母),并且当我们要对这个索引中的文档进行索引、搜索、更新和删除的时候,都要使用到这个名字。在一个......
  • 一种基于偏移流和纯字符串流来存储和读取字符串列表的方法【C#】
    字符串的存储长度是可变的,在C#中,BinaryWriter和BinaryReader在Write,ReadStirng的时候,都在单个流中字符串的二进制数组前面加了一个二进制数组的长度信息,方便读取的时候,造成了记录字符串的流并不纯粹是字符串的内容。但是,有时候,我们可以,也可能必须记录纯粹的字符串的二进制内容,然后......
  • 金融行业CRM选型必看:哪款金融CRM好用?
    市场形式波诡云谲,金融行业也面临着资源体系分散、竞争力后继不足、未知风险无法规避等问题。金融企业该如何解决这些问题,或许可以了解一下Zoho CRM管理系统,和其提供的金融行业CRM解决方案。金融CRM系统可以智能化客户筛选、整合各个资源体系、提升企业核心竞争力、规避安全风险......