求助串口程序编写
这几天刚刚接触VB2005,急需做一个串口通信的程序。研究了几天发现问题不少。因为以前只学过c编程。先贴出我做的程序吧。
Imports System
Imports System.IO.Ports
Imports System.Threading
Public Class PortChat
Shared _continue As Boolean
Shared _serialPort As New SerialPort
Public Shared Sub Main()
' Dim name As String
' Dim message As String
Dim sComparer As StringComparer = StringComparer.OrdinalIgnoreCase
' Dim readThread As Thread = New Thread(AddressOf Read)
' Create a new SerialPort object with default settings.
_serialPort = New SerialPort()
' Set the read/write timeouts
_serialPort.ReadTimeout = 500
_serialPort.WriteTimeout = 500
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
ComboBox1.Items.Add(sp)
Next
ComboBox2.Items.Add("9600")
ComboBox2.Items.Add("115200")
ComboBox3.Items.Add("None")
ComboBox3.Items.Add("Odd")
ComboBox3.Items.Add("Even")
ComboBox3.Items.Add("Mark")
ComboBox3.Items.Add("Space")
ComboBox4.Items.Add("5")
ComboBox4.Items.Add("6")
ComboBox4.Items.Add("7")
ComboBox4.Items.Add("8")
ComboBox5.Items.Add("1")
ComboBox5.Items.Add("2")
End Sub
'打开串口
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (ComboBox1.Text <> "") Then
_serialPort.PortName = ComboBox1.Text
Else
_serialPort.PortName = "COM1"
End If
If (ComboBox2.Text <> "") Then
_serialPort.BaudRate = ComboBox2.Text
Else
_serialPort.BaudRate = 9600
End If
Select Case ComboBox3.Text
Case "None"
_serialPort.Parity = 0
Case "Odd"
_serialPort.Parity = 1
Case "Even"
_serialPort.Parity = 2
Case "Mark"
_serialPort.Parity = 3
Case "Space"
_serialPort.Parity = 4
Case Else
_serialPort.Parity = 0
End Select
If (ComboBox4.Text <> "") Then
_serialPort.DataBits = ComboBox4.Text
Else
_serialPort.DataBits = 8
End If
If (ComboBox5.Text <> "") Then
_serialPort.StopBits = ComboBox5.Text
Else
_serialPort.StopBits = 1
End If
If _serialPort.IsOpen Then
TextBox1.Text = "此串口已打开"
Else
_serialPort.Open()
End If
End Sub
'关闭串口
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
_serialPort.Close()
End Sub
End Class
现在简单的实现了打开和关闭串口。但是无法检测已关闭的串口。看资料中说使用If _serialPort.IsOpen Then可以实现,但是我时间测试无论串口是否被打开,_serialPort.IsOpen的返回值都是false,还有就是如何获取异常信息。就像我打了已经打开的串口程序就会死掉。如何获取这样的异常信息并显示出来保证程序不死。 --------------------编程问答-------------------- _serialPort.IsOpen它只能检测到自己打开的串口状态吗?就是我用其他的串口助手打开了COM1,再执行这个程序这里就无法检测到串口是打开的了。返回值仍然是false,如何才能检测到计算机中其他程序打开的串口啊? --------------------编程问答-------------------- 首先判断串口是否打开,然后在设置端口,就不会有问题了
推荐一段代码:
If SerialPort1.IsOpen Then
SerialPort1.Close()
End If
Try
With SerialPort1
.PortName = ComboBox1.Text
.BaudRate = 19200
.DataBits = 8
.Parity = Parity.Odd
.StopBits = StopBits.One
End With
SerialPort1.Open()
Me.messagelab1.Text = ComboBox1.Text & " " & "Connected" & " "
Catch ex As Exception
MsgBox(ex.ToString)
End Try
补充:.NET技术 , VB.NET