Instructables

Using Visual Basic 2010 to control Arduino Uno

Picture of Using Visual Basic 2010 to control Arduino Uno
I know this has been done in the past a few times so here's one more. This is a skeletal Visual Basic 2010 and Arduino Sketch that I mixed together to test the PC to Arduino Uno connection via serial. It simply turns LED 13 on or off. 

The Visual Basic 2010 code assumes you have Form1 with 2 buttons Button1 and Button2 and SerialPort1 controls. Button1 sends a 1 and Button2 sends a 0 to the serial port COM10 (change this to match your PC to Arduino port setting)

See attached photo of my simple form design.

The Arduino Uno Sketch code simply waits and reads the serial port. If it see 1 it will turn PIN 13 on and if it sees 0 it will turn PIN 13 off. If you have an LED on PIN 13, you can turn it on and off. On the Arduino Uno, PIN 13 is attached to a an on-board LED.

I used COM10 as a serial port but you can (and must) change it to match your Arduino serial port.

The purpose of this code is to simplify explanation of how to connect VB to Arduino. You can add error processing and more intelligence based on your particular needs.  

Make sure you drag the Serial Port control icon from the Toolbox onto your form. It should have the name SerialPort1

WARNING: On my PC I had to close the Arduino IDE Serial Monitor window while runing the VB program, else I run into all sorts of error message about COM port access denied and the program will fail.

You can download Visual Basic Express 2010 for free from Microsoft
http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-basic-express


'------------ START OF VB 2010 CODE -----------------
' NOTE: I am using COM10 so you need to change the Visual Basic code to match your COM port

Imports System.IO
Imports System.IO.Ports
Imports System.Threading

Public Class Form1
Shared _continue As Boolean
Shared _serialPort As SerialPort

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort1.Close()
SerialPort1.PortName = "com10" 'change com port to match your Arduino port
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!
End Sub


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.Open()
SerialPort1.Write("1")
SerialPort1.Close()
End Sub


Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Open()
SerialPort1.Write("0")
SerialPort1.Close()
End Sub
End Class


'------------ END OF VB 2010 CODE -----------------


//------------- START OF ARDUINO SKETCH -----------------
//
// Mixed by: Hazim Bitar
// Based on: Science Guy 14 youTube tutorial http://youtu.be/g0pSfyXOXj8

int ledPin = 13; // the number of the LED pin

void setup() {
Serial.begin(9600); // set serial speed
pinMode(ledPin, OUTPUT); // set LED as output
digitalWrite(ledPin, LOW); //turn off LED
}


void loop(){
while (Serial.available() == 0); // do nothing if nothing sent
int val = Serial.read() - '0'; // deduct ascii value of '0' to find numeric value of sent number

if (val == 1) { // test for command 1 then turn on LED
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // turn on LED
}
else if (val == 0) // test for command 0 then turn off LED
{
Serial.println("LED OFF");
digitalWrite(ledPin, LOW); // turn off LED
}
else // if not one of above command, do nothing
{
//val = val;
}
Serial.println(val);
Serial.flush(); // clear serial port
}

//------------- END OF ARDUINO SKETCH -----------------
 
1-40 of 41Next »
nuruluyul27 days ago

hello..i already tried this and it is awesome.. so i need to do the same things but using arduino and bluetooth hc-05.. it is same or need to add com port? do u have any idea? please help me.. tq sir :)

MarinC28 days ago

When I press Button 2 to turn off LED which is already turned off it turns on first then it turns off. Why so?

oliviAaaaa1 year ago
i have 6 Leds,
Led 1-5 use Integers 0-9 for on & off which works fine.
but when i use 10 to turn on Led 6 then Led 1 goes on. i assume the arduino only reads the first integer.

how can i fix this please thanks,,

**CODE**

while (Serial.available() > 0)

{

input += (char) Serial.read();

delay(5);

}

**/CODE**

This works for words at least!

felixa11 month ago

Error1'SerialPort1' is not declared. It may be inaccessible due to its protection level.C:\Users\Felix\AppData\Local\Temporary Projects\Arduino1\Form1.vb109Arduino1

how should i declare it?

MartinM41 month ago

How I send values from my temp sensor which is connected to A0 of Arduino Uno to vb

