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.
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:
You are likely to be using a different COM port.
The Visual Basic Program
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.
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
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?
Try deleting the combo box and recreating it. Remember to give the new combo box the same name “comPort_ComboBox”
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
Hi Banause,
Thanks for the tip.
I had the same issue with Arduino Leonardo. Problem solved after following your tip.
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.
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.
hello sir. may i know how to read multiple sensors reading and show in different textbox for each reading? please sir
thanks
See https://www.martyncurrey.com/arduino-and-visual-basic-part-2-receiving-data-from-the-arduino-part-2/
thanks sir
i dont understand this line ” If (comPORT “”) Then ” form code what does it mean?
If (comPORT <> “”) Then ….
If comPORT is empty / not equal to nothing then try to make a connection.
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.)
Very nice and interesting article. Thank you
Question1?- when is part 2 due?-
Question 2?- will this program work with windows XP?
Part 2 – https://www.martyncurrey.com/arduino-and-visual-basic-part-2-receiving-data-from-the-arduino-part-2/
Part 3 – https://www.martyncurrey.com/arduino-and-visual-basic-part-3-controlling-an-arduino/
for XP you need to select .NET version 4 or lower. Project => Properties => Application.
If XP is 32 bit, also select any CPU.
Great, Thank you.. work well
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.
Excellent post, friend.
You helped me a lot.
Thank you so much.
very nice tutorial with detail explanation, Thank you and keep update..!
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.
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
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.
Thank you! You helped me so much. I’ve understand it and have modified it. So then.
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
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.
Hello,
When i run my program I get error : AAccess denied to the port ‘COM3’. What can iI do?
Solution, you can’t have open serial port monitor while you use VB program
Hi Martyn,
Great site and very good explanations. Thank you for sharing.
Please continue your great work.
/Henrik
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?
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?
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.
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 :)
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
great work..
please make any projects using arduino rfid and visual basic
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??
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
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).
So simple yet very helpful. Many thanks sir. :)
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?!
Hi,k
unfortunately I cannot help with this. I only have VS 2013 and the code compiles fine with this version.
I’ve caught all issues, thanks any way :)
do u now how to convert 2 bytes in richtexbox to the ASCII?
Awesome detailed project and great share
I have same article which guide to make communication serial between Arduino and Visual C++. Any reader interested, please visit our blogspot:
http://engineer2you.blogspot.com/2016/12/arduino-serial-communication-visual.html
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
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
I can’t help at this time but google visualbasic bar chart for lots of guides.
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 …
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
Where is SerialPort1 declared in VB code?
I don’t see it in the code sections of the article nor the downloaded VB code.
The serial port does not need to be declared. It is declared in the designer when you add it to the form.
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.
Glad it was helpful.
Thank you for this article, it helped me a lot. Very nicely explained and detailed. Great job!
i need a code in vb6 for receive data from rfid device via tcp/ip. thanks.
Great Code..Can i use the same principle with receiving real time data from campbell CR10 data logger
If the CR10 outputs standard serial data then the above will display it. You may need to change the baud rate.
Hello Martyn your tutorial is very good. Thank you for that.
Can you also connect more Arduinos to Visual Basic? When yes how?
yes, however, each connected Arduino would have its own COM port.
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.
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.
Merci beaucoup pour ton aide. Est-ce que vous avez un document sur ce dont vous avez travaillé (communication entre arduino et visual basic) ?