Skip to main content

Introduction to linking Visual Basic to an Arduino

 Visual Basic is an "Object Oriented" language and is a programming environment which I'm comfortable in, so I'm going to look at the steps involved in setting up a Program on a Laptop to control a simple model train layout.

Using an Arduino Uno, connect via a USB Cable, the first thing is to establish communication from Laptop to the Arduino.

This needs the Comms Component to be added.  This link shows how to do that.

    http://www.thaiio.com/prog-cgi/0002_serial.htm

This picture shows the main (functional) sections of code, along with the Program display (Bottom left) when it's running.

The Visual Basic bit (top left)
In VB, you add "Objects" to a form and then attach some code to each Object.
Some of the Objects you get in VB are Command Buttons, Labels, Text Boxes, List Boxes.  There are many others.
This example has "Command Buttons" named "Red On", "Green Off" and all that happens is when, for example you click on the "Red On" is a single character "R" is sent via the serial link to the Arduino.

The Arduino bit - (Right hand side)
When it receives the single character 'R' it sets the red_Led to HIGH, ie the Red LED is switched on.
After that, it is a simple duplication of this bit of code to switch the Red LED off, and also to control the green LED.

The Full code.
Visual Basic first
This first set of code is to enable the serial port for communication.  The bits that do the work are in Orange.  The ones in blue are error trapping so that the Program won't crash
Private Sub Set_Comms_Click()     '  Procedure to enable Serial communication

On Error GoTo porterror          ' Error Trap; allow for folk entering an invalid number - prevents program crashing
  portnumber = InputBox("Enter a number", "Choose Port 1 . . 8", 3)     '   display a message to enter a Port Number
                                                                        '  The default is set at 3
  MSComm1.RThreshold = 1         '   sets buffer size to 1
  MSComm1.CommPort = portnumber  '   allocates number entered a couple of lines ago
  MSComm1.PortOpen = True        '   Switch it on!!
  MSComm1.DTREnable = False      '   Not 100% sure what this does
  MSComm1.Output = "X"           '   Sets a "Non-Functional" into the buffer
  Set_Comms.Visible = False     '   Hides the Select Port button, It's job is finished
 
  Exit Sub                        '   Exits subroutine so no unintended changes are made
porterror:                       '   Label used in code flow
  MsgBox ("Invalid Port Number" & Chr(13) & "Use numbers from 1 to 8")  ' Message box gives info about valid numbers
End Sub

and these lines of code link the command buttons to the relevant bits of code. 
In terms of what we want to do, these are the important lines of code.

Private Sub Green_On_Click()
    MSComm1.Output = "G"      '   Sends G to the Arduino to  Switch on Green
End Sub

Private Sub Green_Off_Click()    
    MSComm1.Output = "g"      '   Sends r to the Arduino to Switch off Green
End Sub

Private Sub Red_On_Click()
  MSComm1.Output = "R"        '   Sends R to the Arduino to  Switch on Red
End Sub

Private Sub Red_Off_Click()
  MSComm1.Output = "r"        '   Sends r to the Arduino to  Switch off Red
End Sub

Now the Arduino Code.

int red_LED=10;    //   assigns pin 10 to the red LED
int green_LED = 7;    //  assigns pin 7 to the Green LED
char inpchar;             //  declares a Character variable to be used in the program

void setup() 
{
pinMode(red_LED,OUTPUT);      //    sets the green LED (pin 7) as an Output
pinMode(green_LED,OUTPUT);  //     sets the red LED (pin 10) as an Output

Serial.begin(9600);                       //  enables serial input to the Arduino

void loop() {
if (Serial.available())  { inpchar = Serial.read();}            // Reads single character from Input Port
if (inpchar == 'R')  {  digitalWrite(red_LED,HIGH);}    // if it's an 'R' set the output to pin 10 to HIGH
if (inpchar == 'r')  {  digitalWrite(red_LED,LOW);} 
if (inpchar == 'G')  {  digitalWrite(green_LED,HIGH);} 
if (inpchar == 'g')  {  digitalWrite(green_LED,LOW);}
inpchar = '.';  //  Change value of input character to prevent repetition
}

And those are the basic steps needed to control LEDs from a Laptop.  After this, it is a case of adding more code to get additional features working.

 

Comments

Popular posts from this blog

Train sequence / timetable using Arduino

                              Following discussions in a MERG Zoom meeting about potential projects for the Cumbria virtual area group I have started this blog to share my ideas for building a train sequence / timetable system based on an Arduino UNO. The trigger for this project was Andy Robb's article in the MERG journal (June 2020 edition). In it Andy describes using an UNO with a OLED display to produce an electronic station display board.  Having tried out Andy's version I started thinking about expanding the idea and have come up the following list of possibilities: 1. Replace my card index train sequence with an electronic version. 2. Have the train sequence synchronised with the on platform displays. 3. Display an analogue clock on the station display and have it display the train times. 4. Store the position reached in the sequence so that it starts where it left off on power up.  To mak...

3D Printing Presentation

Sunday's Zoom meeting had our largest audience so far with 19 members attending from various parts of the country. Alan Geekie gave us an excellent and well received presentation on 3D printing that included FDM (Fused Deposition Modeling) and SLA (Stereolithography apparatus) types He first showed how we can source "things to print" using sites like Thingiverse. His own filament printer was the Prusa i3 Mk 3S which is available either as a kit (£699) or pre-assembled (£899) and features a self leveling bed. It also benefited from an additional multi material upgrade kit and he demonstrated the start up sequence of leveling, homing, clearing remaining filament from the hot end and then beginning the print.  The process of slicing where a 3d object drawing file (.stl) is broken up into the x,y,z drawing coordinates for each individual layer was also explained. Alan then moved on to resin printers using another Prusa model, the SL1 and its associated curing and washing mach...

Mimic Points in Visual Basic

For this project, I wanted to create a moving graphic to mimic a set of points moving from one position to the other.  This Blog shows all that is needed. The first Picture shows the 6 lines needed.                                 This Picture shows the Line Properties.    The tracks are shown with 5 lines, though only the middle ones in red are involved.  The other line shown below the others is the one that actually "moves".  It is shown below the other lines for clarity only.  At the start of the Program running, it is positioned over the lower red line. In VB, each Line has properties and these are shown above.  To get a line to appear to move, all that needs to be done is to gradually change the X2 and Y2 co-ordinates of the line. This is the code for the program. The first 6 lines create a pause Function in the program, by using the Computers internal C...