Arduino and Visual Basic Part 1: Receiving Data From the Arduino

After creating the dropControllerBT app and realizing how much easier controlling the dropController device is through the app I started to think about creating a PC app. I haven’t done any PC programming for many years and so I looked at what various options are currently available. Visual Basic kept being recommended for ease of use and quick development. Visual Basic comes as part of Microsoft’s Visual Studio Suite and I initially download and played with Visual Studio Express which in turn lead to Visual Studio Community. Both are free for personal use.

Visual Studio Express is a striped down version of the larger packages and has some major limitations. Visual Studio 2013 Community, on the other hand, is a full featured IDE and development system free to use for students, open source contributors and small development teams. It includes several languages but for now I am only interested in Visual Basic.

Visual Studio 2013 Community is available for download at https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx. The download is just the installer which will download the main program from the internet. If, like me, you prefer an off line installer, you can get one at http://go.microsoft.com/?linkid=9863609

The main download page is at https://www.visualstudio.com/downloads/download-visual-studio-vs

After installing the software it took me a while and many Google searches before I started to figure out the IDE. For me, fully learning the IDE is beyond what I want and have time for but over the course of a weekend I managed to create my first working program. A simple example of receiving data from the Arduino.

Arduino to Visual Basic 2013 Communication

The example uses a very simply form and shows what ever it recieves from the Arduino in a text box.

Arduino Visual Basic Serial Example

Arduino Visual Basic Serial Example

The Arduino Sketch

The Arduino Sketch sends the string “1234” over the serial connection once every second. At the same time it blinks the built in LED on pin 13.

/* 
* Sketch Arduino and Visual Basic Part 1 - Receiving Data From the Arduino
*
* send "1234" over a serial connection once a second
*
*/
 
 
byte LEDpin = 13;
 
void setup() 
{
     pinMode(LEDpin, OUTPUT); 
     Serial.begin(9600);
}
 
void loop() 
{
     Serial.println("1234");
     digitalWrite(LEDpin,HIGH);
     delay(100);
     digitalWrite(LEDpin,LOW);
     delay(900);
}

To test that the sketch is working you can open the serial monitor:
Arduino Visual Basic Serial Monitor
You are likely to be using a different COM port.

The Visual Basic Program

Here is the form:
Arduino Visual Basic Form

The form includes:
– a drop down list that contains the available COM ports
– a Connect / Dis-connect button.
– a label to show if the timer is active or not
– a text box where the received data is displayed.
– a CLEAR button that clears the contents of the text box.

And here is the program:

'Simple example of receiving serial data
'written in Visual Basic 2013
'

Imports System
Imports System.IO.Ports

Public Class Form1
    Dim comPORT As String
    Dim receivedData As String = ""

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Timer1.Enabled = False
        comPORT = ""
        For Each sp As String In My.Computer.Ports.SerialPortNames
            comPort_ComboBox.Items.Add(sp)
        Next
    End Sub


    Private Sub comPort_ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comPort_ComboBox.SelectedIndexChanged
        If (comPort_ComboBox.SelectedItem <> "") Then
            comPORT = comPort_ComboBox.SelectedItem
        End If
    End Sub


    Private Sub connect_BTN_Click(sender As Object, e As EventArgs) Handles connect_BTN.Click
        If (connect_BTN.Text = "Connect") Then
            If (comPORT <> "") Then
                SerialPort1.Close()
                SerialPort1.PortName = comPORT
                SerialPort1.BaudRate = 9600
                SerialPort1.DataBits = 8
                SerialPort1.Parity = Parity.None
                SerialPort1.StopBits = StopBits.One
                SerialPort1.Handshake = Handshake.None
                SerialPort1.Encoding = System.Text.Encoding.Default
                SerialPort1.ReadTimeout = 10000

                SerialPort1.Open()
                connect_BTN.Text = "Dis-connect"
                Timer1.Enabled = True
                Timer_LBL.Text = "Timer: ON"
            Else
                MsgBox("Select a COM port first")
            End If
        Else
            SerialPort1.Close()
            connect_BTN.Text = "Connect"
            Timer1.Enabled = False
            Timer_LBL.Text = "Timer: OFF"
        End If


    End Sub


    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        receivedData = ReceiveSerialData()
        RichTextBox1.Text &= receivedData
    End Sub


    Function ReceiveSerialData() As String
        Dim Incoming As String
        Try
            Incoming = SerialPort1.ReadExisting()
            If Incoming Is Nothing Then
                Return "nothing" & vbCrLf
            Else
                Return Incoming
            End If
        Catch ex As TimeoutException
            Return "Error: Serial Port read timed out."
        End Try

    End Function


    Private Sub clear_BTN_Click(sender As Object, e As EventArgs) Handles clear_BTN.Click
        RichTextBox1.Text = ""
    End Sub


