© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
G. KochLearn Engineering with LEGOhttps://doi.org/10.1007/978-1-4842-9280-8_2

2. Programming

Grady Koch1  
(1)
Yorktown, VA, USA
 

As described in Chapter 1, the Hub can control motors and sensors, with some functionality under control of the Hub’s front panel. But the real power of the Hub is that it can host computer programs for sophisticated control of inventions. This chapter will show how to program the Hub. Moreover, the process will be described of how to design and build computer programs, starting from a basic idea to the finished product of code. Programs are coded in the Robot Inventor app on a smart device or computer, then downloaded into the Hub’s memory. The Hub can then be disconnected from the host device to work independently. Exercises and the project in this chapter will explain how to install and use the Robot Inventor app, navigate through its functions, and write code in both the Word Blocks and Python computer languages.

Using the Robot Inventor App

Programming the Hub is done in the Robot Inventor app, which can be hosted on a smartphone, tablet, desktop, or laptop computer. Programs developed in the app get downloaded and stored in the Hub’s memory, so programs can then be run without connection to a host device.

Installing and Updating the App

Robot Inventor can typically be downloaded from the app store on a particular device, such as the Microsoft Windows Store on a PC computer or the iOS App Store for an Apple Product. A search in the app store for “LEGO MINDSTORMS Robot Inventor” should find the app. Alternatively, the app can be found on the LEGO website at www.lego.com/en-us/themes/mindstorms/app. Running the app should bring up a home screen like Figure 2-1. The first time the app is run, and every so often afterward, a notice may pop up on the screen indicating that an update is available, and directions on the screen will make the update. This update is from LEGO to improve features of the app and fix small problems that are discovered as more people use the app.

The Interface

The largest feature on the home screen, shown in Figure 2-1, is the five example robots that are featured with the Robot Inventor set. Clicking one of these robots will show instructions for building the robot. These robots are fun to build and a good introduction to LEGO MINDSTORMS, but the main interest in this book is on the icons at the bottom of the home screen for home, community, projects, and code.

A screenshot of the Lego Mindstorms Robot Inventor app displays the home screen featured with five example robots named charlie, Tricky, Blast, M V P, and Gelo. Four icons for home, community, projects, and code are at the bottom of the home screen.

Figure 2-1

The home screen for the Robot Inventor app

  • Home: Returns to the home screen

  • Community: Shows extra projects in addition to the five example robots

  • Projects: Shows a list of saved programs

  • Code: Opens a new screen in which to write programs

Clicking Code accesses the code screen, as in Figure 2-2. There’s a lot going on in this screen, which will be covered in detail in this chapter.

A screenshot displays the code screen of the Lego Mindstorms Robot Inventor app. Nine icons for motor, movement, light, sound, event, control, sensor, operators, and variables are present vertically at the left of the code screen.

Figure 2-2

The code screen in the Robot Inventor app

Connecting the Hub

The Hub gets connected to the app by clicking the small icon in the upper-right corner of the screen. (This icon looks like the Hub’s outline.) The screen shown in Figure 2-3 should then appear to prompt the type of connection: USB cable or Bluetooth.

The USB cable comes with the Robot Inventor set and serves two functions of connecting the Hub to the app and charging the Hub’s battery. With successful connection, the icon of the Hub in the upper-right corner now has a green dot next to it.

The second option for connection is by Bluetooth, which is useful if the host device doesn’t have a USB port, such as smartphone or many tablet computers. Bluetooth is a type of radio communication, so it doesn’t require a cable. Clicking the Bluetooth tab at the top of the Connect Hub screen will bring up instructions for making the connection, which involves pressing the button on the Hub’s front panel.

Once successfully connected, the app returns to the code screen in Figure 2-2. However, a prompt may appear to update the Hub, as described in the following section.

A screenshot displays the connect hub screen of the Lego Mindstorms Robot Inventor app. It presents two types of connection U S B and Bluetooth.

Figure 2-3

The Connect Hub screen presents two options for connecting the Hub to the Robot Inventor app

Updating the Hub Operating System

After the Hub is connected to the Robot Inventor app for the first time, a notice is likely to appear to prompt for an update of the Hub’s operating system, such as in the screenshot in Figure 2-4. This update will make the Hub run better, with improvements and bug fixes that LEGO releases every few months or so. Clicking start update will proceed with loading the update onto the Hub. This update for the Hub is different from the update for the app, but in either case the app will give a pop-up menu when it’s time for either update.

A screenshot of the Lego Mindstorms Robot Inventor app displays a pop-up box with a message that a hub operating system update is available.

Figure 2-4

The Robot Inventor app will prompt the user when an update is needed to the Hub’s operating system

Exploring the Hub Screen

Once the Hub is connected to the Robot Inventor app and needed updates are done, the Hub icon again should appear in the upper-right corner of the code screen. Clicking this icon will bring up a diagnostic view of the Hub, as reproduced in Figure 2-5. Information at the top of the screen includes the Hub’s operating system version and the level of the battery’s charge. The purple oval in the upper-right corner will disconnect the Hub from the device running the app. Disconnecting the Hub in this way avoids potential problems with data transfers that could occur if the USB cable was pulled out or Bluetooth abruptly shut off.

