Вы находитесь на странице: 1из 87

World Skills Robotics Collection

Basic Programming

Studica Limited | | May, 2018


Contents
2 The Quick Start Guide .................................................................................................................. 5
3 Introduction.................................................................................................................................. 6
4 The NI myRIO................................................................................................................................ 7
INPUTS-OUTPUTS ......................................................................................................................... 7
5 Programming the myRIO .............................................................................................................. 9
SETTING UP THE MYRIO ............................................................................................................... 9
Figure 2 NI myRIO USB monitor ................................................................................................ 9

LABVIEW BASICS2....................................................................................................................... 11
Figure 4 An Example Block Diagram on the Left and a Front Panel on the Right................... 11
Terminals ................................................................................................................................ 12
Figure 5 Controls Palette ......................................................................................................... 11
Wires and Nodes ..................................................................................................................... 11
Table 1 Common Wire types ................................................................................................... 12
Figure 7 Functions Palette ....................................................................................................... 13
Figure 8 Dataflow Programming Example .............................................................................. 13
Basic Loops and structures ..................................................................................................... 14
Figure 9 Case Structure ........................................................................................................... 14
Figure 10 Sequence Structure ................................................................................................. 14
Figure 11 For Loop .................................................................................................................. 14
Figure 12 While Loop .............................................................................................................. 15
Running the Code.................................................................................................................... 16
Important: Try to avoid using the abort execution button when interfacing with real
hardware!!! ............................................................................................................. 16
Debugging the code ................................................................................................................ 16
Interfacing with the myRIO hardware .................................................................................... 17
CONNECTING TO THE MYRIO OVER WIFI ............................................................................... 21
COMMON MISTAKES .............................................................................................................. 22
6 WSR Sensors and Motors ........................................................................................................... 23
SENSORS ..................................................................................................................................... 23
Switches 23
Figure 19 Switches .................................................................................................................. 23
How to write your first myRIO program – Switch Output ......................................................... 25

........................ 25
Example code for a Switch ...................................................................................................... 25
REMEMBER – Whenever using myRIO for LabVIEW we need to start with a project .............. 26
Line Sensor Board ................................................................................................................... 33
IR Distance Sensor .................................................................................................................. 41
Example Code for the IR sensor............................................................................................... 43
The Studica Toolkit and Custom FPGA .......................................................................................... 44
Studica Toolkit for World Skills Robotics and the MD2 Motor Driver .................................... 44
Studica provides a WorldSkills Toolkit which add libraries of functions, VIs, interactive
wizards, examples, utilities, and documentation for World Skills competitors
effectively reducing the time required to finish your task. ..................................... 44
The Toolkit is shipped in a VIP format. VI Packages are similar to zip files in that they contain
all the VIs and resources for a specific LabVIEW add-on, as well as information the
VIPM software uses to install, remove, and manage the add-on. Simply click on the
VIP package to launch and install the toolkit. The Toolkit require a user to be using
LabVIEW for Myrio 2017. ........................................................................................ 44
Installing the Custom FPGA .................................................................................................... 44
Studica FPGA Personalities (LabVIEW 2017 Studica Toolkit) ................ 45
Supported Channels ...................................................................................................... 46
MD 2 Motor Adapter for NI myRIO......................................................................................... 47
Servo Motor ............................................................................................................................ 60
Webcam 63
Robotics Navigation Sensor .................................................................................................... 65
Ultrasonic Distance Sensor ..................................................................................................... 73
Basic Robot Drive .................................................................................................................... 75
Example Program.................................................................................................................... 86
Example Program........................................................................Error! Bookmark not defined.
Case “1” Error! Bookmark not defined.
Helpful links ................................................................................................................................... 88
2 The Quick Start Guide
This section will give quick references on how to get started with the myRIO. However, to fully
understand myRIO and how it is being used within World Skills Robotics, you must read
through the rest of the Manual.

1. Install LabVIEW.
2. Watch the video explaining what the myRIO is and what comes with it.
http://www.ni.com/video/3094/en/ - Update this (make video?)
3. Watch the video on how to write your first myRIO program.
https://www.youtube.com/watch?v=Ak-N8o6C7C0 Update
this (make video?)
4. Watch the video that shows how to program a more involved myRIO program.
https://youtu.be/R4tWLmBUqA8 Update this (make video?)

The following resources from NI will provide you with additional support for LabVIEW

• Learn LabVIEW—Video Training


• LabVIEW Environment Overview
• Creating Custom Controls
• LabVIEW Dataflow
• LabVIEW Tools
• LabVIEW Data Structures
• LabVIEW Debugging

5
3 Introduction
This document describes the components of the World Skills Robotics Collection which, most
importantly, includes the NI myRIO controller shown in Figure 1. The controller is a portable
reconfigurable I/O (RIO) device used in the design of control, robotics, and mechatronics
systems. The controller is programmable with LabVIEW and C languages. The WSR collection
includes; four DC motors with built in encoders, 2 Servo motors, and two MD2 motor control
boards. There are also multiple sensors included with the collection: two ultrasonic distance
sensors, two IR distance sensor, a 9-axis inertial/magnetic sensor and motion processor, and
one Line Sensor Breakout Board. This document includes explanations of the controller and
Motor Control boards, general LabVIEW programming, and operating instructions for each item
in the collection with sample VI’s.

Figure 1 myRIO- 1900

6
4 The NI myRIO
The NI myRIO is an embedded hardware device designed specifically to help students design
real, complex engineering systems quickly and affordably. More information can be found at
http://www.ni.com/myRIO/what-is/.

INPUTS-OUTPUTS
The NI myRIO-1900 provides analog input, analog output, digital input and output, audio, and
power output. The NI myRIO-1900 connects to a host computer over USB and wireless
802.11b,g,n.

The MXP ports (the A and B ports), shown on the left side of Figure 1, both have 16 Digital
Input-Output, 2 Analog Output, 4 Analog Input and UART communication channels. The
channels can also be configured to accept an Encoder input, 3 PWM outputs and SPI and I2C
communication. The MSP (the C port) labeled 7 in Figure 1 has 8 Digital Input-Output, 2 Analog
Output, and 2 Analog Input channels. The C port can also accept 2 encoders.

See the full myRIO manual at http://www.ni.com/pdf/manuals/376047a.pdf for more


information about the ports.

With each Motor Adapter, you can easily connect and control either one stepper motor, two
DC motors, or two servos independently through the MXP connector on your myRIO. This
design does not need additional circuitry to drive motors. Just supply power. The 34-pin
female breakout allows direct user access to signal pins.

7
8
5 Programming the myRIO
SETTING UP THE MYRIO
1. Download LabVIEW 2017 for myRIO from here, or you
can use the supplied software bundle on DVD. If
downloading, make sure that the download does not
timeout during the download, check the size on disk
etc.
2. Install the Software bundle. Your serial number is
provided in the package.

Figure 2 NI myRIO USB monitor

3. Connect power to the NI myRIO device


4. Connect the USB cable form NI myRIO to your PC.
5. The NI myRIO USB Monitor appears (Figure 2)
6. Launch the Getting Started Wizard and follow the
instructions. Update to the recommended drivers if
prompted.
7. Studica provides a LabVIEW Toolkit VI package for the
WSR Collection in LabVIEW VIP format. Find the
Studica LabVIEW Toolkit folder. You can install the
VIP package by double clicking on the VIP file. The
current toolkit requires LabVIEW 2017.
8. Open LabVIEW
9. Click File->Create Project
10. Use the myRIO Project Template and any name
11. The LabVIEW Project Explorer opens Figure 3 Connect to myRIO in
12. Right Click on “myRIO-1900 (172.22.11.2)” and right- Project Explorer
click Connect (Figure 3) 1
13. If the process finishes successfully then everything is
set up correctly and you can begin programming the
device.

1
If you are using the myRIO over Wi-Fi then click properties and insert the correct IP address and click connect.
9
10
LABVIEW BASICS2

LabVIEW is a visual programming language. Execution of the code is determined by a graphical


block diagram where the programmer connects different function-nodes by drawing wires.
These wires propagate variables and any node can execute as soon as all its input data becomes
available. Since this might be the case for multiple nodes simultaneously, LabVIEW is inherently
capable of parallel execution.

LabVIEW links the creation of user interfaces, called front panels, into the development cycle.
LabVIEW programs/subroutines are called virtual instruments (VIs). Each VI has two main
components: a block diagram and a front panel. The front panel is built using controls and
indicators. Controls are inputs – they allow a user to supply information to the VI. Indicators are
outputs – they indicate, or display, the results based on the inputs given to the VI.
The block diagram contains the graphical source code. All of the functional objects placed on
the front panel will appear on the block diagram as terminals (either input or output). The block
diagram also contains structures and functions that perform operations on controls and supply
data to indicators. Examples of the front panel and the block diagram can be seen in Figure 4.

Figure 4 An Example Block Diagram on the Left and a Front Panel on the Right

2
It is advised, however not compulsory, that the students complete the “WSR participant guide package supplied
to WSR collection holders

11
The structures and functions are found on the Functions palette which will be visible by right-
clicking on an empty area in either the front panel or the block diagram. Collectively controls,
indicators, structures and functions will be referred to as nodes. Nodes are connected to one
another using wires – e.g. two controls and an indicator can be wired to the addition function
so that the indicator displays the sum of the two controls.

The graphical approach also allows non-programmers to build programs by dragging and
dropping virtual representations of lab equipment with which they are already familiar. The
LabVIEW programming environment, with the included examples and documentation, makes it
simple to create small applications compared to traditional text-based programming.

VIs are LabVIEW programs, and multiple VIs can be used together to make a LabVIEW
application. To group these related Vis together, use a LabVIEW project, that includes
references to all the LabVIEW files and non-LabVIEW files in the project, configuration
information, build information, and deployment information. When you open a LabVIEW
project, the Project Explorer opens. From there you can open all the files that are linked to the
project and add new ones. You will need to create a LabVIEW project and have the myRIO
included in the project to run your VIs and download them to the myRIO.

Tip: You can easily switch between the front panel


and block diagram by pressing ctrl+e

