使用VB.Net进行串口通信(端口不显示)

时间:2012-08-15 10:00:23

标签: vb.net winforms serial-port

首先,我不擅长编程,我试图在我的代码中尽可能地解释。我一直在尝试编写一个程序,使用户能够使用简单的定制IR调制解调器通过串行端口聊天(接收和发送)消息。我构建了调制解调器,现在尝试编写自己的简单程序,而不是使用终端或其他已编写的程序(即Tera Term)。顺便说一下,我使用的是Windows 7并使用Microsoft Visual Express 2010环境

我根据本网站的教程编写了以下代码。 (把它放在这里以防万一) MSDN on Serial Port

问题(截至目前) 组合框cmbComPort似乎没有捕获我的计算机上的任何可用端口。我怀疑可能没有!所以我查了一下,这就是我找到的。基于此,我假设我的计算机上有一个串口,因此这不是问题的根源(让我知道,否则,因为我不太确定)。我运行调试并弹出一条错误消息。然后我构建程序来测试它。这两条错误消息都附在

下面

问题  1.似乎下面的代码没有捕获可用的端口并将它们存储在myPort数组中。

'procedure to detect all available ports and store them in the myPort array
    For Each port_name As String In IO.Ports.SerialPort.GetPortNames
        Dim myPort As New IO.Ports.SerialPort(port_name)
        If myPort.IsOpen = True Then
            cmbComPort.Items.Add(port_name)
        End If
    Next

我想知道端口本身是否存在问题并且未被检测到。但是,使用下面的代码,我能够确认COM1存在并正常工作。

Imports System
Imports System.IO.Ports

Module SerialPortExample

Sub Main()
' Get a list of serial port names. 
Dim ports As String() = SerialPort.GetPortNames()

Console.WriteLine("The following serial ports were found:")

' Display each port name to the console. 
Dim port As String 
For Each port In ports
    Console.WriteLine(port)
Next port

Console.ReadLine()

End Sub 
End Module

这是控制台输出的内容 -

找到以下串口:COM1

所以,港口就在那里。这部分代码可能存在问题(我还不完全确定)?

'procedure to detect all available ports and store them in the myPort array
For Each port_name As String In IO.Ports.SerialPort.GetPortNames
    Dim myPort As New IO.Ports.SerialPort(port_name)
    cmbComPort.Items.Add(port_name)
Next

无论如何我可以在这一行之后查看myPort数组的内容吗?以及cmbComPort的项目?

还有一件事,这是一个接受任何额外功能的项目(编写我自己的程序绝对是其中之一)。如果你们可以放弃任何关于功能的想法,无论是与串口通信还是程序接口本身有关,我都会感激不尽。我可以想到一些,比如保存聊天文件,加载聊天文件,帮助/教程文件 - 一旦我发现上述错误,所有这些都将被实现。而且,我在想​​,无论如何我可以画一个'泡泡聊天'来显示对话而不是纯文本框?那会很好。

提前致谢! :d Project files

CODES:

'Chatty Raffy Version 1.3
'This is a simple program to demonstrate Serial Ports communication via a simple custom made IR Modem. 

Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports

Public Class frmMain

Dim myPort As Array  'an array to store list of available ports

Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiveing of data

Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)

    'Fill up the cmbBaudRate Combo box to common baud rates used
    cmbBaudRate.Items.Add(9600)
    cmbBaudRate.Items.Add(19200)
    cmbBaudRate.Items.Add(38400)
    cmbBaudRate.Items.Add(57600)
    cmbBaudRate.Items.Add(115200)

    'procedure to detect all available ports and store them in the myPort array
    For Each port_name As String In IO.Ports.SerialPort.GetPortNames
        Dim myPort As New IO.Ports.SerialPort(port_name)
        If myPort.IsOpen = True Then
            cmbComPort.Items.Add(port_name)
        End If
    Next

    'initiate the combo boxes
    cmbComPort.SelectedIndex = 0  'set cmbComPort text to the first COM port detected
    cmbBaudRate.SelectedIndex = 0    'set cmbBaudRate text to the first Baud rate on the list
    cmbParity.SelectedIndex = 0    'set cmbParity text to the first Baud rate on the list
    cmbStopBit.SelectedIndex = 0    'set cmbStopBit text to the first Baud rate on the list

    'btnDisconnect.Enabled = False   'disable the disconnect button

End Sub

