VB串口通信
的有关信息介绍如下:以前做工程用的,你修改一下,可能对你有用,你看看吧
'======================串口初始化=======================
Private Sub Comm_initial(Port As Byte, BaudRate As String, ParityBit As String, DataBit As Integer, StopBit As Integer)
On Error GoTo ErrorTrap
If MSComm1.PortOpen = True Then MSComm1.PortOpen = False ' 串口若已打开,则先关闭
MSComm1.CommPort = Port ' 设置端口号
MSComm1.Settings = BaudRate & "," & ParityBit & "," & DataBit & "," & StopBit ' 设置波特率、校验位、数据位、停止位
MSComm1.InBufferSize = 1024 ' 设置接收缓冲区为1024字节
MSComm1.OutBufferSize = 4096 ' 设置发送缓冲区为4096字节
MSComm1.InBufferCount = 0 ' 清空输入缓冲区
MSComm1.OutBufferCount = 0 ' 清空输出缓冲区
MSComm1.SThreshold = 1 ' 发送缓冲区被清空时,触发OnComm事件
MSComm1.RThreshold = 1 ' 接收缓冲区每接收到一字节数据时,触发OnComm事件
MSComm1.PortOpen = True '打开串口
If MSComm1.PortOpen = True Then
txtstatus.Text = "STATUS:" & cboport.Text & " OPEND," & cbobps.Text & "," & Left(CboParity.Text, 1) & "," & Cbobit.Text & "," & cbostop.Text
Else
txtstatus.Text = "STATUS:COM Port Cloced"
End If
Exit Sub
ErrorTrap:
Select Case Err.Number
Case comPortAlreadyOpen
MsgBox "串口冲突,请更改串口号", 48, "公司车辆管理系统"
CloseCom
Case Else
MsgBox "没有发现此串口,请确认连接", 48, "公司车辆管理系统"
CloseCom
End Select
Err.Clear
End Sub
Private Sub cmdclose_Click()
Call CloseCom
End Sub
Private Sub cmdset_Click()
Call Comm_initial(Val(Mid(cboport.Text, 4, 1)), cbobps.Text, Left(CboParity.Text, 1), Val(Cbobit.Text), Val(cbostop.Text))
End Sub
Private Sub Form_Load()
Call Comm_initial(Val(Mid(cboport.Text, 4, 1)), cbobps.Text, Left(CboParity.Text, 1), Val(Cbobit.Text), Val(cbostop.Text)) '串口初始化
MSComm1.InputMode = comInputModeText '通过文本方式读取数据
End Sub
'=========================数据接收子程序=========================
Private Sub dataReceive()
Dim strByte() As String '数据分割用数组
Dim receiveData As String ' 接收数据暂存
Dim i As Integer
If (MSComm1.InBufferCount > 0) Then
receiveData = "" ' 清接收数据暂存
receiveData = MSComm1.Input '接收数据
'txtreceive.Text = txtreceive & receiveData
'===============数据在相应文本框里显示=======
strByte = Split(receiveData)
For i = 0 To UBound(strByte)
txt1(i).Text = strByte(i)
Next i
txt1(8).Text = Now
End If
End Sub
'====================OnComm事件===========================
Private Sub MSComm1_OnComm()
Select Case MSComm1.CommEvent ' 设置oncomm事件,读取片机内存的值
Case comEvReceive
Call dataReceive
Case Else
End Select
End Sub
'====================关闭串口子程序=====================
Private Sub CloseCom()
On Error GoTo Err
If MSComm1.PortOpen = True Then MSComm1.PortOpen = False ' 串口若已打开,则关闭
txtstatus.Text = "STATUS:COM Port Cloced"
Err:
End Sub