Terminals
The front panel is created with interactive input and output terminals of the VI, referred to as
controls and indicators, respectively. Controls are knobs, push buttons, dials, and other input
devices. Indicators are graphs, LEDs and other displays. Controls simulate input devices and
supply data to the block diagram of the VI. Indicators simulate output devices and display data
the block diagram acquires or generates. You can get the Controls Palette as seen in Figure 5
by right clicking on an empty area. Objects on the front panel window appear as terminals on
the block diagram. Terminals are entry and exit ports that exchange information between the
front panel and block diagram.

10
Tip: You can move between the
front panel and block diagram by
double-clicking on an indicator or
control

Figure 5 Controls Palette

The Controls and Indicators can be of the following types:

• Numeric – Can represent numbers of various types, such as integer or real.


• Boolean – Represents data that only has two possible states, such as TRUE and FALSE or
ON and OFF or HIGH and LOW.
• String – Is a sequence of ASCII characters
• Other – All of the data types can be in multiple dimensional arrays and combined with
other data types that are defined in .ctl files.
Wires and Nodes
Nodes are objects on the block diagram that have inputs and/or outputs and perform
operations when a VI runs. They are analogous to statements, operators, functions, and
subroutines in text-based programming languages. Nodes can be functions, subVIs, Express VIs,
or structures. Structures are process control elements, such as Case structures, For Loops, or
While Loops. You can transfer data among block diagram objects through wires. Each wire has a
single data source, but you can wire it to many VIs and functions that read the data. Wires have
different colors, styles, and thicknesses, depending on their data types. Table 1 shows the most
common wire types. Blue lines are integers and orange lines are of the type double.

11
A broken wire appears as a dashed black Line with a red X in the middle . To clean
up any broken wires press ctrl+b3.

Table 1 Common Wire types

Figure 6 Wiring tool


You must connect the wires to inputs and outputs that are compatible with the data that is
transferred with the wire. You must connect the wires to only one input and at least one
output. To draw a wire, hover the mouse over an input or an output until the cursor changes to
the “wiring tool”, then left click to start drawing a wire. This is seen in Figure 6.

3
All keyboard shortcuts can be found at http://zone.ni.com/reference/en-XX/help/371361H-
01/lvhowto/keyboard_shortcuts/

12
The Functions palette seen in Figure 7
contains the VIs, functions, and constants
used to create the block diagram. You can
access the Functions Palette by right clicking
on an empty area in the block diagram.

Tip: If you know what you are looking


for, you can find it fast with Quick Drop
by pressing ctrl+space

Figure 7 Functions Palette Figure 8 Dataflow Programming Example


The order of execution is determined by how your objects on the block diagram are wired
together. A node will execute only when data are available at all of its input terminals and
supplies data to the output terminals only when the node finishes execution. For example, In
Figure 8, it is impossible to know which segment will execute first – the Add, Random Number,
or Divide function. This unknown order of execution occurs because inputs to the Add and
Divide functions are available at the same time, and the Random Number function has no
inputs. In a situation where one code segment must execute before another, and no data
dependency exists between the nodes, you should use other programming methods, such as
sequence structures or error clusters, to force the order of execution. These structures are
further explained in the next section.

13
Basic Loops and structures
The Case Structure has one or more subdiagrams, or cases, exactly one of which executes when
the structure executes. Whether it executes depends on the value of the Boolean, string, or
numeric scalar you wire to the external side of the terminal, labeled selector. A sample Case
Structure is shown in Figure 9.

Figure 9 Case Structure


The Sequence Structure Consists of one or more subdiagrams, or frames, that execute
sequentially. As an option, you can add sequence locals that allow you to pass information from
one frame to subsequent frames by wiring a wire to the edge of the structure. You can add
more frames by clicking “Add Frame After” from the right-click menu. A Sequence Structure can
be seen in Figure 10.

Figure 10 Sequence Structure


A For Loop executes its subdiagram N times, where N is the value contained in the count
terminal. A For Loop is shown in Figure 11.

Figure 11 For Loop

14
A While Loop executes its subdiagram until a Boolean value you wire to the conditional terminal is
TRUE. A While loop can be seen in Figure 12. Note that you can wire any Boolean value to the
conditional terminal, it does not have to be a button on the Front Panel. As an option, you can again
add shift registers so you can pass information from one iteration to the next. The value you wire
to the shift register on the right side can be read from the shift register on the left side in the next
iteration (these can also be used in For Loops). In the while loop shown in Figure 12 the numeric
indicator on the front panel is going to display “1” the first iteration of the while loop and “0” for
any consequent because the initial condition is “1” and there is a constant “0” wired to the right
side shift register.

A Local Variable lets you read or write to one of the controls or indicators on the front panel of your
VI. Writing to a local variable has the same result as passing data to a terminal, except that you can
write to it even though it is a control or read from it even though it is an indicator.
Local variables are useful when sending data between structures becomes very messy. You can
insert a local variable onto the block diagram by searching “Local Variable” in the Quick Drop menu
(ctrl+space) or alternatively you can right click on a control or indicator and choose “Local
Variable”. You can choose whether to read from the terminal or write to it. However, using

Figure 12 While Loop


local variables is not good practice, because the program flow will be less clear and race conditions
(when a data block is read from and written to at the same time), may occur.

15
Running the Code

To run the code, click on the arrow on the top of the Block diagram or the Front Panel. If the
arrow is broken it means there are errors in your code and you can see the error list by
pressing on it. The abort execution button stops the code regardless where execution of the
code is.
Important: Try to avoid using the abort execution button
when interfacing with real hardware!!!

IMPORTANT: By default, the myRIO will not run a program when


you plug it in. To run the code autonomously, the following steps
are necessary:

1. Right click new->Real-Time Application on Build Specifications


under the myRIO tree in Project manager.
2. A configuration dialog opens. Go to Source Files and move the
VI that you wish to run (e.g., “Main.vi”) to the startup VI-s
3. Click OK
4. Right click on the Real-Time application you created under Build
Specifications and click Build.
5. Right click on the Real-Time application
and click “Set as Startup”.
6. Right click on the Real-Time application
you created and click “Deploy”.
7. If the myRIO reboots your code will run
automatically (note that it takes about
20 seconds for the myRIO to start up)
If you change the code you need to
build and deploy the code again.

Debugging the code

To debug your code you can press on the highlight execution button in the block diagram
and you will see the code running slowly with values written on wires. Alternatively, you can
right click on a wire and click on probe or left click on a wire when running the code. This will
allow you to see the value of that wire when the code is running at full speed. You can also
always add indicators that will display data on the front panel.

This was a very brief intro to LabVIEW programming. There is an extensive help section in LabVIEW. In
addition, there is a lot of information and examples on ni.com as well as other locations on the Internet. If you
register your copy of LabVIEW on ni.com you are eligible for free self-paced trainings offered at
http://sine.ni.com/myni/self-paced- training/app/main.xhtml

16
Interfacing with the myRIO hardware
From the Functions Pallet you will find the myRIO section where there are a variety of Express
VI, Low Level Programming Tools and the Studica Toolkit, which are all you need to utilize the
inputs and outputs of the myRIO.

An Express VI is a VI with settings that you can configure interactively through a dialog box.
Express VIs appear on the block diagram as expandable nodes with icons surrounded by a blue
field.

You can configure an Express VI by setting options in the configuration dialog box that appears
when you place the Express VI on the block diagram. You can double-click the Express VI or
right-click the Express VI and select Properties from the shortcut menu to reopen the
configuration dialog box. You can also configure the Express VI by wiring values to terminals of
the Express VI on the block diagram.

Below are some of the Express VIs are used in this manual:

• Digital Input – Reads an on/off signal from a sensor such as a switch


• Analog Input – Reads the Voltage on a specified channel
• Encoder – Reads the number of clicks and gives the direction of rotation
• PWM – Outputs a PWM signal on a specified channel
• Digital Output – Writes and on/off value to a channel
• LED – Lets the user control the LEDs on the myRIO4
• Button – Reads the on-board Button0 that is on the myRIO5
• Accelerometer – Reads the values from the on-board accelerometer

When you select an Express VI, drag it to the block diagram and a configuration dialog box
appears where you will choose the channels you want to include.

4
Functionality is the same as compared to the Digital Output Express VI
5
Functionality is the same as compared to the Digital Input Express VI

17
CONNECTING TO THE MYRIO OVER WIFI
It might be desirable to talk to the controller wirelessly. You may want to do so when multiple
people wish to communicate with the device, or when you cannot (are not allowed) to be
physically in contact with your device.

To set it up please follow the steps.

1. Plug the myRIO to your computer through USB


2. Go to http://172.22.11.2 in your internet browser
3. Go to “Network Configuration” on the left side menu
4. Choose “Create wireless network” under "Wireless Adapter wlan0"
5. Enter the name of your network under “SSID” and choose the security features you
want.
6. In your computers network settings log into the WI-FI network you just created. (If
your Ethernet cable is not plugged in you probably will not be able to connect to the
internet until you reconnect to your standard network)
7. To program the myRIO and view data over WI-FI right click on the myRIO in the
project explorer in LabVIEW and choose "properties". Then under "general" change IP
address to 172.16.0.1

*To communicate through USB again, you will need to change the IP address in the
project manager back to 172.22.11.2

21
COMMON MISTAKES

• The WiFi button on the myRIO does nothing.


• It takes about 20 seconds for the myRIO to boot up. (Tip: use an LED indicator to show
when the myRIO is running.)
• If you have not set a start-up VI the myRIO will do nothing when powered on.
• If a switch is not connected, the myRIO will read "TRUE" because of this
concept: http://en.wikipedia.org/wiki/Pull-up_resistor - you are dealing with low level
electronics. This means: switch pushed is “FALSE”, released is “TRUE”
• The myRIO can use up to 1 A (the bigger power adapter can supply max 3 A) of current
so it is advisable to use both power adapters at the same time when using many
actuators to ensure that everything works reliably.
• When you use the "wait" blocks to do timing, the entire structure where it is at will be
on pause.
• Any structure or VI used in in your code will only execute if ALL the inputs have been
given a value.
• If all elements on your block diagram have executed the program will stop. This is the
reason why in most cases you will need a while loop to keep your code running.

22
6 WSR Sensors and Motors
This chapter will explain the components included in the collection. For each component, its
basic principle of operation will be discussed; then, how to program the myRIO to utilize each
component will be covered.

SENSORS

