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

 
 

Trouble Shooting

If you are not receiving data in the VB program but the Arduinos serial monitor works then on the serial port within VB, set “DtrEnable = true” and “RtsEnable = true”. Thank you Banause for the tip. This seems to be required for the Arduino Leonardo.

 
 

This is a very simple 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

 
 
 
 

68 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?

    Reply
  2. 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

    Reply
    • 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

      Reply
      • 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.

        Reply
    • 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

      Reply
  3. 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.

    Reply
  4. 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?

    Reply
    • 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.

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

    thanks

    Reply
  6. 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.)

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

    Reply
  8. 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

    Reply
    • 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.

      Reply
  9. 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

    Reply
    • 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.

      Reply
  10. Hello Martyn,

    First of all, thank you very much for your tutorial which is one of the few and complete on the internet. You are also one of the few people who answer questions. I can not integrate a Bluetooth connection with your example that will allow me to have a wireless connection to manage a relay card. Could you advise me to connect a relay with bluetooth and vb.net?

    Thank you very much for your help and continue to make tuto that is great

    Reply
    • Take a look at the next 2 posts. Part 3 is the most helpful but go through part 2 first.

      To control a set of relays you can adapt the example in part 3. Simply use the same number of buttons as you have relays.

      Reply
  11. i try to be use the rfid tag as password .. but i get not found when i write same code it worked !
    If (TextBox1.Text = ” 212 79 21 219″) Then

    Form3.Show()
    Else
    MsgBox(“not found”)
    End If

    Reply
  12. so oddly I had one board (pro micro) that didn’t read, and another (uno) that did, so no idea why your hint with setting the serialport.rtsenable and serialport.dtrenable to true worked,, but i had been struggling with that for a long time. Thanks for that tip.

    Reply
  13. Hey Guys!

    I hope someone can help.
    I did stopwatch in my visual studio program, but i cant start my stopwatch with “command”.

    For example

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RichTextBox1.TextChanged
    If TextBox1.Text = “Motion detected!” Then
    Timer2.Start()
    Stopwatch.Start()
    End If
    End Sub
    ….
    Someone know how can i solve this problem ? What private sub i need to use?

    Reply
  14. Thank you for your article, which is exactly what i am looking for!
    Question: is there any way to avoiding COM select? if the Form only work with Arduino, Can i make it automatically connect with Arduino Board?

    Reply
    • You can hard code the COM port if will only ever use the same Arduino and you never reset the assigned USB port.

      The form will work with anything that uses usb for serial communication. This can be another microprocessor or something else.

      Reply
  15. First I would like to thank you for this helpful tutorial, I would like to inquire or rather consult my experience while studying this program, I have followed all the stages that have been described, the program can be run well without error warning appears, all COM Can be detected on combobox, but when I have selected one COM in Combobox, the program is not running properly, it always appears msgBox that I have to choose Comport first, but I have chosen one of them, is it because I use VB2010 so there is little difference of setting , I hope you can give me help, thank you :)

    Reply
    • The message is generated when comPORT is empty:

      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

      If this is not working test the value of comPORT after you click the connect button. See what value it has.

      You can use the textbox to display the value of comPORT or any other messages:
      RichTextBox1.Text &= “my message” & vbCrLf

      Reply
  16. Why this will not work ??

    If receivedData = “1111” Then
    lb_status.Text = “OK!”
    Else
    lb_status.Text = “nOK!”
    End If

    It’s always a nOK and when 1111 comes out of the serial??

    Reply
  17. Hi there,

    Completely new to visual basic; when i use this code my visual basic wants me to declare “serialport1” as it cannot be found (for the connect_BTN_Click sub)

    Any help would be appreciated.

    Anthony

    Reply
    • Are you using the files from the download or are you copy/pasting?
      If copy/paste download the example files.

      Are you using Visual Studio 2013 Community?
      This is the only IDE I have tried. I cannot guarantee the code will work in other versions (although it should).

      Reply
  18. Hi Martyn,
    when I try to compile the VB program I get 2 mistakes-
    1) BC30506 Handles clause requires a WithEvents variable defined in the containing type or one of its base types. Relates to this line -Private Sub ComPort_ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comPort_ComboBox.SelectedIndexChanged
    2) BC30451 ‘comPort_ComboBox’ is not declared. It may be inaccessible due to its protection level. Relates to all lines with comPort_ComboBox

    I am using Microsoft Visual Studio 2017. Can u help with these mistakes please?!

    Reply
  19. Dear Martyn,
    First I want to say Thank you very much for your sharing. Now I having problem only output data.
    For Example ,
    my message
    31/01/18,14:39:28,0067.1
    31/01/18,14:39:28,0067.1
    31/01/18,14:39:28,0067.1
    my message
    31/01/18,14:39:28,0067.1
    31/01/18,14:39:29,0067.1
    my message
    31/01/18,14:39:29,0067.1
    31/01/18,14:39:29,0067.1

    31/01/18my message <<<<<< so weird , It takes about 2-4 sec to appear one.
    ,14:39:29,0067.1
    31/01/18,14:39:29,0067.1
    31/01/18,14:39:30,0067.1

    Please help me , Thank you.
    Opart

    Reply
  20. I want to display data in bar chart. Arduino will send data and it will be displayed on bar chart. Like spectrum of frequency.
    Request you to help

    Reply
  21. Thank you very much for the article. Especially for the troubleshooting comment about RTS and DTR, Would never be able to figure out myself why with the same sketch UNO R3 is responding and Pro Micro is not. While the serial monitor shows no problem for both. Now by setting them Enable, the Pro Micro works fine, and VB stopped reading from UNO R3 …

    Reply
  22. Hi,

    I am working on Azure IoT project using MXchip AZ3166 board. I installed visual basic studio and Arduino. I installed Azure IoT workbench Dev kit in visual basic. I configured Aurdino path in it. When I compiled a sample projects from Azure IoT workbench I am encountering a error stating that install Arduino or add Arduino path and another error unable to find Aurdino path.

    Kindly anyone suggest me some solutions to solve this error. Thank you.

    Sri Krishna

    Reply
  23. Thank you for your guide and releasing the source code. It worked perfectly with my Arduino Nano and was a big help getting started.

    I now get a pop up on my computer when my door bell is pushed or laser trip wire is broken.
    Look forward to reading your other guides.

    Reply
      • Thank you for your quick reply :)
        I think it will be possible to connect several Arduino with a bus system (maybe the RS485) and display it in a single com-port.Or what do you say about this?

        It can be take then the code from your tutorial 3 (see if the Arduino is there) with the connecting_timer and instead of write , it can be write the different adresses from the Arduino.
        I think I try this with some Arduino Uno and temperatur sensor.

        Reply
        • I’m not that familiar with RS485 so had to google a refresher.
          While it is possible to link Arduinos together (there are lots of examples online) there doesn’t appear to be an easy way to have a link to a computer.
          You could possibly create a network of Arduinos using RS485 and then have one that acts as a master device and connect this to a computer. The network management would then be on the Arduino rather than in VB.

          My solution, if using not too many Arduinos, would be to connect them all to the computer via USB and manger the COM ports through VB. However, in my recent projects I have moved away from USB (and Bluetooth) and have started using ESP8266s and ESP32s with wifi. The ESP32s especially are proving to be very good for mini networks/meshes.

          Reply
  24. Merci beaucoup pour ton aide. Est-ce que vous avez un document sur ce dont vous avez travaillé (communication entre arduino et visual basic) ?

    Reply

Leave a Reply to zaid Cancel reply