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