Switches
Momentary switches send a signal to the myRIO when they are triggered. These switches serve
as basic user-interface devices as well as simple sensors, e.g., push buttons, bumper sensors…
Simple Switches can provide feedback as events "happen" and can be useful as a trigger in a
variety of applications.
They are simply two wires connected by a mechanically triggered attachment. In the relaxed
state, the two wires are said to be open, not connected. When the lever is pressed down,
closing the switch, the two wires are shorted and a current flow. The long-arm switch is
momentary; its circuit only remains closed while the lever is pressed. The pushbutton switch is
a toggle switch. Once pressed, it will remain in the switched position until pressed again. The
switches provide an input signal in one of two possible states. A “LOW” corresponds to a
closed circuit, the condition when the switch is closed, while a “HIGH” corresponds to an open
circuit, which is the condition when the switch is not pressed. “LOW” and “HIGH” can also be
interpreted as “FALSE” and “TRUE”. 6

Figure 19 Switches

6
It might not seem logical why “LOW” and “HIGH” are interpreted as such but is a common concept in electronics
http://en.wikipedia.org/wiki/Pull-up_resistor.

23
Learning Objectives: After completing the activities in this exercise you will be able to:

1. Discuss the essential concepts associated with a pushbutton switch:

(a) Pushbutton switch appears as a short circuit when pressed, otherwise as an open circuit,

(b) Interface circuit to the digital input relies on the DIO internal pull resistors to eliminate the need
for additional components (pull-up on MXP Connectors A and B, pull-down on MSP Connector C),

(c) Block diagram views the switch as a Boolean (two-level) signal that is either active-high or active-
low depending on the type of pull resistor, and

2. Apply software-based edge detection to convert a pushbutton press into a trigger event.

Select These Parts from the WSR Collection:


1. Limit Switch
2. MD2 Motor Adaptor for NI myRIO
3. Jumper wires, M-M (2X)

Build the interface circuit:

This single-pole, double-throw (SPDT) momentary switch can be used as a general-purpose micro switch
or tactile bump sensor for your robot.

The pushbutton switch interface circuit requires two connections to NI myRIO MXP Connector A, to do this
we will use the 34-pin female breakout allowing direct access to the signal pins. Plug a motor control board
into MXP A and wire the switch.

1. Basic Switch NO - A/DIO0 (pin 11)


2. Basic Switch COM - A/GND (pin 12)

Normally Open Configuration

24
Run the demonstration VI:

1. Open the project Pushbutton demo.lvproj contained in the subfolder Pushbutton demo located in
the Part 2 – myRIO Interfacing folder for the WSR Learning files,
2. Expand the hierarchy button (a plus sign) for the myRIO item and then open Main.vi by double-
clicking,
3. Confirm that NI myRIO is connected to your computer, and
4. Run the VI either by clicking the Run button on the toolbar or by pressing Ctrl+R.

Expect to see a “Deployment Process” window showing how the project compiles and deploys (downloads)
to NI myRIO before the VI starts running.

NOTE: You may wish to select the “Close on successful completion” option to make the VI start
automatically.

Expected results: The demo VI displays the input state of three DIOs, one on each connector. The states of
the Connector A and B DIOs should be high due to the internal pull-up resistors, and the Connector C DIO
should be low because of the internal pulldown resistor. Press the pushbutton and you should see the
A/DIO0 state indicator change to low; release the pushbutton and the state should go high again.
The demo VI also counts pushbutton presses detected on B/DIO0. Stop and restart the VI to clear the
counter value.

Click the Stop button or press the escape key to stop the VI and to reset NI myRIO; a myRIO reset causes all
of the digital I/O pins to revert to input mode.

Interface Theory
Interface circuit: The pushbutton switch normally appears as an open circuit and becomes a short circuit
when pressed. The pushbutton may be connected directly to the digital input without any additional
components because of the internal pull resistors on the NI myRIO DIO lines.

How to write your first myRIO program – Switch Output

Example code for a Switch


25
Each switch is connected to a data channel through the Digital Input Express VI. Choose the
channels you want to use and name them accordingly. Refer to the myRIO documentation for
a list channels. In order for a program to act upon the state of the switch, a case structure (can
be used the same way as “If – Then - Else” in text-based programming) can be used. This
example program reads the input from the switch using the Digital Input Express VI, displays it
on the front panel and executes a case structure where the user can write routines for “TRUE”
and “FALSE” cases. You will need to add a loop (usually a while loop) around this code to read
the digital input more than one time.

REMEMBER – Whenever using myRIO for LabVIEW we need to start with a project

Using the same circuit lets write our first program for the myRIO using case structure.

1. Open Labview for myRIO


2. Choose Create Project
3. In the Create Project Dialog you will see all of the default templates that National Instruments has
provided. Select MyRIO from the template and choose to create a myRIO Project.

4. The next window allows you to rename the project, in this case use myswitch, you can change
where the project is saved and ensure that you choose the myRIO that you want to use in the
project. The myRIO should currently be plugged in over USB. We would choose a generic target as
an example if we wanted to program today for hardware that we will connect later. Click: Finish.

26
5. Now we have a LabVIEW project with a myRIO added to it, now expand out myRIO and you will see
that we have a VI named Main.vi, this VI will run on the processor side of myRIO and will use the
predefined program that is on the FPGA. So, let’s double click Main.VI and have a look at how to
program myRIO. Switch to the block diagram and you can see the code for reading from the
accelerometer of myRIO. You will see that this code uses a flat sequence structure and we use this
code to show you that there will always be code that you need to put in to initialize first, you will
need to in your main area do something to read or write to or from the device, and then close your
references. The flat sequence structure is not necessary to make the code run but it provides a
nice template. If you want to run your applications on the myRIO make sure that all the Vis and
other files are actually under the myRIO.
6. For now, we will not use this default VI we will create a VI from scratch, right click on the myRIO
and choose new VI.
7. You will see front panel where you have all the User Interface elements, you code will be on the
block diagram. To switch between the two, click Ctrl-E or go to Window and click show block
diagram or show front panel.
8. In this program we are going to use the switch to turn on the LED’s on the myRIO.
9. Add the While Loop from the Programming - Structures section of the Functions Palette and drag it
onto the block diagram. This while loop allows us to run the program multiple times until we tell it
to stop. Without the loop the program would only run once.

27
10. It is important that when you have completed the VI that you reset the pin values on the myRIO. If
you do not all of the preexisting values on the pins will remain. As an example, if you have motors
running they may stay on until you change the previous values. On the Functions Palette find the
myRIO section which will have all the hardware interfaces to the myRIO, choose Device
Management and drag the Reset myRIO VI onto the block Diagram.

11. Right now, we do not know which will execute first, the Reset myRIO VI or the Loop, there is no
dependency between the two. In order to enforce that we will add a structure that is called a flat
sequence, From the Programming – Structures section of the Function Palette choose Flat
Sequence and draw it around the While Loop.

28
12. On the right edge of the sequence structure right click and choose add frame after and drag the
reset myRIO into the second frame. We have now assured that after the while loop has ended the
flat sequence will execute the second frame where we have the reset myRIO.
13. Next, go back to the myRIO section of the Functions Palette and choose the Digital Input Express
VI. Drag the VI into the Loop, in the Configure Digital Input Dialog set the Channel to A/DIO0 (pin
11). Remember the Motor Control Board is plugged into MXP Port A. You will see an output set for
Digital Output 0 (Pin 11).

14. What will do is a simple program, if the button is pushed, turn on the LED’s on the myRIO. If it is
pushed turn the LED’s off. So in LabVIEW we can do this by using what is called a case structure. In
Programming - Structures section of the Functions Palette add a case structure in the While Loop
to the left of the switch input.

29
15. The structure will have a Case Selector on the left edge and a Selector Label on the top, wire the
input to the Case Selector, if the case is true we want to turn on the LEDs. Go back to the myRIO
section of the Functions Palette and add the LED VI, make sure that all the LED’s checked, that will
make them all available. We see that this VI has 4 inputs.

16. Right click on the upper terminal and choose create constant. The constant will be a Boolean False,
we do not want that so click on it to make it true. Wire all of the inputs to the true case.

30
17. The false case is current empty so if we ran the VI the LEDs would turn on but they would never
turn off because we have not told them to. Window everything from the True case, copy it to the
clipboard. Change the Selector Label to the False case and copy everthing into the false case.
Change the boolen value to false.

18. The value coming from the switch will decide what case will be used. The run time button currently
shows an error. If you click on it will show that the while loop conditional terminal is not wired.
Click Show Error and it will show that the error is in the while loop.

19. We will create a front panel object that is called a control, this is an object that the user can
interact with. Right click on the loop condition in the lower right corner of the loop and choose
create control. If you switch to the front panel you will see that a Button has shown up.

31
20. Essentially our program is complete, however in order to help debug the program we will add an
indicator. An indicator is a from panel object that simply indicate something, you cannot interact
with them. We will add a Boolean LED that will show us what the state of the switch is. Wire the
Boolean on the block diagram as show.

21. We can now run the program, the first time the VI compiles it may take a bit of time, when you are
just making changes it will work faster. If asked to save give the VI that name Switch Example. The
VI is now running and you can see if you toggle the switch the indicator on the front panel will
toggle on and off. To stop the VI you should click the STOP button. Avoid using the Abort Execution
button on the toolbar as this will abort and will not reset the pins on the myRIO.

Did the switch work as discussed? Why – Remember the default states of the DIO’s. The states of the
Connector A and B DIOs are be high (true) due to the internal pull-up resistors, and the Connector C DIO
should be low because of the internal pulldown resistor. Change the states to correct the program.

32
Line Sensor Board

The Studica Line Sensor Board consists of 4 IR LED/phototransistor pairs mounted on a 9mm pitch, making
it a great detector for a line-following robot. The Line Sensor Board allows the robot to tell objects or
surfaces apart based on how dark or light they are. It shines a beam of infrared light out onto the object,
and measures how much light is reflected back.

Each sensor provides a separate analog voltage output. The sensor board is an infrared emitter/receiver
that is able to differentiate between a dark surface (with low IR reflectivity – 3.3V to 5V) and a light surface
(with high IR reflectivity – 0V to 0.5V). However, this range can vary depended on the installed height of
the sensor board.

