VB.NET串口通讯

前端之家收集整理的这篇文章主要介绍了VB.NET串口通讯前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


Mitsubishi公司的FX2N系列PLC与计算机之间的串口通讯,参考代码如下

mports System.IO.Ports
Public Class Form1
    '使用WithEvents关键字声明一个通信端口对象
    Dim WithEvents RS232 As SerialPort
    '初始化取得计算机中存在的可用串行通讯端口
    Sub initializing()
        For Each sp As String In SerialPort.GetPortNames()
            cmbCOM.Items.Add(sp) 'cmbCOM是ComboBox控件,该代码用来取得系统找到的所有串口名称
        Next
        cmbCOM.Sorted = True       '排序
        cmbCOM.SelectedIndex = 0 '第一个是预设选项
    End Sub

    '联机,使用正确的通讯参数建立一个通讯端口对象
    Sub online()
        Try
            RS232 = New IO.Ports.SerialPort(cmbCOM.SelectedItem.ToString,9600,Parity.Even,7,StopBits.Two)
            'RS232.Encoding = System.Text.Encoding.ASCII,如果系统支持中文,可以使用Encoding.Unicode编码方案
            If Not RS232.IsOpen Then RS232.Open()
        Catch ex As Exception
            MsgBox("通讯端口打开错误!" & vbCrLf & "故障信息:" & vbCrLf & ex.Message,MsgBoxStyle.OkCancel)
        End Try
    End Sub

    '离线,关闭通讯端口
    Sub offline()
        Try
            If RS232.IsOpen Then RS232.Close() : RS232 = Nothing '释放资源
        Catch ex As Exception
            MsgBox("通讯端口关闭错误!" & vbCrLf & "故障信息:" & vbCrLf & ex.Message,MsgBoxStyle.OkCancel)
        End Try
    End Sub

    '通讯延时,通讯延时与串口处理数据时的ReadTimeout和WriteTimeout的含义是完全不同的
    Sub TimeDelay(ByVal DT As Integer)
        Dim ET As Integer
        ET = Environment.TickCount()
        Do
            If Environment.TickCount() - ET >= DT Then Exit Do
            Application.DoEvents()  '处理队列中的讯息
        Loop
    End Sub

    '串口数据接收函数
    Function DataReceive() As String
        Dim input As String,strfst As String
        DataReceive = Nothing
        input = RS232.ReadExisting()
        If input <> Nothing Then
            '以下代码用来判断接收的数据起始字符是STX(Chr(2))/ACK(Chr(6)),NAK/(Chr(21))
            strfst = Asc(Microsoft.VisualBasic.Left(input,1)).ToString
            Select Case strfst
                Case "2"
                    If rCheckSum(input) = "OKSUM" Then Return (input)
                    If rCheckSum(input) = "ERSUM" Then Return "ERSUM"
                Case "6"
                    Return Asc(input).ToString
                Case "21"
                    Return Asc(input).ToString
                Case Else
                    Return "ERCOM" '如果所选串口返回的未知数据,说明串口通讯故障/计算机连接到未知设备!
            End Select
        Else
            Return "ERCOM" '如果所选串口没有任何数据返回,说明串口通讯故障/PC Command ERROR!
        End If
    End Function

    '**************************************************************

    Private Sub Form1_Load(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles MyBase.Load
        initializing()
        btnoffline.Enabled = False
        stx.Text = "Chr(2)"
        cmd.Text = "0"
    End Sub

    Private Sub btnonline_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnonline.Click
        online()
        If RS232.IsOpen Then btnonline.Enabled = False
        If RS232.IsOpen Then btnoffline.Enabled = True
    End Sub

    Private Sub btnoffline_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnoffline.Click
        offline()
        btnoffline.Enabled = False
        btnonline.Enabled = True
    End Sub

    Private Sub btnEnd_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnEnd.Click
        If RS232 Is Nothing Then                         '判断是否已建立通信对象
            End
        Else
            If RS232.IsOpen Then RS232.Close() '若已经打开,就将其关闭
        End If
        End
    End Sub
    
    Private Sub btnSend_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnSend.Click
        Try
            If Not RS232 Is Nothing Then '判断是否已建立通信对象
                Dim OutCmd As String
                Dim indat As String
                OutCmd = Nothing
                indat = RS232.ReadExisting() '使用.ReadExisting()方法清空缓冲区
                If cmd.Text.Trim = "0" Then OutCmd = cmd.Text.Trim + address.Text.Trim + byten.Text.Trim + Chr(3)
                If cmd.Text.Trim = "1" Then OutCmd = cmd.Text.Trim + address.Text.Trim + byten.Text.Trim + data.Text.Trim + Chr(3)
                OutCmd = Chr(2) + OutCmd + tCheckSum(OutCmd) '发送命令调用CheckSum函数生成CheckSum字符串
                RS232.Write(OutCmd)
                TimeDelay(300)
                indat = DataReceive()
                If indat = "ERCOM" Or indat = "ERSUM" Then
                    MsgBox("通讯故障!PLC OFFLINE!!!/数据传输错误!!!")
                Else
                    txtResult.Text += OutCmd + "->" + indat + vbCrLf
                    txtResult.SelectionStart = txtResult.TextLength   '将光标自动移至最下一位
                    txtResult.ScrollToCaret()                                      '将光标自动移至最下一位
                End If
            Else
                MsgBox("通信端口尚未打开!",MsgBoxStyle.OkCancel)
            End If
        Catch ex As Exception
            MsgBox("通讯端口发生故障!" & vbCrLf & "故障信息:" & vbCrLf & ex.Message)
        End Try
    End Sub

    '应用程序窗口关闭时的响应事件,如果RS232通讯已建立就将其关闭退出
    Private Sub Form1_FormClosing(ByVal sender As Object,ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If RS232 Is Nothing Then                         '判断是否已建立通信对象
            End
        Else
            If RS232.IsOpen Then RS232.Close() '若已经打开,就将其关闭
        End If
        End
    End Sub

End Class

猜你在找的VB相关文章