热度 7
2014-8-26 10:22
1017 次阅读|
0 个评论
VB串口通信学习 一直想学习好上位 机软件开发,之前对VB有了解所以又道选VB来学习串口通信,主要是对MSCOMM控件的使用。 要先在部件里添加:Microsoft comm control6.0 MSComm1.InputMode:以字符传输还是二进制数据 MSComm1.CommPort串口号 MSComm1.PortOpen设置为1为打开,也可以查询此属性 Rthreshold:设置当有多少个字符可以触发oncommon事件 inputlen:每次接收多少个字符。0为读走接收缓存所有字符 ‘’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ Private Sub Form_Load() On Error GoTo ErrLine Dim i As Integer Dim count As Integer Form1.AutoRedraw = True Form1.KeyPreview = True Form1.BorderStyle = 2 'Me.MaxButton = False 'Me.MinButton = True 'Form1.ControlBox = False Timer1.Interval = 1000 cmd1.Visible = True CmdClose.Value = False 'add aviliable port to cmb MessageCount = 0 MSComm1.InputMode = comInputModeText For i = 1 To 16 ' 检查所有可以打开的串口,然后加到列表框中供选择 MSComm1.CommPort = i '注意如果再给 commport设置打开的串口就会报错,而不是portopen=ture时才报错 MSComm1.PortOpen = True If MSComm1.PortOpen = True Then MSComm1.PortOpen = False cmb1.AddItem "COM" + CStr(i), count count = count + 1 End If Next i cmb1.ListIndex = 0 Exit Sub ErrLine: If Err.Number = 8005 Then 'if error: port already opened cmb1.AddItem "COM" + CStr(i), count count = count + 1 End If Resume Next End Sub ‘’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ Select Case MSComm1.CommEvent Case comEvReceive S = (MSComm1.Input) 'MSComm1.InBufferCount = 0 '要克服一次接收固定的长字节出现一次接收不完的问题, '如果第二次oncommon事件产产时与上一次时间间隔大于0.1秒,认为是一个新的信息 '把一条完整的信息放在第三方变量里,然后在TIMER1中断里取走整条信息 If Timer - T 0.1 Then TextTemp = "" N = 0 End If T = Timer ' S = (MSComm1.Input) TextTemp.Text = (TextTemp.Text (S)) End Select End Sub ‘’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ Private Sub Timer1_Timer() 'timer1 ‘在oncommon事件没产生时即没有接收事件时把之前接收到的完整长数据取走 Dim InString As String Dim A As Integer Dim DateNow As String Dim TimeNow As String DateNow = Format(Now, "yyyymmdd") TimeNow = Format(Now, "hh:mm:ss") Dim temp As Integer 'If MSComm1.InBufferCount Then 'While MSComm1.CommEvent = 2 ' wait 'Call delayms(3000) 'Wend MSComm1.CommEvent comEvReceive Len(TextTemp.Text) = 1 If ((MSComm1.InBufferCount = 0) And (Len(TextTemp.Text) = 1)) Then InString = TextTemp.Text " " TimeNow " " DateNow TextTemp.Text = "" If Len(InString) 20 Then 'if more than 20 character ,inset /n End If List1.AddItem InString, 0 List1.ListIndex = 0 'set cursor to index 0 MessageCount = MessageCount + 1 If MessageCount = 20 Then MessageCount = 0 End If If List1.ListCount = 20 Then List1.RemoveItem 19 End If End If End Sub