The LSB uses a QRD1114 infrared (IR) reflective sensor to determine the reflectivity of the surface below it.
When the QTI sensor is over a dark surface, the reflectivity is very low; when the QTI is over a light surface,
the reflectivity is very high and will cause a different reading from the sensor.

The optimum height distance is 3-5 mm; however, the reflectivity values will change depending on
distance. A daylight filter is built into the sensor. Below is a picture of the WSR QTI sensor.

Sensor Type Light, Infrared (IR)


Interface Analog
Voltage - Supply 5V

Learning Objectives: After completing the activities in this exercise you will be able to:

1. Use the sensor for pattern detection: differentiate between light and dark surfaces, such as a black line
drawn on a piece of white paper (useful as a robot line follower).
2. Use the sensor for object detection: judge whether the sensor is close to an object by how much
infrared light is reflected from it (useful as a tabletop edge detector).

Component Demonstration

Follow these steps to demonstrate correct operation of the Line Sensor Board.

Select these parts from the World Skills Collection:


• Line Sensor Board
• MD2 Motor Driver Board
• 6 Jumper Wires (M/F)

33
Build the interface circuit: Refer to the picture, the LSB interface requires six connections to The MD2 MXP
Connector A:

5V Terminal A/5V+ Pin 1


S1 Terminal A/AI0 Pin 3
S2 Terminal A/AI1 Pin 5
S3 Terminal A/AI2 Pin 7
S4 Terminal A/AI3 Pin 9
GND Terminal A/GND Pin6

34
Create the VI:

• Follow the Lab VI programming tutorial provided for a sample VI the follows.

Sample VI for reading the LSB Sensor

1. Launch LabVIEW 2017 for myRIO and click on Create Project.

2. Click on myRIO under Templates and choose the myRIO Project, Click Next.

3. Enter a name for your project in the Project Name field. From Target, choose the Plugged in USB option
and make sure your myRIO device appears on the right. Hit Finish.

35
4. A Project Explorer window will open. Make sure that you are connected to the myRIO, A green dot will
be present if you are. If you are not connected, right click on the myRIO in the project browser and choose
connect from the shortcut menu. We will not use this default VI we will create a VI from scratch, Right
click on the myRIO and choose new VI.

5. Use the keyboard shortcut Ctrl+T to show both the Block Diagram and the Front Panel windows side-by-
side on the screen.

6. Right click on the empty space of the Block Diagram to see the functions pallet. From here, go to
Structures and choose While Loop. Drag your mouse over the Block Diagram to create the while loop
structure. This is the main loop that will keep the program running and where we will place the rest of our
code.

36
7. Bring up the functions pallet again and this time go to myRIO --> Low Level --> Analog In 1 --> Open.
Place this Analog Input block outside the while loop. This will be used to read the values generated by the
LSB sensor. We use the Advanced I/O Analog Input VIs to perform analog input operations on the NI
myRIO. This provide more control over the allocating and releasing of I/O channels.

37
8. We will now open a reference to the 4 analog input channels for the LSB. You must open a reference
before you read values from an analog input channel. Placing it outside of the loop ensures that you are
only opening the specified channels once.

Right click on the Channel Names Input chose create constant. Drag the constant down so that are 4
constants available which will correspond to the 4 analog inputs.

9. Right click on the arrow facing downward. This will open up a dropdown menu allows the selection of
channels. Select channel A/AI0 for the first box, A/AI1 for the second box, A/AI2 for the third box and
A/AI3 for the last box.
38
10. Bring up the functions pallet again and this time go to myRIO --> Low Level --> Analog In 1 --> Read.
Place this inside the While Loop as Shown and wire the AI reference out from the Open to the AI reference
in of the Read

8. From the Functions Palette add 2 Programming > Index Array as shown.

9. Drag the Index Size of each array to four elements to allow for the value of each of the IR sensor in the
array. Then create an Indictor to show the Raw Voltage that is coming from the LSB for calibration
purposes.

39
10. We will now compare the Raw Data values to the the Threshold Value. Complete the block diagram as
shown using the greater then function and a control to set the Threshold value. Then add an indictor to
show if the value is greater then or equal to the threshold value. The completed block diagram is shown.

Expected results: This VI display the voltage output value from the Line Sensor Board. The lower the
number, the lighter the surface. Or for object detection, the closer the sensor is to the object. The higher
the number, the darker the surface. Or for object detection, the farther the sensor is to the object.

Troubleshooting tips: Not seeing the expected results? Confirm the following points:
• Glowing power indicator LED on NI myRIO,
• Black Run button on the toolbar signifying that the VI is in run mode, and
• Correct MXP connector terminals - ensure that you are using Connector A and that you have the
correct pin connections.

Interface Theory

Interface circuit: The way that infrared range sensors (QTI sensors) work is by using infrared light. Two
infrared LEDs are used, one as a transmitter and one as a receiver. The transmitter simply outputs like any
normal led, since it is in the infrared spectrum we cannot see it with our eyes. If any infrared light bounces
off an object the infrared receiver outputs a voltage seemingly proportional to the intensity of that light.
When your microcontroller measures the time it takes for the QTI's capacitor to decay, it's measuring a
rate of charge transfer through an infrared phototransistor. This rate indicates how much infrared is
reflecting off a nearby surface.

40
IR Distance Sensor
The Infrared (IR) Distance uses a beam of reflected light to detect objects within a given
range. To determine the distance of an object, the sensor first sends an IR beam; it then
receives this beam, once reflected from an object. The time between when the beam was
sent and when it was received is used to calculate the distance of the object. Applications of
an IR range finder include ranging and object detection for robots, proximity sensing, and
touchless switches.

Learning Objectives: After completing the activities in this section you will be able to:
1. Describe the features of the SHARP GP2Y0A21YK0F IR range finder,
2. Discuss the principle of operation of IR range finders, and
3. Apply calibration techniques using single or multiple measurements.
Component Demonstration
Follow these steps to demonstrate correct operation of the IR Sensor.
Select these parts from the WSR Collection:
• IR Range Finder
• Sharp IR Sensor Cable
• Jumper Wires, M-M (3X)
Build the interface circuit: For this example you will be connecting the wires from the IR
sensor to NI myRIO MXP Connector A, wire the rangefinder as shown.
1. 5-volt power supply - A/+5V (pin 1)
2. Ground - A/GND (pin 6)
3. Output signal - A/AI0 (pin 3)

41
Read more about the measurements on the supplied datasheet. The proper way to wire the IR
sensor is shown.

Run the demonstration VI:

1. Open the project IR Range Finder demo. Lvproj contained in the subfolder IR Range Finder demo
located in the Part 2 – myRIO Interfacing folder for the WSR Learning files,
2. Expand the hierarchy button (a plus sign) for the myRIO item and then open Main.vi by double-
clicking,
3. Confirm that NI myRIO is connected to your computer, and
4. Run the VI either by clicking the Run button on the toolbar or by pressing Ctrl+R.

Expect to see a “Deployment Process” window showing how the project compiles and deploys (downloads)
to NI myRIO before the VI starts running.

NOTE: You may wish to select the “Close on successful completion” option to make the VI start
automatically.

Expected results: The demo VI displays both the IR range finder output voltage and the range In
centimeters to a reflective target. Use a meter stick or yard stick to measure the distance from the back
side of the sensor to a reflective target placed somewhere between 0 cm and 80 cm. Compare the
measured range to the known range; how well do these values match?

Record the sensor voltage VO when the target is placed at a known range R of between 10 cm and 40 cm,
calculate the calibration scale factor Kscale = R x VO, and then enter this value into the Kscale [cm-V] front-
panel control. Repeat your earlier range measurements; do you observe improved measurement
accuracy?
42
Try moving the target to ranges closer than 10 cm. You should observe that the measured range begins to
increase even though the target is obviously very close to the sensor. You can mitigate this non-ideal
behavior by ensuring that the sensor is mounted at least 10 cm from the nearest target. With the robot
platform, for example, mount the sensor towards the interior of the platform rather than at the edge.
Use a smartphone camera or webcam to view the IR range sensor. Infrared light appears blue on such a
digital image sensor. Which side of the sensor is the IR emitter?

Click the Stop button or press the escape key to stop the VI and to reset NI myRIO; a myRIO reset causes all
of the digital I/O pins to revert to input mode.

Interface Theory

Interface circuit: The SHARP GP2Y0A21YK0F IR range finder creates an output voltage VO that varies in
inverse proportion with range to a reflective target. The myRIO reads the voltage that is sent by the sensor.

Use the Analog Input Express VI. To create your own VI for the IR Distance sensor. You need to convert the
voltage readings to distances. Sample code is shown in the figure below and another sample can be found
in the Part 2 - myRIO Interfacing folder (Sharp IR Sample). This program below reads the analog input,
computes an estimation of the DC levels of the input signal, converts the distance to CM and does a logical
comparison with 15 (an arbitrary distance). In the case structure if the distance is greater than 15CM the
LED on the myRIO will turn on. The while loop is stopped when a stop button is pressed on the front panel.
Finally, the myRIO is reset.

Example Code for the IR sensor

43
The Studica Toolkit and Custom FPGA

Studica Toolkit for World Skills Robotics and the MD2 Motor Driver

Studica provides a WorldSkills Toolkit which add libraries of functions, VIs, interactive wizards, examples, utilities, and
documentation for World Skills competitors effectively reducing the time required to finish your task.
The Toolkit is shipped in a VIP format. VI Packages are similar to zip files in that they contain all the VIs and resources for a
specific LabVIEW add-on, as well as information the VIPM software uses to install, remove, and manage the add-on. Simply click
on the VIP package to launch and install the toolkit. The Toolkit require a user to be using LabVIEW for Myrio 2017.

Installing the Custom FPGA

NI ships the FPGA of myRIO pre-defined with AI, AO, PWMs, Quad Encoder inputs, UART, SPI, and I2C

Default Personality

A standard myRIO project is the best for beginners. This project option provides the user with a pre-defined and pre-compiled
FPGA VI. The default FPGA VI contains pre-implemented functions and libraries (PWM, analog input, analog output, encoder, SPI,
I2C, UART, LED control, digital read, digital write, accelerometer…). The default FPGA VI is known as “Default FPGA Personality”
and is hidden from the user it supports general I/O, protocols, and interrupts. The created Labview project provides the user with
the RT main VI for editing and a myRIO toolkit to interfacing with the available functions. Use the default personality for control
applications

