在VB.net中的代码中创建串行端口

时间:2008-12-01 02:25:48

标签: vb.net visual-studio serial-port

我正在尝试仅使用代码在VB.net中创建一个串口。因为我正在创建一个类库,所以我无法使用内置组件。我试过实例化一个新的SeialPort()对象,但这似乎还不够。我确信有一些简单的我想念,任何帮助将不胜感激!谢谢!

P.S。我应该补充一点,我此时遇到的问题是获取代码来处理datareceived事件。除此之外,它可能正在起作用,但由于这个问题我无法分辨。

4 个答案:

答案 0 :(得分:7)

如果要使用事件,请确保使用'withevents'声明serialPort对象。下面的示例将允许您连接到串行端口,并将使用接收的字符串引发事件。

Imports System.Threading

Imports System.IO

Imports System.Text

Imports System.IO.Ports


Public Class clsBarcodeScanner

Public Event ScanDataRecieved(ByVal data As String)
WithEvents comPort As SerialPort

Public Sub Connect()
    Try
        comPort = My.Computer.Ports.OpenSerialPort("COM5", 9600)
    Catch
    End Try
End Sub

Public Sub Disconnect()

    If comPort IsNot Nothing AndAlso comPort.IsOpen Then
        comPort.Close()
    End If

End Sub

Private Sub comPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles comPort.DataReceived
    Dim str As String = ""
    If e.EventType = SerialData.Chars Then
        Do
            Dim bytecount As Integer = comPort.BytesToRead

            If bytecount = 0 Then
                Exit Do
            End If
            Dim byteBuffer(bytecount) As Byte


            comPort.Read(byteBuffer, 0, bytecount)
            str = str & System.Text.Encoding.ASCII.GetString(byteBuffer, 0, 1)

        Loop
    End If

    RaiseEvent ScanDataRecieved(str)

End Sub
End Class

答案 1 :(得分:2)

我发现this article非常好。

我写的代码是:

port = new System.IO.Ports.SerialPort(name, 4800, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
port.Open();

void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    buffer = port.ReadLine();
    // process line
}

对不起,这是C#,但......

我遇到的唯一问题是,如果端口在打开时被丢弃,应用程序似乎在退出时失败。

答案 2 :(得分:1)

谢谢大家的帮助,尤其是关于使用WithEvents关键字实例化类的答案。

我发现了一篇非常好的文章,解释了如何为串口创建管理器类。它还讨论了将二进制数据和十六进制数据发送到串行端口。这非常有帮助。

http://www.dreamincode.net/forums/showtopic37361.htm

答案 3 :(得分:0)

我在过去的项目中使用过SerialPort .Net类,我工作得很好。你真的不需要别的。检查控制面板中的硬件设置,并确保使用相同的参数实例化类。

相关问题