chenyubo1977 2011年11月26日
请帮忙看一下用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
...全文
34 点赞 收藏 4
写回复
4 条回复

还没有回复,快来抢沙发~

发动态
发帖子
API
创建于2007-09-28

1196

社区成员

2.3w+

社区内容

VB API
社区公告
暂无公告