© 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_7

7. The Motion Sensor

Grady Koch1  
(1)
Yorktown, VA, USA
 

The Robot Inventor comes with several sensors that connect to the Hub, as well as a built-in one: the Motion Sensor, which is found inside the Hub’s enclosure. This chapter will explore the capability of the Motion Sensor for tilt angle, orientation, gyro rate, and acceleration. A feature of the Hub will be described for triggering sound, with control of sound through motion data. The chapter summary project combines sensor data with motor action into a machine that always points up, regardless of the tilt angle.

Tilt Angle: Yaw, Pitch, and Roll

As was touched on briefly in Chapter 1, data can be accessed from the Motion Sensor from the Robot Inventor app. With the Hub connected to the app, going to the Hub Dashboard screen will show three motion measurements at the top of the screen as shown in Figure 7-1. These three measurements are of yaw, pitch, and roll.

A screenshot of the Hub Dashboard. Hardware and programs options are at the top. Below are 4 options with tilt angle selected. The tilt angle of the yaw is 129, and of pitch and roll are 0.

Figure 7-1

Hub Dashboard view of the tilt angle of yaw, pitch, and roll

Yaw, pitch, and roll are angles at which the Hub is tilted with respect to three axes, diagrammed in Figure 7-2. To develop a mental picture of these tilt angles, the Hub can be placed on a table with the front panel facing upward. Spinning the Hub while keeping it flat on the table, as in Figure 7-3a, changes the yaw. Lifting up one end of the Hub along its long axis, as in Figure 7-3b, changes the pitch. Lifting it instead along the short axis, like in Figure 7-3c, changes the roll. Each of the three angles can either be positive or negative; the angles drawn in Figure 7-2 indicate positive rotations. When controlling a robot or vehicle, the signs of these angle measurements can indicate at a glance the direction in which it might be headed.

A 3-D model of a hub with 3 coordinate axes. The x, y, and z axes refer to rotations at pitch, roll, and yaw angles, respectively.

Figure 7-2

The coordinate system for the Hub refers to three axes (x, y, and z) and the rotations about these axes as pitch, roll, and yaw

Three photographs of a hub with different rotations. a. Two LEGO characters push the hub while it is kept on the table. b and c. Two LEGO characters lift one end of the hub along the width and length sections, respectively.

Figure 7-3

Possible rotations include (a) yaw, (b) pitch, and (c) roll

An important feature in tilt angles is to what an angle is based on. In other words, what orientation the Hub is in if the roll, pitch, and yaw are all zero? Roll and pitch have a zero that’s easy to understand in that when the Hub is resting on a table with the control panel facing up, then the roll and pitch are zero. Yaw is a little more complicated in that the desired orientation of zero may depend on the application. For example, zero yaw may be desired to point north so that directions can be correlated with compass heading. Or, if building a robot that travels across a table top, zero yaw may be desired to align with a side of the table.

Because of these requirements, the Robot Inventor allows setting zero yaw. This is done by placing the Hub on a stable surface (such as a table) and pointing the Hub in the direction desired for zero, then going to the Hub’s front panel to power it off by pressing the center button. After powering the Hub back up, without moving it, the Hub’s yaw will now indicate zero. All movement in yaw will now be referenced to this zero. Yaw can also be zeroed in a program with a Word Block or Python function.

Exercise: Programming with Tilt Data

Tilt data from the Motion Sensor allows the Hub to easily be turned into an alarm system. This alarm will set off an alert on the Hub’s speaker if the measured roll or pitch exceeds 5 degrees. This alarm could be placed on or inside some object that needs to be protected from someone walking away with. Or the alarm can be turned into a game to challenge someone to pick up the Hub without tilting it or walk while holding the alarm. In robotics applications, tilt measurements are an important tool for sensing whether a robot is headed in the desired direction, carrying something, driving up or down an incline, spinning around, or falling over. There’s nothing mechanical to build for this alarm, since the Motion Sensor is already built into the Hub.

Measuring Tilt Angles in Word Blocks

Figure 7-4 shows the Word Blocks code for the tilt alarm. A loop in the program continuously checks whether a button has been pressed on the Hub that would end the program. Inside the loop is a conditional that checks the Hub’s roll and pitch angles. Noteworthy blocks are described following Figure 7-4.

A screenshot presents the Word Blocks code. It presents 6 steps between the start and exit as follows. 1. start. 2. repeat. 3. test. 4. beep. 5. shut. 6. stop and exit the program.

