Creating a serial port in VB.net code

I am trying to create a serial port in VB.net using only code. Since I am creating a class library, I cannot use the built-in component. I tried to instantiate a new SeialPort () object, but that doesn't seem to be enough. I am sure that there is something simple that I went missing and any help would be greatly appreciated! Thank you

PS I have to add that the problem that I am facing at the moment is that the code is processing data obtained using data. Other than that, it can work, but I can’t say because of this problem.

+6
visual-studio serial-port
source share
4 answers

If you want to use events, make sure you declare your serialPort object using "withevents". In the example below, you can connect to the serial port and raise an event with an accepted string.

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 
+7
source share

I found this article to be nice.

The code I wrote from it:

 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 } 

Sorry C #, but ...

The only problem I encountered is that when you remove the port when opening it, the application seems to fail on exit.

+2
source share

Thanks to everyone for your help, especially the answer to the question of creating an instance of the class using the WithEvents keyword.

I found a really wonderful article that explains how to create a manager class for a serial port. It also discusses sending binary as well as hexadecimal data to the serial port. It was very helpful.

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

+1
source share

I used the SerialPort.Net class in a previous project, and I worked fine. You really don't need anything. Check the hardware configuration in the control panel and make sure that you instantiate the class with the same parameters.

0
source share

All Articles