Two tabs near the top of the screen are noteworthy: Hardware and Programs. The Hardware tab includes a picture of the Hub, as well as any sensors or motors connected to it and any measurements coming from them. In the example in Figure 2-5, a motor is connected to port A and a Distance Sensor connected to port B. In addition to any external components connected to the Hub, the Hardware tab also displays readings from the built-in Motion Sensor, which indicates the tilt angle, orientation, gyro rate, and acceleration of the Hub. Chapter 7 explores this Motion Sensor in detail, but a quick experiment can be done now by tilting the Hub and watching the yaw, pitch, and roll angle values change.

A screenshot of the Lego Mindstorms Robot Inventor app displays the Hub screen. Two tabs of hardware and program are presented at the middle top. The information at the top left includes the battery level and version of O S.

Figure 2-5

The Hub screen

The Programs tab lets the user view and manage the files stored on the Hub. It shows the 20 storage slots available for programs, as well as the name, size, date of creation, and date of last modification of all programs. Programs can also be deleted from this screen, which may occasionally be desired to clear memory space as new programs are developed.

The last important item on the Hub screen is the three-dot icon at the top-right edge. Clicking this feature will bring up a submenu that allows renaming the Hub, resetting the Hub, and updating connected motors. If using more than one Hub, for instance, in working with a school group or team, different names for the Hub can avoid confusion. “Reset hub” is a quick way to delete all the programs on the Hub, so care must be taken to be sure such action is actually desired. “Update motors” starts a set of instructions that checks the motors’ operation and calibration, notably related to their reference zero home position (a feature described in Chapter 6). If motors are used often, they can develop problems, which can likely be fixed with this update feature.

Now that a tour of the Hub screen is complete, it’s time to develop a program. Clicking the X in the upper-right corner of the Hub screen should return the user to the code screen, such as in Figure 2-2.

The Program Design Process

The code screen, shown in Figure 2-2, is where a program is entered. But in implementing a program, entering the code is the last of three parts. The first two parts are algorithm development and flowcharting, which are written out separately from the code screen, such as in a word processing app or even on paper. The reason not to just jump right into coding is that the whole picture of a computer program has to be understood. It’ll actually save time and effort to write out the big picture first, in words, of the steps involved in the program. These steps are called an algorithm. Then an intermediate component of flowcharting will help translate algorithm steps into code. In the professional world of computer programming, more time is spent debugging and fixing computer code than in writing code. But by taking the time up front to design a computer program with a logical process from an algorithm to a flowchart to code, time and trouble can be saved in the long run. The following sections walk through the process of each of the three parts of the algorithm, flowchart, and code. Then, in the rest of the book, the three parts of the algorithm, flowchart, and code will be used in building projects. As a first example of the program design process, the following exercise has the Hub to spell out a name, beep the speaker, and light up the center button with a specific color.

Writing the Algorithm

An algorithm is a set of step-by-step instructions to solve a problem. To start creating an algorithm, the problem or goal should be understood and written out. For example, a goal to achieve could be the following:
  • Display my name, emit a beep from the Hub’s speaker, and light up my favorite color on the Hub’s center button. Keep my favorite color lit up for ten seconds.

Next, the sequence of steps needed to achieve this goal is written out:
  1. 1.

    Start the program.

     
  2. 2.

    Display the text “Grady” on the Hub’s front panel.

     
  3. 3.

    Beep the Hub’s speaker.

     
  4. 4.

    Set the center button color to blue.

     
  5. 5.

    Wait for ten seconds.

     
  6. 6.

    Stop the program.

     

Of course, the reader can change the code to their own name and favorite color.

Drawing the Flowchart

A flowchart is a graphical representation of an algorithm and serves as an intermediate component in implementing the final product of code. The reason to use a flowchart is that it shows how the algorithm flows and how algorithm steps may be interrelated. This flow and interaction of steps matches how to represent instructions in computer languages. Flowcharts use shapes to represent different types of algorithm functions, such as in Table 2-1. These functions include starting and stopping a program, manipulating data, asking for input, providing output, making decisions, and repeating steps with a loop. A flowchart can be sketched on paper for a quick solution or by using the shapes built into most word processors. There are also many apps that are meant for quickly drawing flowcharts.
Table 2-1

Flowchart Shapes and Functions

Shape

Name

Description

An illustration displays a downward arrow used to represent the direction of algorithm steps.

Flow direction

Direction of algorithm steps

A diagram of the round rectangle. It represents the terminal box used at the beginning and end of an algorithm.

Terminal

Beginning or end of an algorithm (usually the first and last steps of an algorithm)

A diagram of the rectangle box. It represents the process box which used to change the value, form, or location of data.

Process

Instruction to change the value, form, or location of data

A diagram of the parallelogram. It represents the input and output box which used for sending data into or out of the algorithm.

Input/output

Sending of data into or out of the algorithm

A diagram of a rhombus. It represents the decision box which used to offer choices in the path of the algorithm

Decision

Question to offer choices in the path of the algorithm

A diagram of the hexagon. It represents the looping concept used to repeat a set of steps in the algorithms.

Looping

Repetition of a set of steps

An image displays a delay box of a D-shape that is used to pause the algorithm.

Delay

Pause in the algorithm for a specified duration of time

A diagram of a circle. It represents a connector used to join the flow paths in the algorithm.

