Reading from a Serial Port and Saving to a Database

Reading from a Serial Port and Saving to a Database

  • Comments 15

Recently I was sent a question about how to read from a serial port and save the information to a database so instead of following up privately I thought I'd post my answer here. There's a good article in the MSDN Library that has some hints on how to do this with the System.IO.Ports.SerialPort class. In Visual Basic 2005 you can use the My Namespace to access the ports on your computer easily. For instance, you can open a port to COM4 like this:

Dim WithEvents mySerialport As SerialPort
mySerialport = My.Computer.Ports.OpenSerialPort("COM4", 56000, Parity.None, 8, StopBits.One)

Once we open the serial port we can listen to the DataReceived event. In my sample I just append the incomming messages to a StringBuilder and then save the string to a DataSet when we stop listening to the port. Its important to note that the DataReceived event will fire on a separate thread than your main thread. So if you need to update UI elements on a Form you need to use the Form's Invoke method in order to execute code onto the UI thread.

Dim myStringBuilder As New StringBuilder

Private Sub mySerialport_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles mySerialport.DataReceived

    'This happens on another thread

    myStringBuilder.Append(mySerialport.ReadExisting())

    Me.Invoke(New EventHandler(AddressOf UpdateControls))

End Sub

 

Private Sub UpdateControls(ByVal sender As Object, ByVal e As EventArgs)

    'Do any UI code here on the main thread

    Me.TextBox1.Text = myStringBuilder.ToString()

End Sub

I just created a simple SQL-Server Express database with one table called Message that has a field called Message. I then created a DataSet called MessageDataSet with the one MessageDataTable and then dropped that onto a grid onto my form to hook up some data binding automatically. When we stop reading from the serial port I just add a new MessageRow and then save it back using the MessageTableAdapter.Update() method.

Private Sub Stop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopRead.Click

    If mySerialport IsNot Nothing Then

        mySerialport.Close()

    End If

    Try

        Dim message As MessageDataSet.MessageRow = Me.MessageDataSet.Message.NewMessageRow()

        message.Message = myStringBuilder.ToString()

        Me.MessageDataSet.Message.Rows.Add(message)

 

        Me.Save()

 

        myStringBuilder.Remove(0, myStringBuilder.Length)

        Me.TextBox1.Text = ""

    Catch ex As Exception

    End Try

End Sub

Private Sub Save()

    Me.Validate()

    Me.MessageBindingSource.EndEdit()

    Me.MessageTableAdapter.Update(Me.MessageDataSet.Message)

End Sub

It's kind of hard to test hardware without hardware so if you don't have the hardware setup it's suggested that you get a null modem and hook that up between two USB to Serial converters to simulate two ports, one read one write. Unfortunately I don't have a null modem so I couldn't fully test my code. I've attached the entire solution to this post, you just need Visual Basic Express (or Visual Studio) and SQL-Server Express to run the example. If anyone has the hardware setup for this and finds a bug, please let me know and I'll post any corrections. You can also check out the forums for more info. Have fun!

Attachment: ReadFromSerialPort.zip
Leave a Comment
  • Please add 4 and 7 and type the answer here:
  • Post
  • Beth this is great!  I'm in the infancy stages of developing an application that will need to read data from a serial port and I wasnt finding many resources on it.  You are a Queen for opening this door for me :-)

  • Thank you for this article. it really proved beneficial in an application i am working on. couldn't have done it without you.

  • Bethy

    Thank you very much for the videos you sent to me.

    Now, and for the first time my  application is working very well without producing any error.

    Thaaaaaaaaanks.

  • Hee Cool stuff,

    Im not good at this, so i have a question!

    I want to control not only the input from a port, but also the output, i want to send out a decimal or binary number to a port. But how do i do this?

    And I want to use Microsoft DLL's (Windows DLL's when possible)

    When you have a awnser you can mail me at: jluijten1@student.han.nl

  • Thank you for posting this.

    I'm trying to write my first VB program and after mind numbing hours of trying to find something useful, I finally have!

  • Thank you very much Beth for the serial code. I've converted it in VB2008 for use with a container filling machine I'm designing. It's given me the insight I needed.

    As this is my first attempt at a software controlled machine, the serial port is proving to be tricky. It would be good to use the serial port from VB2008 but I can't find any info on the subject. Do you know of any such document? If not, I'll just have to stick with you girl!

    Thank you again,

    Neil@polevolt.co.uk

    PS I'm restoring a 1972 TVR Vixen

  • Your article was very helpful in helping me write my first Serial Port programming App in VB.Net (VS2005). I only infd a very funny issue - which i am unable to solve.

    When I write the code similar to your code in a Windows App (vb.net) - it works fine. But, if i have to write it as a Windows Service (but ofcourse i do not call the Invoke UpdateControls - i just use the Received string from the DataReceived event for my logic). I noticed that the Windows App recieves the data correctly, and the Windows Service App receives the data but there are breaks in the data (Enter lines). I use the same ReadExisting method.  I am not sure if i should use any other of the ReadMethods. Do you have any advice?

    Thanks

  • Thanks for the info, really helpful.

  • so nice.

    sir. i really want to know how to send data (text) from pc to led display with application like gui. that application build with vb

    i'm using microcontroller at89s51 with basic language.

    i have finish build led matrix. but i dont know how to design gui interface.

    please give me solution. beni-aceh

    indonesian benny_mrd@yahoo.co.id

  • my probleme is :

    i m working with serialport

    each week i have the deadscren(blue screen)

    how can i resolve the problem?

    ryanryan1970@hotmail.com

  • Hi Beth, is a great article!!!

    I have a question, In the program I added a column to the database is called "Time"

    How I can save the the time in this column in the same style that the data saved in the "message"?

           Dim message As MessageDataSet.MessageRow = Me.MessageDataSet.Message.NewMessageRow()

           message.Message = myStringBuilder.ToString()

           Me.MessageDataSet.Message.Rows.Add(message)

    Thanks

  • Hello Beth,

       This is very useful. I need the code to access the database and send it's contents to the serial port. For example if I receive a 7 digit number which is an ID number, the program has to send data of that person to the serial port by searching it in the database. Can you please help me?  

  • Hi Beth,

    First, thank you for your blog on this subject -- it has been most helpful.  You asked for any bugs so I will report a couple.  I have a check scanner attached to COM5 to read the MICR data at the bottom of checks.  Also, I am running Visual Studio 2010.

    1.  There is an error in the parameters used to open the com port.  I removed the parameters and just opened COM5.

    2.  When START is clicked and I read a check it works fine.  The data is displayed in the textbox fine.  Then I click CLOSE and the data is written to the database.  When I then click START again and read a check no data is read.  Not sure what is happening here.

    Anyway, this put me on the right path to read serial data.  Again, thank you.

  • Hi,

    Just an update form my earlier comment.  The problem I listed in item 1 was bacause I was using the wrong baud rate.  The check reader uses a different baud rate.  That part now works OK.

    I still haven't figured out what is going on with problem two.  It appears that the probram will only open the com port once.

    At any rate, I have used portions of your code in my check reading program and it works great.  Thank you so very much!

  • please, how can i contact beth? Urgent please...

Page 1 of 1 (15 items)