VB做个小串口程序
各位老鸟们好
有人拖我做一个VB串口小程序
碍于情面接下来了
由于有关串口与下位机通讯方面的,从来没接触过下位机,所以有点摸不着头脑
程序要求很简单
能够加载下位机时间,并进行修改就行了
请教下各位老鸟该怎么编这个程序
如何用MSComm进行下位机连接?
怎么加载它的时间
是否需要什么协议?
[解决办法]
给你一个关于串口通讯的代码,你自己去参考一下
mscomm控件上点右键属性,打开后设置串口的端口号,端口参数,如波特率等等,PC一般默认的串口设置为9600,n,8,1
设置完后再用以下代码就可以通讯
Option Explicit
Dim strRec As String
Private Sub CommTest_Click()
On Error GoTo ErrorMessage
If MSComm1.PortOpen = False Then
MSComm1.PortOpen = True
MsgBox Chr(13) + "串口打开成功!", vbOKOnly
End If
Exit Sub
ErrorMessage:
MsgBox Chr(13) + "串口打开失败!" + Chr(10) + "错误代码:" & Err.Number & Chr(10) + "原因:" & Err.Description, vbQuestion
End Sub
Private Sub Exit_Click()
Timer1.Enabled = False
If MSComm1.PortOpen = True Then
MSComm1.PortOpen = False
End If
End
End Sub
Private Sub Form_Load()
MSComm1.InBufferSize = 1024 ' 设置接收缓冲区1024Byte
MSComm1.InBufferCount = 0
MSComm1.OutBufferSize = 512 ' 设置发送缓冲区512Byte
MSComm1.OutBufferCount = 0
MSComm1.RThreshold = 1 ' 每个字符到接收缓冲区都触发接收事件
MSComm1.InputMode = 0 '接收文本型数据
Timer1.Interval = 250 '设置定时器事件间隔时间为500毫秒
Timer1.Enabled = False '启动定时器
Timer2.Interval = 250 '设置定时器事件间隔时间为500毫秒
Timer2.Enabled = False '启动定时器
Timer3.Interval = 250 '设置定时器事件间隔时间为500毫秒
Timer3.Enabled = False '启动定时器
MSComm1.InputLen = 2 '设置或返回一次从接收缓冲区中读取字节数,0表示一次读取所有数据
End Sub
Private Sub MSComm1_OnComm() 'oncomm事件接收串口信息
Select Case MSComm1.CommEvent
Case comEvReceive
strRec = strRec + MSComm1.Input
TextReceive.Text = strRec
Select Case strRec
Case "s1"
TextSend.Text = ""
strRec = ""
Shape1.BackColor = &HFF00&
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
Timer1.Enabled = False
Case "n1"
strRec = ""
Shape2.BackColor = &HFF00&
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
Case "h1"
Timer2.Enabled = False
TextSend.Text = ""
strRec = ""
Shape3.BackColor = &HFF&
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
Case "z1"
Timer3.Enabled = False
TextSend.Text = ""
strRec = ""
Shape4.BackColor = &HFF&
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
End Select
End Select
End Sub
Private Sub StartComm_Click()
Timer2.Enabled = True
End Sub
Private Sub StartTest_Click()
Timer1.Enabled = True
End Sub
Private Sub StopComm_Click()
Timer3.Enabled = True
End Sub
Private Sub Timer1_Timer()
MSComm1.Output = TextSend.Text
TextSend.Text = "s"
MSComm1.OutBufferCount = 0
End Sub
Private Sub Timer2_Timer()
MSComm1.Output = TextSend.Text
TextSend.Text = "h"
MSComm1.OutBufferCount = 0
End Sub
Private Sub Timer3_Timer()
MSComm1.Output = TextSend.Text
TextSend.Text = "z"
MSComm1.OutBufferCount = 0
End Sub
[解决办法]