Connector

Joining of flow paths coming from different directions

The flowchart is a sequence of these shapes joined by arrows. As an example, Figure 2-6 shows a flowchart to match the name and color algorithm laid out in the previous section.

A flowchart presents an algorithm to match the name and color. It involves six steps, start, display name, beep speaker, set button, delay 10 S, and stop.

Figure 2-6

Flowchart for the name and color algorithm

Writing the Program

Now that a flowchart is written, it’s easy to see the commands needed to enter into the code. The Hub can be programmed with two different computer languages in the Robot Inventor app: Word Blocks or Python. Word Blocks is the default language that comes up when the Robot Inventor app is opened to the code screen, such as in Figure 2-2. Commands are entered in Word Blocks by dragging them from the left side of the screen into the center, linking blocks from top to bottom. To program in Python, there’s an extra step from the code screen to open a new screen for entering commands, described in a section later. Python is entered by typing lines of code. Deciding on which language to use depends on several factors. If using a smartphone or tablet computer without a keyboard, then Word Blocks is probably a better choice. Using Python requires a lot of typing, which is rather tedious without a keyboard. Word Blocks is easier for a beginner to use and has more built-in commands in the Robot Inventor app. Python is oriented toward more experienced users. The benefit of Python is that it more directly interacts with the Hub, so it can be used for more advanced inventions. Python is widely used outside MINDSTORMS, such as for programming microcontrollers, sophisticated computer programs, and scientific applications. So MINDSTORMS or SPIKE Prime can be a good introduction to building up skill with Python.

In the following sections, and throughout this book, code will be presented in both Word Blocks and Python. This way, the reader can choose whichever computer language is preferred or whichever language is better suited to the type of smart device or computer.

Coding in Word Blocks

Word Blocks is the computer language that appears by default in the code screen, such as in Figure 2-2. Programs are built by clicking a command from the left side of the screen and dragging it to the center part of the screen to link below an existing Word Block. There are many Word Blocks to choose from. They’re arranged in pallets of various colors on the left side of the screen, as shown in Figure 2-7, to group the blocks into families that, for example, work with particular motors or sensors. At the bottom of this column of colored circles, there’s an icon that looks like an outline of two stacked Word Blocks, which will access Word Block features used to perform advanced functions.

A screenshot of the Lego Mindstorms Robot Inventor app displays the word block. Nine icons for motor, movement, light, sound, event, control, sensor, operators, and variables are present vertically at the left of the code screen.

Figure 2-7

Families of Word Blocks are organized by color

The code screen has the first block preloaded of when program starts, which starts the program and represents step 1 of any algorithm and the first step in a flowchart. Figure 2-8 shows the insertion of the second command of the flowchart in Figure 2-6 by selecting write from the left side of the screen and dragging it underneath when program starts. The text to get written is entered by clicking the text oval within write and typing in the desired text.

A screenshot displays the code screen of the Lego Mindstorms Robot Inventor app. It presents the insertion of the second command by selecting the write.

Figure 2-8

Programs are built in Word Blocks by dragging commands to the center of the screen

The next steps of the name and color code are added by dragging in a block for each step in the flowchart. Figure 2-9 shows the finished code with all the Word Blocks to be used, but the step-by-step addition of each block is described following Figure 2-9. The Word Blocks code is remarkably similar to the flowchart in Figure 2-6, which shows the utility of a flowchart in implementing code.

A screenshot displays the code screen of the Lego Mindstorms Robot Inventor app. It presents the addition of name and color code by dragging in a block for each step in the flowchart.

Figure 2-9

Word Blocks code for the name and color algorithm

  • Step 3: The play beep block makes a sound on the Hub’s speaker. Inside the block are ovals to click to change the values of parameters. In this case, the parameter is the musical note of the beep and how long it should play. The problem statement (described in a previous section) didn’t specify what the note should be or for how long to play it, so in situations like this the programmer can decide such details. For example, the default setting of 60 can be used for the musical note. The second parameter to input on is the duration of the sound, with 0.2 a good starting point.

Programming Musical Notes
Robot Inventor and SPIKE Prime represent musical notes using MIDI notation. The Musical Instrument Digital Interface (MIDI) is a way for computers to describe music by assigning notes a number from 0 to 127. For example, MIDI note 60 corresponds to middle C on a piano, and 61 corresponds to C#.
  • Step 4: The set Center Button light block controls the light in the center of the Hub. The parameter setting on this block is a drop-down menu of various colors. Blue is selected in this example, but the reader can select their favorite.

  • Step 5: The wait block pauses the program to give a little time to admire the color on the center button. The flowchart and algorithm call this step “delay,” since this is the standard term used when making flowcharts, but in Word Blocks code, it’s called wait. The two terms mean the same thing. The problem statement specified a ten-second delay, so 10 is set for the delay parameter.

  • Step 6: The stop block closes out the program and lets the Hub know that it’s done for now. A program would still work without this block, but it’s a good practice to gracefully end a program. This way, the computer knows it can go back to a state of being ready for another program to be run. Such a stop block is used in all the programs of this book. From the drop-down menu, a selection and exit program tells the Hub that the program is really done. There are other options that come up in more advanced projects, but and exit program is a good choice for most projects.

Writing Comments

