SerialPort的简单应用

最近做了一个数码相机包装流水线控制的项目,在包装作业的几道工序中,其中有一条工序是重量检查。检查相机重量的工具是电子秤,可以精确到0.01克(NB),通过串口连接到电脑上。

下面代码的功能是,程序向电子秤发送命令"Q",电子秤向程序返回测重数据。

 

 

代码
Private Function OpenSerialPort() As Boolean
'通信端口
Me.SerialPort1.PortName = "COM1"
'波特率
Me.SerialPort1.BaudRate = 2400
'奇偶校验
Me.SerialPort1.Parity = System.IO.Ports.Parity.Even
'数据长度
Me.SerialPort1.DataBits = 7
'停止位
Me.SerialPort1.StopBits = 1
End Function

''' <summary>
''' 从电子秤上获取重量
''' </summary>
Private Function GetWeightFromElectronicDevice() As Boolean
'打开端口
If OpenSerialPort() = False Then
Return False
End If
'获取重量
Me.SerialPort1.WriteLine("Q")
Return True
End Function

''' <summary>   
''' 回调函数  
''' </summary>  
Public Sub DelegateMethod(ByVal content As String)
'设置画面重量
Me.txtWeight.Text = Convert.ToDecimal(content)
'关闭端口
Me.SerialPort1.Close()
End Sub

Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim content As String = Me.SerialPort1.ReadLine
Me.BeginInvoke(New BarcodeDelegate(AddressOf DelegateMethod), content)
End Sub

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2010-09-25 11:10  cnbwang  阅读(504)  评论(0编辑  收藏  举报