Figure 7-4

Word Blocks code for the tilt alarm

  • Step 2: The repeat until block sets up a loop that repeats indefinitely until the condition is met of pressing a button on the Hub. This button press provides a way of exiting the program.

  • Step 3: The if then else block tests the value of the roll and pitch angles measured by the Hub in its if part. If either angle is greater than 5 degrees, the then part of the block is run. If the condition isn’t met, the else part runs instead. These angles could either be positive or negative, which doesn’t matter for this application, so the absolute value operator is used to disregard the positive or negative signs.

  • Step 4: The play beep block makes a sound on the Hub’s speaker to sound an alarm. This block is within the then section of the conditional setup in step 3.

  • Step 5: The stop all sounds block shuts off the speaker, since the alarm condition is no longer present. Being located in the else section of the conditional setup in step 2, the beeping sound is shut off since the measured roll and pitch angles are both less than 5 degrees.

Measuring Tilt Angles in Python

Like the Dance Floor code from Chapter 2, the Python code for the tilt alarm uses a loop and if statement to check for a button press on the Hub to stop the program:
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 "tilt_alarm".  Beep speaker if roll or pitch > 5 deg.
while True:
           if myhub.left_button.is_pressed() or myhub.right_button.is_pressed():
              exit()
        1 roll = myhub.motion_sensor.get_roll_angle()
        2 pitch = myhub.motion_sensor.get_pitch_angle()
        3 if abs(roll) > 5 or abs(pitch) > 5:
              myhub.speaker.beep(60,0.2)
        4 else:
              myhub.speaker.stop()

The functions motion_sensor.get_roll_angle and motion_sensor.get_pitch_angle read in roll and pitch angles from the Hub. These angle measurements are given the variable names roll and pitch so they can be referenced in the next section of the code 1, 2.

Next, a conditional tests whether the roll or pitch value is greater than 5 degrees 3. Because of the or operator, the condition will be met if either one of the angles is greater than 5 degrees. Since only the magnitude of the angles is of interest in this application, the Python built-in abs function is applied to roll and pitch. If the condition is met, a beep is played on the Hub’s speaker with a MIDI note 60 for a duration of 0.2 seconds. The action under else will shut off the Hub’s speaker 4.

Exercise: The Cat Sound Generator

Orientation is a measurement of which side of the Hub is facing upward. For example, an orientation measurement of front means that the front panel is facing up toward the ceiling if the Hub is resting on a table. The Robot Inventor app offers a way to take a quick look at orientation measurement by going to the Hub Dashboard and selecting the Orientation tab. Six possible sides of the Hub could be facing upward: front, back, up, down, left side, and right side.

Orientation is vital information for any robot or vehicle that can roll around, fly, navigate underwater, or find itself in other situations where there can be uncertainty as to which way is up. A quick orientation measurement can be a matter of life or death when things go wrong in a submarine or airplane. In LEGO inventions, orientation data can determine which way a robot or vehicle is facing or if a robot has had a sudden change, like falling over.

An example in working with orientation data can be found with the Cat Sound Generator described as follows, which plays a different cat sound for each possible orientation of the Hub. This exercise will also introduce the capability of playing sound on a computer or smart device as controlled by the Hub. The following problem statement summarizes the functionality of the Cat Sound Generator:
  • Have your computer’s or smart device’s speaker play a different cat sound for each of the six possible orientations of the Hub. Use the six different cat sounds in the Robot Inventor app’s library of sounds. Include a shutoff capability by pressing either the left or right button on the Hub.

This problem statement can be solved with the following algorithm:
  1. 1.

    Start the program.

     
  2. 2.

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

     
  3. 3.

    Test to determine whether the Hub’s front is upward. If yes, go to step 4. If no, skip to step 5.

     
  4. 4.

    Play the sound Cat Meow 1.

     
  5. 5.

    Test to determine whether the Hub’s back is upward. If yes, go to step 6. If no, skip to step 7.

     
  6. 6.

    Play the sound Cat Meow 2.

     
  7. 7.

    Test to determine whether the Hub’s top is upward. If yes, go to step 8. If no, skip to step 9.

     
  8. 8.

    Play the sound Cat Meow 3.

     
  9. 9.

    Test to determine whether the Hub’s bottom is upward. If yes, go to step 10. If no, skip to step 11.

     
  10. 10.

    Play the sound Cat Hiss.

     
  11. 11.

    Test to determine whether the Hub’s left side is upward. If yes, go to step 12. If no, skip to step 13.

     
  12. 12.

    Play the sound Cat Purring.

     
  13. 13.

    Test to determine whether the Hub’s right side is upward. If yes, go to step 14. If no, return to step 2.

     
  14. 14.

    Play the sound Cat Whining.

     
  15. 15.

    Stop the program.

     