eulermath1 year ago
hi.
First, I want to thank the programmer who filled this gap. I built on this code snippet and made a robot control environment that is pretty cool.
I'm not very advanced with windows programming. I remember that we can add a drop-down box or a menu for choosing the specific COM port. Is there anyone here who has done that?
I just want to make my program look neat and decide what COM port to connect to at run time (arduino boards choose different COM's at different computers or different times).
Is there a way to make the VB program detect the ARDUINO board COM port automatically so that the user does not do anything (plug and play)?

you may use the below code.All the available COM ports will be listed in a combo box. For Arduino to be detected auto, i also been searching for the solution.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim strPortNames() As String
strPortNames = SerialPort.GetPortNames
Array.Sort(strPortNames)
ComboBox1.Items.AddRange(strPortNames)
ComboBox1.SelectedIndex = 1

ComboBox1.SelectedIndex = 1

This will auto select the 2nd Item of your combobox. Use 0 index for 1st item.

sabirpaints4 months ago

Hi, I'm new on instructables and also on ARDUINO, Can you please guide me that is the SKETCH is necessary for an ARDUINO SENSOR? Can we not directly control our arduino uno from visual basic.net?
Actually I want to measure water level in my water tank using arduino ultrasonic sensor and I'm not familiar with the programming language used in sketch that's why I asked this stupid question.

pauljuy5 months ago

hola quieria saber donde puedo encontrar informacion para realisar este tipo de programas

ivver8 months ago

is there any way to do the same thing but using bluetooth?

champ0231 year ago
hi guys, I've got a problem. Whenever I use a command to open serial port, if I use board rate from 19200 and above VB will automatically send some data (I don't know what this data is and where it's from) to controller via serial port. But when I use board rate 9600 this problem doesn't occur.


'-------------------------------------------vb code----------------------------------

Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel


Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With SerialPort1
         
            .PortName = "Com6"
            .RtsEnable = True
            .DataBits = 8
            .BaudRate = 19200
            .Parity = IO.Ports.Parity.None
            .StopBits = StopBits.One
            .Open()


        End With
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       
Dim int As Integer = 7

        SerialPort1.Write(BitConverter.GetBytes(int), 0, 1)

       
    End Sub
End Class

'------------------------------------------------end of vb coe----------------------------------

//----------------------------------- START OF ARDUINO SKETCH --------------------

void setup(){

Serial.begin(19200);
Serial1.begin(19200 );

}


void loop(){

   if (Serial.available()) {
    
         int val = Serial.read();
         Serial1.print(val);
      }  
     

     
}

//------------- END OF ARDUINO SKETCH -----------------


Thanks.

CHAMP



cpadilla101 year ago
Thank you, this post is really useful, could you tell me please what changes are necessary in VB code to control 4 leds with keyboard?,
can some one please explain this code for me i really feel stupid :(



int incomingByte = 0;
int r = 9;
int g = 10;
int b = 11;
int datar = 0;
int datag = 0;
int datab = 0;
int part = 0;
int numbertrans = 0;

void setup() {
Serial.begin(9600);
}

void loop() {


if (Serial.available() > 0) {

incomingByte = Serial.read();
if (incomingByte == 48) { numbertrans = 1; }
if (incomingByte == 49) { numbertrans = 25; }
if (incomingByte == 50) { numbertrans = 51; }
if (incomingByte == 51) { numbertrans = 76; }
if (incomingByte == 52) { numbertrans = 102; }
if (incomingByte == 53) { numbertrans = 127; }
if (incomingByte == 54) { numbertrans = 153; }
if (incomingByte == 55) { numbertrans = 178; }
if (incomingByte == 56) { numbertrans = 204; }
if (incomingByte == 57) { numbertrans = 255; }
if (incomingByte == 44) { part++; }
if (part == 0) {datar = numbertrans;}
if (part == 1) {datag = numbertrans;}
if (part == 2) {datab = numbertrans;}
if (part == 3) {
analogWrite(9, datar);
analogWrite(10, datag);
analogWrite(11, datab);
part = 0;}
// Below is evil dubug stuff
Serial.println(incomingByte, DEC);
}
}
acalaguin1 year ago
How about connecting to ethernet shield using vb2010?
ozzykaka1 year ago
it's cool~
But it still not work when I try it in VB
I "change com port to match your Arduino port"
And it work when I test in ARDUINO.(To check if it's ok)
If there any thing I need to check?


Cool! Works out just fine. I'm just wondering about this code:
Shared _continue As Boolean
Shared _serialPort As SerialPort
It happens to have an error and i just commented it, Still the program works. Can you explain why?
Muiz_99892 years ago
How to read and send serial data from a pushbutton attached to Arduino?
Hey, this lets me control pin 13, what if I want to control multiple pins???
Please let me know, how to control multiple pins.
Thanks,
techbitar (author)  booliminator2 years ago
You can accomplish this in many different ways. One way is to send a byte from the PC to Arduino containing a pin number and a value.

If we divide the byte we are sending into 2 X 4-bits, we can use 4-bits for pin number 0 to 15 and the other 4 bits to also send any value from 0 to 15. This requires basic binary math which is supported by both Arduino and VB. Of course you can decide how to interpret the bit patterns you are getting from the PC

Example: Suppose you want to control pin 4 to turn it on.

1) We can set the most significant 4-bits to number 4: In binary that's 0100.

2) Then we set the least significant 4-bits to 1111 to signify ON. (use whatever system that works for you)

3) Then we send 01001111 from PC to Arduino