Another feature of writing code is to add comments to the code. These comments are not commands, but an explanation to help remember what the program or command line does. Comments are helpful when looking back at an old program that might be used again. The comments will quickly explain what the program does and how it works, so time can be saved when reusing the code. Also, several people may be working on a project, and having all the comments in place will help other people figure out what another person might have done. Word Blocks includes a way to add comments in the code area, implemented as light yellow blocks to the right of the Word Block commands.

Figure 2-10 shows a comment being added as the code is developed, which can be initiated by right-clicking anywhere in the area where the code is being built and selecting Add Comment from the pop-up menu. The comment box will then appear on the screen, looking like a sticky note, where text can be entered. The comment box can be as big as needed, so there’s lots of room for detail. For example, in commenting on step 1 of the code in Figure 2-10, there’s an explanation of the code’s file name, programmer’s name, and date. Then the problem statement is written to explain what the program does. When the comment is complete, clicking the triangle in the upper left-hand corner of the comment box will collapse the block to a convenient size on the screen. The complete entry in the comment box can later be read by clicking this triangle. A comment for every command in the code can be useful, as has been done in Figure 2-9 with a comment off to the right of each Word Block step. Each comment includes the step number of the algorithm to see how the code relates to the algorithm steps.

A screenshot displays the code screen of the Lego Mindstorms Robot Inventor app. It presents a comment box to start the program.

Figure 2-10

Comment box for step 1

Once comments are all added, the complete program needs to be saved on the host computer or smart device from the toolbar at the top of the screen.

Coding in Python

Python is a text-based programming language that requires typing in commands with a very specific syntax. While the following projects are good examples, a complete introduction to Python is outside the scope of this book. The full details on Python can be found at python.org.

To start programming in Python, a new program is initiated on the code screen, either by clicking the + symbol at the top of the screen or by selecting FileNew Project in the toolbar. A pop-up menu should appear, as in Figure 2-11. Clicking Python and then Create will bring up the screen in Figure 2-12 for entering code.

A screenshot of the Lego Mindstorms Robot Inventor app. It presents a new project pop-up menu with two options, word and Python, and a create button at the bottom.

Figure 2-11

The New Project menu presents options for Word Blocks or Python

A screenshot of the Lego Mindstorms Robot Inventor app. It presents several lines of Python coding. It includes 4 lines for import code, 1 line for creating your objects, and 1 line for writing your program.

Figure 2-12

The Python coding screen opens up with several lines of code automatically entered

The Complete Code

The complete Python program for the name and color algorithm is shown as follows, which will be explained in detail in the following sections. The first four lines of code automatically appear on the code screen and need not be typed in.
from mindstorms import MSHub, Motor, ...
from mindstorms.control import wait_for_seconds, ...
from mindstorms.operator import greater_than, ...
import math
import hub
from sys import exit
#Create your objects here.
myhub = MSHub()
# Program "name_color". Display name, beep speaker, light up center button
myhub.light_matrix.write('Grady')
myhub.speaker.beep(60,0.2)
myhub.status_light.on('blue')
wait_for_seconds(10)
exit()

Comments in Python are written by preceding them with a # sign. All text after # is part of the comment, which the code screen automatically changes to purple text to make it easier to see. Code gets saved and given a file name by clicking FileSave As in the toolbar at the top of the screen.

Importing Code

The first four lines of code are included whenever the Python coding screen is opened and should be kept in place as they are. These lines feature from and import statements, which are used to include external code that allows working with all the components of Robot Inventor or SPIKE Prime, such as motors, sensors, and the Hub:
1from mindstorms import MSHub, Motor, ...
from mindstorms.control import wait_for_seconds, ...
from mindstorms.operator import greater_than, ...
2import math
3import hub
4from sys import exit

The from statement references various packages, called mindstorms, mindstorms.control, and mindstorms.operator. A package is a folder of files that contains extra features for using Python, called modules. These modules are files containing statements and definitions that help perform specific tasks. Within the module’s code, these statements and definitions may take up many lines, but can be referenced in a program with just a single line of code, making the program more efficient. Modules to include are indicated with the import statement. For example, the first line in the code calls many modules, including MSHub, Motor, and others 1 from the mindstorms package.

Some modules are used often and so aren’t contained in a specific package. These more common modules, like math, can be called with just import 2.

Two more lines are needed to add to the list of modules. The hub module provides a way to interact with various features on the Hub 3, and the exit module, stored in the sys package, allows a smooth end to a program 4. These two extra import statements are added to all the programs in this book.

Creating an Object and Assigning It to a Variable

The following line shows the creation of an object:
myhub = MSHub()

An object, in programming terminology, is a collection of data and functions that act on the data. Here, the code MSHub() creates an object containing the data and functions associated with the internal workings of the Hub. MSHub() comes from a module within the mindstorms package that was imported in the very first line of code.

Also, this object has been assigned to the variable myhub. A variable is a name for a piece of data. An object can be given a variable name, so long as it doesn’t conflict with other names in a program. Now the data and functions of the Hub can be accessed by referring to the variable myhub. In later chapters, objects will be used to represent the data for motors or sensors.

The code written so far forms the beginning of all Python programs in this book and so will be seen again many times.

Displaying Text on the Hub Screen

