'不清楚的地方请百度HI我,添加一个按钮和一个mscomm控件,然后粘贴代码
Dim recive(1 To 5) As Byte
Dim send() As Byte
Private Sub Command1_Click()
MSComm1.CommPort = 1
' 9600 波特,无奇偶校验,8 位数据,一个停止位。
MSComm1.Settings = "9600,N,8,1"
' 当输入占用时,
' 告诉控件读入整个缓冲区。
MSComm1.InputLen = 0
' 打开端口。
MSComm1.PortOpen = True
MSComm1.InputMode = comInputModeBinary'二进制方式发送
MSComm1.Output = recive' 发送数据
Do Until MSComm1.InBufferCount >= 5'等待数据
DoEvents
Loop
send = MSComm1.Input'接受
Dim i As Integer
Dim s As String
For i = 0 To UBound(send)
s = s & Hex(send(i)) & " "
Next i
MsgBox "收到5字节:" & s'显示
End Sub
Private Sub Form_Load()
recive(1) = &H41
recive(2) = &H42
recive(3) = &H43
recive(4) = &H44
recive(5) = &H45
End Sub
Option Explicit
Dim Receive() As Byte '按你的要求写的,放要发送的数据
Dim Send() As Byte '存放已收到数据
Private Sub Command1_Click()
If MSComm1.PortOpen = False Then '端口未打开,则打开
MSComm1.PortOpen = True
End If
MSComm1.OutBufferCount = 0 '清空发送缓冲
Dim i As Integer
ReDim Receive(4) '下面只是填充数据,你根据自己情况给Receive赋值
For i = 0 To 4
Receive(i) = i + 48
Next
MSComm1.Output = Receive '发送数据
End Sub
Private Sub Form_Load()
With MSComm1 '初始化Mscomm1属性
.CommPort = 1 '端口COM1
.Settings = "9600,n,8,1"
.SThreshold = 0
.RThreshold = 5 '接收阀值,收到5个字节后会触发OnComm事件
.InputMode = comInputModeBinary '数据通过 Input 属性以二进制形式取回
End With
End Sub
Private Sub MSComm1_OnComm()
If MSComm1.CommEvent = comEvReceive Then '收到5个数据后
Send = MSComm1.Input '数据保存在Send数组中.
Debug.Print Hex(Send(0)); Hex(Send(1)); Hex(Send(2)); Hex(Send(3)); Hex(Send(4)) '调试用,不要可以删除
'你可以在这里加入一些对收到的数据的处理,
End If
End Sub
楼上 都 代码不错
推荐看书
Visual_Basic与_RS-232_串行通信控制