World Skills MD2 Custom Personality

A Custom personality is provided for the World Skills users to implement the full functionality of the MD2 Driver Board. The
Custom FPGA personality VI includes all implemented functions
In order to use the new compiled LabVIEW FPGA VI (bitfile) on a myRIO target device use Measurement and Automation Explorer
(MAX) to download the bitfile to your target even without having the LabVIEW FPGA Module installed.
To download or erase the bitfile using MAX:

1. Locate your target in MAX.


2. If your target is a local target, select your target's FPGA (named "RIO0" or similar)
3. If your target is remote (and therefore shows up under Remote Systems), expand your target, expand Devices and
Interfaces, and select your target's FPGA (named "RIO0" or similar)
4. In the right-hand pane, choose any options desired and then select Update Firmware.
5. Navigate to the location on disk of your bitfile and select it.

44
Press the reset button on your myRIO, It may take a minute or two for the target to restart.

Studica FPGA Personalities (LabVIEW 2017 Studica Toolkit)


FPGA personalities consist of predefined FPGA bitfiles for you to program with NI myRIO. The LabVIEW myRIO Toolkit
provides the following FPGA personalities.

• Default—Supports general I/O, protocols, and interrupt. Use the default personality for control applications.
• Studica Toolkit—Supports additional PWM, Encoder and Sensor Output for Robotics. Use the Studica Personality for
World Skills Robotics using the MD2 Motor Driver Board and the Studica Blackhawk.
You can choose a personality when you create a myRIO project. With different personalities, you can implement different
functionalities and use different channels on the NI myRIO.
The following table lists the functionalities and channel numbers that each personality supports.

Supported Functionalities Studica FPGA


myRIO-1900 myRIO-1900
Analog Input (1 Sample) 12 12
Analog Output (1 Sample) 8 8
Digital Input 40 8
Digital Output 40 16
Button 1 1
LED 4 4
Accelerometer 3 3
PWM 8 12
Encoder 4 6
SPI 2 /
I2C 2 2
UART 2 /
Interrupt 8 /

45
Supported Channels
The default FPGA personality supports the following channels of the I/O connectors on the NI myRIO.

Supported Channels
Supported Functionalities
myRIO-1900 myRIO-Studica
Analog Input A/AI0~A/AI3* A/AI0~A/AI3*
B/AI0~B/AI3* B/AI0~B/AI3*
C/AI0, C/AI1* C/AI0, C/AI1*
AudioIn/Left, AudioIn/Right AudioIn/Left, AudioIn/Right
Analog Output A/AO0, A/AO1 A/AO0, A/AO1
B/AO0, B/AO1 B/AO0, B/AO1
C/AO0, C/AO1 C/AO0, C/AO1
AudioOut/Left, AudioOut/Right AudioOut/Left, AudioOut/Right
Digital Input A/DIO0~A/AI15 C/DIO0~C/DIO7
B/DIO0~B/DIO15
C/DIO0~C/DIO7
Digital Output A/DIO0~A/AI15 A/DIO5~A/DIO7, A/DIO13
B/DIO0~B/DIO15 B/DIO5~B/DIO7, B/DIO13
C/DIO0~C/DIO7 C/DIO0~C/DIO7
Button Button0 Button0
LED LED0~3 LED0~3
Accelerometer X-Axis, Y-Axis, Z-Axis X-Axis, Y-Axis, Z-Axis
PWM A/PWM0~A/PWM2 A/PWM0~A/PWM4
B/PWM0~B/PWM2 B/PWM0~B/PWM4
C/PWM0, C/PWM1 C/PWM0, C/PWM1
Encoder A/ENC A/ENC0, A/ENC1
B/ENC B/ENC0, B/ENC1
C/ENC0, C/ENC1 C/ENC0, C/ENC1
SPI A/SPI
B/SPI
I2C A/I2C A/I2C
B/I2C B/I2C
UART A/UART
B/UART
Interrupt A/AI0 (Interrupt),
A/AI1 (Interrupt),
A/DIO0 (Interrupt)~A/DIO3 (Interrupt),
Button0 (Interrupt)
Input Device USB USB

* A/, B/, and C/ stand for connector A, B, and C on the NI myRIO. Refer to the NI myRIO User Guide and
Specifications for specifications of the I/O connectors and channels on the NI myRIO.
Related Information
NI myRIO Shipping Personality Reference
NI myRIO User Guide and Specifications
I/O Connectors

46
MD 2 Motor Adapter for NI myRIO

The MD 2 Motor Adapter for NI myRIO connects directly to an MXP port and integrates an H-bridge motor
controller and power manager into a trouble-free solution to drive two DC motors using pulse-width
modulation (PWM) to control the speed of the motors. Both the motor adapter and the compatible geared
motor are included with the WSR Collection. The Motor Adapter supports motor voltages in the 8 to 16 V
range with up to 12 A current continuous per motor with quadrature encoder feedback for position and
speed control using PID feedback loops. It supports 3 servo motors and one stepper motor and includes
current over limit protection.

This motor driver board has two motor channels, M0 and M1, each of which can be used to
independently control a bidirectional brushed DC motor. Each motor channel is comprised of a pair of
pins—Mx+ and Mx- —that connect to the two terminals of a DC motor and can deliver a continuous
12 A (30 A peak).

Each VNH5019 motor driver IC has a maximum continuous current rating of 30 A. However, the chips
by themselves will overheat at lower currents. In our tests on a sample unit, we were able to deliver
30 A for a few milliseconds, 20 A for several seconds, 15 A for over a minute, and 12 A for around
five minutes. At 6 A, the chip just barely gets noticeably warm to the touch. The actual current you can
deliver will depend on how well you can keep the motor driver cool. The shield’s printed circuit board
is designed to draw heat out of the motor driver chips, but performance can be improved by adding a
heat sink.

We strongly encourage you to consult the VNH5019 datasheet for detailed pin descriptions, truth tables,
and electrical characteristics

Theory:

A direct current, or DC motor works off the fact that that two electromagnets that are alike repel each
other and two that are alike attract. By constantly changing the direction of magnetic fields, rotational
motion is achieved. The DC motor included in the World Skills Robotics collection has a voltage range from
6 to13.8 volts. Applying voltage will spin the motor shaft at a relatively high rotational speed. DC motors are
used in a variety of robotics systems, from drive to object management systems.

47
DC motors can be connected to the MD2 Motor Adapter using the two screw terminal connectors. The board
conveniently connects the motor outputs and encoder inputs to the proper pins on the myRIO MXP connector so that
you can use the included custom FPGA and Studica Toolkit in the myRIO palette for either MXPA or MXPB:

In this exercise you will start with a simple on/off control of a DC motor. You will connect the motor via the MD2
motor control board plugged into MXP Port A on the NI myRIO.

You will then build a computer program VI in LabVIEW that will control the motor. After being able to turn the motor
on and off in LabVIEW. You will on/off the motor using a physical device (XXX) for providing inputs to myRIO.

Learning Objectives: After completing the activities in this section you will be able to:

1. Describe the H-bridge principle of operation,


2. Explain how to control the motor speed and direction of rotation,
4. Apply the Studica Motor VI to control the motor speed, and
5. Apply the Encoder VI to measure Distance.

Component Demonstration

Select these parts from the WSR Collection:

MD2 Motor Adapter for NI myRIO


2 x 12V DC Motor with encoder installed
12V Battery

You will also need a small screwdriver

Build the interface circuit: Refer to the picture below. Simply connect the Motor Adapter to MXP
Connector A, attach the DC motor and Encoder Cable, and then attach a 12V power supply (Battery) as
48
shown to J7. Use a small Phillips or straight-bladed screwdriver to loosen and tighten the screws on the
motor supply voltage connector.

Wire the motor power cable to M0 (+) Red and M0 (-) Black.

Plug the respective encoder cables to the ENC0 and ENC1 inputs on the MD2 Board. The black wire is towards the
MXP Ports:

49
50
Exercise: Basic Motor Control

Step 1: Start Labvieew and create new project: by choosing “Create Project”. The “Create Project” window will pop
up. Click on “myRIO” on the left side list under Templates then click “myRIO Project” on the right site list menu. Click
“Next”. See the Figure below.

You can use the myRIO Project template as a starting point for creating myRIO applications with the myRIO default
FPGA personality. With the myRIO Project template, you can easily access myRIO I/O channels and onboard devices
without making major modifications to the structure of the application.

51
Another window will appear. Change the Project Name to “Motor Drive (Your Name)”. Then click “Finish”. See the
figure below. Note that in this figure we are connected to a myRIO over USB using the default IP.

Once you click “Finish”, the “Project Explorer” window will appear. Right click on”myRIO-1900 (172.22.11.xx)” and
“Connect”. A green light on the myRIO icon will be ON. See the figure below.

52
Once you click “Connect”, “Deployment Progress” will show the deployment status. Click “Close” when it is finished,
or it may close automatically of the check box is selected.

Again, right click on “myRIO-1900 (172.22.11.xx)” and click “New>>VI”. A new VI “Untitled 1” will be added to your
project.

Right click on “Untitled 1” and save it as “DC motor On Off”. Make sure that the “File Directory” is your “Project
Folder”.

Click “OK”

53
Step 2: Build the VI: In the Block Diagram window, right click to show the “Functions” palette. Hover the cursor over
“Structures” A new window will pop open, and then click “While Loop”.

Your cursor will now change into a drawing tool. Hold the mouse and draw the square for your “While Loop”. You will
want it to be relatively large since you will be placing several components inside. Release the mouse when you’re
ready to set it in place.

Right click to show the “Function” palette. Hover the cursor over”myRIO” near the bottom of the menu. Then select
the “Digital Output” block. This will represent the output signal to the DC motor. See the figure below. Place the icon
somewhere inside of the while loop.

54
Another window will appear as shown below. You will need to configure the channels for the Digital Outputs.

55
In the dropdown menu labeled “Channel,” select A/DIO5 (Pin 21), Add another Channel and select A/DIO6 (Pin 23)

Motor rotation is determined by the states of the two channels and motor speed is controlled by the duty cycle of a
PWM signal supplied to the drivers PWM pin. See the truth table below for information on how the pins affect the
driver outputs.