Now that the basics of the program are out of the way, action can be taken to implement steps 2 through 5 of the name and color algorithm. Step 2 is to display a name on the LED matrix of the Hub’s front panel. Due to the power of Python modules, this can be done with one line of code:
myhub.light_matrix.write('Grady')

This code uses a function called light_matrix.write(). A function in Python is code that performs a specific task. In this case, the function spells out text on the front panel. Functions are saved in modules; in this case, the function used here is in the MSHub module. When the myhub object was created, access was gained to its functions, one of which is light_matrix.write(). To use the function, a command is written of the object’s name (myhub in this case), then a period, then the function’s name (light_matrix.write() in this case).

Certain functions, like this one, accept parameters or optional values specified within parentheses. In this case, the parameter is whatever text is to be spelled out. This text is in quotation marks, which tells the program that it’s working with a data type called a string. A string is essentially text, which can be thought of as a sequence of characters that can be printed, such as letters, numbers, punctuation marks, or whitespace (the space between words).

Beeping the Hub Speaker

Step 3 of the algorithm is to beep the Hub’s speaker. This can be done using a function, too:
myhub.speaker.beep(60,0.2)

Just as in the previous step, this function is called by referencing the myhub object, followed by the function’s name, speaker.beep(). The note and duration of the beep are specified inside the parentheses. In this case, a note has been assigned a value of 60 for a duration of 0.2 seconds. (Notes are defined by MIDI notation, as described earlier.) The numbers passed into the function don’t have quotation marks around them, because they represent numerical values, not text like the string used in step 2.

Setting the Center Button Light

Next, another function sets the center button light on the Hub to a specified color:
myhub.status_light.on('blue')

The name of the function for controlling the center light is status_light_on(). The color choice is written in quotation marks inside the parentheses. Possible choices include azure, blue, cyan, green, orange, pink, red, violet, yellow, and white.

Waiting Ten Seconds

The next task is to delay the program for a time period of ten seconds to give time to admire the color on the center button. This delay is accomplished with a function called wait_for_seconds():
wait_for_seconds(10)

This function looks a little different than earlier functions, with no reference to an object or variable. In other words, there’s no variable name or period before this function name, since this particular function is not grouped within an object. The number of seconds to delay the program gets inserted inside the parentheses of the function.

Ending the Program

The algorithm ends with the exit() function:
exit()

This function lets the Hub know that the program is over. Now the Hub can go into a standby mode and get ready for whatever might be coming next. The program will still work without this function by ending the program when it gets to the last line of code. However, it’s a good practice to formally stop and exit a program.

Downloading and Running Code

Once code is finished, it’s time to load it into the Hub using the three icons in the lower-right corner of the code screen as in Figure 2-13. This procedure is the same regardless of whether the code was written in Word Blocks or Python.

A screenshot of the code screen of the Lego Mindstorms Robot Inventor app. It presents three icons to download and run the program.

Figure 2-13

Icons for loading and running programs are at the lower-right section of the code screen

The first icon includes a number that represents the slot on the Hub in which to save the program. There are 20 possible slots, numbered from 0 to 19, allowing many programs to be stored in the Hub’s memory. Upon clicking the program number icon, a pop-up menu will appear for selecting the slot number. (Slot 0 is selected in Figure 2-13.) This same pop-up window allows download of the code onto the Hub without running the program. The program then gets run from the front panel of the Hub.

If it’s preferred to both download and run the program in one step, the play icon can be found at the far right of the group of icons. This option is more convenient, but the two-step process can be useful if it’s desired to closely watch results as the code runs. For example, if running a program for the first time that involves complex motor action, it might be desired to check for a coding mistake that causes a motor to run wild. In this case, it would be preferable to download the program from the code screen, take a moment to shift attention to the Hub, and run the program from its front panel. The remaining icon to consider is the stop icon, which halts execution of the program. Such a stop may be warranted if a mistake is found or if something about the code takes a long time to run.

After the program is saved into the Hub’s memory, the Hub can be disconnected from the app. Pressing the center button of the Hub will run the program. If needed, another press of the center button will abort the program. If multiple programs are stored on the Hub, the left and right buttons will scroll through all the programs stored on the Hub.

Debugging and Troubleshooting

It’s quite common for there to be a mistake in code when it’s run for the first time. For example, for the name and color code in Word Blocks, the name may have been spelled wrong or the wrong color was selected for display on the center button light. When this sort of thing happens, the programmer can go back to the code, make corrections, and try the program again.

Python is easier to make a mistake with than Word Blocks. A command may have been typed in with the wrong spelling or the () forgotten after many commands. Another common mistake is in trying to use a function that wasn’t properly called. The Python code screen includes an area where problems will be identified and described to give a suggestion on how to fix the problem. As shown in Figure 2-14, this error message area is near the bottom of the screen that can be opened by clicking the >- icon. In the example in Figure 2-14, the code for the name and color algorithm was changed to intentionally add in the mistake in line 12 of misspelling write with writ. When this code is run, the program will fail because of the mistake. The program halts when it gets to this mistake and gives the error message seen in Figure 2-14. The error message indicates that there’s a mistake in spelling write. Aside from the error message in the app’s code screen, the Hub will also indicate that there’s a problem by blinking red on the center button light.

