您现在所在的是:

串口通信

回帖:0个,阅读:1688 [上一页] [1] [下一页]
984
guangtoujian
文章数:16
年度积分:50
历史总积分:984
注册时间:2004/11/7
发站内信
发表于:2005/8/18 8:48:00
#0楼
希望各位男女前辈们,给指点一下!谢谢
 以下为程序代码:

Option Explicit

Dim lHandle As Long



Private Sub Form_Load()
Dim lResult As Long

Call SendHand

lResult = CloseHandle(lHandle)

End Sub


Private Function OpenThePort(cPort As String, cBaud As String, cParity As String, cData As String, cStop As String) As Boolean
Dim lResult As Long
Dim SECURITY As SECURITY_ATTRIBUTES
Dim DCB_COMM As DCB
Dim cDCBConfig As String


Select Case cParity
      Case "NONE"
      cParity = "n"
      Case "EVEN"
      cParity = "e"
      Case "ODD"
      cParity = "o"
End Select
     


lHandle = CreateFile(cPort, GENERIC_READ Or GENERIC_WRITE, 0&, SECURITY, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0&)
If lHandle = -1 Then '打开串口失败
OpenThePort = False
MsgBox "串口可能正被其他应用程序占用!"

lResult = CloseHandle(lHandle)
Exit Function
End If


cDCBConfig = cBaud & "," & cParity & "," & cData & "," & cStop '设置DCB

lResult = BuildCommDCB(cDCBConfig, DCB_COMM)  '按用户设定配置一个DCB结构
If lResult = 0 Then
OpenThePort = False
MsgBox "无法建立DCB设备控制块"
lResult = CloseHandle(lHandle)
Exit Function
End If
lResult = SetCommState(lHandle, DCB_COMM)  '实际设置一个串口的DCB
If lResult = 0 Then
OpenThePort = False
MsgBox "无法建立DCB设备控制块"
lResult = CloseHandle(lHandle)
Exit Function
End If
OpenThePort = True
'lResult = CloseHandle(lHandle)

End Function



Private Sub SendHand()   '发送握手信号的子过程
Dim Nchars As Long
Dim Readbuff As String
Dim Writebuff As String
Dim lpDCB As DCB
Dim lRet As Long
Dim lpOverlapped As OVERLAPPED
Dim RNum As Integer
Dim Nlen As Long
Dim Duration As Variant





Call OpenThePort("COM2", "9600", "NONE", "8", "1")

lRet = PurgeComm(lHandle, 1)  '清输出缓冲区
lRet = PurgeComm(lHandle, 0)  '清输入缓冲区
lRet = GetCommState(lHandle, lpDCB)   '获得通讯口的状态

Shand:
DoEvents
Writebuff = "AT" + vbCr
Nlen = Len(Writebuff)

lRet = WriteFile(lHandle, Writebuff, Nlen, Nchars, lpOverlapped) '送握手信号入串口缓冲区


If lRet <= 0 Then
MsgBox "发送操作出错,握手信号未发送成功", 16
'GoTo Shand '不成功则重发
End If
'Else

'GoTo Qtest
'End If
'GoTo Shand
'Qtest:
Readbuff = "" '清除缓冲区为空
'Do While lHandle '循环查询串口
'RNum = 0 '设置读串口次数的指针为0
Duration = Timer + 5
Do
DoEvents
lRet = ReadFile(lHandle, Readbuff, 1, Nchars, lpOverlapped)

If InStr(1, Readbuff, "OK") Then
MsgBox "跟MODEM连接成功!"
    Exit Do
End If

Loop Until Timer >= Duration

If Timer >= Duration Then
MsgBox "跟MODEM连接失败!"
Exit Sub

End If

Writebuff = "AT" + "13779936832" + vbCr
Nlen = Len(Writebuff)


lRet = WriteFile(lHandle, Writebuff, Nlen, Nchars, lpOverlapped) '送握手信号入串口缓冲区

Duration = Timer + 10
Do
DoEvents
lRet = ReadFile(lHandle, Readbuff, 1, Nchars, lpOverlapped)

If InStr(1, Readbuff, "CONNECT") Then
MsgBox "拨号成功!"
    Exit Do
End If

Loop Until Timer >= Duration

If Timer >= Duration Then
MsgBox "拨号失败!"
Exit Sub

End If


End Sub



关于我们 | 联系我们 | 广告服务 | 本站动态 | 友情链接 | 法律声明 | 非法和不良信息举报

工控网客服热线:0755-86369299
版权所有 工控网 Copyright©2024 Gkong.com, All Rights Reserved

31.2002