-
VB.NET串口通讯
imports 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
栏目列表
最新更新
python爬虫及其可视化
使用python爬取豆瓣电影短评评论内容
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比