电工技术基础_电工基础知识_电工之家-电工学习网

欢迎来到电工学习网!

VB2005中SerialPort源代码

2017-11-13 12:31分类:电子技术 阅读:

 

VB2005中SerialPort源代码
示例代码功用有:查找悉数串口,查找可用串口,串口翻开与封闭,字符串发送,字符串接联接纳。发送接纳用的是同一串口,查验时端接串口2、3脚即可。接联接纳时无法直接闪现收到字符(触及到跨线程疑问),用了个守时器守时改写闪现收到的字符串。
程序界面:

程序代码:
Imports System
Imports System.IO.Ports '运用SerialPort所引证的命名空间
Imports System.Threading '运用Thread所引证的命名空间
Public Class Form1
Dim strRec As String '接纳字符串
Dim strSend As String '发送字符串
Dim intNum As Integer '接纳字节数=字符数+1(vbLf)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ComboBox1.Items.Clear() '清空列表
ComboBox2.Items.Clear()
For Each portName As String In My.Computer.Ports.SerialPortNames
ComboBox1.Items.Add(portName) '闪现悉数串口
Try
SerialPort1.PortName = portName
SerialPort1.Open()
ComboBox2.Items.Add(portName) '闪现可用串口
SerialPort1.Close()
Catch ex As Exception
'MsgBox("可用串口查看" & portName)
End Try
Next
If ComboBox1.Items.Count > 0 Then ComboBox1.SelectedIndex = 0
If ComboBox2.Items.Count > 0 Then
ComboBox2.SelectedIndex = 0
Button2.Enabled = True '有可用串口,能够翻开操作
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If Button2.Text = "翻开串口" Then
SerialPort1.PortName = ComboBox2.Text
If Not SerialPort1.IsOpen Then
SerialPort1.Open()
Button2.Text = "封闭串口"
Button3.Enabled = True '串口翻开,能够发送数据
End If
Else
If SerialPort1.IsOpen Then SerialPort1.Close()
Button2.Text = "翻开串口"
Button3.Enabled = False
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
strSend = TextBox1.Text
SerialPort1.WriteLine(strSend)
End Sub
'接联接纳字符串
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Thread.Sleep(100) '依据字符数量及波特率核算延时
intNum = SerialPort1.BytesToRead
strRec = SerialPort1.ReadLine
End Sub
'封闭程序时封闭串口
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If SerialPort1.IsOpen Then SerialPort1.Close()
End Sub
'守时更新闪现接纳字符串
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
TextBox2.Text = strRec
TextBox3.Text = intNum
End Sub
End Class

上一篇:飞思卡尔单片机需求留神的引脚阐明

下一篇:无线话筒频率根底知识

相关推荐

电工推荐

    电工技术基础_电工基础知识_电工之家-电工学习网
返回顶部