A screenshot of the code screen of the Lego Mindstorms Robot Inventor app. It presents an error message at the bottom of the screen.

Figure 2-14

Python debugging error messages are in a monitor at the bottom of the code screen

Project: The Dance Floor

Now having experience with the Robot Inventor app and seeing how computer programs are designed, programming techniques of a little more complexity can be explored with the Dance Floor. The Dance Floor creates a miniature dance floor for LEGO minifigures, as shown in Figure 2-15. The Dance Floor can also be used as a metronome for practicing with a musical instrument. Whereas the name and color program earlier in this chapter was a straightforward series of steps, the Dance Floor incorporates programming techniques for the use of variables, decision making, and loops. Variables are values that can change, in this case to count from 1 to 5. Decision making in a program provides multiple paths of operation, in this case presenting two paths that depend on whether a button on the Hub is pressed. Loops in a program repeat some actions, in this case to cycle through colors on the center button, draw a diagonal line of lights on the LED matrix, and click a musical beat.

An illustration presents a miniature dance floor for LEGO. The light matrix is arranged diagonally on the floor and a robotic dancer is present on the dance floor.

Figure 2-15

The front panel of the Hub can be used as a dance floor for minifigures

To start designing our program, the problem statement defines what the Dance Floor should accomplish:
  • Create a musical beat that plays on the Hub’s speaker at five beats per second. On each beat, change the color of the center button and light up pixels on the LED matrix. Start by lighting the pixel in the upper-left corner, then light up the pixel diagonally adjacent to it. When all the pixels in the diagonal have been lit, begin again in the upper-left pixel. Include the ability to stop the beat by pressing either the left or right button.

The following algorithm can achieve the task laid out in this problem statement. It uses a variable called count to represent values of 1 through 5, each of which corresponds to a new color on the front button and a different pixel to light up on the LED matrix. A loop in step 3 repeats the sound and light action, which gets halted only if the left or right button is pressed on the Hub’s front panel.
  1. 1.

    Start the program.

     
  2. 2.

    Define the variable count = 1.

     
  3. 3.

    Create a loop that repeats unless the left or right button is pressed. If either button is pressed, skip to step 12.

     
  4. 4.

    Set the center button to the color represented by count.

     
  5. 5.

    Beep the Hub’s speaker.

     
  6. 6.

    Light up the LED matrix pixel at coordinates count, count.

     
  7. 7.

    Delay for 0.2 seconds. This delay sets the timing between beats.

     
  8. 8.

    Increase the value of count by 1.

     
  9. 9.

    Test to determine if count is greater than 5. If yes, proceed to step 10. If no, return to step 3.

     
  10. 10.

    Reset the value of count to 1.

     
  11. 11.

    Turn off all pixels on the LED matrix.

     
  12. 12.

    Stop the program.

     
The preceding algorithm includes steps that repeat and a decision point that can be a little difficult to follow when expressed as words. The power of a flowchart as the next component in developing code is to provide a visualization of loops and decisions, where the flow of the program can go in different directions. With the flow visualized in a flowchart, the next step of coding will become easier to write. The flowchart for the Dance Floor is shown in Figure 2-16. Step 3 starts a loop that executes through to step 11, unless a button is pressed on the Hub. Pressing a button exits the loop and then proceeds to stop the program. Loops are easy to see in a flowchart by the long arrows that direct flow back to an earlier step. The decision in the algorithm, step 9, is drawn in a flowchart with a diamond shape. Arrows flow from the decision to represent the possible outcomes from the decision, in this case deciding if the count variable has reached a value of more than 5.

A flowchart presents the eleven steps for the Dance Floor algorithm. Step 3 starts a loop that is directly executed by step 11.

Figure 2-16

Flowchart for the Dance Floor algorithm

The Dance Floor algorithm can be coded in either Word Blocks or Python, with the code for each language given in the following sections. Handling variables, loops, and decisions are built in to either programming language, but with some minor differences. For example, the rows and columns of the LED matrix are represented by a number of 1–5 in Word Blocks, but 0–4 in Python. So if moving back and forth between the two languages, a little adjustment may be needed to the way things are done. But in either programming language, the basic structure is the same as developed in the flowchart step.

The Word Blocks Code

Figure 2-17 shows the Dance Floor program written in Word Blocks. Each step in the flowchart corresponds to a Word Block, as labeled with the comments. Particular Word Blocks to note are as follows.

A screenshot presents the Dance Floor program written in Word Blocks. Each Word Bock labels with a comment. It includes 11 step process, other options of start programs, exit programs, play beep, set pixel at, and turn off pixels.

Figure 2-17

Word Blocks code for the Dance Floor algorithm

  • Step 2: The set count block defines a variable and sets its initial value. Programs typically give variables descriptive names that make it clear what the variable represents. In this case, the value of the count variable will range from 1 to 5. Variables are created in Word Blocks by clicking the orange circle menu labeled Variables. A pop-up menu should then appear, as shown in Figure 2-18, where the name of the new variable is entered. After clicking OK, any variables created will appear as choices in Word Blocks under the Variables menu. One such place to find a variable loaded into a block in the Variables menu is the set Word Block, which can be left here at drop-down menu selection for count. The initial assignment of the value for the variable inside the parameter oval should be given a value of 1.

