文件名称:串口通信——txt
文件大小:3KB
文件格式:TXT
更新时间:2018-08-12 13:57:34
串口
Imports System Imports System.IO.Ports Public Class Form1 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) Next ComboBox1.Text = ComboBox1.Items(0) ComboBox2.Items.Add(1200) ComboBox2.Items.Add(4800) ComboBox2.Items.Add(9600) ComboBox2.Text = ComboBox2.Items(2) Serial_Port1() TextBox2.Text = SerialPort1.IsOpen TextBox1.Text = "串口未连接" TextBox1.ForeColor = Color.Red TextBox3.Text = "123" CheckBox1.Text = "" End Sub Private Sub Serial_Port1() SerialPort1.BaudRate = ComboBox2.Text SerialPort1.PortName = ComboBox1.Text SerialPort1.DataBits = 8 SerialPort1.StopBits = IO.Ports.StopBits.One SerialPort1.Parity = IO.Ports.Parity.None End Sub '关闭串口连接 Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try SerialPort1.Close() TextBox2.Text = SerialPort1.IsOpen If SerialPort1.IsOpen = False Then TextBox1.Text = "串口未连接" TextBox1.ForeColor = Color.Red TextBox4.Text = "" 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 Try SerialPort1.Open() TextBox2.Text = SerialPort1.IsOpen If SerialPort1.IsOpen = True Then TextBox1.Text = "串口已连接" TextBox1.ForeColor = Color.Green End If Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Try SerialPort1.Write(TextBox3.Text) Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub Public Sub Sp_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived Me.Invoke(New EventHandler(AddressOf Sp_DataReceiving)) End Sub Public Sub Sp_DataReceiving(ByVal sender As Object, ByVal e As EventArgs) Dim strIncoming As String Try CheckBox1.Text = Str(Val(CheckBox1.Text) + SerialPort1.BytesToRead) If SerialPort1.BytesToRead > 0 Then Threading.Thread.Sleep(100) strIncoming = SerialPort1.ReadExisting.ToString SerialPort1.DiscardInBuffer() TextBox4.Text = strIncoming End If Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub End Class