VB串口通信程序
用VB写了一个通过串口接收数据显示温度的小程序,为什么老是说端口没有打开?可是我明明已经打开了端口连接了开发板的,请大神帮忙看看是不是程序有问题:DimstartAsBo...
用VB写了一个通过串口接收数据显示温度的小程序,为什么老是说端口没有打开?可是我明明已经打开了端口连接了开发板的,请大神帮忙看看是不是程序有问题:Dim start As BooleanDim indata(6) As ByteDim ovt As Integer 'ovt是干嘛的Private Sub dispose_data()If indata(2) = 1 ThenShape1.BackColor = &H80FF&Text1.Text = ""Text1.Text = Val(Trim(indata(1))) & " ℃" 'Val将数值表达式的值换成字符串,Trim除掉数据前后的空格End SubPrivate Sub Command1_Click()Dim Tempe(0) As ByteTempe(0) = "&H" & 1MSComm1.Output = TempeEnd SubPrivate Sub Form_Load()If MSComm1.PortOpen = True ThenMSComm1.PortOpen = FalseMSComm1.CommPort = 3MSComm1.Settings = "9600,n,8,1"MSComm1.InputMode = comInputModeBinary '十六进制接收MSComm1.PortOpen = TrueEnd IfEnd SubPrivate Sub MSComm1_OnComm()Select Case MSComm1.CommEvent Case comEvReceivefloop: Dim aa As Variant aa = MSComm1.Input If aa(0) = &HFA Then start = True ovt = 0 End If If aa(0) = &HFB Then start = False indata(ovt) = aa(0) Call dispose_data End If If start = True Then indata(ovt) = aa(0) ovt = ovt + 1 End If If MSComm1.InBufferCount <> 0 Then GoTo floop End IfEnd Select End SubPrivate Sub Timer1_Timer()Dim Temp(0) As Byte Timer1.Enabled = False Temp(0) = "&H" & 2 MSComm1.Output = TempEnd SubPrivate Sub Timer2_Timer()Dim Temp(0) As Byte Timer2.Enabled = False Temp(0) = "&H" & 3 MSComm1.Output = TempEnd Sub
展开
2个回答
展开全部
串口初始化
Private Sub Form
Load()
MSComm1.CommPort = 1
设置通信端口号为
COM1
MSComm1.Settings = "9600,n,8,1"
设置串口
1
参数
MSComm1.InputMode = 0
接收文本型数据
MSComm1.PortOpen = True
打开通信端口
1
End Sub
把字符通过串口发送出去
Private Sub Cmdsend
Click()
If Textsend.Text = "" Then
pp = MsgBox("
发送的数据不能为空!
Exit Sub
End If
MSComm1.Output = Trim(Textsend.Text)
For i = 1 To 20000000
Next i
End Sub
通过时钟控制来自动接收字符
Private Sub Timer1_
Timer()
Dim buf$
buf = Trim(MSComm1.Input)
将缓冲区内的数据读入
buf
变量中
If Len(buf) <> 0 Then
判断缓冲区内是否存在数据
TextReceive.Text = TextReceive.Text +Chr(13) + Chr(10) + buf
回车换行
End If
End Sub
关闭通信端口
停止程序运行
Private Sub Cmdquit
Click()
MSComm1.PortOpen = False
Unload Me
End Sub
Private Sub Form
Load()
MSComm1.CommPort = 1
设置通信端口号为
COM1
MSComm1.Settings = "9600,n,8,1"
设置串口
1
参数
MSComm1.InputMode = 0
接收文本型数据
MSComm1.PortOpen = True
打开通信端口
1
End Sub
把字符通过串口发送出去
Private Sub Cmdsend
Click()
If Textsend.Text = "" Then
pp = MsgBox("
发送的数据不能为空!
Exit Sub
End If
MSComm1.Output = Trim(Textsend.Text)
For i = 1 To 20000000
Next i
End Sub
通过时钟控制来自动接收字符
Private Sub Timer1_
Timer()
Dim buf$
buf = Trim(MSComm1.Input)
将缓冲区内的数据读入
buf
变量中
If Len(buf) <> 0 Then
判断缓冲区内是否存在数据
TextReceive.Text = TextReceive.Text +Chr(13) + Chr(10) + buf
回车换行
End If
End Sub
关闭通信端口
停止程序运行
Private Sub Cmdquit
Click()
MSComm1.PortOpen = False
Unload Me
End Sub
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询