A screenshot of the code screen of the Lego Mindstorms Robot Inventor app. It presents the pop-up menu for the new variables. The text box of the new variables reads count. Ok and cancel buttons are at the bottom.

Figure 2-18

The new variable menu

  • Step 3: The repeat until block sets up a loop that repeats indefinitely until a certain condition is met. In this case, the condition is that a button is pressed on the Hub. In other words, pressing a button will stop the loop. Loops in Word Blocks are two horizontal yellow bars with a space between them, into which the blocks to be repeated are inserted. The hexagon-shaped parameter entry area indicates the condition by which the loop will repeat, in this case an or Word Block, which can be found under the Operators group of blocks. The or block contains two hexagon parameter entry areas, which should be filled with is Left Button pressed and is Right Button pressed. Now, if either of these conditions is met, the loop will stop.

  • Step 4: The set Center Button light to block, which goes inside the loop, displays a new color on the Hub’s light. The color is represented here by the count variable; as the count progresses, the center button light will change colors. Color is usually selected from a drop-down menu in this block, but in this case a number is used as represented by the count variable. The count variable can be found in the Variables menu on the left side of the screen.

  • Step 5: The play beep block makes a sound on the Hub’s speaker to create a musical beat. A MIDI note of 72 produces a pleasant sound and is a good starting point for experimentation. Since the note is serving as a musical beat, its duration should be short, like 0.01.

  • Step 6: The set pixel at block lights up a pixel on the Hub’s LED matrix. A particular pixel is specified by its row and column numbers. Since the problem statement indicated that a diagonal line be lit up, the following row and column pairs accomplish this: 1,1; 2,2; 3,3; 4,4; and 5,5. These numbers for the rows and columns are the same as the value of the count variable, so this variable can be used to indicate which pixel to light up. As the count progresses when the loop repeats, the next pixel in the diagonal line will be lit. The variable count can be found at the left side of the screen, to be dragged into the pixel parameter numbers in set pixel at. The brightness setting at the default value of 100% gives a bright display.

  • Step 7: The wait block delays the action before the loop starts over again. This time delay sets the beep’s tempo, which the problem statement specified to be five beats per second. This tempo corresponds to a 0.2-second delay between beats, so 0.2 is entered in the parameter oval.

  • Step 8: The change count by block increases the value of the count variable by 1. As a result, when the loop restarts, this variable will have increased. With a new value for count, the color will change on the center button, and the next pixel will light up.

  • Step 9: The if block presents a condition—it checks whether the count variable has exceeded a value of 5. If so, any Word Blocks contained inside the if block will run, resetting the count variable to a value of 1. If count is 5 or less, no change is made to the count variable. This greater-than conditional test goes into the hexagon-shaped condition parameter, with a > block from the Operators menu.

  • Step 10: The set count to block goes inside the if block to reset the count variable since it has exceeded a value of 5.

  • Step 11: The turn off pixels block blanks out the LED matrix. This step resets the diagonal of pixels lit up on the matrix so it can begin again when the loop repeats.

A useful feature of the Robot Inventor app can be seen by running the Dance Floor program with the host computer or smart device still connected to the Hub. Clicking the card icon on the right side of the screen will bring up a window with two tabs. Clicking the Monitor tab, as in Figure 2-19, will show the current values of any variables involved in the code that is running. For the Dance Floor program, the value of the count variable should update as the loop runs, incrementing from 1 to 5 then repeating. This monitor can be helpful in debugging code if a problem arises, because it allows a verification that variables are behaving as expected.

The loop used here repeats quickly, so the variable also updates quickly in the monitor. If having trouble seeing the variable value with the fast update, the loop can be slowed by changing the wait block in step 7 to have a longer time value than 0.2 seconds.

A screenshot of the code screen of the Lego Mindstorms Robot Inventor app. It presents the current values of any variables In the monitor tab. It includes 11 step process, other options of start programs, exit programs, play beep, set pixel at, and turn off pixels.

Figure 2-19

A monitor in the code screen allows viewing of variable values as the program runs

The Python Code

The following Python code is the completed Dance Floor program:
1from mindstorms import MSHub, Motor, ...
from mindstorms.control import wait_for_seconds, ...
from mindstorms.operator import greater_than, ...
import math
import hub
from sys import exit
# Create your objects here.
2myhub = MSHub()
# Program "dance_floor".  Beep musical beat, change button color, light matrix.
count = 0
while True:
    if myhub.left_button.is_pressed() or myhub.right_button.is_pressed():
        exit()
    hub.led(count)
    myhub.speaker.beep(72,0.01)
    myhub.light_matrix.set_pixel(count,count)
    wait_for_seconds(0.2)
    count = count + 1
    if count > 4:
        count = 0
        myhub.light_matrix.off()

The program begins by importing modules 1 and creating the myhub object 2, as described earlier in the chapter for the name and color program. The following sections describe coding the remaining steps of the algorithm.

Defining a Variable

A variable represents a numerical value that will change as the program runs. Variables are often given names that suggest what data they represent. In this case, the variable will increase in value from 0 to 4 as the program runs, so count is a good representative name for it:
count = 0

The variable is created by assigning a value to it with an equals sign.

Beginning the Loop and Checking for a Button Press

