-
Welcome to the wonderful world of graphical programming for Lego
Robotic Systems! Before you are introduced to any actual code, it
is necessary to settle a few fundamental questions regarding this
new language you must be so eager to tackle.
What is NXT-G? If you don't know, don't worry. The language
itself is rather uncommon outside of circles that deal directly
with the Lego NXT Block on a regular basis. Now let's establish the
correct terminality from the beginning:
~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~
Do other languages exist? Yes. NXT-G is not the only way to
program a robot using the Lego NXT Module, however it is the
easiest to learn for an inexperienced programmer, as well as the
easiest to understand. The two other languages which are commonly
used are called RobotC and LabView. NXT-G, although it's own
language, is built on top of LabView which is also a graphics based
language. RobotC however, is entirely code based. Only NXT-G will
be further addressed after this point.
Why NXT-G? So, there are other languages, huh? Even as an
experienced programmer, it is necessary to understand the learning
curve of a language and the amount of time necessary to gain
experience using it. NXT-G is easy to grasp, therefore it can be
implemented quickly to solve a variety of programs. Unlike LabView
or RobotC, errors are easy to find and correct due to a unique
Lego-like layout. Building a program (in theory) is just as easy as
building with Legos.
This is NXT-G. It is a graphics based language developed by
National Instruments and Mindstorms to allow novice users to
develop and implement simple robotic systems. Don't let my
description fool you though, the language is quite capable of
handling moderately complex designs, especially at a low level. It
is a common issue to confuse the two terms. NXT-G is a Language,
while "the brick" (NXT Module) is a physical Lego piece
This is an NXT Module. It is the metaphorical brain of any
system you could conceive for your Legos. The unit is responsible
for receiving signals from your sensors, performing calculations
based on input, and moving motors and servos accordingly. The unit
can be attached to four sensors and three motors; more than enough
for a truly amazing system!
Introduction: What is NXT-G?Saturday, August 22, 200911:59
PM
NXT-G Page 1
-
In this chapter you will:
Build a small robot-
Learn the basics of the NXT-G Interface-
Learn to manage memroy-
Program your robot to move-
Resources you will need:
Your orange box of Legos-- Contains all parts necessary for
building a robot-
An NXT Brick-
A USB cable for your NXT-
An install CD for NXT-G-
Chapter One: Getting StartedSunday, August 23, 200912:40 AM
NXT-G Page 2
-
This is a guide on teaching you to program robots in a
proprietary language. That's great and all, however it seems you
may b e missing one thing. A robot… Before programming is
addressed, it will be necessary to fabricate a small drive train
and space to mount sensors. Don't worry, it's not terribly
difficult and it will give you a good idea of how to physically
design the systems you will later provide logic to. It always pays
to be well rounded!
It is necessary however, to tell you that Lego includes a guide
on programming as well as building right in it's software. I f you
have ever put together furniture from IKEA, you know that sometimes
having words, or at least part numbers can be helpful. The
following instructions have been inc luded in this document for
your convenience, however they can be accessed directly from NXT-G
if you so desire.
Building the Robot--Just follow these directions before you
continue any further.
1.
Aha! This is one of those times it helps to be able to comment!
You may notice there is an eight next to the black shaft. Th at is
to denote it's length in "Lego units". The piece displayed is just
as long as the width of eight single units, meaning it could span
eight blocks side by side. The circle denotes length of the unit,
while a square would represent width.
2.
3.
Disoriented? Make sure you flipped your motor over. Also, the
square with the thirteen in it is used to show the widths or length
of a piece with holes in it. I must admit, counting the holes is
much easier than trying to understand how long those black and grey
shafts are.
Chapter One: Before you beginSunday, August 23, 200912:43 AM
NXT-G Page 3
-
admit, counting the holes is much easier than trying to
understand how long those black and grey shafts are.
4.
TIP: its usually easier to build the unit in yellow separately
and then attach it to the larger unit than to build both simul
taneously.
5.
6.
7.
NXT-G Page 4
-
8.
9.
10.
11.
NXT-G Page 5
-
12.
Great Job! You just built the mount for your NXT to sit on! Now
for the other components...
This wheel will be built separately, and then attached once you
are finished.
13.
NXT-G Page 6
-
14.
15.
16.
NXT-G Page 7
-
17.
NOTE: Make sure you have your motor-unit turned to the
orientation in the diagram. The round end of the motor should be
facing up.All that is left is mounting the NXT.
18.
NOTE: Although pictured, you do not need to use the rechargeable
battery as shown in the diagram.
19.
It goes up!
NXT-G Page 8
-
20.
21.
IMPORTANT!!: When looking at the unit shown with the NXT
directly facing you, make sure the RIGHT motor is connected to port
C, and the LEFT on port B. If this is incorrect your programs will
not work. Period.
22.
NXT-G Page 9
-
Congratulations! You just built a robot! In it's current state,
you creation just stands as a trophy to your [perhaps] newly
acquired engineering skills with Legos. Let's make it do something
worthwhile!
Again, before we start with programming it is necessary to
introduce to you the NXT -G interface, seeing as you will be using
it extensively from now on. To begin, launch NXT-G.
When you begin, you will be greeted by a screen giving you a few
options, much like other GUIs.
~~~~~~~~~~~~~~~
As a new project, your canvas will be blank. You should see a
starting block
Note: The program itself is not directly labeled by the language
it is used as an interface for. Nowhere in the name is NXT-G.
Funny, huh?
For this lesson, you are going to create a new program called
"Move Forward". Go ahead and use the program creation menu to do
so.This project will be the name of the file stored on your NXT
device, so make sure to make it descriptive. If you are going to
make changes to something that currently works, it's often a good
idea to save it as a new file first. File versions are also often
helpful to include in a file name, especially for large
projects.
Think of this as the beginning of a word document. What makes
NXT-G somewhat different from other languages is that it is
represented in linear fashion, meaning data is read from left to
right.
Start ---> [function] ---> [function ]---> end
Most languages are read from top to bottom or bottom to top.
Start FunctionFunctionEnd
Chapter One: Getting to know the NXT-G interfaceSunday, August
23, 20091:28 AM
NXT-G Page 10
-
The Three Function Menus
To add different "blocks" to create your program, take a look at
the left hand side of the screen.
Common Complete Custom There you should find a menu looking like
one of the tree seen here. Toggle between these windows by using
the tabs at the bottom:
Each of the tabs is called a "palette", and just like an artists
palette it contains an array of different formulas used to create
something larger.
NXT-G offers three palettes: common, complete, and custom. For
the purpose of this guide, we will always be using the complete
palette with the occasional use of the custom one. The common
palette is a small collection of very basic functions that you will
outgrow rather quickly.
The complete palette contains several menus for users to
use.
The Common menu: You don't quite escape the common palette by
switching to the complete menu. This collection of functions are
the basic workings of any program. From this menu you can access
functions available from other menus, however it is the only place
you can access the Move function, which as the name states, allows
you robot to move.
The Action menu: From here you have access to functions that
cause your robot to DO something, such as moving a motor or
emitting a sound. This menu is for when you want something physical
to happen within your program.
The Sensor menu: As the name implies, the sensor menu is were
one would go to access functions dealing with sensors. The
functions created by this menu are primarily used to interface with
the sensor directly. For example, you would use a function from
here with an Ultrasonic sensor to see the distance the sensor was
currently reporting.
NXT-G Page 11
-
The Flow menu: This is were the majority of your program's
structure will come from. If you have had any experience with
programming before, you will know the necessity of loops and switch
statements, however an interesting concept called "wait" has been
added, which pauses the continuation of the program till the
statement has been met.
The Data menu: Although for extremely basic programs this menu
is unnecessary, it is used in more complex situations to perform
calculations as well as create and store variables. Functions found
here can be used to test if a situation is true or false, perform
basic arithmetic, and compare values.
The Advanced menu: Although it is called "advanced", this menu
might as well be called miscellaneous, seeing as it’s contents have
no relative correlation and really nowhere else to go. There are
only a few functions in this menu you will use to begin with,
however keep it in the back of your mind.
The NXT Control Panel
Found on the lower right hand corner of the screen , the small
collection of buttons allows you to control the NXT while it is
connected to the computer.
The Download and Run key: This key is used to compile, download,
and execute the current program on the currently running NXT. The
program will start soon after you press this button, so be careful
if your robot is still plugged in!
The Stop key: Used to stop the current program running on the
NXT. This only works if the NXT is connected to the computer.
The Download key: Unlike the download and run key, this will
just download the current project to the NXT. This is often helpful
if you want to start the program after you have moved your robot
away from the computer, or have unplugged it.
The Download and Run Selected key: Do not use this key. It is
used to change only parts of the code that you specify and can lead
to problems later on. If you want to make changes to only part of
the code, save it as a new file and download it as a new
program.
The NXT Window key: This is an important button to keep in mind.
From this you can access information about the currently connected
NXT device.
NXT-G Page 12
-
Finally! Time to get into the real portion of this guide. In the
following lesson, you will be programming your robot to go forward,
as well as understanding what is happening when you do so. A good
programmer understands what he is engineering, just as a good
pharmacist understands the disease they are treating. Without a
fundamental understanding of engineering AND programming,
developing competent systems can be quite a challenge.
Your first task will be to start a new program. If you created a
project called "Move Forward" previously, then you are where you
need to be, otherwise create that file now.
To program your robot to go forward, grab the "move" block from
the common menu, dragging it onto the square labeled "start".
Now that you have placed the block on the beginning of your
"program timeline", click on your newly placed function and look at
the bottom of your screen to find a menu like the one shown
below.
The Move block is a unique function that allows you to control
multiple motors simultaneously, often with the intent of driving or
steering a robot. Within the menu you will come across multiple
options to control the speed and direction of the motors, a few of
which are briefly outlined in the following section. Each of these
will be covered more in depth in later lessons.
Port: Selects the motor/s that are to be controlled by the
function. Up to two can be selected . Motors correspond with the
port letters they are plugged into on the top of the NXT unit.
Direction: as the name implies, the radio button array can be
used to select the direction a motor goes in. There is one button
however, that is used for braking. Using this setting will cause
the motors to LOCK, meaning they will not slow down to a stop, but
rather stop immediately.
Steering: This is a setting unique to the Move block, seeing as
it can be used to determine the direction of two motors, whereas
the Motor block can only be used to control one. Use the slider to
determine the direction you want your robot to go in.
Power: this particular type of power determines the speed of the
motor, not it's strength.
----Drag---->
Chapter One: Programming Your RobotSunday, August 23, 20096:04
PM
NXT-G Page 13
-
Time: Motor turns for a specified unit of time.Degrees: The
motor itself turns a select number of degrees. Please note that
this does not cause the robot to rotate that exact distance, just
the motor.Rotations: Motor/s turn a specified number of
times.Unlimited: The motor turns until it is told to stop by
another function, or not at all.
Duration: Within duration you can select four methods to
determine the length of time the motor should turn.
Next Action: Used only if duration is not unlimited, the next
action is used to determine if the motors are locked or not after
they turn their specified distance.
Finalizing your program and putting it on the robot
Now that you understand a bit about how the Move block works,
it's time to compile the program and execute it. Start by setting
the "rotations" setting to 5. At the moment, your program should
look like this:
Here's the big surprise: that's all you need! Plug in your
NXTUnit to the computer and turn it on.
NOTE: It is always a good idea to have a long cord and set your
robot on the ground, as the program will start as soonas soon as it
is downloaded.
In the lower right hand corner of the screen, press the Download
and Run key (center) from the NXT controlpanel.
At this point you should feel giddy with joy as you watch your
robot move forward a foot or so and then stop. The best part? You
did that.
NXT-G Page 14
-
There are times when there may be too much content on your NXT
device to load a program onto it. You can easily manage and delete
files from your NXT from the memory window.
There are also buttons which allow you to control how programs
on the NXT are dealt with. Interestingly enough, you can actually
upload from the NXT a program you might not have saved on your
computer.
To access the memory window, first open the NXT screen window
from the control station in the lower right hand corner of the
screen. This will bring up a menu showing the name of your NXT and
the type of connection you currently have established.
A few other interesting things such as battery life and
remaining memory can be found from this menu, however to direct man
age memory, go to the memory tab.
The menu is composed to two different elements. There is the
memory usage graph, which is to the right, and there is the program
menu, which shows all of the components currently on the NXT. From
the graph, select different types of programs to see the files of
their type on the NXT.
Chapter One: Memory ManagementMonday, August 31, 20093:34 PM
NXT-G Page 15
-
In hindsight, this will prove to be useful if you understand how
it is done before you encounter a problem. If you are using the new
NXT-G 2.0 software, as you most likely are, it may be necessary to
update the firmware of your NXT Device to load programs onto
it.
You will know if you need a firmware update if you press the
download and run button and get an error message. Such as the one
shown to the left.
Don't worry, fixing this isn't difficult at all, however you
will need an active network connection to download the new
files.
NXTFirmwarePC
For your convince, I have included a file with an update to
version 1.05. This may not help you if you are using NXT-G 2.0
however, so know there is another way to access the files. Although
you can find firmware updates online at :
http://www.lego.com/education/school/default.asp?locale=2057&pagename=softu&l2id=3_2&l3id=3_2_4&l4id=3_2_4_2
, there exists a better way to get files.
To get the latest firmware automatically, first go to the
"tools" menu on the file bar and then go to update NXT-G Firmware.
This will open up a menu much like the one shown.
Shown here, my NXT has firmware version 1.21 currently
installed. NXT-G 2.0 uses firmware 1.25 and above.
To check and see if there is a new version of firmware available
for download, press the "Check" button at the top of the menu.
To install firmware, select the version you would like to use
(the latest version of course) and press the download button
below.
If everything downloads correctly, the progress bars should fill
up as shown below.
Chapter One: Firmware UpdatesTuesday, September 01, 20094:35
PM
NXT-G Page 16
http://www.lego.com/education/school/default.asp?locale=2057&pagename=softu&l2id=3_2&l3id=3_2_4&l4id=3_2_4_2http://www.lego.com/education/school/default.asp?locale=2057&pagename=softu&l2id=3_2&l3id=3_2_4&l4id=3_2_4_2http://www.lego.com/education/school/default.asp?locale=2057&pagename=softu&l2id=3_2&l3id=3_2_4&l4id=3_2_4_2
-
In this chapter you will:
Learn to use the Display of the NXT Module -
Learn to put out sound through the NXT Module.-
Learn about wait function-
You will need:
Your NXT Device-
A USB cable-
Chapter Two: NXT Related Functions and Wait StructuresSunday,
August 23, 200911:16 PM
NXT-G Page 17
-
If you have ever programmed before, chances are that using NXT-G
is somewhat different than anything you have experienced before. By
programming a robot, you loose the familiar interface of a computer
screen and instead see the results of your code through physical
movement.
The NXT Brick allows you to show functions on it's screen and
NXT-G provides an easy way to "print" the image or text you want to
the screen.
To begin, we will print a simple diagram to the screen. Open up
NXT-G and create a new program called "Print_To_Screen"'
Displaying an Image
Select Display from the Action menu and drag it onto the main
timeline
If you were to export this now, the screen would display the
image for a fraction of a second and then exit.Consider the way the
code is built:
Start ---> Display ---> End
When run, the current program will do everything you tell it to,
however it will not necessarily do what you WANT it to do.
What you want is for the NXT screen to display your image long
enough for you to read it, or until some other stimulus gets rid of
it. What you are looking for is for the program to wait till you
are ready for it to continue. Fortunately, such a structure
exists.
Using the Wait Structure
Using your current program, you will introduce the Wait
Structure from the Flow menu.
Once you have the function on the timeline, click on it to get
to it's properties. From here you will change the image to the
checkmark below.
Chapter Two: The NXT Display and Wait StructuresThursday, August
27, 200912:45 PM
NXT-G Page 18
-
Place the structure after the display function, seeing as you
are waiting before going on to the next piece of the program (which
in this case is the end.)
Go ahead and run this function on your NXT. Your screen should
display the following for five seconds:
Displaying Text
In retrospect, I realize it may be helpful to demonstrate how to
display text through the Display function. Go ahead and change the
"action" in the display panel from image to text.
If you notice, the default setting for the Wait structure is for
it to be used with a touch sensor. Although that could work for
this program, it is easier to just set the structure to wait for a
period of time.
Go to the function properties (bottom of the screen), and change
the "control" of the function from sensor to time. Set the number
of seconds to 5.
After it does this, the program ends.
Using the textbox provided, write what you would like to be
displayed.
NOTE: You are limited to 15 characters.
NXT-G Page 19
-
Although sound may not play a huge part in the actual logic in a
system, it can help developers know what stage of a program is
currently executing, or if the robot is encountering something
unexpected.
To start, create a program called "Sound"
Take the Sound function from the Action menu and drop it onto
the starting square.
Using Sound Files
The difference in the two is the fact that a sound file takes up
a lot of memory. The NXT device has less memory than a floppy
diskette. Much less. A tone however, requires no legitimate memory
at all, seeing as the capabilities are already built into the
device. To select which you would like to play, look at the
properties menu for the sound function.
By default, NXT-G has the sound function play "Good Job" .
Download and Run the current program as it is, and listen to the
sound file it plays.
At this point it may be necessary to point out a key difference
in the use of a Sound Function over that of a Display Function. If
you notice, a Sound function waits until it has played it's sound
to move on to the next part of the program. This is an optional
piece that builds in a wait function.
It is helpful to recognize that you don't need to add a wait
function on top of a sound function to get the desired result.
Using Tones
Like sound files, tones have a built in wait function as
well.
From here, it is necessary to explain the two different types of
sound that can be played. The NXT can play a sound file, which can
be anything from a number to a phrase such as "hello"; and the NXT
can play a Tone, which is just a note.
Chapter Two: Using Sound Saturday, August 29, 200910:52 PM
NXT-G Page 20
-
Like sound files, tones have a built in wait function as
well.
You can select the note you would like the NXT to play, as well
as the length of time you would like to play it.
Note: When a program starts on the NXT, it plays a tone
automatically. If you play a tone at the beginning of your program,
you will hear both tones.
Create a program
To illustrate the difference between the built in wait functions
and the real ones, build a program that plays a note, displays what
note is playing, and then waits a second to play the next, higher
note.
If you need some help, look at the following model:
Sound
If you are using Microsoft One Note to view this, you can right
click the file to the right and save it to your computer or double
click to open it in OneNote. It contains the above code. If you are
not a OneNote user, then all that is an image.
NXT-G Page 21
-
At first, I thought it would be a good idea to teach about
sensors in this chapter, however then I realized that the majority
of new programmers reading this might want to familiarize
themselves with the logicbehind programming before building
anything to control robots.
In this chapter you will learn about:
Variables-
Basic arithmetic -
Advanced function controls in NXT-G (Data Wires)-
You will need:
Your NXT Device-
A USB cable-
Chapter Three: Math and VariablesSaturday, August 29, 200911:47
PM
NXT-G Page 22
-
If you are not a programmer, chances are you have little concept
of what a variable is. Within programming, there are many types of
variables, however they all have one thing in common: they
represent a named place to store a value. Consider them like a box.
You can put things in a box, hide them away, and then take them out
when you need them again. Variables are used in much the same way.
You can create a variable, naming it "NUMBER" and then assign a
number for it to store. When you ask what the value of "NUMBER" is,
it will give you that number back.
Variables are most often used to keep track of things, and
compare them to other things. An ambiguous definition, I know. It
is helpful to use variables, however, because things in a program
change. These things need to be kept somewhere while tests are
performed on them to determine what to do with them. These "tests"
are functions.
Variables in NXT-G
At this point, it will be easier to show you within NXT-G how to
use variables than to give you a rant on them.
To begin, create a new program called "My_First_Logic"
From here you will need to do something that is quite unlike any
other programming experience. Usually, when you write code, you
create variables manually. In NXT-G, you are required to go to the
edit menu (at the top toolbar) in order to create variables.
In the menu, click "Define Variables" from the options.
A menu like the one on the left will come up. This menu will
allow you to create the variables you will use in your program.
Click on the "create" button to create a variable.
Call it "loop number"
Chapter Three: VariablesSunday, August 30, 200912:02 AM
NXT-G Page 23
-
When creating a variable, make sure to set the datatype to the
type of variable you want to create. For this program, "loop
number" should be a number.
When you have done all of this, close the menu.
Now, get the variable block from the Data menu, and put it into
your program.
The default value of a variable is one of NXT-G's predefined
variables.Make sure to go into the properties of the block and
change it to the variable you want it to be
In this case, we want this variable to be the one we just
defined, so we select "loop number"You are also given the option to
read or write and in this case we will be later reading the
variable.
My_First_Logic
Before we do anything more, it is necessary to understand how to
do simple math to change variables.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the right directly into
NXT-G.
~~~~~~~~~~~~~~~
NXT-G Page 24
-
Unfortunately, we are not going to be flying a rocket into
space, or piloting an aircraft with this system. The mathematic
functions offered by NXT-G are basic arithmetic. They are most
commonly used in conjunction with a variable.
Using Math
To perform a mathematic function, go to the Data menu and select
Math
We will be building on top of our previous program using
variables, so drag this function to the next slot in the program
"timeline"
The purpose of this is going to be to add one to "loop number".
The math function works by taking two numbers, A and B, and adding
them together. To set a number to either A or B, click on the
little wire holes next to the Pound Symbol on the Variable (#), or
the letter A. End the wire by clicking on the other one.
At this point, the function will add A and B together, however
you have not written anything to do with the number it produces.
The sum of the two numbers can be linked to a variable by drawing a
wire from this:
In this case, you want to set the new value of "Loop Number" to
be the result of this equation. To do so, enter another variable
block, this time setting it to "write" in the properties bar.
One of the things you may notice at this point in time that you
have not yet encountered with other blocks, is the drop down menus.
These menus are used for what are called "data wires". Data wires
can be used to connect blocks and exchange information.
When you are finished, it should look something like this.
The next step is adding a set number (in this case 1), to the
number set to A.
To do this, go to the properties menu of the math function.
O f course, this is going to be addition, however you will need
to set the static value of B to 1.
Chapter Three: Basic MathSunday, August 30, 200912:31 AM
NXT-G Page 25
-
Your final program should look like the diagram to the left.
My_First_Logic
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
~~~~~~~~~~~~~~~
NXT-G Page 26
-
This is more of a trivial addition to the guide, however it is
important to be able to take a data value and display it on the NXT
screen. You will be displaying the value of the variable "Loop
Number".
To begin, select the Number to Text function from the Advanced
Menu
Put this on your timeline after the last variable. In order to
have a number to convert to text, you will need to read the
variable "Loop Number" again. Draw a wire connection from the value
of the variable, to the input on the Number to Text function. You
program should look like the following:
Now, you will take the text and display it on the screen using
the Display function from the Action menu.
When you add it to the timeline, click on the lower left hand
corner to extend the full bank of input options.
Be sure to change the type of input to "text" from the
properties bar.
As you may be able to figure out, you will be using the text
output from the Text to Number function to draw a data wire to the
text input on the display. Once you have drawn the wire, you can
click the lower corner again to collapse all unused connectors.
Remember, this is a display function, therefore you will need a
wait function after it in order to read what is going on.
The addition to the program should look like this (There is more
to the left):
My_First_Logic
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
Run this program now. The NXT screen should display the number
1.
Chapter Three: The Number to Text FunctionSunday, August 30,
200912:54 AM
NXT-G Page 27
-
The next logical step in establishing your foundation in
computer science and program development is to explain the use of
different program structures. While different languages call these
"structures" different things , the concepts behind them remain the
same.
In this chapter you will learn about:
Loop or repeat statements-
Switch statements-
Comparative operators-
Wait Statements (This is a type of structure, however we have
already covered it)-
You will need:
Your NXT Device-
A USB cable-
Code from the previous chapter-
Chapter Four: Programming StructuresTuesday, September 01,
20099:35 PM
NXT-G Page 28
-
Using the program we created before, we will now actually put
that "Loop Number" variable to use.Open up the program
"My_First_Logic" if you do not already have it open. The following
chapter will use the entire program created in the previous
chapter, therefore if you have not written it yet, the following
code may not make sense.
Using Loop Statements:
To access loops, go to the Loop block of the Flow menu.
From here, drag the loop onto the beginning of the program
"timeline"In NXT-G, anything inside of a loop will repeat until the
loop no longer needs to continue. For this exercise the entire
program will repeat, adding one to the variable "loop number" and
then printing them out to the screen.
To put the blocks into the loop, select them all just as you
would select multiple files (dragging a box around them)
Now drag the selected functions inside of the loop block at the
beginning of the program.Notice how the loop expands to fit the
content inside of it.
Chapter Four: Loop StatementsSunday, August 30, 20092:31 PM
NXT-G Page 29
-
At this point, download and run this program. Your NXT screen
should start counting up from one.If it takes a while to count, you
can always set the wait function to 1 second in order to count
faster.
If you continue to let the program run, the loop will continue
till you hit the back button or the batteries die. Loop statements
have something built in that is a little like a wait block. It's
called a while statement.
Click on the right hand side of the loop to open up the
properties bar.
Loops can end because of a time limit, a specified number of
executions, when a comparative statement is true (which you will
study later in this chapter), or because of sensor telling it to.
We will study methods to break out of a function in the next
chapter.
My_First_Logic
By default, NXT-G has loops perpetuate infinitely. If you have
anything after an infinite loop it will never be executed, seeing
as the loop will never end. Your other options are for the loop to
exit when a certain contrition has been met.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the leftdirectly into
NXT-G.
~~~~~~~~~~~~~~~
NXT-G Page 30
-
There often comes a time where you only want to do something if
another something is right. Yes, this can talk about a lot of
things, however it describes a situation where you are comparing
two different things and determining if the result of their
comparison is right (true) or not (false).
Programs have a way of doing this as well. They do so through
what are called "Comparative Operators". NXT-G allows you to
directly select three types of operators:
Greater than >Less than <Equals to =
Compare Functions
To use the Compare function, go to the data menu.
For this program, put the compare block at the end of the loop
so that it is still inside of it.
You will be using the comparative operator to see if the
variable "loop number" is greater than 10. If it is, the result
will be the end of the loop.
The setup for a comparative functions is much like that of a
math function. Drag the value of the variable to data connector for
"A" and set "B" to (in this case) a static value.
Just as a tip, you don't have to put in a new variable block
every time you need to access a variable. You can "recycle" old
ones and have additional data wires come off of them.
Just as a rule of thumb, you can't "double up" data wires if one
block is in a loop and another is not. Also, make sure the block
you are using is a "read" function, instead of a "write" one.
Moving on, go to the properties bar for the comparative
statement. From there set the value of "B" to be 10 and the
operation to be greater than.
Chapter Four: Using Comparative OperatorsSunday, August 30,
20094:36 PM
NXT-G Page 31
-
Download and run this program now. If you notice, the program
will count up to ELEVIN. This is not an error. 11 is the first
number greater than 10. If you want the program to end when you get
to 10 you can do one of two things. First, you could change
comparative statement to A = 10, with A being the value of "loop
number" or set A>9, with 10 being the first integer greater than
9.
My_First_Logic
Finally, you want you loop to exit when this statement is
"true". Go into the properties bar of the loop and change the
control to "logic"
If you notice, by changing the control the Loop block gained a
data connector. Connect a data wire from the comparative statement
to this connector in order to pass on the result of the
comparison.If the result is true (if the number of loops is greater
than ten) then the loop will exit.Otherwise it will continue.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
~~~~~~~~~~~~~~~
NXT-G Page 32
-
It might make sense to use a comparative function if you are
checking to see if something is true or false and then acting on
one of the end results. What do you do if you want the program to
do a certain thing in a situation and another thing in a different
situation? Switch statements allow the program to execute a
specified portion of code based on the value the statement is
given.
We will again be working with the program "My_First_Logic". If
you do not currently have it open, bring it up now.
Switch Statements
Like the other statements we have encountered in this chapter,
the switch statement can be found under the Flow menu.
When you enter the block into the timeline, place it between the
wait function and the comparative statement. By default, the Switch
statement is set to use a touch sensor. For this part of the
exercise, we will be using the numeric value of the "loop number"
variable.
Again, by default, NXT-G sets a logical (true/false) action to
the type of control. From the "type" menu in the properties bar,
change "logic" to number.
Flat View
From the property bar, change the control from "sensor" to
"value"
If you look at the program timeline, the switch block should
look like the image to the left. Weird right? Even though you are
telling the program you want to do different things based on
numbers, you get a true or false execution method. This is what is
called the "flat view" While in this view, switch statements can
only have two options. A value can be equal to 0 or 1, and
therefore true or false. To get out of "flat view" and add more
options, first uncheck the box in the properties bar.
After being unchecked, your switch box should look like the
image to the right. If you notice the tabs at the top, each one can
be used to select a different value of input. At the moment you
only have two. Lets add some more.
Additional Conditions
Chapter Four: Switch StatementsSunday, August 30, 20097:14
PM
NXT-G Page 33
-
Additional Conditions
To add additional conditions, go to the properties bar of the
switch statement.
As you may have guessed, click on the "+" to add conditions to
the list. Use the text box at the bottom to give a value to the new
conditions.Create one new condition and set it to 9 and change the
value of the second condition to 5.
You might notice that there is a check mark next to the first
condition. This is because it is called the default condition. If a
value does not match any of the specified conditions, it executes
the code within in that part of the switch statement. You can
select which value you want as default by clicking the asterisk
button to the right.
Adding Code to Each Condition
Back on the timeline, you should now have three tabs on your
switch statement. You can hover over each one to see what value the
code inside corresponds to.
Click the second tab, which should be the value 5.Inside of the
statement, print "Halfway There" to the screen. In the 9 tab, print
"almost done". If you need help, it should look somewhat like
this:
Remember to set the output type on the display to textAlso keep
in mind that you need to include a wait function so that you can
read what is on each screen.
As you are wrapping up, make sure to connect the input to the
switch statement to a data wire carrying the value of "loop
number". It is easiest to use the one for the comparative
function.
Download and Run this program now.This program should count up
to five and then display the message "halfway there", count up to
nine and finally print out "almost done".
My_First_Logic
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
~~~~~~~~~~~~~~~
NXT-G Page 34
-
One of the things that makes robots unique from other types of
systems is that fact that robots have the capabilities of being
perceptive. This is to say that robots have hardware that allow
them to measure things in their environment and respond to stimuli
in a physical way.
Before you are fully introduced to sensors, let's start out with
using the hardware that is built right into the NXT. The NXT
buttons are some of the most basic sensors Lego includes.
In this program you will:
Use the NXT buttons to return a value -Create switch statements
to act on these values-Use the "reset" function for the display
function-Use wait functions that rely on sensors. -
You will need:
Your NXT Device-A USB Cable-
Chapter Five: Introduction to Sensors, the NXT ButtonsSunday,
August 30, 20099:45 PM
NXT-G Page 35
-
You now understand the basics of logical programming and
structures to implement it in NXT-G. A good robotic program
however, responds to input from the user. Such input is derived
from various types of sensors. In the following lesson you will be
using the NXT Buttons as your first sensor input.
Sensor Blocks
Under the Sensor menu, find the NXT buttons block and drag it
onto your program timeline.
In NXT-G, you can access the "value" of a sensor by using a
sensor block. The value of something like a sound sensor would be
the amount of sound, however buttons and touch sensors are
different. They have three states "Pressed", "Released", and then
"bumped"- which is pressed and then released.
What to do With Sensor Values
To be clear, there are only actually three buttons. The right
arrow, left arrow, and center orange key. The bottom button is the
"back" key, which if pressed will end you program.
At this point, please create a new program called "NXT_Buttons".
This program will print out the name of the button you are
pressing.
If you look at the properties bar for the NXT button sensor
block (isn't that a mouthful of a name?), you will see these
options outlined for you. From here, you can also select which
button you would like this function to pertain to.
If you notice, the actual block on the timeline shows a Boolean
value as it's output. For clarification, Boolean is a programming
term for a true or false value. This is because when the program
comes to this function, it checks to see if the conditions
(currently if the enter button is pressed) are true or not and then
passes them off along the data wire you would attach to the
function.
The only thing is, this checks the state of the sensor once and
then moves on. If you want a program testing to see if a button is
pressed over a period of time, you will need to put this into a
loop. For this purpose, an infinite loop will be alright, seeing as
the entire program will be within it
Chapter Five: The NXT ButtonsSunday, August 30, 200910:06 PM
NXT-G Page 36
-
Most likely, you will want your program to do something
different based on the value of the input. This is the perfect time
to use switch statements. In this program, you want to print out
"enter button" to the screen only when the key is pressed. Although
we will not finish the function in this lesson of the chapter, put
in a switch statement right after the sensor block at this
time.
NXT_Buttons
Surprisingly, we will not be using an NXT-Button switch
statement. They are only used to discern between howthe buttons are
pressed. Use a logical switch statement.The image to the left shows
the program in "flat view" which is much easier to deal with in my
opinion, seeing as it takes up less room and is less likely to
confuse you.Note: this all should be in a loop.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
~~~~~~~~~~~~~~~
NXT-G Page 37
-
Using the beginning of the program we created in the last
lesson, we should now add the content that the NXT should
display.
According to the current program, the sensor block for the NXT
buttons will tell the switch statement if the enter button is
pressed or not.
When you run the program, it should show the running screen
until you press the "enter button".However, when you release the
button….Nothing! The text stays on the screen!This is because you
need to "reset" or "clear" the screen if it the value is false, and
it should not be told to display anything.
Using the Reset Screen Attribute
Looking at your switch statement, if the sensor passes along a
"true" value, then text is displayed, however if "false" is passed
along, the program just continues. You actually want the program to
do something if the button is not pressed. You want it to display
nothing.
There are two locations you could logically place a new display
function that would achieve the same logical effect.
If the button is pressed, we want the screen of the NXT to print
out "Enter Button". Use the display function from the action
menu.
Make sure you place the function in the "true" part of the
switch statement. You only want this to execute if the statement is
true.
Be sure to add a wait function to the end of the display
function, seeing as you will need to read what is displayed.
At this point, download and run the program on your NXT
device.
or
To set a display block to reset the screen, go to the properties
menu and select "reset" from actions.
Chapter Five: Resetting the DisplayMonday, August 31, 200912:17
PM
NXT-G Page 38
-
The first scenario places the reset function within the switch
statement itself. With this syntax, the screen resets every time
the enter button is not pressed. While this may work for this
smaller program, what if you want the screen to display text when
you press the right key? When the right key is pressed, the enter
button is not. This causes a conflict. Part of the code says "reset
the screen" and another says "display this text!" What results in
both happening, and the screen flickering- constantly resetting and
displaying just as you asked it to.
The second option on the other hand, executes after the switch
statement has been evaluated. In a switch statement, if the
timeline within it is empty, it just moves on within the program
timeline. If you were to add in the scenario with the right button,
the two switch statements would check to see if buttons were
pressed, and otherwise continue on into the program until the
screen is reset.
Multiple Scenarios
If you didn't guess before, you will have the screen display
text in accordance to all three buttons on the NXT. Really, all
that requires is two more copies of pieces of code you have already
created.
Your code should end up looking like the image below (with an
additional piece for the left button).
Download and run this code now. You may notice that there is a
one second lag between the buttons you press.This will be addressed
in the next lesson of the chapter.
NXT_Buttons
The shown piece of code is used to see if a button is pressed,
and then displays text accordingly. Just make to more instances of
this code, changing the text displayed and the buttons pressed to
match the right and left buttons.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
~~~~~~~~~~~~~~~
NXT-G Page 39
-
As the program is, if a button is pressed, it displays a message
showing that the button is pressed. Wouldn't this program make more
sense if it stopped having to display the message when you were no
longer pressing the button?
It would be much more logical to wait until the button you are
pressing is released.
This program will display the key you are pressing, only when
you are pressing it!
~~~~~~~~~~~~~~~
NXT_Buttons
The current program uses a wait function to display the name of
the button pressed for one second before continuing. While this
makes sense, it causes the message to display even after you have
let go of the button.
Go to the wait function in the piece of code displaying the
"enter button" in the properties bar of the wait function, change
the type of control to "sensor", seeing as the buttons are
sensors.
For the type of sensor, use NXT Buttons.
Because this function is dealing with the enter button, make
sure you have it selected.
Wait functions are designed so that the function before them
continues to execute until the condition of the wait function is
met. We want the message to display until the button is
released
At this point you wait function should look like this. It's a
big change from just an hourglass, isn't it? Go ahead and make
changes to all of the other button's display functions and then
download and run.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
Chapter Five: Wait Functions Using SensorsMonday, August 31,
20091:00 PM
NXT-G Page 40
-
This is the first official chapter to deal directly with
offboard sensors, meaning logical hardware that exists beyond the
NXT Device. Touch sensors behave like mountable buttons, and can be
customized to do a number of things.
In this chapter you will:
Learn how to use touch sensors to stop a robot-
Use a touch sensor to count touches-
Learn to program so that the robot can respond to multiple
sensors.-
You will need:
The robot from Chapter One-
Your NXT Device-
A Touch Sensor and mount-
A USB cable-
Touch_Sensor
This is a PDF included by Lego that gives a short overview of
touch sensors.
Chapter Six: Touch Sensors and the "or" opperatorMonday, August
31, 20092:46 PM
NXT-G Page 41
-
Time for a break from programming! Before you can truly use any
sensor, you need to mount it to the robot you are planning on using
it with. We will be mounting the touch sensors to the front of the
robot.
Chapter Six: Building a Mount for Touch SensorsMonday, August
31, 20092:52 PM
NXT-G Page 42
-
NXT-G Page 43
-
Be sure to connect this to port one of the NXT. This is the
default port for the touch sensor.
NXT-G Page 44
-
This very well may be the shortest lesson you will have to
complete. The purpose of the following is to demonstrate the uses
of the touch sensor on a small scale robot. One of the most common
uses of a touch sensor is to detect an obstacle in the direct
premises of the robot (touching against it).
Create a new program called: "React_to_Bump"
Seeing as this program is going to start with movement, start by
adding a move block from the common menu. Place it in the start
square of the timeline.
Just like in the previous program, you want the function to run
until the touch sensor is pressed. Anytime you logically use
anything until anything else is done, you use a wait function.
Guess what! That's it! If you download and run this program now,
the robot will move forward until it hits and object and the touch
sensor is pressed.
~~~~~~~~~~~~~~~
React_to_Bump
From here, go to properties and select "unlimited" for the
amount of rotations. We want he robot to move until it hits an
obstacle, only stopping if the touch sensor is pressed.
In this instance, the default wait function's use of the touch
sensor is exactly what we are looking for. We want the robot to
stop if the touch sensor in port one is pressed.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
Chapter Six: Stopping Using a Touch SensorMonday, August 31,
20093:15 PM
NXT-G Page 45
-
The following program will require you to do a little work.
First, you will need another one of the touch sensor mounts you
designed for the first part of this chapter. Mount it directly to
the back of the robot on the rear wheel. For this exercise, plug it
into port 4 of the NXT.
In this program, we are going to do a little reworking of our
previous bump reaction program. To begin, everything is going to
exist within a loop.
We want the robot to move, and by extension the loop to
continue, if the buttons are NOT pressed. In the properties bar of
the loop statement, change the unit of repetition from "true" to
"false".
At this point, you will need to remove the wait function. There
is no reason to have to wait for the program to end using one of
them, seeing as the program will end when the loop ends. In it's
place, place two blocks for touch sensors.
You want the loop to end and the robot to stop if the front
touch sensor is pressed or if the back one is pressed. Using an or
statement can be achieved through the logic block under the "data"
menu.
Place one of these blocks on the end of the timeline. Now look
at the properties bar.
By "isolating" portions of code to a loop, you can stop the
execution of entire pieces of programs based on how the loop is
supposed to end. In the case of this program, the loop should be
logic based.
With this, the loop will continue till the button returns that
it has been pressed, a "true" value.
The touch sensors are currently be set to return the state of
the touch sensor plugged into port 1. If you remember how you wired
the robot, you have a touch sensor plugged into both port one and
four. In the properties bar, change one of the blocks to correspond
with port four.
You want the function to return a "true" value and end the loop
if either touch sensor returns a "true" value. The settings shown
to the left ask if they are returning "false" values. Check off the
check marks to change this.
Chapter Six: Multiple Touch Sensors and the "or"
StatementTuesday, September 01, 20094:56 PM
NXT-G Page 46
-
If you have not done so already, create data wires for your
values to travel over. When you are finished, download and run the
program.If you tap the front or back, the robot stops.
React_to_Bump
-
The following lesson is more of an optional activity to further
explain the uses of sensors, loops, and variables. If you feel you
understand touch sensors completely, then it is alright to move on
to the next chapter.
In this project you will create a short program that counts the
number of times you have pressed a touch sensor. For this example,
we will use both the front and back mounted touch sensor used in
the previous lesson. Understand this can apply to NXT buttons as
well.
First, create a new program called "Bump_Count"
Seeing as you want your program to count multiple times, the
entire program will need to exist within a loop. There is really no
reason for this loop to end based on any given input, so let it be
infinite.
Within the loop, use the same piece of code you used from the
last lesson. Two touch sensors and an "or" unit of logic. This will
be used to determine if any buttons are pressed. Remember to change
one of the sensor blocks to port 4, and set the values of the "or"
statement to check that the sensors are "true". Also, change the
buttons to being "bumped".
Instead of using this logic to end a loop, we will use it to
create a switch statement. The switch statement should be logical,
and a data wire should feed to it from the "or" operator.
In order to record the number of times a sensor has been
pressed, the value needs to be recorded to a variable. Go to the
"edit" menu in the filebar, select "Define Variables", and a menu
like the one shown to the right will come up.
Create a new variable and call it "count"Make sure the variable
is a number, seeing as that is the type of data counting usually
deals with.
When you are done, create a variable block within the "true"
section of the switch statement.
Set the action to read the variable. Make sure to select "count"
as the variable that needs to be read.
Chapter Six: Counting TouchesTuesday, September 01, 20095:24
PM
NXT-G Page 48
-
From here, if you were to run this program in it's current
state, one would be added to the value of "count" every time a
sensor was pressed. This is what you wanted, right? Well, yes, but
I assume you wanted to see it as well!
Download and run the program now. When you press either touch
sensor and then release it, the counter on the screen should go
up.
~~~~~~~~~~~~~~~
Bump_Count
Now it's time to do a little bit of math. If one of the touch
sensors is pressed and the switch statement performs the code, you
want to add one to the current value of "count" and then set the
sum to the new value of "count". Remember to set the value of "B"
to one.
When you are finished, set the sum of the variable to the new
value of "count". Make sure you have the variable set to "write"
and that the current variable it is setting to is "count".
Create a variable set to read the value of "count" and convert
the number into text. With that text, create a display function
from the action menu. Notice, that in this instance you do not need
a wait function to see what is on the display. This is because the
display is constantly updating due to being in a loop. Adding a
wait function would cause the program to lag.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
NXT-G Page 49
-
Sound sensors are one of the least used sensors available to the
platform. The are not a "microphone" sensor as one may be compelled
to believe, but rather a device used to measure the intensity of
sound.
Although you may not use it, sound sensors can be used to
demonstrate a few things.
In this chapter you will:
Build a sound sensor mount-
Make a robot stop based on sound-
Make a robot that accelerates based on sound. -
You will need:
The robot from Chapter One-
Your NXT Device-
A Sound Sensor and mount-
A USB cable-
Sound_Sensor
This is a PDF included by Lego that gives a short overview of
sound sensors.
Chapter Seven: Sound Sensors and Acceleration Tuesday, September
01, 20096:04 PM
NXT-G Page 50
-
This unit plugs into port 2 by default.
Chapter Seven: Building a Mount for Sound SensorsTuesday,
September 01, 20096:08 PM
NXT-G Page 51
-
This program is nearly identical to the one dealing with touch
sensors in the previous chapter. Create a new program called:
"React_to_Sound"
Seeing as this program is going to start with movement, start by
adding a move block from the common menu. Place it in the start
square of the timeline.
Guess what! That's it! If you download and run this program now,
the robot will move forward until it encounters a loud sound.
~~~~~~~~~~~~~~~
React_To_Sound
From here, go to properties and select "unlimited" for the
number of rotations. We want he robot to move until it hears a loud
sound, only stopping if the sound is above the defined level.
Just like in the previous program, you want the function to run
until the sound sensor reaches a desired level.
To set the desired level to stop at, go to the properties bar
the default level of the sound being greater than 50 will work well
if you are in a quiet room.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
Chapter Seven: Stopping with a Sound SensorTuesday, September
01, 20096:30 PM
NXT-G Page 52
-
One unique thing you can do with a sound sensor is control the
level of power given to the motors. With this in mind, you can
create a program where a robot will move faster or slower based on
the level of sound it is receiving.
To begin, create a new program called "Sound_Acceleration"
Because in this program you will be evaluating the level of
sound and adjusting the speed of the motors multiple times, this
entire program will need to be in a loop. This loop can be left to
repeat infinitely.
Within the loop, place a sensor block to receive the level of
sound from a sound sensor. By default, the sound sensors are
attached to port 2.The level of sound a sensor returns as a value
is a number between one and one hundred.
Now insert a move function from the "common" menu, placing it
after the sound sensor on the program timeline. Click the drop down
menu for data wire connectors on the move function.
The sixth connection down is the "power" level. The number that
is set to this value controls the power level the motors are given,
and thus the speed the robot travels at.
A higher value gives you a greater amount of power, therefore if
the sound sensor reports a higher level of sound, the robot will go
faster.Also, make sure to change the rotations of the motors to
unlimited.
You can download and run the program at this time.
Sound_Acceleration
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
Chapter Seven: Sound for AccelerationTuesday, September 01,
20096:52 PM
NXT-G Page 53
-
Ultrasonic sensors are a bit more important than sound sensors.
For some robots, the ultrasonic sensor will have the most
programming out of any other system. These sensors return a value
based on the distance an object is in either inches or centimeters
. They work relatively like sonar.
In this chapter you will:
Use ultrasonic sensors to turn a robot at a distance from an
object.-
Print a distance to a screen-
Approach an object if it is within a range -
You will need:
The robot from Chapter One-
Your NXT Device-
A Sound Sensor and mount-
A USB cable-
Ultrasonic_Sensor
Left is a PDF included by Lego that gives a short overview of
sound sensors.
Chapter Eight: Ultrasonic SensorsTuesday, September 01, 20099:26
PM
NXT-G Page 54
-
Chapter Eight: Building a Mount for Ultrasonic SensorsTuesday,
September 01, 20099:43 PM
NXT-G Page 55
-
Wire this to port 4 for typical programming.
NXT-G Page 56
-
The following use of the ultrasonic sensor is actually quite
much like the programs we have created in the past that forces the
program to quit when the sensors returned a true value.
Instead of quitting, this program will cause the robot to turn
when it gets within a specified distance.
Start by creating a new program called "Turn_at_Distance"
Turn_at_Distance
Seeing as this program will not need to end, that is, the robot
can keep driving in a square, the first thing you will need to
create is a loop function for the program to go into.
As with most programs, you want your robot to move forward to
begin with. You should set the rotation value to unlimited, seeing
as the robot will move forward until it is within a distance of an
object.
Did you catch that keyword? Use a wait function with the
ultrasonic sensor to have your robot move forward until the
prerequisite is met.
In the properties bar, you can set the values of the distance
your robot should be within. You can also change weather they are
inches or centimeters. Set it to less than 60 Centimeters.
Remember, this program is going to have the robot turn when it
comes within range. To turn, create a new move block from the
common menu.
To have the robot turn right sharply, drag the slider in the
properties bar for steering all the way to the right.
To have the robot turn about 90 degrees, have the duration
reduced to only half a rotation.
You can download and run at this time Source code ---->
Chapter Eight: Turning at a DistanceTuesday, September 01,
20099:51 PM
NXT-G Page 57
-
The following use of the ultrasonic sensor is actually quite
much like the programs we have created in the past that forces the
program to quit when the sensors returned a true value.
Instead of quitting, this program will cause the robot to turn
when it gets within a specified distance.
As with most programs, you want your robot to move forward to
begin with. You should set the rotation value to unlimited, seeing
as the robot will move forward until it is within a distance of an
object.
To have the robot turn right sharply, drag the slider in the
properties bar for steering all the way to the right.
NXT-G Page 58
-
Sometimes it helps to know what your sensors are doing in order
to create a program that works with them well, or to spot errors.
Just like when we printed out the state of the NXT buttons, you can
print out the distance of an object from the ultrasonic sensor.
Create a new program called "View_Distance".
If you want to use the value the ultrasonic sensor is currently
returning, you need to use a sensor block, specifically that of the
ultrasonic type.
If you download and run this program now, it will print out the
distance from the ultrasonic sensor that an object is.
~~~~~~~~~~~~~~
View_Distance
Like most programs you have created, you want the screen to
display readings constantly. Of course, this means that you have to
put all of the program within a loop.
Seeing as the data wire coming off of the ultrasonic sensor is
carrying a number, that is the distance from current object, you
can convert this number to text by using the number to text
function found under the advanced menu.
Using what you already know, it isn't difficult to see that this
text is going to be output to the screen. Create a display
function, make sure to switch the action to text, and create a data
wire from the number to text function to it.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
Chapter Eight: Print a DistanceTuesday, September 01, 200910:23
PM
NXT-G Page 59
-
One of the useful functions that can be used in conjunction with
the ultrasonic sensor is the range function. As a logical function,
it reports if a value is within two values by returning a
Boolean.
To begin, create a new program called "Range_Control"
In this program you will only move forward if an object is
within range. As you could imagine, this will mean you will need to
check the range multiple times and therefore the program will need
to be in a loop.
Of course you are going to need an ultrasonic sensor block to
return the value of the distance you are currently away from an
object, however to compute range you will also need a range block.
They can be found under the data menu. Be sure to link a data wire
between the output of the ultrasonic sensor, and the input on the
range function.
As with most statements that have a logic based return, we only
want the robot to accelerate if the range is within 50 and 65. Use
a switch statement to set up the structure necessary to act only on
a true value.
From the properties bar, set the range to be within 50 and 65.
Change the sensor to that this is centimeters.
Because this is going to move until it is out of the range,
place a move block within the "true" tab of the switch
statement.
Chapter Eight: The Range FunctionTuesday, September 01,
200910:41 PM
NXT-G Page 60
-
This logic works for stationary objects of course, so if you
were to download and run this code now the robot would approach an
object until it got within range of it, however we want this code
to work for moving objects.
Download and run the program at this time. You may notice that
the robot moves forward in bursts. That is because every time the
switch statement's loop is evaluated, the wheels rotate once.
~~~~~~~~~~~~~~~
Range_Control
To continually evaluate if the object has moved out of range,
you will need to create a loop within the switch statement. At this
point you can also get rid of the wait statement, seeing as this
will be logically ended. Also, switch the move function to rotate
once if it is not doing so already. From within this new function
we will check again to see if after moving the values returned from
the ultrasonic sensors are within the specified range.
You want this robot to move forward until it is out of range.
Logically speaking, if the robot is approaching an object, the
range should decrease. If the object were stationary, you could
program the robot to approach it until the sensor reached the lower
end of the range.
You will use the exact piece of code used before to see if you
are within the range of the object. You can copy and paste if you
would like.Just make sure your two range functions match in the
values they are comparing.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
NXT-G Page 61
-
Light sensors are just as important to a well working robot as
ultrasonic sensors can be. A light sensor has limitations much to
the same degree as the sound sensor does. Just as a sound sensor
can only measure the "loudness" of sound, light sensors can only
determine the intensity of the color. Light sensors can not discern
colors from one another in any way beyond how dark the color is.
They certainly can not be used as cameras to navigate an
environment.
In this chapter you will:
Use a light sensor to stop at a black line-
Use a light sensor to return a value-
Use a light sensor to follow a black line-
Use switch statements based off of light sensor's returns -
You will need:
The robot from Chapter One-
Your NXT Device-
A Light Sensor and mount-
A USB cable-
A Black length of tape-
Light_Sensor
Left is a PDF included by Lego that gives a short overview of
sound sensors.
Chapter Nine: Light SensorsWednesday, September 02, 200912:01
AM
NXT-G Page 62
-
Wire this to port three by default.
Chapter Nine: Building a Light Sensor MountWednesday, September
02, 20095:57 PM
NXT-G Page 63
-
The following lesson is much like the ones in past chapters
dealing with stopping a robot using a sensor.If you so choose, you
can skip this lesson and advance to the next one. A bit of warning
though, light sensors are introduced in this portion of the
program.
Create a new program called: "React_to_Light"
Seeing as this program is going to start with movement, start by
adding a move block from the common menu. Place it in the start
square of the timeline.
Just like in the previous program, you want the function to run
until the light sensor is activated. Anytime you logically use
anything until anything else is done, you use a wait function.
With this in mind, you will need to tweak the settings of your
program depending on the environment a robot will be working in.
Seeing as in this program you want the robot to stop at a black
line, it should return a value well over fifty. What you don't want
to happen is the normal environment your robot is traveling over to
be dark enough to trip a function.
You may also notice the "generate light" option. This will cause
a little LED on the sensor to light up adding additional value to
the return of the sensor.
If you download and run this program now, the robot will move
forward until the light sensor comes over a black line.
From here, go to properties and select "unlimited" for the
amount of rotations. We want he robot to move until it hits an
obstacle, only stopping if the light sensor detects a high
value.
In this instance, change the control of the wait function to
sensor and select "light sensor" as the type of sensor. Notice that
light sensors use port three as default.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
If you consult the properties bar for the light sensor wait
function, you will see two unique options. The first option sets
the threshold for the "darkness" a color must be to trip the wait
function. If you will be operating the robot on a light colored
surface such as carpet, < 40 is fine.
React_to_Light
~~~~~~~~~~~~~~~
Chapter Nine: Stopping Using a Light SensorWednesday, September
02, 20096:02 PM
NXT-G Page 64
-
Again, this lesson may sound a bit repetitive from the work you
did with ultrasonic sensors, however designing a system that can
return the values of an environment you are working in can be
invaluable useful in setting the thresholds in values.
Sometimes it helps to know what your sensors are doing in order
to create a program that works with them well, or to spot errors.
Just like when we printed out the state of the NXT buttons, you can
print out the value a light sensor is returning.
Create a new program called "View_Light".
If you want to use the value the light sensor is currently
returning, you need to use a sensor block, specifically that of the
light type.
If you download and run this program now, it will print out the
amount of light a surface is currently reflecting. Note that
generating light will change this.
~~~~~~~~~~~~~~
Like most programs you have created, you want the screen to
display readings constantly. Of course, this means that you have to
put all of the program within a loop.
Seeing as the data wire coming off of the light sensor is
carrying a number, that is the "shade" of current surface, you can
convert this number to text by using the number to text function
found under the advanced menu.
Using what you already know, it isn't difficult to see that this
text is going to be output to the screen. Create a display
function, make sure to switch the action to text, and create a data
wire from the number to text function to it.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
View_Light
Chapter Nine: Print a Value from the Light SensorWednesday,
September 02, 20096:44 PM
NXT-G Page 65
-
This is most likely one of the most common (and useful) uses of
the light sensor is to cause a robot to follow a line. In many
robotic competitions, there are markings on the field designed to
allow users to control robots in just that way.
To begin, create a new program called "Follow_Line".
~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~
Because want the robot to continually check to see if it is on
the line, the entire program should exist within a loop. As you may
have noticed by now, many programs use a loop to repeat themselves
indefinitely.
Within this loop, create a switch statement with it's sensor
setting set to light sensors. Switch statements for light sensors
compare the level of light to a set level. If the level is true,
code within this tab will execute.
To set the level of light for the switch statement to act on,
use the compare option. For this lesson, set it to less than
forty.
Now consider for a moment what this switch statement is doing.
It is comparing two values, the current amount of light and the
number 40, and then acting accordingly. This piece of code will do
the EXACT same thing. In programming, there are often multiple ways
to do the same thing. It takes a good programmer to decide which
method to choose. For now, stick with the first switch statement we
chose. Do not enter the code to the left
Logically, to follow a line you need to turn to stay on it. To
help the robot stay centered, it will need to turn in both
directions. For the "true" side of the statement, we will have the
robot turn right until it is off of the line. For the "false" side,
the robot will turn left.
The easiest way to turn in this manner is to brake one side of
the robot and to give power to the other.
Chapter Nine: Following a LineWednesday, September 02, 20096:56
PM
NXT-G Page 66
-
No switch over to the other tab in the switch statement:
As it is, this robot will only turn counter clockwise when
"looking" for a line. With this in mind, you can have the robot go
around a square or circle of black tape in a counter clockwise
fashion. The light sensor is mounted in the center of the robot,
therefore the wheels are always evenly spaced over the line even
when it makes a turn.
~~~~~~~~~~~~~~~
When you are done, download and run the program. Just know that
you will need black tape or something of the like to make this
program work properly.
Follow_Line
In the true portion of the switch statement, first set the motor
in port B to brake by going into the properties bar and unchecking
"c"
Next, set motor C to turn forward unlimitedly, till the switch
statement stops.
Within this section of the switch statement (the false one), you
want to brake the C motor and turn the B one. With the current
setup, the robot will turn one way if it's on the line, and another
if it's not.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
NXT-G Page 67
-
Lego motors have built in sensors that are able to detect the
degree the motor it turned to. In most commercially available
motors, sensors such as this are called encoders and are mounted
and implemented separately from the motor. Lego makes it easy for
you.
In this chapter you will:
Create a robot that moves and displays the rotation of the
sensor. -
Reset the rotation sensors-
Commit a position to memory and have the robot turn back to that
point.-
You will need:
The robot from chapter one-
Your NXT Device-
A USB cable-
Interactive_Motor
Left is a PDF included by Lego that gives a short overview of
sound sensors.
Chapter Ten: Motor EncodersWednesday, September 02, 20099:19
PM
NXT-G Page 68
-
In the following lesson you will be displaying the current
position of the motor as a robot moves forward. When working with
rotation sensors, it is important to note that the rotation of one
wheel is not always exactly the same as another, especially after
turning the robot. When you are dealing with rotation, typically
you will only choose one motor. Be logical in your choice.
To begin, create a new program called "display_position"
Within the loop, first insert a rotation sensor block to return
the current orientation of the encoder.
You can now download and run the program.
display_position
Like the programs we have created in the past, this will also
exist within a loop, seeing as you will need to continually display
the current rotation of the motor as well as move forward.
By default, the sensor is set to return the orientation of the
motor attached to port A. In your current robot, there should not
be any attachments to that port. Change the sensor to use port C,
which controls the left motor. You can select the port in the
properties bar for the rotation sensor block.
Like the other functions you have had print values to the
screen, convert the rotation output of the sensor block to text and
create a display function to print to the screen the current output
of that text block.
This program would work fine as it is, however in order to
actually make sense it requires the robot to move forward. Create a
move function with unlimited rotations as well as a power setting
of about 40.
By setting the power settings to be lower, it is easier to see
the rise of the rotation sensors.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
Chapter Ten: Displaying Motor PositionThursday, September 03,
20098:01 PM
NXT-G Page 69
-
As you may notice, the sensors do not stop at 360 degrees. This
can be helpful in determining the exact number of rotations a motor
and wheel have turned, however it often does little help in
determining direction. Luckily, you can reset the value of a
rotation sensor so that it starts back from zero.
We will be using the code from the previous lesson for this
one.
Download and run the program now. The display should count up to
360 as the wheels turn, and then start over a 0 when they make a
complete rotation.
~~~~~~~~~~~~~~
display_position
To begin, place a new rotation sensor block before the existing
one. Remember to change the port the sensor is monitoring the motor
of to match the one in the function you were using previously.In
this case, I have used C, the motor used to control the left side
of the robot.
Here you will need to use a comparative operator. Remember, we
only want to reset the count for rotations if the motor has turned
past 360 degrees. To do so, we need to compare the current state of
the rotation sensor to 360 and reset only if it is greater.
Here, insert a switch statement to act upon the comparison. The
type of switch statement should be logical, seeing as comparative
operators only return true or false values.
Within the "true" portion of the switch statement, place another
sensor block for rotation. Just as you have with the others, make
sure to adjust the port to match the motor you are monitoring.
Within the properties bar, select reset as the action to act upon
if the rotation is greater than 360.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
Chapter Ten: Resetting the RotationThursday, September 03,
20098:46 PM
NXT-G Page 70
-
If you are working with the kit part number W979797, then
chances are you will not have this sensor in your box. If by chance
your team or instructor has purchased one, then I have included
this to show the usefulness of the sensors.
Although the robot includes built in sensors on the motor, it is
much easier to pass a single number into functions than it is to
calculate the orientation of a robot based on both wheels.
In this chapter you will:
Not do anything… After working with the sensors in NXT-G their
usefulness has let me down. To truly utilize these sensors consider
using LabView or RobotC. Otherwise, use the rotation sensors to
accomplish the same task.
Chapter Eleven: Compass SensorsThursday, September 03, 200911:10
AM
NXT-G Page 71
-
Okay, let's face it: you are now a programmer. As you develop
more complex programs, you may start to loose track of what things
are doing what. As a developer it is important to know what EVERY
piece of code is doing at all times.
Take for example, the first program we created. You really don’t
need to explain to a user that the code makes the robot go forward,
right ? Due to it's size and relative simplicity, it is easy for
another person to come and look at your program and understand what
everything is doing.
In more complex programs, such as the one with the light sensor
that follows a line, it is more difficult to tell what is going on.
Often it is helpful to type in little comments that explain what
the code is doing.
To add comments to code, change the cursor type to "comment" by
clicking on the icon in the taskbar.
This will allow you to click anywhere within a program and add
text.
Comments do nothing to the program structure and are entirely
optional.
Also note that comments do not affect the size of the file on
the NXT.If you are avoiding commenting to conserve space, it will
defeat the purpose.Besides, if your program is that big, you are
going to need them!
Chapter Twelve: Commenting in CodeThursday, September 03,
200911:10 AM
NXT-G Page 72
-
There may come a time that you need to use multiple touch
sensors in conjunction with other sensors. Seeing as the robot only
has room for 4 sensors, lego made a multiplexer to "split" one port
into four for use by up to three additional sensors.
In this chapter you will:
Display which sensor is being pressed based on touch
multiplexer.-Display multiple values simultaneously. -
Chapter Thirteen: Touch MultiplexersThursday, September 03,
200911:11 AM
NXT-G Page 73
-
Touch multiplexers are not actually Lego products. They are
produced by HiTechnic to be used with the NXT Device. To attach
this to an NXT, plug in the cable to the single port on the
multiplexer labeled NXT.
To begin programming, create a new program called
"Mulit_Test"
If run now, your program will display text if the button is
pressed. To display if multiple buttons are pressed, create another
switch statement just like the one you just created, but this time
do insert the value of touch sensor two from the multiplexer.
Change the line of the display to line 4 as well, making sure to
uncheck the "clear" box. Also make sure to reset the screen if no
buttons are pressed.Download and run this program now.
Multi_Test
As with any program that will continually check the state of a
sensor, you will need to create a loop to put all of your content
in. Due to it's use of touch sensors, the multiplexer itself is a
type of sensor.
From within the sensor menu, find the multiplexer block. It
looks like a succession of four touch sensor icons. Place this
within the loop.
The sensor block itself might look a little odd, seeing as the
value types it returns appear to be text. Looks can be deceiving
however, seeing as the value they return are actually Booleans. T1
returns the value of the button. Note that this eliminates the
"bump" option, seeing a button is either pressed or it is not.
To create a function that displays the state of the button
pressed on the multiplexer, create a logic based switch statement
that contains a display function under it's true condition. Have it
display text on line three, and turn clearing off.
Attached is a copy of the program up to this point. If you are
using OneNote, you can open the icon to the left directly into
NXT-G.
Chapter Thirteen: Using a MultiplexerFriday, September 04,
200910:12 PM
NXT-G Page 74
-
There is a feature on the NXT that allows the device to capture
the motor movements and play them back in a short sequence. It's a
neat feature, however it rarely comes in helpful unless you want to
create a program that does not perform a predefined set of