Imports System.IO.Ports
Imports System.Text
Public Class Form1
Dim WithEvents Rs232 As SerialPort
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each a As String In SerialPort.GetPortNames()
CmbCom.Items.Add(a)
Next
CmbCom.SelectedIndex = 0
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim mPortName As String
Dim mBuandBit As Integer
Dim mDataBit As Integer
Dim mStopBit As IO.Ports.StopBits
Dim mParityBit As IO.Ports.Parity
mPortName = CmbCom.SelectedItem.ToString
mBuandBit = 9600
mDataBit = 8
mStopBit = StopBits.One
mParityBit = Parity.None
Rs232 = New SerialPort(mPortName, mBuandBit, mParityBit, mDataBit, mStopBit)
If Not Rs232.IsOpen Then
Rs232.Open()
btnSend.Enabled = True
Timer1.Interval = 100
Timer1.Enabled = True
MsgBox("~~通讯端口打开成功!~~", MsgBoxStyle.OkCancel)
Else
MsgBox("~~通讯端口打开失败(通讯端口已打开)~~", MsgBoxStyle.OkCancel)
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As 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
txtReceive.Text += bData.ToString & vbCrLf
Next
End If
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
If Rs232 Is Nothing OrElse Not Rs232.IsOpen Then
MsgBox("~~通讯端口尚未打开~~", MsgBoxStyle.Critical Or MsgBoxStyle.OkCancel)
Else
btnSend.Enabled = False
Timer1.Enabled = False
Rs232.Close()
End If
End Sub
Private Sub btnEnd_Click(sender As Object, e As EventArgs) Handles btnEnd.Click
If Not Rs232 Is Nothing Then
If Rs232.IsOpen Then Rs232.Close()
End If
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
Dim bDataOut(0) As Byte
Try
bDataOut(0) = CType(txtSend.Text, Byte) '文本中输入0-255的数字
Rs232.Write(bDataOut, 0, 1)
Catch ex As Exception
MsgBox(ex.Message.ToString(), MsgBoxStyle.OkCancel)
End Try
End Sub
End Class
学习VB.net串口发送与接收(二)
最新推荐文章于 2021-09-06 10:38:09 发布