-
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
栏目列表
最新更新
求1000阶乘的结果末尾有多少个0
详解MyBatis延迟加载是如何实现的
IDEA 控制台中文乱码4种解决方案
SpringBoot中版本兼容性处理的实现示例
Spring的IOC解决程序耦合的实现
详解Spring多数据源如何切换
Java报错:UnsupportedOperationException in Col
使用Spring Batch实现批处理任务的详细教程
java中怎么将多个音频文件拼接合成一个
SpringBoot整合ES多个精确值查询 terms功能实
数据库审计与智能监控:从日志分析到异
SQL Server 中的数据类型隐式转换问题
SQL Server中T-SQL 数据类型转换详解
sqlserver 数据类型转换小实验
SQL Server数据类型转换方法
SQL Server 2017无法连接到服务器的问题解决
SQLServer地址搜索性能优化
Sql Server查询性能优化之不可小觑的书签查
SQL Server数据库的高性能优化经验总结
SQL SERVER性能优化综述(很好的总结,不要错
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比