Imports System.IO.Ports
Public Class Form1
Public WithEvents SerialPort As New SerialPort Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ports As String() = SerialPort.GetPortNames() Dim port As String
For Each port In ports ComboBox1.Items.Add(port)
'If Then‘测试过程返回bolean ' '这里就是最后的端口 ' '把可用串口的名字添加到列表中 'End If
Next port ' ComboBox1.SelectedIndex = 0 End Sub '串口配置
Private Sub Serial_Port1() '设置串口参数 SerialPort1.BaudRate = 57600 '波特率 SerialPort1.DataBits = 8 '数据位 SerialPort1.StopBits = IO.Ports.StopBits.One '停止位 SerialPort1.Parity = IO.Ports.Parity.None '校验位
End Sub '关闭串口连接
Private Sub SerialPort_Close()
Try
SerialPort1.Close() '关闭串口
Label3.Text = SerialPort1.IsOpen
If SerialPort1.IsOpen = False Then Label2.Text = "串口未连接" Label2.ForeColor = Color.Red
End If
Catch ex As Exception MessageBox.Show(ex.Message)
End Try
End Sub '打开串口连接
Private Sub SerialPort1_Open()
Try
SerialPort1.Open() '打开串口
If SerialPort1.IsOpen = True Then Label2.Text = "串口已打开" Label2.ForeColor = Color.Green
End If
Catch ex As Exception MessageBox.Show(ex.Message)
End Try End Sub
'接收数据
Private Sub Sp_DataReceived()
Me.Invoke(New EventHandler(AddressOf Sp_Receiving)) '调用接收数据函数
End Sub Private Sub Sp_Receiving(ByVal sender As Object, ByVal e As EventArgs)
Dim strIncoming As String
Try
TextBox2.Text = Str(Val(TextBox2.Text) + SerialPort1.BytesToRead) If SerialPort1.BytesToRead > 0 Then Threading.Thread.Sleep(100) '添加的延时 strIncoming = SerialPort1.ReadExisting.ToString '读取缓冲区中的数据 SerialPort1.DiscardInBuffer()
TextBox2.Text = strIncoming
End If
Catch ex As Exception MessageBox.Show(ex.Message)
End Try End Sub '串口查找
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Serial_Port1()
SerialPort1_Open()
End Sub
Private Sub BtnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSend.Click SerialPort1.Write(TextBox1.Text) Sp_DataReceived()
End Sub
End Class