Figure 7-5 shows a flowchart implementation of the algorithm. A loop is used to continuously run a series of tests to determine what side of the Hub is facing upward.

A flowchart with 6 conditions to play different cat sounds for different situations. The cat sounds generated are cat meows 1, 2, and 3, cat hiss, cat purring, and cat whining. There are 15 different steps between the start and end comprising a set of loops.

Figure 7-5

Flowchart of the Cat Sound Generator algorithm

The Word Blocks Code

Figure 7-6 shows the Word Blocks code for the Cat Sound Generator. In a similar technique to the tilt alarm, a loop continuously checks for a button to be pressed on the Hub that would end the program. Inside the loop is a series of conditionals to determine which side of the Hub is facing upward and play a particular cat sound. Key blocks in the program are described in detail following the figure.

A screenshot presents the Word Blocks code. It presents 15 steps between the start and exit of the program to play 6 different cat sounds. Steps 4, 6, 8, 10, 12, and 14 play the sound of cat mew 1, 2, 3, cat hiss, cat purring, and cat whining, respectively.

Figure 7-6

Word Blocks code for the Cat Sound Generator

  • Step 3: The if then block sets up a condition to test if the front side of the Hub is facing upward. If yes, the blocks within the if then block will run. This if then block is repeated again in steps 5, 7, 9, 11, and 13 to test for different orientations.

  • Step 4: The play sound block prompts the computer’s speaker or smart device to play the selected sound. In order for the sound to work, the Hub has to be connected to the Robot Inventor app. Cat Meow 1 is the default sound for the play sound block, and this default can be kept.

  • Step 6: The play sound block triggers playing Cat Meow 2. To select this sound option, there’s a pull-down menu in the oval area of the play sound block. From this pull-down menu an option for Add Sound will appear. Clicking Add Sound will bring up the Library tab, as shown in Figure 7-7, where many sounds can be found for selection. While this step involves selecting Cat Meow 2, the various cat sounds for the rest of the program can also be found in this library.

A screenshot of the sound library presents 18 different sounds. Out of these, 8 are cat sounds. The top panel has tabs for editor and record.

Figure 7-7

Several cat sounds are stored in the Sound Library

The Python Code

As in the code for the tilt alarm, the Python code for the Cat Sound Generator uses a loop and if statement to check for a button press on the Hub that would stop the program:
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()
1 app = App()
# Program "cat_sound".  Play cat sounds in App for different orientations.
while True:
    if myhub.left_button.is_pressed() or myhub.right_button.is_pressed():
        exit()
  2orientation = myhub.motion_sensor.get_orientation()
    if orientation == 'front':
        app.play_sound('Cat Meow 1')
  3 elif orientation == 'back':
        app.play_sound('Cat Meow 2')
    elif orientation == 'up':
        app.play_sound('Cat Meow 3')
    elif orientation == 'down':
        app.play_sound('Cat Hiss')
    elif orientation == 'leftside':
        app.play_sound('Cat Purring')
    elif orientation == 'rightside':
        app.play_sound('Cat Whining')

To play sounds within the Robot Inventor app, a module is assigned as an object, called app 1. Rather than using an if else conditional, which tests for a condition and gives an alternate action if the condition is false, this program uses an if elif conditional. The elif can be thought of as an abbreviation for “else if.” Essentially, it allows presentation of additional conditions if the initial condition is not met. In this case, each conditional statement asks about the value of a variable, orientation, that measures the orientation of the Hub 2. First, the if statement tests whether the value of orientation is ‘front’, and if it is, the first cat sound is played. If this first condition is not met, an elif statement then presents another test: whether the value of orientation is ‘back’ 3. All of the possible values for orientation are tested in this way.

Using elif is more efficient than using a series of conditionals (like in the Word Blocks version of the algorithm), because once a condition has been found to be true, the remaining options aren’t tested. Word Blocks doesn’t have an equivalent of elif. Testing for values is done with two equals signs (==) in Python. If a single equals sign were instead used, Python would assume this to be assigning a variable with a new value.

To play sounds in the Robot Inventor app, which will be played through the speakers of the computer or smart device that hosts the app, the Mindstorms function play_sound() is used. The name of the particular sound to play goes inside the parentheses as a string, such as ‘Cat Meow 1’.

