Form1.frm
资源名称:CommTest.rar [点击查看]
上传用户:machunbo88
上传日期:2022-07-03
资源大小:8k
文件大小:4k
源码类别:
串口编程
开发平台:
Visual Basic
- VERSION 5.00
- Object = "{648A5603-2C6E-101B-82B6-000000000014}#1.1#0"; "MSCOMM32.OCX"
- Begin VB.Form Form1
- Caption = "串口通讯"
- ClientHeight = 3345
- ClientLeft = 60
- ClientTop = 345
- ClientWidth = 4680
- Icon = "Form1.frx":0000
- LinkTopic = "Form1"
- ScaleHeight = 3345
- ScaleWidth = 4680
- StartUpPosition = 2 'CenterScreen
- Begin VB.TextBox Text2
- Height = 2400
- Left = 660
- MultiLine = -1 'True
- ScrollBars = 2 'Vertical
- TabIndex = 2
- Top = 195
- Width = 3360
- End
- Begin VB.TextBox Text1
- Height = 375
- Left = 675
- TabIndex = 1
- Top = 2820
- Width = 2280
- End
- Begin VB.CommandButton Command1
- Caption = "发送"
- Height = 375
- Left = 3030
- TabIndex = 0
- Top = 2820
- Width = 975
- End
- Begin MSCommLib.MSComm MSComm1
- Left = 0
- Top = 225
- _ExtentX = 1005
- _ExtentY = 1005
- _Version = 393216
- DTREnable = -1 'True
- End
- End
- Attribute VB_Name = "Form1"
- Attribute VB_GlobalNameSpace = False
- Attribute VB_Creatable = False
- Attribute VB_PredeclaredId = True
- Attribute VB_Exposed = False
- Dim mSend As String
- Private Sub Command1_Click()
- MSComm1.Output = Text1.Text
- End Sub
- Private Sub Form_Load()
- mSend = "120102"
- Call ComPortOpen
- End Sub
- Private Sub MSComm1_OnComm()
- Dim nReceive As Long
- Dim bb() As Byte
- Dim sSend As String
- Dim nCheck As Integer
- With MSComm1
- Select Case .CommEvent
- '判断MSComm1通信事件
- Case comEvReceive
- bb = MSComm1.Input
- nReceive = bb(0)
- Select Case nReceive
- Case 1
- 'msend
- Case 2
- mSend = Right("000" & (Val(Left(mSend, 3)) + 1), 3) & Right(mSend, 3)
- End Select
- For i = 1 To 6
- 'check = Int(num / 10 ^ n) + check
- nCheck = nCheck + Val(Mid(mSend, i, 1))
- Next i
- sSend = mSend & Right(nCheck, 1)
- .Output = sSend
- Text2.Text = Text2.Text & "接收:" & nReceive & "自动回送:" & sSend & vbCrLf
- End Select
- End With
- End Sub
- Public Sub ComPortOpen() '开串口
- With MSComm1
- .CommPort = 1 '使用COM1
- .Settings = "9600,N,8,1" '设置通信口参数
- .InBufferSize = 1024
- '设置MSComm1接收缓冲区为1024字节
- .OutBufferSize = 512
- '设置MSComm1发送缓冲区为4122字节
- .InputMode = comInputModeBinary 'comInputModeText ' =
- '设置接收数据模式为二进制形式
- .InputLen = 0
- '设置Input 一次从接收缓冲读取字节数为1
- .SThreshold = 1
- '设置Output 一次从发送缓冲读取字节数为1
- .InBufferCount = 0 '清除接收缓冲区
- .OutBufferCount = 0 '清除发送缓冲区
- .RThreshold = 1
- On Error Resume Next
- '设置接收一个字节产生OnComm事件
- If .PortOpen = False Then
- '判断通信口是否打开
- .PortOpen = True '打开通信口
- If Err Then '错误处理
- msg = MsgBox(" 串口 COM1 无效! ", vbOKOnly, "警告")
- Exit Sub
- End If
- End If
- End With
- 'MsgBox "端口已打开"
- End Sub