下面是一个接收串口数据的程序,可是有时候接不到,帮我看看原因吧
Option Explicit
Dim atok As Integer
Private Sub Form_Load()
MSComm1.CommPort = 1
'如果串口关闭则将其打开
If MSComm1.PortOpen = False Then
MSComm1.Settings = "9600,n,8,1"
MSComm1.PortOpen = True
End If
'清空缓冲区
MSComm1.OutBufferCount = 0
MSComm1.InBufferCount = 0
atok = 0
'给列表框赋值
lst_at.AddItem "at"
lst_at.AddItem "at+creg?"
lst_at.AddItem "at+cmgf=0"
lst_at.AddItem "at+cmgs=19"
lst_at.AddItem "at+cmgl=0"
lst_at.AddItem "at+cmgr"
End Sub
Private Sub cmd_ok_Click()
Dim code() As Integer
Dim instring As String
Dim string1 As String
Dim length As Integer
Dim i As Integer
Dim temp As Integer
instring = txt_ad.Text
length = Len(instring)
ReDim code(length + 1)
For i = 1 To length '把手机号码按每位数字存入数组code
string1 = Left(instring, i)
code(i) = Right(string1, 1)
'Text2.Text = Text2.Text & code(i)
Next i
'Text2.Text = vbCrLf
'对手机号码编码
For i = 1 To length + 1 Step 2
If i = length Then
If length \ 2 Then
ReDim Preserve code(length + 2)
code(length + 1) = &HF
End If
End If
temp = code(i)
code(i) = code(i + 1)
code(i + 1) = temp
txt_send.Enabled = False
txt_send.Text = txt_send.Text & Hex(code(i)) & code(i + 1)
'Text2.Text = Text2.Text & Hex(code(i)) & code(i + 1)
Next i
txt_send.Enabled = True
txt_send.Text = "0891683108100005F011000D91" & txt_send.Text & "000800" & "046D4B8BD5"
End Sub
Private Sub cmd_send_Click()
'初始化设置
txt_sent.Enabled = True
MSComm1.InputMode = 0 '以二进制形式从输入缓冲区中读数据
MSComm1.InputLen = 0 '一次读出输入缓冲区中的所有数据
MSComm1.RThreshold = 1 '每接收到一个字符就引发一次Oncomm事件
'发送信息
If atok = 1 Then
MSComm1.Output = txt_send.Text & Chr(&H1A)
MSComm1.OutBufferCount = 0
txt_sent.Text = txt_sent.Text & txt_send.Text
atok = 0
txt_flag.Text = ""
Else
MSComm1.Output = txt_send.Text & vbCr
txt_sent.Text = txt_sent.Text & txt_send.Text & vbCrLf
End If
End Sub
Private Sub cmdclear1_Click()
txt_send.Text = ""
txt_send.SetFocus
End Sub
Private Sub cmdclear2_Click()
txt_ad.Text = ""
txt_sent.Text = ""
txt_receive.Text = ""
lst_at.Enabled = True
End Sub
Private Sub Command1_Click()
atok = 1
txt_flag.Text = ">"
atok = 1
txt_send.Text = ""
txt_ad.SetFocus
lst_at.Enabled = False
End Sub
Private Sub MSComm1_OnComm()
txt_receive.Enabled = True
'从缓冲区中读出接收到的字符并记录在文本中
If MSComm1.InBufferCount Then
txt_receive.Text = txt_receive.Text & MSComm1.Input '& vbCrLf
End If
End Sub
Private Sub txt_send_Change()
cmd_send.Enabled = True
End Sub
Private Sub cmd_atok_Click()
txt_send.Text = lst_at.Text
End Sub
Private Sub lst_at_Click()
cmd_atok.SetFocus
End Sub
Private Sub lst_at_DblClick()
cmd_atok_Click
End Sub