收藏 分享(赏)

[API实现]VB的串口通信模块.doc

上传人:yjrm16270 文档编号:6783317 上传时间:2019-04-22 格式:DOC 页数:17 大小:111KB
下载 相关 举报
[API实现]VB的串口通信模块.doc_第1页
第1页 / 共17页
[API实现]VB的串口通信模块.doc_第2页
第2页 / 共17页
[API实现]VB的串口通信模块.doc_第3页
第3页 / 共17页
[API实现]VB的串口通信模块.doc_第4页
第4页 / 共17页
[API实现]VB的串口通信模块.doc_第5页
第5页 / 共17页
点击查看更多>>
资源描述

1、http:/ 2007-07-24 15:30:41 阅读 96 评论 0 字号:大中小*模 块 名:SerialPort*说 明:YFsoft 版权所有 2006 - 2007(C)*创 建 人:叶帆*日 期:2006-08-17 14:32:29*修 改 人:*日 期:*描 述:串口异步读写(API)*版 本:V1.0.0*Option ExplicitPrivate Type COMSTATfCtsHold As LongfDsrHold As LongfRlsdHold As LongfXoffHold As LongfXoffSent As LongfEof As LongfTxim

2、 As LongfReserved As LongcbInQue As LongcbOutQue As LongEnd TypePrivate Type COMMTIMEOUTSReadIntervalTimeout As LongReadTotalTimeoutMultiplier As LongReadTotalTimeoutConstant As LongWriteTotalTimeoutMultiplier As LongWriteTotalTimeoutConstant As LongEnd TypePrivate Type DCBDCBlength As LongBaudRate

3、As LongDWORD DCBlength; /* sizeof(DCB) */DWORD BaudRate; /* Baudrate at which running */* Binary Mode (skip EOF check) */* Enable parity checking */* CTS handshaking on output */* DSR handshaking on output */* DTR Flow control */* DSR Sensitivity */* Continue TX when Xoff sent */* Enable output X-ON

4、/X-OFF */* Enable input X-ON/X-OFF */* Enable Err Replacement */* Enable Null stripping */* Rts Flow control */* Abort all reads and writes on Error */* Reserved */fBitFields As Long See Comments in Win32API.TxtwReserved As IntegerXonLim As IntegerXoffLim As IntegerByteSize As ByteParity As ByteStop

5、Bits As ByteXonChar As ByteXoffChar As ByteErrorChar As ByteEofChar As ByteEvtChar As BytewReserved1 As Integer Reserved; Do Not UseEnd TypePrivate Type OVERLAPPEDInternal As LongInternalHigh As Longoffset As LongOffsetHigh As LonghEvent As LongEnd TypePrivate Type SECURITY_ATTRIBUTESnLength As Long

6、lpSecurityDescriptor As LongbInheritHandle As LongEnd TypePrivate Declare Function CloseHandle Lib “kernel32“ (ByVal hObject As Long) As LongPrivate Declare Function GetLastError Lib “kernel32“ () As LongPrivate Declare Function ReadFile Lib “kernel32“ (ByVal hFile As Long, lpBuffer As Any, ByVal nN

7、umberOfBytesToRead As Long, lpNumberOfBytesRead As Long, lpOverlapped As OVERLAPPED) As LongPrivate Declare Function WriteFile Lib “kernel32“ (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToWrite As Long, lpNumberOfBytesWritten As Long, lpOverlapped As OVERLAPPED) As Long OVERLAPPEDPriv

8、ate Declare Function SetCommTimeouts Lib “kernel32“ (ByVal hFile As Long, lpCommTimeouts As COMMTIMEOUTS) As LongPrivate Declare Function GetCommTimeouts Lib “kernel32“ (ByVal hFile As Long, lpCommTimeouts As COMMTIMEOUTS) As LongPrivate Declare Function BuildCommDCB Lib “kernel32“ Alias “BuildCommD

9、CBA“ (ByVal lpDef As String, lpDCB As DCB) As LongPrivate Declare Function SetCommState Lib “kernel32“ (ByVal hCommDev As Long, lpDCB As DCB) As LongPrivate Declare Function GetCommState Lib “kernel32“ (ByVal nCid As Long, lpDCB As DCB) As LongPrivate Declare Function CreateFile Lib “kernel32“ Alias