'open the selected serial port and start the connection
Private Sub btnConnect_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
    SerialPort1.PortName = cmbComPort.Text      'set Serial Port to the selected COM port 
    SerialPort1.BaudRate = cmbBaudRate.Text      'set Baud rate to the selected value Baud rate
    SerialPort1.Parity = cmbParity.Text     'set parity setting to the selected value 
    SerialPort1.StopBits = cmbStopBit.Text  'set stop bit setting to the selected value

    SerialPort1.DataBits = 8    'use the default 8 bit for data bit length

    SerialPort1.Open()      'open the chosen serial port

    btnConnect.Enabled = False      'disable the Connect button
    btnDisconnect.Enabled = True    'enable the Disconnect button
    picboxDisconnect.Visible = False 'disable the disconnect picture
    picboxConnect.Visible = True 'enable the disconnect picture
End Sub


'close the serial port currently in used, hence closing the connection
Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
    SerialPort1.Close()     'close the used Serial Port

    btnConnect.Enabled = True  'esable the Connect button
    btnDisconnect.Enabled = False  'disable the Disconnect button
    picboxDisconnect.Visible = True 'enable the 'disconnect' picture
    picboxConnect.Visible = False 'disable the 'connect' picture
End Sub

'send the text contained in the txtText to the serial port in ASCII using the 'SEND' key
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    SerialPort1.Write(txtTransmit.Text & vbCr)
End Sub


'detect data at the serial port and call ReceivedText automatically 
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
    ReceivedText(SerialPort1.ReadExisting())
End Sub


'read incoming messages at serial port once data is detected
Private Sub ReceivedText(ByVal [text] As String)
    'compare the ID of the Creating Thread to the ID of the Calling Thread
    If Me.rtbReceived.InvokeRequired Then
        Dim x As New SetTextCallback(AddressOf ReceivedText)
        Me.Invoke(x, New Object() {(text)})
    Else
        Me.rtbReceived.Text &= [text]
    End If
End Sub



'this section prevents user from making any changes to the current connection without disconnecting

Private Sub cmbComPort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    If SerialPort1.IsOpen = False Then
        SerialPort1.PortName = cmbComPort.Text
    Else
        'pop an error message if user try to change port without closing the current port in use
        MsgBox("Please close the currently used port before making any changes to the connection setting", vbCritical)
    End If
End Sub


Private Sub cmbBaudRate_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBaudRate.SelectedIndexChanged
    If SerialPort1.IsOpen = False Then
        SerialPort1.BaudRate = cmbBaudRate.Text
    Else
        'pop an error message if user try to change Baud rate without closing the current port in use
        MsgBox("Please close the currently used port before making any changes to the connection setting", vbCritical)
    End If
End Sub

Private Sub cmbParity_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBaudRate.SelectedIndexChanged
    If SerialPort1.IsOpen = False Then
        SerialPort1.Parity = cmbParity.Text
    Else
        'pop an error message if user try to change Baud rate without closing the current port in use
        MsgBox("Please close the currently used port before making any changes to the connection setting", vbCritical)
    End If
End Sub

Private Sub cmbStopBit_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBaudRate.SelectedIndexChanged
    If SerialPort1.IsOpen = False Then
        SerialPort1.StopBits = cmbStopBit.Text
    Else
        'pop an error message if user try to change Baud rate without closing the current port in use
        MsgBox("Please close the currently used port before making any changes to the connection setting", vbCritical)
    End If
End Sub

End Class

1 个答案:

答案 0 :(得分:-1)

好吧,我确实误解了一个港口之前的“开放”或“关闭”意味着什么,并且被我的朋友指出。从那时起,我将这部分代码修复为

    'procedure to detect all available ports and store them in the myPort array
    For Each port_name As String In IO.Ports.SerialPort.GetPortNames
    Dim myPort As New IO.Ports.SerialPort(port_name)
        cmbComPort.Items.Add(port_name)
    Next

@hans:实际上电路已经在实验室的计算机上使用终端IR调制解调器(随Windows一起使用)。我已经确认使用这些代码,事实上,串口确实退出并正常工作

Imports System
Imports System.IO.Ports

Module SerialPortExample

Sub Main()
    ' Get a list of serial port names. 
    Dim ports As String() = SerialPort.GetPortNames()

    Console.WriteLine("The following serial ports were found:")

    ' Display each port name to the console. 
    Dim port As String 
    For Each port In ports
        Console.WriteLine(port)
    Next port

    Console.ReadLine()

End Sub 
End Module

这是控制台输出的内容 -

找到以下串口: COM1

所以,港口就在那里。这部分代码可能存在问题(我还不完全确定)?

'procedure to detect all available ports and store them in the myPort array
    For Each port_name As String In IO.Ports.SerialPort.GetPortNames
        Dim myPort As New IO.Ports.SerialPort(port_name)
        cmbComPort.Items.Add(port_name)
    Next

无论如何我可以在这一行之后查看myPort数组的内容吗? 以及cmbComPort的项目?