PWM duty cycle ranges from 0 – 1 at a max 20 kHz frequency. Enable will move the motor in one direction, and
direction will move the motor in the other direction. If all outputs are 0 the motor will be in a coast mode. If all
outputs are high the motor is in brake mode.

PWM A (ENA) B(DIA) M+ M-


LOW 0 0 0 0
HIGH 1 0 1 0
HIGH 0 1 0 1
HIGH 1 1 1 1

The completed block diagram should look like the following:

56
Complete the Block Diagram as follows:

Run and test the VI

Now let’s have a look at the Studica Toolkit VIs

The Studica Motor VI can be used to control the motor speed (Use Speed M0 and Speed M1 for Invert M0 and Invert
M1 for speed and direction for each motor respectively)

The Studica Encoder VI can be used to read the distance travelled for Motor0 and Motor1

*DC Motors* Connect the DC motor(s) to the screw terminals (J14 and/or J15) and if using encoders, wire signals to
ENC0 and ENC1. Connect motor power (16V max) to the Motor Power screw-terminals (J7). Speed/Torque is
controlled by setting the duty cycle (Frequency [Hz]. The VNH5019 driver has been configured for a 12A max current.

57
Run the demonstration VI:

1. Open the project Motor Adapter & Geared DC Motor. Lvproj contained in the subfolder Motor
Adapter Code,
2. Expand the hierarchy button (a plus sign) for the myRIO item and then open Motor Adapter & DC
Gear Motor.vi by double-clicking,
3. Confirm that NI myRIO is connected to your computer, and
4. Run the VI either by clicking the Run button on the toolbar or by pressing Ctrl+R.

Expect to see a “Deployment Process” window showing how the project compiles and deploys (downloads)
to NI myRIO before the VI starts running.

NOTE: You may wish to select the “Close on successful completion” option to make the VI start
automatically.
Expected results: Increase the PWM duty (duty cycle) slider for each motor until the motors
begin to turn. The Motor Distance indicator value increment should increment in the positive
direction. If the encoders are counting in the wrong direction Invert the encoder signal using
the Invert Encoder button.

In this example with the speed settings, 0 will not move the motor, 0.5 will move it at 50%
duty cycle and 1 will move the motor at full speed. Direction is controlled with the Direction
Motor Control.

• Continue increasing the PWM duty slider to speed up the motors.

• Reduce the motor speed and then click the Direction button to reverse the motor direction. You
should see the distance indicator begin to count down.

• Set the motor speed back to zero and then reset the encoder.

Click the Stop button or press the escape key to stop the VI and to reset NI myRIO.

Pulse-width modulation (PWM)

Pulse-width modulation (PWM), as it applies to motor control, is a way of delivering energy


through a succession of pulses rather than a continuously varying (analog) signal. By increasing
or decreasing pulse width, the controller regulates energy flow to the motor shaft.

One essential aspect of controlling motors is the ability to change the speed of rotation and the
amount of torque produced. One simple but usually impractical means of achieving this is to
adjust the supply voltage up and down as required. However, it is more effective and common
to use the PWM concept. By adjusting the duty cycle of the signal (modulating the width of the
pulse, hence the “PWM”) i.e, the time fraction it is "on", the average power can be varied, and
hence the motor speed.

58
This is a control technique where power to the motor is switched on and off rapidly, at rates
high enough that the effects of the switching can be negligible. The diagram below illustrates
the PWM concept. The drive signal is switched on and off with a given period and is in the “on”
state at voltage VON for a fixed fraction of the period.

Usually, PWM frequencies in the range of 100Hz to 1000 Hz will give good results. Choosing the
right PWM frequency is essential to the efficiency of the motor controller.

For the MD2 Board 40Hz is the minimum value and for this example the Frequency is set at a
constant of 100Hz.

Other Ideas

1. What PWM frequency range makes it easiest to start the stopped motor when increasing the PWM duty
cycle from zero?
2. What PWM frequency range causes audible tones?
3. What PWM frequency range is best for very slow rotation?

59
Servo Motor

A servomotor—usually called a servo for short— combines a DC motor, gearbox, potentiometer, and
controller electronics to provide relatively precise angular position control of a rotating shaft. Servos
provide motion control for robot arms, rotating sensor scanners, and other actuators. Servos have been
used for many years in remote-controlled airplanes, cars, and boats to manipulate control surfaces (aileron,
elevator, rudder) and steering. The WSR Collection includes a standard servo and a continuous-rotation
servo.

Learning Objectives: After completing the activities in this chapter you will be able to:

1. Discuss the main components of a servo feedback control system: pulse-style command input, controller,
DC motor, gearbox, and potentiometer as an angular position sensor,
2. Create a pulse-width modulated (PWM) signal to command the servo spline to a desired angle,
3. Null any non-ideal offsets in the angular position, and
4. Explain the fundamental difference between a standard servo and a servo intended for continuous
operation.

Component Demonstration

Follow these steps to demonstrate correct operation of the servo.

Select these parts from the WSR Collection:

• Standard Servo

Connect the Servo to the MD2: Plug the servo into the PWM2 port on the MD2 Motor Driver Board, if you
are not using the myRIO custom FPGA this is the only Servo Port that is available and it on PWM2. Ensure
that the orientation of the connector matches the labelling on the MD2 Board.

To run the Servo motors, you must connect 5V power to J8.

Alternatively, you could wire to the MXP breadboard using M/M jumpers and use the 5V provided by the
myRIO.

1. Vcc (red) A/+5V (pin 1)


2. Ground (black) A/GND (pin 6)
3. Command signal (white/yellow) A/PWM2 (pin 31)

Make certain that you are using the correct servo; the WSR Collection includes a continuous-rotation servo
with similar appearance.

60
Run the demonstration VI:

1. Open the project Servo demo. Lvproj contained in the subfolder Servo demo,
2. Expand the hierarchy button (a plus sign) for the myRIO item and then open Main.vi by double-clicking,
3. Confirm that NI myRIO is connected to your computer, and
4. Run the VI either by clicking the Run button on the toolbar or by pressing Ctrl+R.

The Block Diagram of the Main VI. The main body of the code runs within a while loop, so that the Servo’s
position can be changed indefinitely as the code runs. The VI reads required position and frequency values
from the front panel. These are used to generate a PWM signal

Expected results: The demo VI includes a pointer slide control to adjust the servo angle. Move the slider
and confirm that the servo shaft turns in response. You may also use the Page-Up and Page-Down keys to
move the slider. Which slider values (positive or negative) correspond to clockwise motion?

The slider is calibrated in “percent full scale” (%FS). Estimate the servo angle at =100%FS and then at
-100%FS. Use the direct entry box at the top of the slider to apply step changes, e.g., +100%FS to -100%FS;
how quickly does the servo rotate between these two angles?

The default limits on the slider allow a 2X “over travel” factor. At what %FS values does the servo reach its
rotation limits?

The servo command input is a variable-width pulse with 1.0 ms at -100%FS and doubling to
2.0ms at +100%FS; the midpoint pulse width 1.5 ms — called the neutral-position pulse width
—corresponds to 0%FS. The pulse must be repeated at a sufficiently fast rate and yet not too fast. Try
adjusting the freq [Hz] control to a lower frequency (say, 10 Hz) and to a higher frequency (say, 200 Hz),
each time moving the position slider to command different angles. Note the two indicators under this
control that indicate the pulse width and “duty cycle” (percent of time that the pulse is active) of the signal
61
sent to the servo command input. What happens to the servo angle at these frequency extremes?
Experiment to determine a range of frequencies that yields satisfactory control of the servo angle.
Within the code the Servo’s position is converted into a value ranging from -1 to 1. This is used to set the
pulse-width of the output signal. This pulse width is the true control of the motor’s position and this can be
seen within the code. Even when varying the frequency of the signal at a given position, pulse width always
remains the same. At varying frequencies, the duty cycle must be changed to achieve a given pulse width,
as the available “high” time in the signals highs changes. Try experimenting with the frequency and position
values and observe the duty cycle’s changes to see this. Once an appropriate duty cycle has been
determined to achieve a particular pulse width, the signal is written to the servo motor’s signal channel.

Experiment with the null offset control. This allows the user to establish a true “zero” position for the
servo’s motion. By moving the servo to what you select as a “zero” position, you can press and then
deselect the null offset button. The servo will then move the correct number of degrees off its current
position, so that when the position control is set to zero, the servo will be oriented to the new zero.

Disconnect the servo and replace it with the continuous-rotation servo. Investigate the behavior of this
servo and compare it to your earlier results.

Click the Stop button or press the escape key to stop the VI and to reset NI myRIO.

Interface Theory

Interface circuit: The servo adjusts its shaft angle according to the command input, a periodic pulse that
varies in width between 1.0 and 2.0ms. A pulse width centered between these two limits (1.5 ms)
commands the servo to its neutral (center) position.

62
Webcam

NI myRIO includes support for USB webcams, and can work with multiple webcams attached via a USB hub.
With the Vision Acquisition and Development modules installed you can acquire and process still images
and video streams with a wide variety of image processing and machine vision tools.

Learning Objectives: After completing the activities in this section you will be able to:

1. Acquire and process a single image,


2. Acquire and process a video stream,
3. Set the webcam’s video mode (resolution and frame rate),
4. Set a webcam attribute such as saturation, and

Component Demonstration

Follow these steps to demonstrate correct operation of the webcam.

Select these parts:

1. USB webcam
2. Plug the Camera into the USB Port on the myRIO

Run the demonstration VI:

1. Open the project Webcam demo.lvproj contained in the subfolder Webcam demo,
2. Expand the hierarchy button (a plus sign) for the myRIO item and then open Main.vi by double-
clicking,
3. Confirm that NI myRIO is connected to your computer, and
4. Run the VI either by clicking the Run button on the toolbar or by pressing Ctrl+R.

Expected results: This project contains three distinct Main.vi top-level applications:

1. Main - single image.vi – This demo VI captures a single image and detects the edges in the image.
Select your webcam with the webcam front-panel control and then run the VI. You should see the
webcam image on the left side and its edge-detected version on the right side. Adjust the high
threshold HThresh control to change the sensitivity of the edge detector.

2. Main - video stream.vi – This demo VI captures a video stream and processes the stream in real
time. Select your webcam with the webcam front-panel control and then run the VI. You should see
the webcam image on the left hand side and its processed version on the right hand side; the VI
begins with no processing (pass through mode). Select the type of video processing with the
processing front-panel control. Adjust the high threshold HThresh control to change the sensitivity
63
of the edge detector. Try the “hue” processing mode to display a gray level image where each gray
level represents a different color; can you relate the color in the image to its gray tone? Also try the
“luma” processing mode to display the gray-level equivalent of the source image. Click adjust
saturation to enable adjustment of the webcam “Saturation” property and then move the horizontal
pointer control. What level seems to provide the most pleasing color balance?

3. Main - camera info.vi – This demo VI displays information for all cameras that have ever been
connected to your NI myRIO as well as available attributes and video modes for the selected
webcam. Select a specific webcam with the webcam control and then run the VI to update update
the display (you need to run the VI again each time you select another webcam). Click the up/down
arrows on the array index control of all cameras to see the details on each camera. Identify one of
the video modes (resolution and frame rate) besides the mode at the top of the list, make note of its
number, and then enter this value into Main - video stream.vi (you need to re-run the VI to change
the video mode). Confirm that the resolution matches that reported in the camera information
display underneath the source image display on the left-hand side.

Interface Theory

NI myRIO file system: The LabVIEW Vision and Motion VIs provide a comprehensive set of tools to acquire
and process images as well as to extract useful numerical information from images. Connect the web cam
to the NI myRIO USB port and then use the Vision And Motion VIs to quickly create an application.

Interface Ideas QR Code Scanner: QR codes are a popular type of 2-D bar code that encodes a website’s
URL. The LabVIEW Vision library includes the VI IMAQ Read QR Code to extract the URL as a string. A quick
Internet search reveals many free QR code generating services, i.e., www.qrstuff.com. Because you can
enter arbitrary text, the generated QR code pattern is not restricted to URLs but may be used to represent
any type of information that you wish. For example, you could create unique QR codes for an inventory
control system in which each object or container has a QR code label that can be conveniently scanned by a
webcam.

64
Robotics Navigation Sensor

The WSR navX-Micro is custom designed 9-axis inertial/magnetic sensor and motion processor. Designed
for plug-n-play installation onto robots such as those used in the World Skills challenge, navX-Micro helps
build better robots by adding sophisticated navigation capabilities.

The navX features a 32-bit ARM processor, the Invensense MPU-9250 sensor system-on-chip, and software
algorithms which include enhanced sensor calibration, data fusion combining gyro, accelerometer and
magnetometer data into a “9-axis heading”, and high-quality magnetometer calibration including magnetic
disturbance detection. In addition to being an Inertial Measurement Unit, navX-Micro capabilities are
referred to within the aerospace industry as an “Attitude/Heading Reference System” (AHRS).

The sensor can be used for the following:

• Court – Oriented Drive


• Auto-balance
• Auto-rotate to angle
• Motion Detection
• Collision Detection

The navX-Micro measures a total of 9 sensor axes (3 gyroscope axes, 3 accelerometer axes and 3
magnetometer axes) and fuses them into a 3-D coordinate system. In order to effectively use the values
reported by navX-Micro, a few key concepts must be understood in order to correctly install navX-Micro on
a robot.

Learning Objectives: After completing the activities in this section you will be able to:

1. Install the NavX for use on a Robot with the MD2 Board,
2. Read and display angular rate values.

65
3-D Coordinate System

When controlling a robot in 3 dimensions a set of 3 axes are combined into a 3-D coordinate system, as
depicted below:

In the diagram above, the green rounded arrows represent Rotational motion, and the remaining arrows
represent Linear motion.

Axis Orientation Linear motion Rotational Motion

X (Pitch) Left/Right – Left / + Right + Tilt Backwards

Y (Roll) Forward/Backward + Forward / – Backward + Roll Left

+ Clockwise/ –
Z (Yaw) Up/Down + Up / – Down Counter-wise

Reference Frames

Note that the 3-axis coordinate system describes relative motion and orientation; it doesn’t specify the
orientation with respect to any other reference. For instance, what does “left” mean once a robot has
rotated 180 degrees?

66
To address this, the concept of a reference frame was invented. There are three separate three-axis
“reference frames” that should be understood:

Coordinate
System Technical Term X Axis Y Axis

Front (Head) of
Field World Frame Side of Field Field

Front (Head) of
Robot Body Frame Side of Robot Robot

navX-
Micro Board Frame See diagram Below See diagram below

Joysticks and Reference Frames

Since a three-axis joystick is typically used to control a robot, the robot designer must select upon which
Reference Frame the driver joystick is based. This selection of Reference Frame typically depends upon
the drive mode used:

Drive mode Reference Frame Coordinate Orientation

Standard Forward always points to the


Drive Body Frame front (head) of the robot

Field-
oriented Forward always points to the
Drive World Frame front (head) of the field

67
navX-Micro Board Orientation (Board Frame)

Aligning Board Frame and Body Frame

In order for the navX-Micro sensor readings to be easily usable by a robot control application, the navX-
Micro Coordinate System (Board Frame) must be aligned with the Robot Coordinate system (Body Frame).

Securing navX-Micro to the robot chassis

navX-Micro should be mounted such that it is firmly attached to the robot chassis. The quality of this
mounting will be directly reflected in the quality of navX-Micro inertial measurements. To ensure quality,
carefully follow these guidelines:

• navX-Micro should be tightly mounted to the robot chassis; it should be a part of the chassis mass
and should move exactly as the chassis moves. Avoid mounting navX-Micro in an area of the chassis
that might be flexible, as this could introduce vibration to the inertial sensors that does not
represent the chassis inertial properties.
• navX-Micro should be mounted in the center of the chassis if at all possible, which ensures the origin
of the yaw/pitch/roll axes truly represent the chassis center.
.

68
Gyro/Accelerometer Calibration

The navX onboard sensors require calibration in order to yield optimal results. We highly recommend taking
the time to understand this calibration process – successful calibration is vital to ensure optimal
performance.

Accurate Gyroscope Calibration is crucial in order to yield valid yaw angles. Although this process occurs
automatically, understanding how it works is required to obtain the best results.

If you are tempted to ignore this information, please read the section entitled “The Importance of Stillness”
at the end of this page.

Calibration Process

The navX Calibration Process is comprised of three calibration phases:

Factory Calibration
Startup Calibration
On-the-fly Calibration

Calibration Process

Factory Calibration

Before navX units are shipped, the accelerometers and gyroscopes are initially calibrated at the factory; this
calibration data is stored in flash memory and applied automatically to the accelerometer and gyroscope
data each time the navX circuit board is powered on.

Note that the onboard gyroscopes are sensitive to temperature changes. Therefore, since the average
ambient temperature at the factory may be different than in your environment, you can optionally choose
to re-calibrate the gyroscope by pressing and holding the “CAL” button for at least 10 seconds. When you
release the “CAL” button, ensure that the “CAL” Led flashes briefly, and then press the “RESET” button to
restart navX. When navX is re-started, it will perform the Initial Gyro Calibration – the same process that
occurs at our factory. NOTE: It is very important to hold navX still, and parallel to the earth’s surface, during
this Initial Gyro Calibration period. You might consider performing this process before using your robot the
first time it is used within a new environment (e.g., when you arrive at a competition event).

The value of re-running Factory Calibration at the same temperature navX will be operated at is potentially
increased yaw accuracy as well as faster Startup Calibration. If a significant temperature shift has occurred
since the last Factory Calibration, the Startup Calibration time may take longer than normal, and it’s
possible that yaw accuracy will be diminished until the next On-the-fly Gyro Calibration completes.

69
Startup Calibration

Startup Calibration occurs each time the navX-Micro is powered on and requires that the sensor be held still
in order to complete successfully. Using the Factory Calibration as a starting point, the sensor calibrates the
accelerometers and adjusts the gyroscope calibration data as well based upon current temperature
conditions.

If the sensor continues to move during startup calibration, Startup Calibration will eventually timeout – and
as a result, the navX-Micro yaw angle may not be as accurate as expected.

Initial Yaw Offset Calibration

Immediately after Startup Calibration, an Initial Yaw Offset is automatically calculated. The purpose of the
Initial Yaw Offset is to ensure that whatever direction the “front” of the navX circuit board is pointed to at
startup (after initial calibration is applied) will be considered “0 degrees”.

Yaw Offset Calibration requires that navX be still for approximately 2 seconds after Startup Calibration
completes. After approximately 2 seconds of no motion, navX will acquire the current yaw angle, and will
subtract it from future yaw measurements automatically.

NOTE: If navX is moving during startup, this Yaw Offset Calibration may take much longer than 2 seconds,
and may not be calculated at all if the sensor continues moving long enough. Therefore, it is important to
keep navX-Micro still until initial calibration and Initial Yaw Offset calibration completes.

On-the-fly Gyro Calibration

In addition to Startup Calibration, during normal operation navX will automatically re-calibrate the
gyroscope (e.g., to account for ongoing temperature changes) during operation, whenever it detects 8
seconds of no motion. This process completes after about 7-8 more seconds and is completely transparent
to the user. Therefore, each time navX is still for approximately 15 seconds, the gyroscopes are re-
calibrated “on-the-fly”. The purpose of On-the-fly Gyro re-calibration is to help maintain yaw accuracy
when shifts in ambient temperature occur during operation.

This On-the-fly Gyro Calibration can help deal with cases where the sensor was moving during Startup
Calibration but note that the yaw is not zeroed at the completion of On-the-fly Calibration. So once again,
it’s important to keep the sensor still during Startup Calibration.

Runtime Yaw Zeroing

Your robot software can optionally provide the robot operator a way to reset the yaw angle to Zero at any
time. Please see the Studica Toolkit for more details.

70
The importance of stillness

This is the most important takeaway from this discussion: It is very important that navX be held still during
the above Initial Gyro and Initial Yaw Offset calibration periods. In support of this, navX indicates when it is
calibrating; we recommend you incorporate this information into your software.

Component Demonstration

Follow these steps to demonstrate correct operation of the NavX.

Select these parts:

• NavX Micro
• NavX Cable

Connect the NavX by using the included 4 pin cable and plugging it into the NavX connection (NavX) on the
MD2.

Alternatively, you could Build the interface circuit:


The NavX needs four connections to myRIO MXP Connector A:

1. +5-volt supply A/+5V (pin 1)


2. Serial Data A/I2C.SDA(pin34)
3. Serial Clock A/I2C.SDA(pin32)
4. Ground A/GND (pin 30)

Run the demonstration VI:

1. Open a blank VI in your myRIO project


2. Right click on the block diagram and navigate to the Studica Toolkit Section
3. Find the NavX folder and then choose the get subfolder
4. Inside the get subfolder there should be a VI called Test Window, drag it to the block diagram and
then double click on it to open the sub VI.
5. The test window for the NavX should open
6. Press ctrl + E, now in the block diagram on the left there is an A or B constant. Select the mxp port
that you have the NavX connected to.
7. Press ctrl + E again to get to the front panel and then hit Run.
8. You will now see all the features that the NavX has and its values.

Sections of the demo VI explained:

1. Board Information – this shows you the information regarding firmware, settings for how the NavX is
mounted, which NavX you are using and the address of the NavX
2. Status – shows the update rate of the NavX, the sensor ranges, self-testing statuses, it also shows what the
sensor is doing such as moving, or when the yaw is stable
71
3. MPUTemp and Timestamp – this will show the temperature of the sensor this is sometimes used for
calibration in certain situations. The timestamp is a timer that counts the time since the NavX was powered
on. Useful for timeouts, camera calibration, and other functions
4. YRPHfH – This contains the yaw, roll, pitch, heading and fused heading of the NavX. The most important value
is here and that is the yaw. The yaw will tell you the angle of change of the robot.
5. Quaternion – gives your w, x, y, z quaternion values. These are creating advanced movement algorithms.
6. Displacement – will show your velocity and displacement on the x, y, z axis.
7. Linear acceleration – Gives you your linear acceleration in the x, y, z axis.
8. Raw Values – produces all the raw values outputted by the NavX. These values are raw uncalibrated values.
9. Buttons at the bottom – these are used to set certain values to zero. For example, zero yaw would zero the
yaw. This is mostly used so when the robot hits a certain known position you can zero the yaw to keep the
robot within your parameters for autonomous programming.

Block Diagram:

The block diagram provides examples of how to connect each VI in the Toolkit for you to use. You do not need to
connect everything, you can choose what is required. Please take note the update rate; in order for the i2c bus to
communicate properly with the NavX it must match the update rate of the NavX in the while loop. The NavX has a 50
Hz update rate, which 1000/50 = 20ms. Therefore, always remember that whatever loop the NavX code is in IT MUST
HAVE A 20ms TIMER ATTACHED TO IT. It is recommended to have a separate loop running in parallel to your code
and use variables to send data throughout.

72
Ultrasonic Distance Sensor
The robot collection includes PING))) ultrasonic sensors that detect objects by emitting a short ultrasonic
burst and then listening for the echo. Under the control of a host microcontroller, the sonar sensor emits a
short 40 kHz (ultrasonic) burst. This burst travels through the air at about 1130 feet per second, hits an
object, and then bounces back to the sensor. The PING))) sensor provides an output pulse to the host that
terminates when the echo is detected; hence, the width of this pulse corresponds to the distance to the
target. This sensor can sense obstacles in a range from 2 cm to 3 m. The distance is measured by the
sensor by measuring the time for the echo to return.
MyRIO Realtime does not support the speed required to measure pulse distance, however the FPGA will
support the required timing. The Studica Toolkit provides you with a Ping read VI that operates on the
custom FPGA.
Ping Ultrasonic Distance Sensor - The Parallax PING ultrasonic range sensor incorporates an activity status
LED and has one I/O pin.