10、 “CreateFileA“ (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, ByVal lpSecurityAttributes As Long, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As LongPrivate Declare Function FlushFileBuffers Lib “kernel

11、32“ (ByVal hFile As Long) As LongPrivate Declare Function CreateEvent Lib “kernel32“ Alias “CreateEventA“ (lpEventAttributes As SECURITY_ATTRIBUTES, ByVal bManualReset As Long, ByVal bInitialState As Long, ByVal lpName As String) As LongPrivate Declare Function SetCommMask Lib “kernel32“ (ByVal hFil

12、e As Long, ByVal dwEvtMask As Long) As LongPrivate Declare Function SetEvent Lib “kernel32“ (ByVal hEvent As Long) As LongPrivate Declare Function PurgeComm Lib “kernel32“ (ByVal hFile As Long, ByVal dwFlags As Long) As LongPrivate Declare Function ClearCommError Lib “kernel32“ (ByVal hFile As Long,

13、 lpErrors As Long, lpStat As COMSTAT) As LongPrivate Declare Function GetOverlappedResult Lib “kernel32“ (ByVal hFile As Long, lpOverlapped As OVERLAPPED, lpNumberOfBytesTransferred As Long, ByVal bWait As Long) As LongPrivate Declare Function WaitForSingleObject Lib “kernel32“ (ByVal hHandle As Lon

14、g, ByVal dwMilliseconds As Long) As LongPrivate Declare Function SetupComm Lib “kernel32“ (ByVal hFile As Long, ByVal dwInQueue As Long, ByVal dwOutQueue As Long) As LongPrivate Const GENERIC_WRITE = &H40000000Private Const GENERIC_READ = &H80000000Private Const OPEN_EXISTING = 3Private Const FILE_A

15、TTRIBUTE_NORMAL = &H80Private Const FILE_FLAG_OVERLAPPED = &H40000000Private Const DTR_CONTROL_DISABLE = &H0Private Const RTS_CONTROL_ENABLE = &H1Private Const PURGE_RXABORT = &H2Private Const PURGE_RXCLEAR = &H8Private Const PURGE_TXABORT = &H1Private Const PURGE_TXCLEAR = &H4Private Const ERROR_IO

16、_PENDING = 997Private Const STATUS_WAIT_0 = &H0Private Const WAIT_OBJECT_0 = (STATUS_WAIT_0 + 0)Private Const WAIT_TIMEOUT = 258&Private m_Handle As LongPrivate m_OverlappedRead As OVERLAPPEDPrivate m_OverlappedWrite As OVERLAPPED*函 数 名:OpenPort*输 入:ComNumber(Long) - 串口号* : Comsettings(String) - 配置信

17、息*输 出:(Long) - 0 成功 非 0 失败*功能描述:打开串口*全局变量:*调用模块:*作 者:叶帆*日 期:2006-08-17 14:40:14*修 改 人:*日 期:*版 本:V1.0.0*Public Function OpenPort(ComNumber As Long, Comsettings As String, Optional lngInSize As Long = 1024, Optional lngOutSize As Long = 512) As LongOn Error GoTo handelinitcomDim retval As LongDim Ctim

18、eOut As COMMTIMEOUTS, dcbs As DCBDim strCOM As String, strConfig As String strCOM = “.COM“ & Format(ComNumber, “0“)strCOM = “COM“ & Format(ComNumber, “0“)m_Handle = CreateFile(strCOM, GENERIC_READ Or GENERIC_WRITE, 0, 0&, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL Or FILE_FLAG_OVERLAPPED, 0)If m_Handle =

19、-1 ThenOpenPort = -1Exit FunctionEnd If设置 dcb 块dcbs.DCBlength = Len(dcbs) 长度Call GetCommState(m_Handle, dcbs)波特率 ,奇偶校验,数据位,停止位 如:9600,n,8,1strConfig = “COM“ & Format(ComNumber, “0“) & “:“ & ComsettingsCall BuildCommDCB(strConfig, dcbs)- dcbs.fBinary = 1 二进制方式 dcbs.fOutxCtsFlow = 0 不用 CTS 检测发送流控制 dcb

20、s.fOutxDsrFlow = 0 不用 DSR 检测发送流控制 dcbs.fDtrControl = DTR_CONTROL_DISABLE 禁止 DTR 流量控制 dcbs.fDsrSensitivity = 0 对 DTR 信号线不敏感 dcbs.fTXContinueOnXoff = 1 检测接收缓冲区 dcbs.fOutX = 0 不做发送字符控制 dcbs.fInX = 0 不做接收控制 dcbs.fErrorChar = 0 是否用指定字符替换校验错的字符 dcbs.fNull = 0 保留 NULL 字符 dcbs.fRtsControl = RTS_CONTROL_ENAB

21、LE 允许 RTS 流量控制 dcbs.fAbortOnError = 0 发送错误后,继续进行下面的读写操作 dcbs.fDummy2 = 0 保留dcbs.fBitFields = 1 * 2 0 Or DTR_CONTROL_DISABLE * 2 4 Or 1 * 2 7 Or RTS_CONTROL_ENABLE * 2 12dcbs.wReserved = 0 没有使用,必须为 0dcbs.XonLim = 0 指定在 XOFF 字符发送之前接收到缓冲区中可允许的最小字节数dcbs.XoffLim = 0 指定在 XOFF 字符发送之前缓冲区中可允许的最小可用字节数dcbs.Xon

22、Char = 0 发送和接收的 XON 字符dcbs.XoffChar = 0 发送和接收的 XOFF 字符dcbs.ErrorChar = 0 代替接收到奇偶校验错误的字符dcbs.EofChar = 0 用来表示数据的结束dcbs.EvtChar = 0 事件字符,接收到此字符时,会产生一个事件dcbs.wReserved1 = 0 没有使用dcbs.BaudRate =9600 波特率dcbs.Parity=0 奇偶校验dcbs.ByteSize=8 数据位dcbs.StopBits=0 停止位-If dcbs.Parity = 0 Then 0-4=None,Odd,Even,Mark

23、,Spacedcbs.fBitFields = dcbs.fBitFields And &HFFFD dcbs.fParity = 0 奇偶校验无效Elsedcbs.fBitFields = dcbs.fBitFields Or &H2 dcbs.fParity = 1 奇偶校验有效End If超时设置CtimeOut.ReadIntervalTimeout = 20 0CtimeOut.ReadTotalTimeoutConstant = 1 2500CtimeOut.ReadTotalTimeoutMultiplier = 1 0CtimeOut.WriteTotalTimeoutCons

24、tant = 10 2500CtimeOut.WriteTotalTimeoutMultiplier = 1 0retval = SetCommTimeouts(m_Handle, CtimeOut)If retval = -1 Thenretval = GetLastError()OpenPort = retvalretval = CloseHandle(m_Handle)Exit FunctionEnd If获取信号句柄Dim lpEventAttributes1 As SECURITY_ATTRIBUTESDim lpEventAttributes2 As SECURITY_ATTRIB

25、UTESm_OverlappedRead.hEvent = CreateEvent(lpEventAttributes1, 1, 0, 0)m_OverlappedWrite.hEvent = CreateEvent(lpEventAttributes2, 1, 0, 0)判断设置参数是否成功 设置输入和输出缓冲区是否成功If SetCommState(m_Handle, dcbs) = -1 Or SetupComm(m_Handle, lngInSize, lngOutSize) = -1 Or m_OverlappedRead.hEvent = 0 Or m_OverlappedWrit

26、e.hEvent = 0 Thenretval = GetLastError()OpenPort = retvalIf (m_OverlappedRead.hEvent 0) Then CloseHandle (m_OverlappedWrite.hEvent)Call CloseHandle(m_Handle)m_Handle = 0Exit FunctionEnd IfOpenPort = 0Exit Functionhandelinitcom:Call CloseHandle(m_Handle)m_Handle = 0OpenPort = -2Exit FunctionEnd Funct

27、ion*函 数 名:ClosePort*输 入:无*输 出:(Long) - 0 成功 -1 失败*功能描述:关闭串口*全局变量:*调用模块:*作 者:叶帆*日 期:2006-08-17 14:56:13*修 改 人:*日 期:*版 本:V1.0.0*Public Function ClosePort() As LongIf (m_Handle = 0) ThenClosePort = 1Exit FunctionEnd IfCall SetCommMask(m_Handle, 0)Call SetEvent(m_OverlappedRead.hEvent)Call SetEvent(m_Ov

28、erlappedWrite.hEvent)If (m_OverlappedRead.hEvent 0) Then CloseHandle (m_OverlappedWrite.hEvent)If CloseHandle(m_Handle) 0 ThenClosePort = 0ElseClosePort = -1End Ifm_Handle = 0End Function*函 数 名:ClearInBuf*输 入:无*输 出:无*功能描述:清空输入缓冲区*全局变量:*调用模块:*作 者:叶帆*日 期:2006-08-17 14:57:26*修 改 人:*日 期:*版 本:V1.0.0*Publ

29、ic Function ClearInBuf() As LongIf (m_Handle = 0) ThenClearInBuf = 1Exit FunctionEnd IfCall PurgeComm(m_Handle, PURGE_RXABORT Or PURGE_RXCLEAR)ClearInBuf = 0End Function*函 数 名:ClearOutBuf*输 入:无*输 出:(Long) -*功能描述:清空输出缓冲区*全局变量:*调用模块:*作 者:叶帆*日 期:2006-08-17 15:40:38*修 改 人:*日 期:*版 本:V1.0.0*Public Functio

30、n ClearOutBuf() As LongIf (m_Handle = 0) ThenClearOutBuf = 1Exit FunctionEnd IfCall PurgeComm(m_Handle, PURGE_TXABORT Or PURGE_TXCLEAR)ClearOutBuf = 0End Function*函 数 名:SendData*输 入:bytBuffer()(Byte) - 数据* : lngSize(Long) - 数据长度*输 出:(Long) -*功能描述:发送数据*全局变量:*调用模块:*作 者:叶帆*日 期:2006-08-17 15:43:42*修 改 人

31、:*日 期:*版 本:V1.0.0*Public Function SendData(bytBuffer() As Byte, lngSize As Long) As LongOn Error GoTo ToExit 打开错误陷阱-If (m_Handle = 0) Then SendData = 1SendData = -2Exit FunctionEnd IfDim dwBytesWritten As LongDim bWriteStat As LongDim ComStats As COMSTATDim dwErrorFlags As LongdwBytesWritten = lngSi

32、zeCall ClearCommError(m_Handle, dwErrorFlags, ComStats)bWriteStat = WriteFile(m_Handle, bytBuffer(0), lngSize, dwBytesWritten, m_OverlappedWrite)If bWriteStat = 0 ThenIf GetLastError() = ERROR_IO_PENDING ThenCall GetOverlappedResult(m_Handle, m_OverlappedWrite, dwBytesWritten, 1) 等待直到发送完毕End IfElsed

33、wBytesWritten = 0End IfSendData = dwBytesWritten-Exit Function-ToExit:SendData = -1End Function*函 数 名:ReadData*输 入:bytBuffer()(Byte) - 数据* : lngSize(Long) - 数据长度*输 出:(Long) -*功能描述:读取数据*全局变量:*调用模块:*作 者:叶帆*日 期:2006-08-17 16:04:38*修 改 人:*日 期:*版 本:V1.0.0*Public Function ReadData(bytBuffer() As Byte, lng

34、Size As Long, Optional Overtime As Long = 3000) As LongOn Error GoTo ToExit 打开错误陷阱-If (m_Handle = 0) Then ReadData = 1ReadData = -3Exit FunctionEnd IfDim lngBytesRead As LongDim fReadStat As LongDim dwRes As LonglngBytesRead = lngSize读数据fReadStat = ReadFile(m_Handle, bytBuffer(0), lngSize, lngBytesR

35、ead, m_OverlappedRead)If fReadStat = 0 ThenIf GetLastError() = ERROR_IO_PENDING Then 重叠 I/O 操作在进行中dwRes = WaitForSingleObject(m_OverlappedRead.hEvent, Overtime) 等待,直到超时Select Case dwResCase WAIT_OBJECT_0: 读完成If GetOverlappedResult(m_Handle, m_OverlappedRead, lngBytesRead, 0) = 0 Then错误ReadData = -2E

36、xit FunctionEnd IfCase WAIT_TIMEOUT: 超时ReadData = -1Exit FunctionCase Else: WaitForSingleObject 错误End SelectEnd IfEnd IfReadData = lngBytesRead-Exit Function-ToExit:ReadData = -1End Function*函 数 名:Class_Terminate*输 入:无*输 出:无*功能描述:*全局变量:*调用模块:*作 者:叶帆*日 期:2006-08-17 16:36:21*修 改 人:*日 期:*版 本:V1.0.0*Private Sub Class_Terminate()Call ClosePortEnd Sub

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 企业管理 > 管理学资料

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报