Thursday, 18 April 2013

Serial Port In VB.net

                                            Operation On Serial Port 

We use the serial port for communication with the hardware,like parallel port,printer port is the easiest available hardware for communicate with home made hardware devices.Here i explain the how we connect to port in vb.net and illustrate the data transmission.
                                                                Now at this time or new versions laptop,Pc, may have not serial port ,so you can not use this feature with them. Here I also give a small examples for syntax.

Open the serial port present in your computer,it's name was like COM1, COM2, COM3 bydefault .If prot is not present then we have to create a new port-
Dim comPort As SerialPort
       comPort = My.Computer.Ports.OpenSerialPort("COM5", 9600)
Here COM5 is open and 9600 is it's BaudRate, which is present in your system.

Create a  port ,in case if any port not present-
Dim comPort As SerialPort
comPort=New SerialPort("COM##", ...)
This is create a new port with name and other properties.

Write on port with check whether the port is open or not-
    Dim message As String = "hello"
    If comPort.IsOpen Then          
          comPort.WriteLine(message)
          comPort.Close()
     Else
        comPort.Open
        comPort.WriteLine(message)
        comPort.Close()
    End If

Read the data from port-
Dim msg As String = comPort.ReadLine()
            Console.WriteLine(msg) Or
            MsgBox(msg)

Close the serial port-
 comPort.Close()

Here i write the simple program for serial port-
 Imports System.IO.Ports
    Dim name As String 
    Dim message As String 
   
    ' Create a new SerialPort object with default settings.
    comPort = New SerialPort()

    ' Allow the user to set the appropriate properties.
    comPort.PortName = SetPortName(comPort.PortName) Or
    Dim comPort As New SerialPort("COM1")
    comPort.BaudRate = SetPortBaudRate(comPort.BaudRate)
    comPort.Parity = SetPortParity(comPort.Parity)
    comPort.DataBits = SetPortDataBits(comPort.DataBits)
    
    ' Set the read/write timeouts
    comPort.ReadTimeout = 500
    comPort.WriteTimeout = 500

   Dim message As String = "hello"
   Try 
        If comPort.IsOpen Then          
              comPort.WriteLine(message)          
        Else
              comPort.Open
              comPort.WriteLine(message)     
        End If  

       comPort.Close()       
            Catch ex As TimeoutException   
            MsgBox(ex)
            Catch ex1 As IOException       
            MsgBox(ex1)
        End Try 
    
End Sub


No comments:

Post a Comment