读书人

请帮忙看一上用API写的串口模块有关问

发布时间: 2012-12-16 12:02:32 作者: rapoo

请帮忙看一下用API写的串口模块问题出在哪,不能发送和接收

'发送数据
Public Function SendData(bytBuffer() As Byte, lngSize As Long) As Long
Dim m As Integer
On Error GoTo ToExit '打开错误陷阱
'------------------------------------------------
If (m_Handle = 0) Then
SendData = 1
Exit Function
End If

Dim dwBytesWritten As Long
Dim bWriteStat As Long
Dim ComStats As ComStat
Dim dwErrorFlags As Long

dwBytesWritten = lngSize

Call ClearCommError(m_Handle, dwErrorFlags, ComStats)
bWriteStat = WriteFile(m_Handle, bytBuffer(0), lngSize, dwBytesWritten, m_OverlappedWrite)
If bWriteStat = 0 Then
If GetLastError() = ERROR_IO_PENDING Then
Call GetOverlappedResult(m_Handle, m_OverlappedWrite, dwBytesWritten, 1) '等待直到发送完毕
End If
Else
dwBytesWritten = 0
End If

SendData = dwBytesWritten
'------------------------------------------------
Exit Function
'----------------
ToExit:
SendData = -1
End Function

'读取数据
Public Function ReadData(bytBuffer() As Byte, lngSize As Long, Optional Overtime As Long = 3000) As Long
On Error GoTo ToExit '打开错误陷阱
'------------------------------------------------
If (m_Handle = 0) Then
ReadData = 1
Exit Function
End If

Dim lngBytesRead As Long
Dim fReadStat As Long
Dim dwRes As Long

lngBytesRead = lngSize

'读数据
fReadStat = ReadFile(m_Handle, bytBuffer(0), lngSize, lngBytesRead, m_OverlappedRead)
If fReadStat = 0 Then
If GetLastError() = ERROR_IO_PENDING Then '重叠 I/O 操作在进行中
dwRes = WaitForSingleObject(m_OverlappedRead.hEvent, Overtime) '等待,直到超时
Select Case dwRes
Case WAIT_OBJECT_0: '读完成


If GetOverlappedResult(m_Handle, m_OverlappedRead, lngBytesRead, 0) = 0 Then
'错误
ReadData = -2
Exit Function
End If
Case WAIT_TIMEOUT: '超时
ReadData = -1
Exit Function
Case Else: 'WaitForSingleObject 错误
End Select
End If
End If
ReadData = lngBytesRead
'------------------------------------------------
Exit Function
'----------------
ToExit:
ReadData = -1
End Function

[最优解释]
楼主,你把你的代码传到资源中,大家下来看看,这样看累!
[其他解释]
已经上传了
[其他解释]
你的问题是没有端口都无法通信?
[其他解释]
我看了下,你的CreateFile和我给你的不一样啊。

读书人网 >VB

热点推荐