-
VB.NET串口通信例子
Form2.vb
001.
Imports
System
002.
Imports
System.Collections.Generic
003.
Imports
System.ComponentModel
004.
Imports
System.Data
005.
Imports
System.Drawing
006.
Imports
System.Linq
007.
Imports
System.Text
008.
Imports
System.IO.Ports
009.
Imports
System.Text.RegularExpressions
010.
011.
012.
Public
Class
Form1
013.
014.
WithEvents
Comm
As
SerialPort =
New
SerialPort
015.
Private
Builder
As
StringBuilder =
New
StringBuilder
'避免在事件处理方法中反复的创建,所以定义到外面
016.
Private
ReceiveCount
As
Long
= 0
'接收计数
017.
Private
SendCount
As
Long
= 0
'发送计数
018.
019.
Private
Listening
As
Boolean
=
False
'是否没有执行完invoke相关操作
020.
Private
Closingg
As
Boolean
=
False
'是否正在关闭串口,执行Application.DoEvents,并阻止再次invoke
021.
022.
Public
Delegate
Sub
UpdateData(
ByVal
mByte()
As
Byte
)
023.
024.
Public
Sub
ShowData(
ByVal
mByte()
As
Byte
)
025.
Console.WriteLine(mByte)
026.
ReceiveCount += mByte.Length
027.
Builder.Clear()
028.
029.
If
CheckBoxHex.Checked
Then
030.
For
Each
b
As
Byte
In
mByte
031.
Builder.Append(b.ToString(
"X2"
) +
" "
)
032.
Next
033.
034.
Else
035.
036.
Builder.Append(Encoding.ASCII.GetString(mByte))
037.
038.
End
If
039.
TxtGet.AppendText(Builder.ToString)
040.
labelGetCount.Text =
"Get:"
+ ReceiveCount.ToString
041.
End
Sub
042.
043.
Private
Sub
Form1_Load(sender
As
System.
Object
, e
As
System.EventArgs)
Handles
MyBase
.Load
044.
045.
'初始化下拉串口名称列表框
046.
Dim
Ports()
As
String
= SerialPort.GetPortNames
047.
Array.Sort(Ports)
048.
ComboPortName.Items.AddRange(Ports)
049.
ComboPortName.SelectedIndex = IIf(ComboPortName.Items.Count > 0, 0, -1)
050.
ComboBaudrate.SelectedIndex = ComboBaudrate.Items.IndexOf(
"9600"
)
051.
'初始化Serialport对象
052.
Comm.NewLine = vbCrLf
053.
Comm.RtsEnable =
True
054.
055.
'AddHandler Obj.Ev_Event, AddressOf EventHandler
056.
'RemoveHandler Obj.Ev_Event, AddressOf EventHandler
057.
'AddHandler Comm.DataReceived, AddressOf Comm_DataReceived
058.
059.
End
Sub
060.
061.
Private
Sub
Comm_DataReceived(sender
As
Object
, e
As
System.IO.Ports.SerialDataReceivedEventArgs)
Handles
Comm.DataReceived
062.
If
Closingg
Then
Return
'如果正在关闭,忽略操作,直接返回,尽快的完成串口监听线程的一次循环
063.
064.
Try
065.
Listening =
True
'设置标记,说明我已经开始处理数据,一会儿要使用系统UI的。
066.
Dim
n
As
Long
= Comm.BytesToRead
'先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致
067.
Dim
Buf(n - 1)
As
Byte
'声明一个临时数组存储当前来的串口数据
068.
069.
Comm.Read(Buf, 0, n)
'读取缓冲数据
070.
Builder.Clear()
'清除字符串构造器的内容
071.
072.
Dim
b
As
UpdateData =
New
UpdateData(
AddressOf
ShowData)
073.
Me
.BeginInvoke(b, Buf)
074.
075.
Catch
ex
As
Exception
076.
Err.Clear()
077.
Finally
078.
Listening =
False
'我用完了,ui可以关闭串口了。
079.
End
Try
080.
End
Sub
081.
082.
Private
Sub
ShowMsg(
ByVal
buffer()
As
Byte
)
083.
If
CheckBoxHex.Checked
Then
084.
For
Each
b
As
Byte
In
Buffer
085.
Builder.Append(b.ToString(
"X2"
) +
" "
)
086.
Next
087.
Else
088.
Builder.Append(Encoding.ASCII.GetString(buffer))
089.
End
If
090.
Me
.TxtGet.AppendText(Builder.ToString())
091.
labelGetCount.Text =
"Get:"
+ ReceiveCount.ToString
092.
End
Sub
093.
094.
Private
Sub
BtnXOpen_Click(sender
As
System.
Object
, e
As
System.EventArgs)
Handles
BtnXOpen.Click
095.
'根据当前串口对象,来判断操作
096.
If
Comm.IsOpen
Then
097.
Closingg =
True
'
098.
While
Listening
099.
Application.DoEvents()
100.
End
While
101.
'打开时点击,则关闭串口
102.
Comm.Close()
103.
Closingg =
False
104.
Else
105.
Comm.PortName = ComboPortName.Text
106.
Comm.BaudRate =
Integer
.Parse(ComboBaudrate.Text)
107.
Try
108.
Comm.Open()
109.
Catch
ex
As
Exception
110.
'捕获到异常信息,创建一个新的comm对象,之前的不能用了。
111.
Comm =
New
SerialPort
112.
'现实异常信息给客户。
113.
MessageBox.Show(ex.Message)
114.
End
Try
115.
End
If
116.
117.
'设置按钮的状态
118.
BtnXOpen.Text = IIf(Comm.IsOpen,
"Close"
,
"Open"
)
119.
BtnXOpen.Enabled = Comm.IsOpen
120.
121.
End
Sub
122.
123.
'动态的修改获取文本框是否支持自动换行。
124.
Private
Sub
CheckBoxNewLineGet_CheckedChanged(sender
As
System.
Object
, e
As
System.EventArgs)
Handles
CheckBoxNewLineGet.CheckedChanged
125.
TxtGet.WordWrap = CheckBoxNewLineGet.Checked
126.
End
Sub
127.
128.
Private
Sub
BtnXSend_Click(sender
As
System.
Object
, e
As
System.EventArgs)
Handles
BtnXSend.Click
129.
Dim
n
As
Integer
= 0
'定义一个变量,记录发送了几个字节
130.
If
checkBoxHexSend.Checked
Then
'16进制发送
131.
'我们不管规则了。如果写错了一些,我们允许的,只用正则得到有效的十六进制数
132.
Dim
Mc
As
MatchCollection = Regex.Matches(TxtSend.Text.Trim,
"(?i)[/da-f]{2}"
)
'"(?i)[/da-f]{2}"
133.
Dim
buf
As
List(Of
Byte
) =
New
List(Of
Byte
)
134.
135.
'依次添加到列表中
136.
For
Each
m
As
Match
In
Mc
137.
' buf.Add(Byte.Parse(m.Value))
138.
buf.Add(
Byte
.Parse(m.Value, System.Globalization.NumberStyles.HexNumber))
139.
Next
140.
141.
'转换列表为数组后发送
142.
Comm.Write(buf.ToArray, 0, buf.Count)
143.
n = buf.Count
144.
Else
'ascii编码直接发送
145.
'包含换行符
146.
If
checkBoxNewlineSend.Checked
Then
147.
Comm.WriteLine(TxtSend.Text)
148.
n = TxtSend.Text.Length + 2
149.
Else
150.
Comm.Write(TxtSend.Text)
151.
n = TxtSend.Text.Length
152.
End
If
153.
End
If
154.
155.
SendCount += n
'累加发送字节数
156.
labelSendCount.Text =
"Send:"
+ SendCount.ToString
157.
End
Sub
158.
159.
Private
Sub
BtnXReset_Click(sender
As
System.
Object
, e
As
System.EventArgs)
Handles
BtnXReset.Click
160.
161.
'复位接受和发送的字节数计数器并更新界面。
162.
SendCount = 0
163.
ReceiveCount = 0
164.
labelGetCount.Text =
"Get:0"
165.
labelSendCount.Text =
"Send:0"
166.
Builder.Clear()
167.
168.
End
Sub
169.
170.
Private
Sub
BtxClear_Click(sender
As
System.
Object
, e
As
System.EventArgs)
Handles
BtxClear.Click
171.
TxtGet.Text =
""
172.
Builder.Clear()
173.
End
Sub
174.
End
Class
栏目列表
最新更新
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.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式