End Class

 

The program in Detail

I am using two global variables; comPORT and receivedData. comPORT is the COM port selected by the user and should be the one the Arduino is connected to. receivedData is the data received on the selected COM port

    Dim comPORT As String
    Dim receivedData As String = ""

 
When the program is first run, the Form1_Load() subroutine populates the COM port combo box / drop down list with the available COM ports. The program then waits for the user to pick one.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Timer1.Enabled = False
        comPORT = ""
        For Each sp As String In My.Computer.Ports.SerialPortNames
            comPort_ComboBox.Items.Add(sp)
        Next
    End Sub

 
When the user selects a COM port, the value is copied to the variable comPORT. This is not really necessary as the selected value can be read from the combo box but I like to keep this kind of data in easy to use variables.

    Private Sub comPort_ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comPort_ComboBox.SelectedIndexChanged
        If (comPort_ComboBox.SelectedItem <> "") Then
            comPORT = comPort_ComboBox.SelectedItem
        End If
    End Sub

 
Sub connect_BTN_Click() triggers when the user clicks on the Connect button. The first thing the routine does is determine if the user is connecting or dis-connecting. The same button is used for both.
If connecting, and comPORT is not empty, then the serial port properties are set, the serial port is opened and the timer is started. To show that the timer is active the timer label is updated to “Timer: ON”.
If comPORT is empty a message is displayed telling the user to select a COM port first.
If dis-connecting, the serial port is closed, the timer is stopped and the timer label is updated to “Timer: OFF”.

The Timer label is there purely for debugging.

    Private Sub connect_BTN_Click(sender As Object, e As EventArgs) Handles connect_BTN.Click
        If (connect_BTN.Text = "Connect") Then
            If (comPORT <> "") Then
                SerialPort1.Close()
                SerialPort1.PortName = comPORT
                SerialPort1.BaudRate = 9600
                SerialPort1.DataBits = 8
                SerialPort1.Parity = Parity.None
                SerialPort1.StopBits = StopBits.One
                SerialPort1.Handshake = Handshake.None
                SerialPort1.Encoding = System.Text.Encoding.Default 'very important!
                SerialPort1.ReadTimeout = 10000

                SerialPort1.Open()
                connect_BTN.Text = "Dis-connect"
                Timer1.Enabled = True
                Timer_LBL.Text = "Timer: ON"
            Else
                MsgBox("Select a COM port first")
            End If
        Else
            SerialPort1.Close()
            connect_BTN.Text = "Connect"
            Timer1.Enabled = False
            Timer_LBL.Text = "Timer: OFF"
        End If
    End Sub

 
A timer is used to check for incoming data. The timer is set to trigger every 500ms or half a second and when triggered it calls the Timer1_Tick() routine. For this example 500ms is fast enough. For more complex tasks the timing may need to be adjusted.
Arduino Visual Basic Timer Properties

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        receivedData = ReceiveSerialData()
        RichTextBox1.Text &= receivedData
    End Sub

 
Timer1_Tick() calls a second subroutine that checks to see if there is any serial data and if there is it then copies the incoming data to the receivedData variable.
receivedData is then added to the textbox.

    Function ReceiveSerialData() As String
        Dim Incoming As String
        Try
            Incoming = SerialPort1.ReadExisting()
            If Incoming Is Nothing Then
                Return "nothing" & vbCrLf
            Else
                Return Incoming
            End If
        Catch ex As TimeoutException
            Return "Error: Serial Port read timed out."
        End Try

    End Function

 
The final subroutine, Sub clear_BTN_Click(), simply resets the contents of the text box.

    Private Sub clear_BTN_Click(sender As Object, e As EventArgs) Handles clear_BTN.Click
        RichTextBox1.Text = ""
    End Sub

 
 

This is a very basic example that I used to learn the basics on making a serial connection between the Arduino and a computer. As such the code can be made much better.
– The COM port is left open all the time and for more complex applications it may be better to open and close the port as required.
– The application simply displays what ever data is received. There is no error checking. To make it more reliable and to ensure you have all the data it would be better if the data was enclosed in start and end tags and then parsed.

For more information on serial communication with the Arduino and using start and end makers take a look at Robin2’s Serial Input Basics on the Arduino forum.

 
 

Download

Download the Visual Basic project files and the Arduino sketch


You will need to have Visual Studio installed to use the VB project files.
 
 

Next Steps

In part 2 we take this further. And in part 3 we start to control an Arduino

 
 
 
 