The program next sets up a loop to run until the user presses a button on the Hub’s front panel. There are several kinds of loops in Python. Here, a loop is used that repeats infinitely using a while True: statement:
while True:
    if myhub.left_button.is_pressed() or myhub.right_button.is_pressed():
        exit()

The while statement checks if the condition after it is true, and since the condition is declared to be True, the loop will run indefinitely. In other words, True is always true, so the while loop will run forever, unless something within the loop interrupts it. This statement has a colon (:) at the end of it, which is required.

All lines of code within the loop must be indented at the same distance. Indentation is critical in writing Python code. If the following line of code wasn’t indented, it wouldn’t be part of the group of statements that run inside the loop.

The first statement in the loop checks to see if a button has been pressed on the Hub. This check is implemented with an if statement. If the condition of the if statement is met, any following lines of code that are indented will run. If the condition isn’t met, those indented lines won’t run. Indentation can be seen here again to be critical. In this case, the indented line would exit the program, step 12 of the algorithm.

To specify a condition for the if statement, the functions left_button.is_pressed and right_button.is_pressed are used, which, as their names suggest, check with the Hub to see if a button has been activated. These two functions are combined with an or, which means that activation of either button will serve to satisfy the if condition.

Setting the Center Button Light Color

Still within the loop, the Hub’s center button light gets set with the led() function:
hub.led(count)

As a parameter, the function accepts a number that corresponds to a color. In this case, the number is represented by the count variable, whose values increment from 0 to 4. Therefore, each time the variable increments, a new color will appear on the center button light. This function is in the hub module and shouldn’t be confused with the myhub object.

Beeping the Hub Speaker

Next, the Hub’s speaker gets beeped with the speaker.beep() function:
myhub.speaker.beep(72,0.01)

This function takes two parameters, separated by a comma: a number indicating the note to play and another number indicating the duration of the note. The choice of MIDI note is up to the programmer, since the problem statement didn’t specify the note to use. Since the beep in this program is a musical beat, it should be quick; hence, a short duration of 0.01 seconds is used.

Lighting Up a Pixel

As each beat is played, a new pixel on the Hub’s LED matrix should light up along a diagonal path, beginning from the upper-left corner (0,0) to the lower-right corner (4,4). This function takes two numbers inside the parentheses as x, y coordinates to light up a pixel at column x (starting from the left) and row y (starting from the top). The pixel’s row and column values correspond to the various values of the count variable, so we can use the count variable in a light_matrix.set_pixel() function:
myhub.light_matrix.set_pixel(count,count)

Setting the Tempo with a Delay

Since the problem statement called for a tempo of five beats per second, a delay of 0.2 seconds is called for. This tempo can be implemented with the wait_for_seconds() function:
wait_for_seconds(0.2)

As a result, the color on the center button light and the pixel lit up on the LED matrix will remain for 0.2 seconds before the loop runs again.

Incrementing a Variable

Now that the loop has beeped and updated the lights on the Hub, the count variable should be updated for the next iteration of the loop. A variable can be updated in Python by redefining its value with an equals sign. In this case, 1 is added to the previous value of count:
count = count + 1

Checking the Value of a Count

After the count variable has been updated, a check needs to be made on the new value of count to see if it has exceeded a value of 4. The problem statement for the Dance Floor asks for 5 beats and for 5 pixels on the LED matrix to be lit, and the count variable keeps track of the actions that take place in a cycle of 5. The count starts at 0 (not 1), so the final value of count should be 4. The value of count is tested with an if statement:
    if count > 4:
        count = 0
        myhub.light_matrix.off()

The if statement checks whether a condition is true or not. In this case, the condition is if the variable count is greater than 4. If this condition is true, then the indented lines of code after the : will be executed. These indented lines reset count to 0 and switch off all the pixels on the LED matrix. If the answer to the condition is false, then no action is taken on the value of count.

Summary

This chapter described how to connect the Hub to the Robot Inventor app. This app allows programming the Hub, but also has functions to update the operating system of the Hub. These updates occasionally come from LEGO to improve the performance of the Hub. The app also has features to check the Hub’s battery level and check for correct operation of motors and sensors that are connected to the Hub. To program with the Robot Inventor app, two different programming languages can be used: Word Blocks or Python. Word Blocks is simpler to use than Python and a good starting point for users new to programming. Since it’s graphical, Word Blocks is easy to use from a smartphone or tablet computer that doesn’t have a keyboard. Python allows for more advanced programming techniques and so may appeal to users already experienced with programming. But before writing code, better results and time savings are likely in the long run by first designing the program's algorithm and flowchart. An algorithm is a step-by-step explanation, written out in words, of how a program will solve the problem. The steps of the algorithm are then expressed graphically in a flowchart, which shows how the algorithm flows through its steps. Then code is writen based on the flowchart, usually with one line of code corresponding to one step of the flowchart. Two example programs in this chapter worked through the design process to control the Hub. For each example program, the last component of writing code can be done in either Word Blocks or Python.

Word Blocks includes many blocks dedicated to controlling the Hub and will be seen in later chapters for working with sensors and motors. In Python, functions are used to work with the Hub. Several coding techniques were shown, including using variables to represent values that can change as a program runs, loops to repeat action multiple times, and conditionals to present multiple options a program can take.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset