Solved

Reading Serial Port with VB.NET 2005

Posted on 2008-06-17
28
2,801 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
Comment Utility
0
 

Author Comment

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

Expert Comment

by:AUmidh
Comment Utility
Are you using .Net Serial Port Component ?
0
 
LVL 14

Expert Comment

by:rachitkohli
Comment Utility
'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
Comment Utility
Yes, I am using .Net SerialPort Component.
0
 
LVL 7

Expert Comment

by:AUmidh
Comment Utility
0
 

Author Comment

by:djoni4343
Comment Utility
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
Comment Utility
make txtBarcode.CheckforIllegalCrossThreadCalls=false
0
 
LVL 14

Expert Comment

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

Author Comment

by:djoni4343
Comment Utility
Aumidh,

I will try your second link, thanks.
0
 

Author Comment

by:djoni4343
Comment Utility
rachitkohli,

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

Author Comment

by:djoni4343
Comment Utility
rachitkohli,

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

Author Comment

by:djoni4343
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 14

Expert Comment

by:rachitkohli
Comment Utility
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
Comment Utility
rachitkohli,

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

Expert Comment

by:rachitkohli
Comment Utility
try

System.Text.Encoding.GetEncoding(65001)
0
 

Author Comment

by:djoni4343
Comment Utility
rachitkohli,

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

Expert Comment

by:rachitkohli
Comment Utility
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
Comment Utility
0
 

Author Comment

by:djoni4343
Comment Utility
rachitkohli,

I think it's not the encoding
0
 

Author Comment

by:djoni4343
Comment Utility
rachitkohli,

I think the SerialPort1_DataReceived event is triggered 2 times.
0
 

Author Comment

by:djoni4343
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Wasnt my answers helpful in any ways as am not getting any points.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

762 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

12 Experts available now in Live!

Get 1:1 Help Now