The site for those who love tinkering with Arduino, Raspberry Pi & Co.
Interfacing Arduino with Visual Basic

Interfacing Arduino with Visual Basic

by

Let's learn how to make Arduino communicate with our Visual Basic software

In this tutorial we will see how it is possible to interface Arduino with Visual Basic using serial communication through the usb port.

It is possible to establish this kind of communication in all versions of Visual Basic, from the legendary version 6 to the most recent .net versions; the components to be used are always the same for all versions, apart from any small differences in syntax or in the names of the methods to be invoked.

Visual Basic 2008 express. In this tutorial we will see an example of serial communication between Arduino Uno and a small program written in Visual Basic 2008 express. The choice to use this version of Visual Basic stems from some advantages it offers:

  • it is a fairly advanced and evolved version, but at the same time very lean;
  • it is free, downloadable from the Microsoft website, and does not require special licenses;
  • requires the 3.5 framework which is already present in Windows 7 and later and which is not excessively heavy if installed in older PCs or with Windows XP (the 4.0 framework is a bit heavier and could create slowdowns if used in PCs with slower processors or with less Ram);
  • compared to vb6 (I guess vb6 lovers wishing not to abandon this version) does not present a drawback that we will talk about shortly that would make the program not very usable.

Operation. Let’s start by saying that whatever version of Visual Basic we decide to use, the working principle of communication between Arduino and Visual Basic will always be the same: serial communication between the two systems will be triggered. Visual Basic will send Arduino a request and Arduino will respond accordingly.

Commands and queries. Just for a matter of simplicity and clarity, and to better fix the ideas, in this tutorial we will distinguish two kinds of requests: commands and queries.

A command will be the request to do something, for example set a pin or execute a procedure present in the Arduino sketch.

The query will be the request to have returned a string from Arduino, which can contain, for example, the value of one or more variables, or the status of a sensor.

It is always good, however, to provide, even in the case of commands, a response from Arduino, which can be a simple confirmation if the command has been executed correctly or an error code if something did not go the right way.

Character versus String. Having made this premise, it is necessary to make a further clarification before moving on to concretely see some simple examples to achieve what we are talking about: Arduino in general can read from the serial one character at a time (let’s say one byte at a time), but it is able to write several bytes on the serial line all together (for example an entire string even quite long).

On its side, Visual Basic is able to write and read whole strings from the serial line without major problems, so to agree on the needs of both we will proceed as follows: Visual Basic will send its request by writing a byte on the serial (agreeing a certain coding, for example ‘T’ means ‘give me the temperature value’, or ‘R’ means ‘trigger the relay’ or ‘3’ means ‘change the state of pin 3′, etc …) and will receive from Arduino a string that may contain the confirmation of the successful execution of a command or the response to the query made.

Ready? Street! Since there are several sensors, each with their own syntax and configurations, let’s start with a very simple example that doesn’t require any additional components.

As with any self-respecting “Hello World”, we write a program in Visual Basic that can turn the LED of pin 13 of Arduino on and off and that can also query it about the current state of the pin.

In Arduino. After choosing the pin and setting the usual variables, in the loop the Serial.available () method tells us if there are bytes arriving on the serial.

In this example we are agreeing that a question mark ‘?’ it has to tell Arduino to read the pin status and return it.

An ‘A’ must make the pin light up, an ‘S‘ must make it go out, a ‘C‘ must change its state. In each case it must then provide a confirmation response which we agree should end with a semicolon.

In each case it must then provide a confirmation response which we agree should end with a semicolon.

#define OFF LOW // off
#define ON HIGH // turned on
#define PinLed 13 // pin to control
char * Resp; // Arduino's answer
byte data; // character received

void setup () {
 pinMode (PinLed, OUTPUT);
 Serial.begin (9600);
}

void loop () {
 if (Serial.available ()> 0) // if a byte arrives from the pc
 {
   Ans = "?;";
   data = Serial.read (); // I read from the serial
 
   if (data == '?') {
     if (digitalRead (PinLed) == ON) Ans = "ON;";
     else Reply = "OFF;";
   }
 
   if (data == 'A') {// turn on the led
     digitalWrite (PinLed, ON);
     Reply = "ON;";
   }
 
   if (data == 'S') {// turn off the led
     digitalWrite (PinLed, OFF);
     Reply = "OFF;";
   } 
 
   if (data == 'C') {// change the status of the led
     if (digitalRead (PinLed) == ON)
       {
       digitalWrite (PinLed, OFF);
       Reply = "OFF;";
       }
   else 
      {
       digitalWrite (PinLed, ON);
       Reply = "ON;";
      }
   }
 
   if (data == 'T') {
      // based on your temperature sensor
      // write the appropriate code
      // read the temperature from the sensor and then
     Ans = "Temperature ...;";
   }

   // more ifs and then ...
  
   Serial.write (Reply); // we return the answer

  } // if serial.available
} // loop