Other Motion Sensor Measurements: Gyro Rate and Acceleration

Besides tilt angle and orientation, the Motion Sensor can also measure gyro rate and acceleration. Neither of these measurement functions is used much, but they’re interesting to know about and study in the Robot Inventor app. As shown in Figure 7-8, gyro rate and acceleration can be selected in tabs in the Hub Dashboard screen. Both gyro rate and acceleration refer to the x, y, and z axes of the Hub, as diagrammed in Figure 7-2. In addition to seeing measurements in the Robot Inventor app, Word Blocks can pull in gyro rate and acceleration with blocks found in the ExtensionsMore Sensors menu.

A screenshot of the Robot Inventor app. Hardware and programs options are at the top. Below are the tabs for tilt angle, orientation, gyro rate, and acceleration. Acceleration is selected. The values of x, y, and z denote 8, 9, and 1006 respectively.

Figure 7-8

Gyro rate and acceleration are two additional measurements that can be viewed in the Robot Inventor app

Gyro rate is the speed at which the Hub is spinning in degrees per second, with measurements showing the rotation about each of the three x, y, and z axes. With the Hub resting on a table, the gyro rates should all be zero, since there is no motion. But picking up the Hub and rotating it, though, will make the gyro rates change. The gyro rates are measured in degrees per second. An interesting challenge is to see how high a gyro rate can be achieved by rotating the Hub by hand.

Acceleration is a measurement of how fast speed is changing, which, like for gyro rate, is measured with respect to three axes. The units of acceleration shown by the Motion Sensor are in milli-g per second. g is an abbreviation for the acceleration due to gravity. 1 g of acceleration is 9.8 meters-per-second-per-second, which can be a lot of words to say, so hence it’s often abbreviated to g. The Hub’s Motion Sensor is quite sensitive to acceleration, measuring it in units of 1/1000 of a g, often abbreviated as mg (for milli-g). When the Hub is resting on a table with the front panel facing up, it should show that the x and y accelerations are near 0 mg, but the z axis acceleration is about 1000 mg. 1000 mg is equivalent to 1 g, so the Hub is being accelerated by 1 g in the z direction. But the Hub isn’t moving, so why is the acceleration 1 g? This is because the Hub would be moving with an acceleration of 1 g if the table weren’t blocking the way. In other words, gravity is pulling down on the Hub, but the table is pushing upward on the Hub. The accelerations due to gravity and the table are canceling each other out, so the Hub is not moving. Setting the Hub onto its left side/right side or top/bottom will make the 1 g of acceleration move to another axis.

Project: The Up Pointer

The exercises built so far in this chapter have involved only the Hub, since the Motion Sensor is embedded in the Hub. But, of course, the Motion Sensor can be combined with external devices that plug into the Hub. As an example, Figure 7-9 shows a project called the Up Pointer, which combines the Motion Sensor with a motor. The Up Pointer always keeps a liftarm pointed toward the ceiling, no matter how the Hub is oriented in roll angle. The Hub can be rolled to any angle, but the liftarm will always point upward.

A photograph of a hub with a lift arm. The lift arm is held vertically with the help of an up-pointer. A toy LEGO character is at the top of the hub.

Figure 7-9

The Up Pointer keeps a liftarm pointed at the ceiling, regardless of the Hub’s roll angle

Building the Up Pointer

A motor attached to the side of the Hub keeps the liftarm pointed toward the ceiling by using the motor’s servo capabilities to rotate it to a precise angle. As the Hub is held and rolled to different angles, the motor will compensate for the roll angle to keep the liftarm pointed upward. Since the right side of the Hub is obstructed by the motor, a pair of connectors on the right side of the Hub allows sitting the Up Pointer for when its left side faces upward. When installing the motor in step 6, it’s important to have the motor in its zero position as discussed in Chapter 6 (as pictured in Figure 6-1).

A set of 2 3-D models exhibits a hub with 4 connectors attached. The top one denotes the number of connectors as 4 and the number of hubs as 1.

A 3-D model of a hub with a pair of extended connectors connected on the side.

A 3-D model of a hub with connectors, and 2 more pin connectors attached. It indicates the number of connecting pins as 2, at the top.

A 3-D model of a hub with an additional connector at the side. It indicates the number of connectors as 1, at the top.

A 3-D model of a hub with connectors along with 3 additional connecting pins on the side. It indicates the number of connecting pins as 3, at the top.

A 3-D model of a hub with a motor attached to the side with the help of connectors. It indicates the 3-D model of the motor separately, at the top.

A 3-D model of a hub with connectors and a motor attached to it. There are 2 connecting pins attached to the motor.

A 3-D model of a hub with connectors, and a motor to it. It indicates the connection of the liftarm to the port F of the hub.

Programming the Up Pointer

To program the Up Pointer, the following problem statement describes what it should do:
  • Keep the straight liftarm of the Up Pointer in the upward direction, regardless of the roll angle of the Hub. Include a shutoff capability by pressing either the left or right button on the Hub.

This problem can be solved with the algorithm:
  1. 1.

    Start the program.

     
  2. 2.

    Set motor speed for maximum speed.

     
  3. 3.

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

     
  4. 4.

    Set the angle position of the motor to be the same as the Hub’s measured roll angle.

     
  5. 5.

    Stop the program.

     
A flowchart implementation of the algorithm is shown in Figure 7-10, using a loop to continuously monitor the Hub’s roll angle.

A flowchart presents 5 steps. 1. Start 2. Set motor speed to 100% 3. Repeat if the button is not pressed 4. Move motor 5. Stop.

Figure 7-10

Flowchart for the Up Pointer algorithm

The Word Blocks Code

Figure 7-11 shows the Word Blocks code for the Up Pointer. As in all the exercises of this chapter, a loop in the program continuously checks whether a button has been pressed on the Hub so that the program can be gracefully stopped. Inside the loop, the angle position of the motor is changed as the Hub’s roll angle changes. Particular blocks to note are described following Figure 7-11.

A screenshot presents the Word Blocks code. It presents 5 steps between the start and exit as follows. 1. start. 2. set speed. 3. repeat. 4. set position. 5. stop.

Figure 7-11

Word Blocks code for the Up Pointer algorithm

  • Step 2: The set speed block assigns a value for the speed of rotation for the motor. Without this block, the motor will assume a default speed of 75 percent. The higher speed setting of 100 percent allows the Up Pointer to react quickly to changes in the Hub’s roll angle.

  • Step 4: The go to position block tells the motor to go to the angle position that matches the angle measured by the Hub’s Motion Sensor for the roll angle. To read in roll angles, a Motion Sensor block (found under the Sensors menu) goes into the oval-shaped angle parameter.

The Python Code

The Python code for the Up Pointer is listed as follows. As described in Chapter 6 for working with motors, an object is created to use motor functions. A loop constantly checks for changes in the roll value as well as monitors for a button press.
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()
motor = Motor('F')
# Program "tilt_alarm".  Beep speaker if roll or pitch > 5 deg.
while True:
    if myhub.left_button.is_pressed() or myhub.right_button.is_pressed():
        exit()
  1 roll = myhub.motion_sensor.get_roll_angle()
  2 roll = (roll + 360) % 360
    motor.run_to_position(roll,'shortest path', 100)

The Hub’s roll angle is measured with the same function 1 used in the tilt alarm exercise. Here, though, there’s a subtle difference involving the way angles are described. Angles around a circle can be described in two ways: as ranging from 0 to 359 degrees or as ranging from –180 to 180 degrees. The Motion Sensor returns a measurement in the –180 to 180 format, but the motor function used in this Python program requires an angle in the 0–359 range. The measurement can be converted from one format to the other with a modulus operation, which calculates the remainder after dividing two numbers. The modulus operation is written as a percent (%) symbol in Python 2.

The final line of code spins the motor to keep the Up Pointer’s liftarm pointed toward the ceiling. This function controls the motor’s angle position setting, as described in detail in Chapter 6. In this case, the motor’s angle is set to correspond to the measured roll angle, so the motor compensates for the motion as the roll angle changes.

Summary

This chapter showed how to work with the Motion Sensor, a sensor embedded in the Hub. The Motion Sensor can measure parameters including tilt angle (roll, pitch, and yaw), orientation, gyro rate, and acceleration. Motion data is in reference to three x, y, and z axes of the Hub, with pitch about axis x, roll about axis y, and yaw about axis z. Exercises with motion data included viewing data in the Robot Inventor app, a tilt alarm, and a sound effect generator. This sound effect generator also demonstrated how to trigger sounds using the Hub, which play on the computer or smart device that runs the Robot Inventor app. The chapter summary project combined a motor with Motion Sensor data for a machine that points the way up, regardless of the roll angle of the Hub.

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

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