ImageVerifierCode 换一换
格式:DOCX , 页数:14 ,大小:17.76KB ,
资源ID:3852340      下载积分:3 金币
快捷下载
登录下载
邮箱/手机:
温馨提示:
快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。 如填写123,账号就是123,密码也是123。
特别说明:
请自助下载,系统不会自动发送文件的哦; 如果您已付费,想二次下载,请登录后访问:我的下载记录
支付方式: 支付宝    微信支付   
验证码:   换一换

加入VIP,免费下载
 

温馨提示:由于个人手机设置不同,如果发现不能下载,请复制以下地址【https://www.bdocx.com/down/3852340.html】到电脑端继续下载(重复下载不扣费)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录   QQ登录  

下载须知

1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。
2: 试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。
3: 文件的所有权益归上传用户所有。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 本站仅提供交流平台,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

版权提示 | 免责声明

本文(C# 用API操作读写串口.docx)为本站会员(b****3)主动上传,冰豆网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知冰豆网(发送邮件至service@bdocx.com或直接QQ联系客服),我们立即给予删除!

C# 用API操作读写串口.docx

1、C# 用API 操作读写串口using System;using System.Runtime.InteropServices;using System.Threading;using System.Windows.Forms;namespace DataGate / public class ComBase public ComBase(string PortNum, int BaudRate, byte ByteSize, byte Parity, byte StopBits, int ReadTimeout) this.PortNum = PortNum; this.BaudRate =

2、 BaudRate; this.ByteSize = ByteSize; this.Parity = Parity; this.StopBits = StopBits; this.ReadTimeout = ReadTimeout; this.Opened = false; this.m_ovWrite.hEvent = CreateEvent(0, true, false, 0); this.m_ovWrite.Internal = 0; this.m_ovWrite.InternalHigh = 0; this.m_ovWrite.Offset = 0; this.m_ovWrite.Of

3、fsetHigh = 0; this.m_ovRead.hEvent = CreateEvent(0, true, false, 0); this.m_ovRead.Internal = 0; this.m_ovRead.InternalHigh = 0; this.m_ovRead.Offset = 0; this.m_ovRead.OffsetHigh = 0; public string PortNum; /COM1 COM2 COM3 COM4 public int BaudRate; /1200,2400,4800,9600 public byte ByteSize; /8 bits

4、 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; OVERLAPPED m_ovWrite = new OVERLAPPED(); OVERLAPPED m_ovRead = new OVERLAPPED(); /win32 api constan

5、ts 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 D

6、CBlength; / 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 contr

7、ol 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 fRt

8、sControl; / 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

9、 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;

10、 / received event character public ushort wReserved1; / reserved; do not use */ private struct DCB /taken from c struct in platform sdk public int DCBlength; / sizeof(DCB) public int BaudRate; / current baud rate public int xData;/ x值 一个32位 public ushort wReserved; / not currently used public ushort

11、 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

12、 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 ReadInterv

13、alTimeout; 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 i

14、nt 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

15、attributes int hTemplateFile / handle to template file ); 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 GetCommState( int hFile, / handle t

16、o communications device 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 SetCommTimeouts( int hFile, / handl

17、e 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 OVER

18、LAPPED 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 lpOverlappe

19、d / overlapped buffer ); DllImport(kernel32.dll) private static extern bool CloseHandle( int hObject / handle to object ); DllImport(kernel32.dll) private static extern int GetLastError( ); DllImport(kernel32.dll) private static extern int WaitForSingleObject( int hHandle, int dwMilliseconds ); DllI

20、mport(kernel32.dll) private static extern bool GetOverlappedResult( int hFile, / handle to file, pipe, or comm device ref OVERLAPPED lpOverlapped, / pointer to overlapped structure ref int lpNumberOfBytesTransferred, / pointer to actual bytes count bool bWait / wait flag ); DllImport(kernel32.dll) p

21、rivate static extern bool PurgeComm( int hFile, / handle to communications resource int dwFlags / action to perform ); DllImport(kernel32.dll) private static extern bool SetupComm( int hFile, / handle to communications device int dwInQueue, / size of input buffer int dwOutQueue / size of output buff

22、er ); DllImport(kernel32.dll) private static extern int CreateEvent( int lpSECURITY_ATTRIBUTES,/ 传递 个NULL 就是0 / pointer to security attributes bool bManualReset, / flag for manual-reset event bool bInitialState, / flag for initial state int lpName / pointer to event-object name ); public void Open()

23、 DCB dcbCommPort = new DCB(); COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); / OPEN THE COMM PORT. int FILE_FLAG_OVERLAPPED = 0x40000000; hComm = CreateFile(PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); / IF THE PORT CANNOT BE OPENED, BAIL OUT. if (hComm = INV

24、ALID_HANDLE_VALUE) throw (new ApplicationException(this.PortNum + 串口打开失败); / 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 MUS

25、T 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 = Sto

26、pBits; dcbCommPort.wReserved1 = 0; SetCommState(hComm, ref dcbCommPort); bool ret = SetupComm(hComm, 200, 200);/十分重要 不然会写进去字节过多 发不出去那么多 if (!ret) MessageBox.Show(设置缓冲区失败); / SET THE COMM TIMEOUTS. GetCommTimeouts(hComm, ref ctoCommPort); ctoCommPort.ReadIntervalTimeout = 10 * 9600 / this.BaudRate +

27、100; / 9600:110 ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout; ctoCommPort.ReadTotalTimeoutMultiplier = 10 * 9600 / this.BaudRate; ctoCommPort.WriteTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutConstant = 2 * 9600 / this.BaudRate; SetCommTimeouts(hComm, ref ctoCommPort); Opened = tru

28、e; this.ClearInOut(); public void Close() if (hComm != INVALID_HANDLE_VALUE) CloseHandle(hComm); Opened = false; CloseHandle(m_ovRead.hEvent); CloseHandle(m_ovWrite.hEvent); public void ClearInOut() if (this.hComm = INVALID_HANDLE_VALUE) return; int PURGE_TXABORT = 0x0001 ; / Kill the pending/curren

29、t writes to the comm port. int PURGE_RXABORT = 0x0002 ; / Kill the pending/current reads to the comm port. int PURGE_TXCLEAR = 0x0004 ; / Kill the transmit queue if there. int PURGE_RXCLEAR = 0x0008; / Kill the typeahead buffer if there. PurgeComm(hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR

30、 | PURGE_RXCLEAR); public byte Read(int NumBytes) byte BufBytes; byte OutBytes = null ; BufBytes = new byteNumBytes; int ERROR_IO_PENDING = 997 ; if (hComm != INVALID_HANDLE_VALUE) int BytesRead = 0; bool bOK = ReadFile(hComm, BufBytes, NumBytes, ref BytesRead, ref m_ovRead); if (bOK = true) OutBytes = new byteBytesRead; Array.Copy(BufBytes, OutBytes, BytesRead); else

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1