Learning Objectives: After completing the activities in this chapter you will be able to:

1. Describe the features of the PING)))™ ultrasonic sensor distance sensor,


2. Determine the measured range to an object.
3. Discuss the principle of operation of sonic range finders, and
5. Understand the beam characteristics presented in the datasheet.

Component Demonstration

Follow these steps to demonstrate correct operation of the ultrasonic distance sensor.

• PING)))™ ultrasonic sensor distance sensor


• 3 wire cable
• MD 2 Motor Driver Board

Build the interface circuit: The Ultrasonic range finder is connected to PING port on the MD2
73
Using the Studica Toolkit create the following demonstration VI:

1. Run the VI either by clicking the Run button on the toolbar or by pressing Ctrl+R.

Expect to see a “Deployment Process” window showing how the project compiles and deploys (downloads)
to NI myRIO before the VI starts running.

NOTE: You may wish to select the “Close on successful completion” option to make the VI start
automatically.

Expected results: The P VI displays the measured range in centimetres. The PING))) sensor cannot
accurately measure the distance to an object that: a) is more than 3 meters away, b) that has its reflective
surface at a shallow angle so that sound will not be reflected back towards the sensor, or c) is too small to
reflect enough sound back to the sensor. In addition, if the PING))) sensor is mounted low on your device,
you may detect sound reflecting off of the floor. In addition, objects that absorb sound or have a soft or
irregular surface, such as a stuffed animal, may not reflect enough sound to be detected accurately.
Temperature has an effect on the speed of sound in air that is measurable by the PING))) sensor.

