|  最新新闻>>本站新闻 字体大小:- +  打印
串口通讯示例
www.dgzdh.com 2004-05-21  东莞市拓创自动化工程公司


在工业控制应用中和现场的通讯是一个比较重要的课题,他的成功与否直接关系到了监控软件的生死,因此,讨论串口通讯的文章比比皆是,本文就串口通讯控件MScomm举一个小程序的例子来加以说明,对于这个控件的属性、方法和事件本文不作进一步的说明,有兴趣的网友可以查阅有关文章。 这个程序在两台计算机上运行可以作为聊天室使用,计算机的连接为(九针串口) 
2<------>3                          3<-------->2
5<-------->5  
   找一条普通的三芯电缆就可以。在工业现场中,当这条线路良好屏蔽时,传输距离可以达到100多米,而不是通常的15米。程序代码如下:
Option Explicit

Private Sub cmdclare_Click()
txtsend.Text = ""
txtreceive.Text = ""
End Sub

Private Sub cmdexit_Click()
MSComm1.PortOpen = False
Close #1
Unload Me

End Sub

Private Sub cmdopen_Click()
Dim s As String
Open "d:\comdata.txt" For Input As #1
Do Until EOF(1)
Line Input #1, s
txtreceive.Text = txtreceive.Text + s
Loop
Close #1
End Sub

Private Sub cmdsend_Click()
Call send
End Sub

Private Sub com1_Click()
MSComm1.PortOpen = False
MSComm1.CommPort = 1
MSComm1.PortOpen = True

End Sub

Private Sub com2_Click()
MSComm1.PortOpen = False
MSComm1.CommPort = 2
MSComm1.PortOpen = True

End Sub

Private Sub Form_Load()
Dim timestart As Data
MSComm1.PortOpen = True
Left = (Screen.Width - Width) / 2
Top = (Screen.Height - Height) / 2
End Sub
'必须将MScomm控件的属性RThreshold和SThreshold都设置为非零值,比如1,onComm事件才会被激发,这是关键。
Private Sub MSComm1_OnComm()
Dim st, inbuf As String * 1000
Dim my As Variant
my = inbuf
If MSComm1.CommEvent = 2 Then
If MSComm1.InBufferCount >= 4 Then
MSComm1.InputLen = 0
my = MSComm1.Input
txtreceive.Text = txtreceive.Text + my
End If
End If

End Sub

Private Sub send()
Dim outbuf As String * 1000
outbuf = txtsend.Text
MSComm1.Output = outbuf
Open "d:\comdata.txt" For Append As #1
Write #1, txtsend.Text, txtreceive.Text
Close #1
End Sub

Private Sub txtsend_KeyPress(KeyAscii As Integer)
If KeyAscii = vbKeyReturn Then
Call send
End If
End Sub