4) At the Arduino, our sketch will read each 4-bit into pin# + command and act accordingly.

Hope this helps.
van05022 years ago
(removed by author or community request)
van0502 van05022 years ago
Also which Arduino Uno did you use (Arduino Uno R3 or R2) and what are its specifications?
techbitar (author)  van05022 years ago
It should not matter.
cmcg1822 years ago
This is great stuff... very helpful!!!! This code helped me understand the concept, however, there's still something I don't understand. How do you control different pins? For instance, if I wanted to add 2 more buttons (button 3 and 4) and have them turn on and off pin 12, along with the other two buttons still controlling pin 13, how would I do that? Thanks!
techbitar (author)  cmcg1822 years ago
Thanks! you can apply the concepts discussed in my serial Arduino guide to send a pin number then act on that value at the Arduino side. For example you can send two bytes, the first one contains the pin number and the second one a 1 or 0 to turn pin on or off. Or you can send a a range of values that you decide their meaning instead of just 1 or 0.
Where can we fund your serial ardunio guide?
Thank you! I will try it with the easy-driver.
creativen2 years ago
I use visual Basic 2010 but it can not run well, it shows:

Error 1 'SerialPort1' is not declared. It may be inaccessible due to its protection level. C:\Documents and Settings\Sugianto\Local Settings\Application Data\Temporary Projects\WindowsApplication1\Form1.vb 10 9 WindowsApplication1

Anyone knows what happen?
techbitar (author)  creativen2 years ago
Change COM ports in the VB code and try it again. My code uses COM10 but may be this port is used by other apps on your PC.
Finally i got the cause. It is not about the COM things.
I just forgot to drag Serial Port to the design window, now it works well.

Thank you for responding.

Anyway, in your code:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort1.Close()
SerialPort1.PortName = "com10" 'change com port to match your Arduino port
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!
End Sub


why do you start with SerialPort1.Close() ?
I have the same problem with you. What you mean by drag Serial Port to the design window? i can't get it!!
techbitar (author)  yhlee922 years ago
There's a Control icon in your VB tools named serial port. it's a control like a button or field. You drag it onto your form so you can access its properties.
techbitar (author)  creativen2 years ago
Glad it worked out.
how to drag the serial port icon into the visual basic 2010

any one help me plzzzz
rdesignee2 years ago
How to paste the code on the VB, after I create 2 buttons and 1 serial Port,
techbitar (author)  rdesignee2 years ago
i replied to your private message. hope that works for you.
I have a problem with this , may be it's easy ,i'm new in this stuff,
http://img210.imageshack.us/img210/9445/arduinoproblem.jpg
why ?
HELP PLEASE!!
techbitar (author)  betokardenas2 years ago
When I open your link I get an error message.
crob092 years ago
How do I do this for a stepper?
I have the VB code working thanks for that!
But I would love to have this work for a stepper motor and don't know how to write the sketch.
Any help greatly appreciated,
Rob

Here is what I have:

#include

while (val == 1) { // test for command 1 then turn on stepper
do
int enA = 10; // Enable pin 1 on Motor Control Shield
int enB = 11; // Enable pin 2 on Motor Control Shield
int dirA = 12; // Direction pin dirA on Motor Control Shield
int dirB = 13; // Direction pin dirB on Motor Control Shield
#If
(val == 0) // test for command 0 then turn on next stepper
do
int enA = 14; // Enable pin 1 on Motor Control Shield
int enB = 15; // Enable pin 2 on Motor Control Shield
int dirA = 16; // Direction pin dirA on Motor Control Shield
int dirB = 17; // Direction pin dirB on Motor Control Shield
end whileloop

const int stepsPerRevolution = 20; // Change this to fit the number of steps per revolution
// for your motor

// Initialize the stepper library on pins 12 and 13:
Stepper myStepper(stepsPerRevolution, dirA, dirB);


void setup() {
// set the speed at 60 rpm:
myStepper.setSpeed(60);

// Enable power to the motor
pinMode(enA, OUTPUT);
digitalWrite (enA, HIGH);

pinMode(enB, OUTPUT);
digitalWrite (enB, HIGH);
}

void loop() {
// Step five revolutions into one direction:
myStepper.step(stepsPerRevolution*5);
delay(2000);

// Step five revolutions in the other direction:
myStepper.step(-stepsPerRevolution*5);
delay(2000);
}

1-40 of 41Next »