Things to Try:

Add a proximity detector (Boolean indicator or onboard LED) with an adjustable threshold level control on
the front panel. For example, when the threshold is set to 20 cm, any object ranging less than 20 cm would
activate the proximity detector indicator.

74
Basic Robot Drive
In this example we will take a simple robot and drive it using the functionality of the MD2 Motor
Adapter and the Studica Toolkit.

1. Open LabVIEW for myRIO and choose Create Project.

2. Click on myRIO under Templates and choose the myRIO Project, Click Next.

3. Enter a name for your project in the Project Name field. Under Target select Connected over WiFi and choose your
Target (refer to Setting up the myRIO for Wi-Fi) so that you can use the myRIO in WiFi mode. Hit Finish when
complete.

75
4. The Project Explorer window will open. Make sure that you are connected to the myRIO, a green dot will be
present if you are. If you are not connected, right click on the myRIO in the project browser and choose connect from
the shortcut menu. Click on the open tab next to the myRIO, right click on Main.vi and select remove from project.

5. When prompted to remove the selected VI choose OK.

6. Right click on myRIO and choose New > VI

76
7. Use the keyboard shortcut Ctrl+T to show both the Block Diagram and the Front Panel windows side-by-side on the
screen.

8. Right click in the Front Panel go to Silver/Boolean and select the pin. To keep the pallet visible.

9. Drag the stop button and an OK button the Front Panel as follows.

10. The Block Diagram will look like the following.

77
11. In the block diagram, right click and choose Structures > While Loop. Please the loop around the objects on the
block diagram as follows:

Notice how the Run Arrow in the top left is broken. This means that the program cannot be run because there is an
error.

12. Move the stop icon closer to the stop button on the bottom right of the while loop and wire them as follows:

13. Right click again and choose Structures > Case Structure.

78
Click inside the while loop and drag it down to fill most of the loop as shown. Wire the ok button to the case selector
as shown.

14. Right click and choose Structures > Flat Sequence Structure

Place this inside the case structure as shown below.

79
15. Right click and choose Studica Toolkit > MD2 >2 Motor and place two copies inside the sequence structure.

16. Right click and choose Numeric and select DBL Numeric Constant. Place the constant above and to the left of the
Motor Icons.

Connect the constant to all the Motor Speed Inputs as shown. This is the Duty Cycle Input; this value is used to control
the motor speed and direction. The closer the value to 1 the faster the motors spins.

17. Right Click on the Frequency node.

Choose Create > Constant and make the value 1000. Typical is 1000 Hz, although you can adjust this number for
better results.

80
18. Complete the block diagram as shown below. The Invert M0 and Invert M1 can be used to adjust motor direction
as required.

19. Wire the error node from each motor VI Bock inout all the way out to the while loop wall. Wiring this will help to
describe any error condition that occues before this node runs.

81
Notice that the red X’s appear indicating a wiring error, this is because the error wring is not yet complete. Right clcik
on the black tunnels on the while loop left edge and choose Repalce with Shift Register.

This will create the paired terminal on the opposite side of the While Loop. The terminal on the right side of the loop
contains an up arrow and stores data on the completion of an iteration. LabVIEW transfers the data stored in the right
terminal of the shift register to the left terminal. The loop then uses the data from the left terminal as the initial values
for the next iteration.

20. Wire the output terminal of the error of Each VI to the right shift register.

Notice that the output tunnel of the case structure is white, this is a visual clue that at least one case has not wired a
value to this output terminal. In this instance only, the True case is wired.

82
21. Use a selection window to copy the motor control portion of the block diagram to the clipboard.

22. Change to the false case and paste the code inside.

23. Clean up the Block diagram for the false case as per the picture below. Notice how the 0.5 constant has been
changed to zero.

83
24. Change back to the True Case and right click on the right border of the flat sequence structure. Select > Add
Frame After and drag to expand it as follows:

84
25. Right click to show the palette and choose Real Time > RT Timing > Wait and drag it into the new sequence. On
the pop up select the drop-down menu and choose mSec, then pick OK.

26. Create a 1500ms constant that connects to to the timer. This will cause the motors to move forward for 1.5
seconds.

27. Now create another frame to the right and expand it.

28. Complete the Block diagram as per the picture below, this will cause the motors to move forward for 1.5 seconds
and then stop.

Additional Activity 1: Add more frames to the sequence structure and make the Robot go in Reverse.
Additional Activity 2: Can you make the Robot do simple left and right turns.

85
Example Program

86
Sample program to Control 2 Motors from the front panel with Sliders

87
Helpful links
http://www.learnni.com – Learn LabVIEW

http://www.learnni.com/getting-started/Home/Index/45 - Debug LabVIEW

http://www.ni.com/white-paper/14621/en/ - Examples and tutorials on how to use different


components with the myRIO

http://www.ni.com/manuals/ - Manuals for LabVIEW and more

http://www.ni.com/pdf/manuals/376047a.pdf - myRIO user guide

http://ni.com/myRIO Lots of resources for the myRIO

http://download.ni.com/support/softlib//labview/labview_myrio/2013/C%20Support%20for%
20NI%20myRIO%20User%20Guide.pdf –How to program the myRIO in C

http://www.ni.com/white-paper/14621/en/ - The guide breaks down wiring, I/O requirements,


device theory, and programming of over 20 different devices common to NI myRIO projects.

88