26 thoughts on “Arduino and Visual Basic Part 1: Receiving Data From the Arduino

  1. Great help. :D
    I’m a newbie at this and I keep receiving this one error in VB..
    Error 1 ‘comPort_ComboBox’ is not declared. It may be inaccessible due to its protection level.
    I copied the entire code exactly as it is and I’m using visual basic express 2010.
    Any idea on what I must be doing wrong?

  2. Pingback: Arduino and Visual Basic: Controlling an Arduino | Martyn Currey

  3. Hi I’m having a problem that I cant figure out. I would appreciate if you can help.
    When I try to read serial data from Arduino to Visual Basic I get nothing in the text field. It works fine with Arduino’s own serial monitor, but VB program sees nothin. I even copied your code exactly and it still doesn’t work. Other examples I found on internet don’t work either. I’m on VB 2013 Ultimate btw.

    Thanks

    • Hi Igor

      I’m too face this issue , I use VB 2013 and Arduino Leonardo board ,when I replace the board with Mega ADK …there is no problem…
      It works very good ..

      Thanks Martyn for this helpful great topic

      • Since the program uses basic serial communication it should work with all versions of the Arduino and other microprocessors.

        If the Arduino serial monitor is working then there is no reason the VB program should not work. There are a few things worth remembering:
        – You cannot have two connections to the same Arduino. If the serial monitor is open then VB cannot use the COM port.
        – Double check the baud rates.
        – If you have changed any of the serial properties (data bits, parity, encoding, etc) change them back to the defaults.

    • Hi, i had this problem so long and didnt know how to fix it. But now i found the solution. Klick on the Serialport in the Form1, then you have to set “DtrEnable = true” and “RtsEnable = true”. Now it should work.

      I know my english inst that good, but i hope u can understand what i wanted to say :D

  4. If the serial monitor is working then you should be able to connect through VB. Use the downloaded programs rather than copy paste from the website. Does the VB program compile OK?

    A couple of basic things to check (sorry if they seem patronising),
    – confirm you are using the correct COM port.
    – check that the baud rate is correct. The above program uses 9600

    Can you connect (are you getting an error message)?
    Does the timer change to ON when you connect?

    Only one connection to a COM port can be made at a time. If you open the serial monitor then you block VB and vice a versa.

    You can also try using a different serial terminal such as putty.

  5. Pingback: Arduino and Visual Basic Part 2: Receiving Data From the Arduino | Martyn Currey

  6. helo
    I’m new to VB and I’m trying developing a VBA application to send and receive data to an RFID reader and put the result into Microsoft Access.
    pless help me?

    • I can’t help directly but I would suggest you break the project down in to smaller parts. Get the Arduino + RFID working, get the MS Access side working and then put them together. My examples can help with the communication between Arduino and VB.

      If not already a member, join the Arduino forum at http://forum.arduino.cc/ you will get help there. Also, search for Arduino and RFID. There are many guides online.

  7. hello sir. may i know how to read multiple sensors reading and show in different textbox for each reading? please sir

    thanks

  8. I tried this code to get really fast into listening to the arduino, while submitting the values from AnalogIn (A0). But reading the whole values is sometimes to much data. Remember, you read the whole buffer once without disposing the buffer.

    So I have altered the code

    from

    [code]
    Incoming = SerialPort1.ReadExisting()
    [/code]

    to
    [code]
    Incoming = SerialPort1.ReadLine()
    SerialPort1.DiscardInBuffer()
    [/code]

    Now it runs pretty good and replies actual data.

    (Hope this blog reads the code tags right. If not, just ignore the tags.)

  9. Very nice and interesting article. Thank you
    Question1?- when is part 2 due?-
    Question 2?- will this program work with windows XP?

  10. I am trying to receive a signal if a limit switch is enabled. All I need is to know how to make a Boolean true in VB.NET. If the switch is closed send a signal either through USB or serial to the computer. I am pretty good at VB. I am not really sure what Adruino board to buy or how to talk to the board. Any suggestions would be greatly appreciated.

    Thanks,

    Chuck

    • If using just one switch then any Arduino would be suitable.

      Start by looking at the main boards; Uno, Mega, Nano. The Uno and Nano are very similar (mainly a different size). The Mega adds extra hardware (additional hardware serial ports) and functions but is bigger and more expensive.

      When making permanent projects I tend to use Nanos. They are small and easy to work with.

  11. hello my english is not very well…..thx for this post it helps me to understand more visual basic because im a beginner. i have a projekt with an arduino uno and an xbee shield with an xbee module on the pc side i have also an xbee now i woul like to receive the data on the pc i get the commands from the print function from the arduino but the problem is that they are only for a short time displayed on the textbox can you help me please that the data is stored in the textbox

    • Not really sure I understand. Is the textbox being cleared or is the data scrolling up too fast?

      It may be worth while having a look at part 2 and part 3. These show how to use different commands.

Leave a Reply

Your email address will not be published. Required fields are marked *


eight + 8 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>