For those wishing to take a small step further, we agree to read the temperature value from the appropriate sensor and return it when a request is received on the serial through the ‘T’ byte.

Visual Basic. In a new Visual Basic project, we insert in the main Form (which we will call Desktop) a picture object in which we will alternate any pair of On and Off images (on Google Images there are a million).

We will save the images in the same folder where the executable will be created with the names on.jpg and off.jpg; the more daring can insert a second picture object with the image of a thermometer.

Then we need a Label in which to view the Arduino return messages.

Visual Basic application example

We insert a SerialPort object into the project and agree to associate it with Com7. In the Form_Load we have to set the variables and, if the Com7 port is not available, we give the user the possibility to rectify the default choice thanks to the interception of error 57.

Private Sub Desktop_Load (ByVal sender As System.Object, ByVal and As System.EventArgs) Handles MyBase.Load
  On Error GoTo Error
  With SerialPort
     .PortName = "COM7" 'or other port 
     .Open ()
     Me.Text = "Serial 2008 Arduino -" & .PortName
  End With
  Dim OnOff As String
  OnOff = Send ("?")
  Img.Load (Application.StartupPath & "/" & OnOff & ".jpg")
  Label1.Text = OnOff
  Exit Sub
Error:
  If Err.Number = 57 Then
    Dim Porta As String
    Port = "" & InputBox (Err.Description & "Enter Port Name",, "COM7")
    If Port <> "" Then
       SerialPort.PortName = Port
       Resume
    End If
  End If
  MsgBox ([" & Err.Number & "]"" & Err.Description)
End Sub

The Send function takes as a parameter a String, that is the character to be sent to Arduino by writing on the serial.

It handles the possible occurrence of errors and returns a string which is the response of the Arduino. This is read from the serial line until the semicolon arrives which decrees the end of the transmission.

In the Form_Load the Arduino is immediately queried about the current state of the pin, and the image on.jpg or off.jpg is displayed.

Private Function Send (ByVal Character As String) As String
  If Character = "" Then
     Return ""
  End If
  Dim Result As String = ""
  Dim c As String = ""
  SerialPort.DiscardInBuffer ()
  SerialPort.DiscardOutBuffer ()
  Try
   SerialPort.Write (Character)
  Catch ex As Exception
   Return "Error[" & Err.Number & "]" & Err.Description
  End Try

  While True
    While SerialPort.BytesToRead> 0
      c = Chr (SerialPort.ReadChar)
      If c = ";" Then
        Return Result
      Else
        Result = Result & c.ToString
      End If
    End While
  End While
  Return ""
End Function

Now it is easy to associate the click of the image with sending a “C” that changes the status of the pin and displays the new jpg.

Private Sub Img_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Img.Click
  Dim OnOff As String
  OnOff = Send ("C")
  Label1.Text = OnOff
  Img.Load (Application.StartupPath & "" & OnOff & ".jpg")
End Sub

Similarly, we can associate the click of the thermometer image with the sending of the “T” character and the display of the response on Label1

Private Sub Temperature_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Temperature.Click
  Label1.Text = Submit ("T")
End Sub

Taking a cue from these simple commands, we can now enrich the project with new character submissions, taking care to create specific procedures in the corresponding Arduino counterpart.

One last recommendation. At present, sending a command not recognized by Arduino results in the return of the string “?;” which will be perceived by Visual Basic as an answer that contains a question mark.

Let’s not forget the final semicolon when Arduino sends a response to Visual Basic, otherwise the latter receives the response but waits for the semicolon, risking to block the serial port in an infinite loop.

To lovers of vb6. As promised, I have one last debt to pay to vb6 lovers.

The same project can also be done in vb6, indeed, I confess that the first time I also wrote it in vb6 to hurry up soon.

However, there is a problem: every time the program is launched in vb6 and the serial connection is established, the Arduino resets itself. Reload the setup and then regularly loop it.

In this way, if for example we have left one or more pins set in a certain way, as soon as we open vb6 we return to the initial setup state.

This is not acceptable if the system has to maintain its life and its configuration continuously over time.

In Visual Basic 2008 this does not happen.

You can turn on a LED, set some pins and exit the program, when you reopen the Arduino program it continues its work.

Serial communication behaves in an absolutely transparent and painless way, unlike vb6.

Ti è rimasta una domanda o un dubbio?

Iscriviti e chiedi nella community

Leave a Reply

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