VB.NET串口通讯

VB.NET串口通讯,第1张

概述Mitsubishi公司的FX2N系列PLC与计算机之间的串口通讯,参考代码如下   mports System.IO.PortsPublic Class Form1 '使用WithEvents关键字声明一个通信端口对象 Dim WithEvents RS232 As SerialPort '初始化取得计算机中存在的可用串行通讯端口 Sub initializin


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

mports System.IO.PortsPublic 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 SubEnd Class
总结

以上是内存溢出为你收集整理的VB.NET串口通讯全部内容,希望文章能够帮你解决VB.NET串口通讯所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1285301.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存