Solved

Reading Serial Port with VB.NET 2005

Posted on 2008-06-17
28
2,805 Views
Last Modified: 2012-06-21
Dear Experts,
I am trying to read data from serial port connected to barcode scanner and dispaly it to a text box.
Please help me with a simple code ?
Thanks in advance for your help.
0
Comment
Question by:djoni4343
  • 13
  • 9
  • 4
28 Comments
 
LVL 7

Expert Comment

by:AUmidh
ID: 21810034
0
 

Author Comment

by:djoni4343
ID: 21810089
AUmidh,
Thanks but i am going to use the SerialPort Component instead.
0
 
LVL 7

Expert Comment

by:AUmidh
ID: 21810097
Are you using .Net Serial Port Component ?
0
 
LVL 14

Expert Comment

by:rachitkohli
ID: 21810112
'Drag a serial port control onto your form & write this function in your code window.
Public Function OpenSerialPort() As Boolean
        'Function to Prepare the serial port connection
        Try
            With SerialPort1
                If .IsOpen Then
                    .Close()
                End If

               
                .Parity = Parity.None
                .PortName = "COM1"
                .DataBits = 8
                .StopBits = StopBits.One

                .Encoding = System.Text.UnicodeEncoding.UTF8    'Setting the Encoding Type

                .Open()

                Return .IsOpen
            End With
        Catch ex As Exception
            MsgBox("Cannot Open Port ", MsgBoxStyle.Critical)
        End Try

    End Function

'To read data, you need to write code on its receive data event. Something like this..
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        'This event will Receive the data from the selected COM port..
      Textbox1.text = SerialPort1.ReadExisting

End Sub
0
 

Author Comment

by:djoni4343
ID: 21810113
Yes, I am using .Net SerialPort Component.
0
 
LVL 7

Expert Comment

by:AUmidh
ID: 21810130
0
 

Author Comment

by:djoni4343
ID: 21810141
rachitkohli,

I got error message : "Cross-thread operation not valid: Control 'txtBarcode' accessed from a thread other than the thread it was created on."
0
 
LVL 7

Expert Comment

by:AUmidh
ID: 21810150
make txtBarcode.CheckforIllegalCrossThreadCalls=false
0
 
LVL 14

Expert Comment

by:rachitkohli
ID: 21810155
in form load write
        Control.CheckForIllegalCrossThreadCalls = False     'Making Thread Safe
0
 

Author Comment

by:djoni4343
ID: 21810157
Aumidh,

I will try your second link, thanks.
0
 

Author Comment

by:djoni4343
ID: 21810175
rachitkohli,

I will try your suggestions, thanks.
I will be back in an hour, sorry.
0
 

Author Comment

by:djoni4343
ID: 21810487
rachitkohli,

It works but my barcode number displayed in parts (2 parts)  ?
0
 

Author Comment

by:djoni4343
ID: 21810772
Aumidh,

Your suggestion (second link) actually same with Rachitkohli sample but both gave same result ie: the barcode number displayed in two parts (8 digits then 5 digits)
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 14

Expert Comment

by:rachitkohli
ID: 21811187
replace your data received event with the following code .


Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        Dim bRead, nRead As Integer
        Dim returnStr As String = ""
        Dim ascStr As String = ""

        bRead = SerialPort1.BytesToRead 'Number of Bytes to read
        Dim cData(bRead - 1) As Byte

        SerialPort1.Encoding = Encoding.GetEncoding(65001)

        nRead = SerialPort1.Read(cData, 0, bRead)  'Reading the Data
        For Each b As Byte In cData
            ascStr += Chr(b)        'Ascii String
            returnStr += Hex(b)     'Hex String
        Next

      TextBox1.Text = returnStr
End Sub
0
 

Author Comment

by:djoni4343
ID: 21829004
rachitkohli,

Got error message "Name 'Encoding' is not declared" at "Encoding.GetEncoding(65001)" text
0
 
LVL 14

Expert Comment

by:rachitkohli
ID: 21829045
try

System.Text.Encoding.GetEncoding(65001)
0
 

Author Comment

by:djoni4343
ID: 21829135
rachitkohli,

No Error but I received "39313730373036383036383533D" instead of "9170706806853" (my barcode number)
0
 
LVL 14

Expert Comment

by:rachitkohli
ID: 21829262
I think you need to check out with your encoding info, this means the data is transmitted & received correctly, should check the encoding now..
0
 
LVL 14

Expert Comment

by:rachitkohli
ID: 21829269
0
 

Author Comment

by:djoni4343
ID: 21829519
rachitkohli,

I think it's not the encoding
0
 

Author Comment

by:djoni4343
ID: 21829539
rachitkohli,

I think the SerialPort1_DataReceived event is triggered 2 times.
0
 

Author Comment

by:djoni4343
ID: 21829575
rachitkohli,

If I insert MsgBox("anything") at first line the event is triggered 1 time and my barcode displayed correctly, so I think I need to put 'the delay' code. Can you give that code ? Thanks.
0
 
LVL 14

Accepted Solution

by:
rachitkohli earned 500 total points
ID: 21829584
I was about to write the delay for you, good you figured it out.
Have
Thread.Sleep (2)
you can change the interval, as should not affect the data received.
0
 

Author Comment

by:djoni4343
ID: 21829595
rachitkohli,

The delay code is :
        System.Threading.Thread.Sleep(1000)          ' 1 second

It seems that my problem solved now, but thanks anyway.
0
 
LVL 14

Expert Comment

by:rachitkohli
ID: 21829720
Good you find the solution,
FYI
Thread.Sleep have been worked if you have Imported System.Threading Namespace.

0
 
LVL 14

Expert Comment

by:rachitkohli
ID: 21881918
Wasnt my answers helpful in any ways as am not getting any points.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now