readfile函数操作成功,但返回的实际读取的字节数为零
之前用MSCOMM控件写的串口通信程序,串口设备是用的水木行(IRXON)的蓝牙转RS232,但每次用input读取数据时就显示comm 设备读错误 8020,实在是解决不了这个错误,后来就用API函数写,可是在用readfile函数进行读的时候还是不成功,readfile函数的返回值不为零,表示操作成功,但是readfile函数的第四个参数lpNumberOfBytesRead总是为零。真的是让我很无奈。不管使用MSCOMM控件还是API函数我直接用RS232线子都能正常通信。这是我第一次用API函数写串口通信,我用的是同步操作,以下是与串口相关的代码,大家帮忙看下哪里不对
'初始化端口
Public Function Init_Com(ComNumber As String) As Boolean
On Error GoTo handelinitcom
Dim ComSetup As DCB, stat As COMSTAT, RetBytes As Long
Dim retval As Long
Dim CtimeOut As COMMTIMEOUTS, BarDCB As DCB
ComNum = CreateFile(ComNumber, GENERIC_WRITE Or GENERIC_READ, 0, 0&, OPEN_EXISTING, 0, 0)
If ComNum = -1 Then
frmerror.Label1.Caption = "Please Choose COM Port!"
frmerror.Visible = True
Init_Com = False
Exit Function
End If
' 超时
CtimeOut.ReadIntervalTimeout = 1
CtimeOut.ReadTotalTimeoutConstant = 10
CtimeOut.ReadTotalTimeoutMultiplier = 0
CtimeOut.WriteTotalTimeoutConstant = 1
CtimeOut.WriteTotalTimeoutMultiplier = 1
retval = SetCommTimeouts(ComNum, CtimeOut)
If retval = 0 Then
retval = GetLastError()
frmerror.Label1.Caption = "COM Port Error!"
frmerror.Visible = True
retval = CloseHandle(ComNum)
Init_Com = False
Exit Function
End If
retval = BuildCommDCB(Comsettings, BarDCB)
If retval = 0 Then
retval = GetLastError()
frmerror.Label1.Caption = "COM Port Error!"
frmerror.Visible = True
retval = CloseHandle(ComNum)
Init_Com = False
Exit Function
End If
retval = SetCommState(ComNum, BarDCB)
If retval = 0 Then
retval = GetLastError()
frmerror.Label1.Caption = "COM Port Error!"
frmerror.Visible = True
retval = CloseHandle(ComNum)
Init_Com = False
Exit Function
End If
Init_Com = True
handelinitcom:
Exit Function
End Function
'发送数据
Private Sub Timer_send_Timer()
On Error GoTo handelwritelpt
Dim RetBytes As Long
Dim retval As Long
Dim comerror As Long
Dim stat As COMSTAT
Dim sendMask As Long
retval = PurgeComm(ComNum, PURGE_TXCLEAR)
retval = WriteFile(ComNum, outdata(num_func, num_byte), 1, RetBytes, 0)'单字节发送
If RetBytes Then
num_byte = num_byte + 1
If num_byte > 3 Then
num_byte = 0
num_func = num_func + 1
If num_func > max_func_number Then
num_func = 0
End If
End If
End If
handelwritelpt:
Exit Sub
End Sub
'接收数据
Private Sub Timer_read_Timer()
On Error GoTo handelwritelpt
Dim i As Long
Dim RetBytes As Long
Dim retval As Long
Dim comerror As Long
Dim stat As COMSTAT
retval = ReadFile(ComNum, inbyte(0), 512, RetBytes, 0)
If retval Then
For i = 0 To (RetBytes - 1)
data_oncomm(rev_ptr) = inbyte(i)
rev_ptr = rev_ptr + 1
If rev_ptr > oncomm_buffer Then
rev_ptr = 0
End If
Next i
Else
Call ClearCommError(ComNum, comerror, stat)
End If
If data_ptr = rev_ptr Then
communicate.FillColor = &HFF&
End If
Do While data_ptr <> rev_ptr
Call pro_revdata
Loop
flash_num = flash_num + 1
If flash_num = 2 Then
Call flash1
End If
If flash_num = 4 Then
flash_num = 0
Call flash2
Call timenow
End If
handelwritelpt:
Exit Sub
End Sub