在使用VB.NET作为开发语言的时候,在针对串口进行操作的时候,可以考虑使用微软提供的官方接口SerialPort进行开发。首先是导入相关头文件。
Imports System.IO.Ports
之后定义相关串口操作对象,并对其先关参数进行设定。笔者此处设置均是读取配置txt,而对其使用字符串进行设置也是可以的。
Public WithEvents spone As New SerialPort '串口操作对象
Public Sub Serial_Portpara() '设置串口参数 配置文本文件
Dim lines As String()
lines = IO.File.ReadAllLines("./config.txt")
spone.BaudRate = Val(Mid(lines(0), 10, lines(0).Length - 8)) '波特率
spone.PortName = Mid(mechinelistbox.Text, mechinelistbox.Text.Length - 4, 4) '串口名称
spone.DataBits = Mid(lines(1), 10, lines(1).Length - 8) '数据位
spone.StopBits = Mid(lines(2), 10, lines(2).Length - 8) '停止位
spone.Parity = Mid(lines(3), 8, lines(3).Length - 7) '校验位
spone.DtrEnable = Mid(lines(4), 11, lines(4).Length - 9)
spone.RtsEnable = Mid(lines(5), 11, lines