-
VB.NET串口通信例子--我的回忆录
Form1.vb
Imports System.IO.Ports
Public Class Form1
Dim WithEvents RS232 As SerialPort
Delegate Sub SetTextCallback(ByVal InputString As String) '声明一个代理
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each sp As String In SerialPort.GetPortNames()
cmbCom.Items.Add(sp)
Next
cmbCom.Sorted = True
cmbCom.SelectedIndex = 0
End Sub
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim mBaudRate As Integer
Dim mParity As IO.Ports.Parity
Dim mDataBit As Integer
Dim mStopBit As IO.Ports.StopBits
Dim mPortName As String
mPortName = cmbCom.SelectedItem.ToString
mBaudRate = 9600
mParity = Parity.None
mDataBit = 8
mStopBit = StopBits.One
RS232 = New IO.Ports.SerialPort(mPortName, mBaudRate, mParity, mDataBit, mStopBit)
If Not RS232.IsOpen Then
RS232.Open()
btnSend.Enabled = True
RS232.ReceivedBytesThreshold = 1 '设置引发事件的门限值
Else
MsgBox("通讯端口打开错误!", MsgBoxStyle.Critical)
End If
End Sub
Private Sub RS232_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles RS232.DataReceived
Dim InByte() As Byte, ReadCount As Integer, strRead As String
If RS232.BytesToRead <= 0 Then Exit Sub
ReDim InByte(RS232.BytesToRead - 1)
ReadCount = RS232.Read(InByte, 0, RS232.BytesToRead)
strRead = ""
If ReadCount = 0 Then
Exit Sub
Else
For Each bData As Byte In InByte
strRead += bData.ToString & vbCrLf '若有数据则加到接收文本框
DisplayText(strRead)
Next
End If
End Sub
'*************************************************
'代理子程序
'处理上述通信端口的接收事件
'由于欲将数据显示到接收文本框中,因此必须检查
'是否由另外得Thread所调用的,若是,则必须先
'建立代理对象
'Invoke用于在拥有控件基础窗口控制代码的线程上
'运行代理
'*************************************************
Private Sub DisplayText(ByVal comData As String)
'如果调用txtReceive的另外的线程,返回true
If Me.txtReceive.InvokeRequired Then
'利用代理类型建立对象,并指定代理的函数
Dim d As New SetTextCallback(AddressOf DisplayText)
Me.Invoke(d, New Object() {comData}) '以指定的自变量列表调用函数
Else '相同的线程
'showstring(comData) '将收到的数据填入接收文本框中
Me.txtReceive.Text += comData
End If
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
If RS232 Is Nothing OrElse Not RS232.IsOpen Then '尚未打开
MsgBox("通讯端口尚未打开", MsgBoxStyle.Critical Or MsgBoxStyle.OkCancel)
Else
RS232.Close()
btnStart.Enabled = False
btnClose.Enabled = False
RS232 = Nothing
End If
End Sub
Private Sub btnEnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnd.Click
If Not RS232 Is Nothing Then
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
Dim bDataOut(0) As Byte
Try
bDataOut(0) = CType(Me.txtSend.Text, Byte) '将类型转换为字节
RS232.Write(bDataOut, 0, 1)
Catch ex As Exception
MessageBox.Show("输入数值错误:" + ex.ToString, "错误通知:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
Private Sub cmbCom_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cmbCom.KeyPress
e.KeyChar = ChrW(0) '禁止用户在其中输入任何文字
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Hide()
Form2.Show()
End Sub
End Class
Form2.vb '************************************************************** '时间:2008-11-08 '作者:lincyang '实际应用中,串行通信的数据可能一次发送大量的数据, '发送之前就必须将数据先编码, '将其编成我们需要的字节数组数据, '才能将这些数据以字节的方式发送出去 '目前操作系统使用的字符数据是Unicode:所有的字符均使用 '两个字节来表示一个字符 '**************************************************************
Imports System.IO.Ports Imports System.Text Public Class Form2 Dim RS232 As SerialPort Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load For Each sp As String In SerialPort.GetPortNames() cmbCom.Items.Add(sp) Next cmbCom.Sorted = True cmbCom.SelectedIndex = 0 End Sub
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim mBaudRate As Integer
Dim mParity As IO.Ports.Parity
Dim mDataBit As Integer
Dim mStopBit As IO.Ports.StopBits
Dim mPortName As String
mPortName = cmbCom.SelectedItem.ToString
mBaudRate = 9600
mParity = Parity.None
mDataBit = 8
mStopBit = StopBits.One
RS232 = New IO.Ports.SerialPort(mPortName, mBaudRate, mParity, mDataBit, mStopBit)
If Not RS232.IsOpen Then
RS232.Open()
btnSend.Enabled = True
Timer1.Interval = 100
Timer1.Enabled = True
Else
MsgBox("通讯端口打开错误!", MsgBoxStyle.Critical)
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim InByte() As Byte, ReadCount As Integer
If RS232.BytesToRead <= 0 Then Exit Sub
ReDim InByte(RS232.BytesToRead - 1)
ReadCount = RS232.Read(InByte, 0, RS232.BytesToRead)
If ReadCount = 0 Then
Exit Sub
Else
For Each bData As Byte In InByte
Me.txtReceive.Text += bData.ToString & vbCrLf '若有数据则加到接收文本框
Next
End If
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
If RS232 Is Nothing OrElse Not RS232.IsOpen Then '尚未打开
MsgBox("通讯端口尚未打开", MsgBoxStyle.Critical Or MsgBoxStyle.OkCancel)
Else
RS232.Close()
btnStart.Enabled = False
btnClose.Enabled = False
Timer1.Enabled = False
RS232 = Nothing
End If
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Dim bDataOut() As Byte, Buf As String
Dim iSentCount As Integer
Dim Encode1 As Encoding = Encoding.ASCII '声明编码对象,使用ASCII
Try
Buf = txtSend.Text.Trim()
bDataOut = Encode1.GetBytes(Buf) '将字符串转换为字节数组
iSentCount = bDataOut.GetLength(0) '发送总字节数
'显示出总字节数
lblSentCount.Text = "总传输量:" & iSentCount.ToString & "字节"
RS232.Write(bDataOut, 0, iSentCount)
Catch ex As Exception
MessageBox.Show("输入数值错误:" + ex.ToString, "错误通知", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
Private Sub btnEnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnd.Click
If Not RS232 Is Nothing Then
If RS232.IsOpen Then RS232.Close()
End If
End
End Sub
Private Sub cmbCom_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cmbCom.KeyPress
e.KeyChar = ChrW(0) '禁止用户在其中输入任何文字
End Sub
End Class
开发环境是VB2008,源码下载 猛击这里!
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式