LEARN.PARALLAX.COM
Published on LEARN.PARALLAX.COM (https://learn.parallax.com)
Home > Cybersecurity: Radio Tilt Control

Cybersecurity: Radio Tilt Control

What it’s about

Control a cyber:bot by tilting a micro:bit! The controller micro:bit measures tilt with its accelerometer, and sends that information to the cyber:bot with its radio. The cyber:bot receives the radio-transmitted tilt data and uses it to set its wheel speeds. 

This tutorial can be approached in two ways:

I just want to tilt-control my cyber:bot!

  • Check the Before you start list below to make sure you are ready.
  • Do the Radio Tilt Tests section to make sure your controller micro:bit and receiver cyber:bot are communicating data properly.

I want to learn about developing this kind of app and how an accelerometer works, or I’m in a class and it’s required:

  • Check the Before you start list below to make sure you are ready.
  • Go through the activities sequentially to learn about accelerometer sensing, tilt angle calculations, radio tests, forward/backward control, add stop range, left right control, and adding exception handling. 

Before you start

You will need:

  • A fully built and tested cyber:bot robot
  • One additional micro:bit module (on or off a cyber:bot)
  • Two USB A to MicroB cables
  • One or more computers with:
  • Access to makecode.microbit.org on a browser
  • Access to Google Chrome Labs Serial Terminal on a browser

Complete these lessons first from the Change this link cyber:bot Tutorial Series:

  • Required
    • Get Started with micro:bit and MakeCode
    • Making micro:bit programs
    • Add extensions to your micro:bit
    • Computer – micro:bit Talk
    • Build your cyber:bot
    • Navigation with the cyber:bot
  • Recommended
    • Dictionary Primer
    • Strings & Characters Primer
    • Cybersecurity: Radio Basics
    • Cybersecurity: Radio Data
    • Cybersecurity: Navigation Control from a Keyboard

After you finish

If you go through the tutorials sequentially, you will gain experience with:

  • How an accelerometer works
  • How sensing axes can be more or less aligned with gravity
  • How a capacitive accelerometer detects acceleration and gravity forces
  • Trigonometry tricks for calculating tilt angle from accelerometer measurements
  • Scaling sensor values for speed/direction control
  • Incremental maneuver feature addition
  • Using key-value pairs to simplify data exchange between devices in a cyber:bot app. This was introduced in Cybersecurity: Radio Data

Measure Accelerometer Tilt

The micro:bit module’s accelerometer has three sensing axes: x, y, and z. You can picture the x-axis running side-to-side, the y-axis running front-to-back, and the z-axis pointing upwards.

When the micro:bit is held still, the accelerometer can sense how much each of these axes aligns with the downward pull of gravity. This can, in turn, be used to sense how you have tilted the micro:bit. In this activity, you will explore how the various numbers the micro:bit reports for its x and y accelerometer axes relate to its tilt direction and level.

Test Tilts

Let’s test tilts: level, left, right, toward, and away from you.

When you vary the tilt angle from left to right, the x-axis accelerometer measurement values vary accordingly.

When you vary the tilt angle from facing toward you to facing away from you, the y-axis accelerometer measurement values also vary accordingly.

Example project: test_tilts_intro

  • Enter this project and name it test_tilts_intro. 
  • Flash the project into the micro:bit

  • Open the terminal at Google Chrome Labs Serial Terminal.
  • Take measurements as shown in the animation, recording the x and y values for each tilt angle in the table below the animation.

 

Direction

Angle X

Y

Vertical facing away 90° 0 1024
Mostly facing away 60°    
Slightly facing away 30° 0 512
Level 0°    
Slightly facing towards you -30°    
Mostly facing towards you -60°    
Vertical facing towards you -90°    
Vertical facing left 90°    
Mostly tilted left 60° 888 0
Slightly tilted left 30°    
Level 0°    
Slightly tilted right -30°    
Mostly tilted right -60°    
Vertical facing right -90°    

A Bit About Acceleration

Acceleration

Accelerometer means acceleration meter, but what is acceleration? 

Probably the most common, every-day example is when a car speeds up. During a few seconds of acceleration, a car’s speed might increase from stopped to commute speed. The physics term for this is the change in velocity over time, which is also one definition of acceleration. A car’s speed also changes as it slows down, so that’s acceleration too. 

A car speeding up is typically considered positive acceleration, and slowing down is negative acceleration. 

Forces and Acceleration

Have you ever felt pressed into a seat back as a car accelerates? That’s the feeling of the car seat back applying force to you to make you accelerate in the forward direction. In physics:

force = mass × acceleration

…commonly noted as

F = ma

So, if you know the mass (m) and the force (F), you can calculate an object’s acceleration with a = F / m. That’s essentially what an accelerometer does when it measures acceleration – it measures the force applied to a known mass inside it.

Another force that causes acceleration in nature is gravity (g). Since our bodies have mass, we feel the force of gravity pulling us to the ground. The ground has to push back equally to prevent us from falling through or sinking in. 

Newton’s Second Law of Motion

Newton’s second law of motion states that the acceleration of an object is directly
proportional to the applied force and inversely proportional to its mass.

a = F / m

To get from this to F = m×a, multiply both sides of a = F / m by m. 

What’s the difference between force and mass?

Your mass is all the protons, neutrons, and electrons in your body. Your weight is a measure of how much downward force your feet apply to a scale when you stand on it. 

When you weigh yourself on the earth, that’s one value because the earth’s gravity is acting on your mass. If you weighed yourself on the moon, your mass would not change, but your weight would be less. In other words, your body would apply less force on the scale. That’s because the moon has less mass than the Earth, so its gravitational pull is weaker.

Inside the micro:bit Accelerometer

The micro:bit accelerometer is a small chip that senses forces due to gravity and acceleration. It is the NXP/Freescale MMA8652, and it’s located on the bottom of the module, near the lower left corner.

Before talking about how the accelerometer works, remember the capacitor from the cyber:bot visible light sensing activities? Picture the inside of a capacitor as two metal plates separated by an insulator. For example, two plates separated by an insulator have a capacitance—the ability to store charge. If that insulator gets compressed, it brings the two plates closer to each other, and the capacitance increases. 

Inside the accelerometer, imagine a tiny object (with mass) held in the middle of a small box. Each wall of the box has capacitors with plates held in place by material that compresses with force. (In the picture, it’s shown as tiny springs.)

When the accelerometer accelerates, the box’s walls have to push on the mass to make it accelerate along with it. As it does so, the tiny springs stretch and compress, changing the distance between the metal plates in each capacitor. 

The electronics inside the accelerometer convert that capacitor measurement to a number that reports to the micro:bit when your project executes a statement like set x to (acceleration (x)).3

Think about how you speed up when you jump down off of something and land on the ground. That’s the acceleration due to gravity, g. In physics calculations, commonly used values are 32 ft/s² or 9.8 m/s². 

The micro:bit won’t typically experience more than 1 g of force from acceleration, unless it’s taking a ride in a high-performance model airplane or attached to a wheel that’s spinning really fast. But it does typically experience force equivalent to 1 g of acceleration from gravity’s pull. 

These are just concept drawings. The micromachined construction of a proof mass and capacitors inside an actual accelerometer is more elaborate than a simple box with a block inside. It involves a small sliding plate anchored to a flexible material. The plate has capacitive fingers that overlap more or less with metal fingers below it, depending on how much force the plate stretches or compresses the flexible material.

The most common unit accelerometers use is 1 g, which is one unit of gravity. The micro:bit reports gravity/acceleration in steps of 8, from -2048 to + 2048 to report -2 g to 2 g. 

If you orient the micro:bit so that the x-axis is pointing down and the y-axis is pointing sideways, the x-axis reports 1024 because it is fully aligned with gravity. The y-axis reports zero because it is not aligned at all. 

If you rotate the micro:bit 45° counterclockwise, the measurement of 736 corresponds with the component of the x sensing axis that’s adjacent to gravity. 

1024 is the ideal value representing 1 g, but your micro:bit might report more or less than that. Also, since it reports accelerometer measurements in steps of 8, if it reports a value like 1040 for 1 g, don’t worry, that’s really only two increments of 8 off from 1024.

How the Project Works

How test_tilts_intro works

The accelerometer methods are part of the microbit module, so no other imports are needed. The instruction pause (1000) is always recommended at the beginning of any project that prints messages to the terminal. After that, the main loop begins.

With the accelerometer held still, a project can get information from each axis about how much it is aligned with gravity. Regardless of whether it’s acceleration (x), acceleration (y), or acceleration (z), the method call returns a value in the range of 1024 to 0 to -1024.

When the measurement is 1024, it means that the accelerometer’s sensing axis is aligned with gravity. As the sensing axis is tilted further out of alignment with gravity, the value decreases. When it’s level (pointing sideways and not at all up or down), the value is zero. As it starts to point away from gravity, the value becomes negative. When it’s aligned with gravity, but pointing the opposite direction, the value is -1024. 

The accelerometer x and y values are printed, and after a 0.75 second pause, the main loop repeats.

Try This: Take X and Y Rotation Samples

X and Y and Rotation

The first tilt experiment measured how far the micro:bit tilted away from being held level. The test isolated each axis. So, when you tilted it toward and away from you, there was minimal left/right tilt. So, the y-axis measurements changed while the x-axis measurements only varied slightly. Then, when you tilted it left and right without tipping the micro:bit toward or away from you, the x-axis changed, and the y-axis only varied slightly. 

You can also set the micro:bit on its edge, like it’s a wheel. As you rotate it, both the x and y axis measurements will go through their ranges. 

If you instead tilt it toward a corner, the x and y axes will return measurements, each indicating the portion of gravity it senses. For example, you might see a measurement like (512, 512). If you balance it on a corner, you might see a measurement like (736, 736). Note that the measurements are different, but their ratios are the same. More about that in the next activity.

Try This: Take X and Y Rotation Samples

Let’s treat your micro:bit like it’s mounted on a wheel, and watch the x and y values change. In the next activity, you will use a project to calculate the rotation angles.

  • Use the same project: test_tilts_intro.
  • Flash the project into the micro:bit and open the terminal.
  • Test at each rotation shown in the animation.

  • Fill your measured values into the table.

Angle

x value

y value

0° 1024 0
45°    
90°    
135°    
180°    
225°    
270°    
315°    
360°    

Your Turn: Combine Tilt and Rotation

Now, let’s try rotation and tilt combined. In this test, you will rotate the micro:bit by a certain angle, and then tilt it away from you by 45°. 

  • Use the same project test_tilts_intro.
  • Flash the project into the micro:bit and open the terminal.
  • While tilting the micro:bit 45° away from you, test at each rotation shown in the animation.

  • Fill your measured values into the table.

Angle

x value

y value

0° 736 0
45°    
90°    
135°    
180°    
225°    
270°    
315°    
360°    

Measure Rotation Angles

Once a project has the x and y tilt values, it can calculate rotation angles. 

For example, if you hold the micro:bit (or cyber:bot) vertically, and then rotate it 30°, the project can tell you so. 

A project can also calculate the overall direction you are tilting the micro:bit, even if you’re not holding it vertically. 

For example, if you rotate it 45° and then tilt it away from you by another 45°, the 45° angle measurement tells you which corner you are tilting it toward. If that angle was 135°, it would mean you are tilting it toward a different corner. 

Measuring Rotation Angles

Example project: test_accel_xy_angle

  • Enter this project and name it test_accel_xy_angle. 
  • Flash the project into the micro:bit.

  • Open the terminal.
  • Verify that the angles reported are correct as you hold the micro:bit vertically, and rotate it to: 0°, 30°, 45°, 60°, 90°, 135°,180°, 225°, 270°, 315°, and 360°. Make a note of x, y, and angle for each rotation.

  • Repeat the rotations, but for each vertical rotation, tilt it away from you by 45° before measuring. As before, note the x, y, and angle values.
  • Divide x into y at 45° rotation.
  • Divide x into y at 45° rotation plus 45° tilt-away. 

Are both results close to 1?

  • Repeat for 90° and 135°.

See how the x and y values are different for rotated vs. rotated+tilted but the y/x ratios work out to the same?

How Measuring Rotation Angles Works

In addition to the microbit module, this project has to import the math module, which contains common trigonometry methods. Then, pause (1000) gives the terminal a second to set up communication with the micro:bit before it has to display any messages.

In the main loop, the x and y axis accelerometer measurements are stored in variables named x and y.

The next block performs a calculation called arctangent. If you have never heard of it, the next page explains it.

The block atan2(x, y) is what returns the angle result, but that result is in radians—a different kind of angle measurement where a half circle is approximately 3.14, or Pi (π), radians instead of 180°. To convert radians to degrees in blocks, use the (…) x 57.296, this is the approximate number that is multiplied by radians to get the degrees.*

Another way to think about the block above is to break it into steps, each in an individual block. For example:

Now that the angle is calculated, the project displays labels for each variable, followed by its value.

*Alternately, the project could multiply by 180 and divide by pi. At this point, there’s a floating point result, and the round block will round to the nearest integer. For example, if the result was 179.5 or higher, it would round to 180. If the value was instead between 179 and 179.499…., it would round to 179 instead.

Did You Know? Trigonometry and Rotation Angles

Trigonometry is used to calculate the rotation angle. Even if you haven’t studied it yet, try to follow along. It’s pretty neat! 

A triangle with a 90° angle (called a right triangle) can have one of its corners marked θ (Greek letter theta) to represent the angle there. Of the right triangle’s three sides, the one is opposite of θ, one adjacent to θ forming the right angle, and the hypotenuse is the side that connects the other two. The diagrams will use the shorthand opp, adj, and hyp for these sides. 

In trigonometry, the ratios of each pair of sides have names: sine (sin), cosine (cos), and tangent (tan). For each angle of θ, the ratio for sin, cos, or tan will be the same, regardless of the size of the triangle. Scientific calculators have sin, cos, and tan keys to complete the division calculation for you, and all you have to do is give it the angle. Makecode’s math library has methods for calculating these as well. 

If you only know the result of a division, like opp/adj, you can get the angle θ with the arctan calculation. That’s also called the inverse tangent. Calculators often have tan-1 key for calculating this, and Makecode’s math module has the atan and atan2 methods.

The arctan calculation is particularly useful for calculating the micro:bit’s rotation angle. All your project needs is the amount of gravity acting on the x and y accelerometer axis. Treat the y-axis measurement as the opposite side and the x-axis measurement as the adjacent side of a right triangle, and the arctan calculation will give you the angle θ.

For any angle you rotate to, the micro:bit accelerometer’s x sensing axis will align with gravity by a certain amount (xg), and the y sensing axis will also align by some amount (yg). Let’s say you are holding the micro:bit vertically and have it rotated by 30°. In that case, yg measures about 512, or 0.5 g. (1 g is 1024). xg will be around 888, which is about 0.87 g. 

If you look closely, the x and y sensing axis triangles are identical. So, you could take the xg leg from the x-axis triangle and fit it on the adjacent side of the y-axis triangle.

 Like the project, if all you know is the x and y axis measurements (xg and yg), you could now use a calculator to figure out the angle θ by taking the arctan of 512 / 888. The result is 29.96, or rounding up, it’s 30. 

Here is an example where the rotation is 45°. Both x and y report 728, and the arctan(728/728) = arctan(1) = 45. 

If you were wondering how the project could calculate the angle even when the micro:bit was tilted, it’s because the portions of the effects on each axis were reduced by the same fraction. When holding vertical, the arctan(728/728) resulted in arctan(1) = 45. Likewise, with the tilt away from you, arctan(512/512) = arctan(1) = 45. In other words, the ratio of the x and y measurements are the same, so the result of the arctan calculation is also the same.

Measure How Far from Vertical or Level

In addition to the rotation angle with opposite and adjacent x and y values, your projects can calculate the triangle’s hypotenuse to determine how far from vertical the micro:bit has been tilted.

Example project: rotate_angle_with_degree_of_tilt

  • Enter this project and name it rotate_angle_with_degree_of_tilt. 
  • Flash the project into the micro:bit.

  • Open the terminal.
  • Hold the micro:bit vertical and pick a rotation angle, like 60°.
  • Note the angle and hyp values.
  • Start holding the micro:bit vertically, rotated at 45 degrees. Make a note of the hyp variable value. It should be near 1024.

Tilt it 45° degrees away from you (toward level) while keeping the rotation at 45°. The angle should stay the same, but the hyp variable should report a smaller value.

 Continuing to hold the rotation at 45°, tilt it a little further toward level. Did the hyp variable value get even smaller?

How It Works

The first portion of the code is the same as the project test_accel_xy_angle from the previous activity.

Here is the one block that was added that calculates a number that can be used to indicate the degree of tilt. It calculates x2 + y2, and then takes the square root of that. What it’s calculating is the length of the hypotenuse of the triangles introduced in the previous Did You Know? page on trigonometry. More details are in the next Did You Know? section below.

A serial write statement was added to show the hypotenuse (hyp) result on another line.

Did You Know?

As you’ve seen with the rotate_angle_with_degree_of_tilt project, the micro:bit can report tilt level along with rotation. But is there really a relationship between the rotation angle and the level of tilt? 

The answer is yes. Just as the x-axis measurement is the adjacent leg of the triangle and the y-axis is the opposite leg, the tilt away from vertical is indicated by the hypotenuse. 

Here’s an example where the hypotenuse is calculated with the 30° values of xg = 888 and yg = 512. The result is 1025, which is essentially a total of 1g, meaning that the micro:bit is being held vertical.

Here is another example where the hypotenuse is calculated with the rotation of 45°, and tilted away at 45°. For this, the values of xg = 512 and yg = 512. The result is 724. The closer the tilt gets to level, the smaller the hypotenuse value will be.

You might encounter this calculation described as a vector magnitude in later physics and engineering classes.

Z-Axis: Which Way Is Up?

Let’s test tilts: level, left, right, toward, and away from you.

When you vary the tilt angle from left to right, the x-axis accelerometer measurement values vary accordingly.

When you vary the tilt angle from facing toward you to facing away from you, the y-axis accelerometer measurement values also vary accordingly.

Example project: test_tilts_intro

  • Enter this project and name it test_tilts_intro. 
  • Flash the project into the micro:bit

  • Open the terminal at Google Chrome Labs Serial Terminal.
  • Take measurements as shown in the animation, recording the x and y values for each tilt angle in the table below the animation.

 

Direction Angle X

 Y

Vertical facing away 90° 0 1024
Mostly facing away 60°    
Slightly facing away 30° 0 512
Level 0°    
Slightly facing towards you -30°    
Mostly facing towards you -60°    
Vertical facing towards you -90°    
Vertical facing left 90°    
Mostly tilted left 60° 888 0
Slightly tilted left 30°    
Level 0°    
Slightly tilted right -30°    
Mostly tilted right -60°    
Vertical facing right -90°    

How it Works: Z-axis

The accelerometer’s z-sensing axis aligns with gravity when the micro:bit is held level with its LED display facing down. In that position, acceleration (z) returns a measurement in the -1024 neighborhood. 

Held vertically, it returns zero since the z-axis is perpendicular to gravity— it doesn’t line up at all. If held vertically, rotation angle won’t matter to the z-axis, it still returns zero. Held with the LED display facing up, the z-axis is aligned with gravity again but pointing in the opposite direction. Because of that, the acceleration (z) block returns a value near -1024.

As for how the project test-z-axis-tilt works, it is basically the z-axis version of test_tilt_intro. The main difference is that:

…has been replaced with

Did You Know? This Way Up

Without the z-axis, the x and y tilt with the atan2 calculation from Measure Rotation Angles can give your project information about how the micro:bit has been rotated. By adding the hyp calculation from the previous activity your project can also have information about the degree of tilt, but that information is incomplete. The reason being, it cannot tell if you are facing the LEDs up or down. 

The hyp calculation is unable to tell up from down because square root(x**2 + y**2) always gives a positive result. That’s because any time you multiply a number by itself, the result is always positive regardless of the number’s sign. For example:

32 = 3 x 3 = 9       -32 = -3 x -3 = 9

For tilt sensing, the accelerometer’s z-axis can complete the picture because the sign is negative for half the range with the LEDs facing up (-1024 to -1) and positive for the other half with the LEDs facing down (-1 to -1024). And of course, it’s zero if it’s neither facing up nor down.

Your project can even use the accelerometer’s z-sensing axis to detect how far from level you are holding the micro:bit as you rotate it. For example, if you hold the micro:bit vertical while you rotate it, the z-axis will report zero the whole time. That’s because the z-axis will remain perpendicular to gravity. Some combination of the x- and y-axes will align with gravity and report values, but the z value will stay at zero.

 

  • Review How Measuring Rotation Angles Works.
  • Make note of the cosine, which is adj/hyp and that θ = arccos(adj / hyp)

Let’s say that you have tilted the micro:bit as you’ve rotated it. As you saw, a project can use atan2(y, x) to determine the rotation angle, but how far have you tilted it from level? Think of the z-axis measurement as an adjacent leg that aligns with gravity in a triangle. The angle θ between the adjacent leg and the 1 g (1024) hypotenuse can be determined by taking the arccos( zg / 1024).

 Keep in mind that the z-axis measurement only tells you how far from level the micro:bit is tilted. For example, these two tilts all result in the same z-axis measurement. So, it doesn’t mean that much without more info from the x and y measurements.

Try This: Get Familiar Z-Axis Angle Measurements

The previous page Did You Know? This Way Up explained how to use arccos to calculate the angle between the micro:bit’s z sensing axis and gravity. 

When the LED display is facing straight down, so is the z-sensing axis. So the angle between z and gravity is zero. 

As the angle between the z-axis and gravity increases, so does the measurement. When the LED display (and z-axis) is facing straight up, it’s angle is 180°. Again, rotating past 180°, the angle decreases, like the last example where it’s back down to 135° again.

Example project: z_axis_degree_of_tilt_try_this

  • Enter z_axis_degree_of_tilt_try_this.
  • Flash it into the micro:bit.

  • Open the terminal and experiment with various levels of tilt and rotation.

  • Fill in the table with your measured z_angle values.
z z_angle

Direction LEDs are facing

1024 0 Straight down
728 45 Halfway between straight down and sideways
    Sideways
-728 135 Halfway between sideways and straight up
-1024 180 Straight up
    Halfway past straight up on way to sideways
    Tilted toward you by 45°
    Tilted away from you by 45°
    GND corner tilted down by 45°
    0 corner tilted down by 45°

Your Turn: All Together Now

You can combine the xy calculated angle from Measuring Rotation Angles with the z angle introduced here to get a complete picture of how the micro:bit is oriented in space.

Example project: z_axis_and_xy_axis_angles_your_turn

  • Enter z_axis_and_xy_axis_angles_your_turn.
  • Flash it into the micro:bit.

  • Open the terminal and try each orientation shown in the pictures above.
  • How close can you get to the angles shown in the pictures’ terminal?

Display Tilt Direction

Makecode’s show clock(…) list has 8 LED patterns that resemble a cardinal compass, hand at each direction. It can be used for more than directions though. It can also point in the direction you are tilting the micro:bit! This visual feedback will be useful for tilt-controlling the cyber:bot. 

First, let’s train an example project that displays each direction hand at N, NW, W and all the way through NE.

Example project: display_clock_positions

  • Enter this project and name it display_clock_positions. 
  • Flash the project into the micro:bit.
  • Verify that it displays all the clock needle positions.

Your Turn: Display Tilt Direction

With the tilt direction display, your project can display a needle that either points up or down.

Example project: display_tilt_direction_with_leds

  • Enter this project and name it display_tilt_direction_with_leds. 
  • Flash the project into the micro:bit.

  • Open the terminal.
  • Try rotating and tilting your micro:bit in various directions, and verify that the display always points downward.

Tilt Radio Tests

The next step toward a radio tilt-controlled cyber:bot is to radio-transmit those measurements to a receiver. 

Before adding tilt control statements, it’s important to just make sure all the data is correctly received and processed. So, in this activity, one micro:bit (or cyber:bot) will measure tilt, and display it with both its terminal and LEDs. It will also radio-transmit its x, y, and needle measurements to a cyber:bot. 

The cyber:bot will display the measurements it receives in another terminal. It will also mirror the transmitting LED display with its own.

Radio-Transmit Tilt

The radio_tilt_transmit_test project is a modified version of display_tilt_down_with_leds with packetizing and transmitting from Cybersecurity: Radio Data’s Send and Receive packets activity. The packet it sends contains x, y, and needle key-value pairs that the receiver will be able to parse and use.

Example project: radio_tilt_transmit_test

  • If you are in a classroom, adjust the radio set group in the project to your assigned channel.
  • Enter and flash radio_tilt_transmit_test into the micro:bit that you will use to measure and transmit tilt data. 

  • Open the terminal.
  • Tilt the micro:bit in various directions.
  • Verify that it displays the direction you are tilting with the LEDs.
  • Verify that it displays the x, y, and needle measurements in the terminal.

Radio-Receive Tilt

The radio_tilt_receive_test project is a modified version of countdown_receiver from the Cybersecurity: Radio Data’s Send and Receive Packets activity. To receive and display tilt, it is adjusted to parse x, y, and needle values from the packet it receives, and then use statements from display_tilt_down_with_leds to display the tilt with its LEDs and in the terminal.

Example project: radio_tilt_receive_test

For best results:

  • Connect your cyber:bot to a second USB port (or to another computer).
  • Open a second makecode.microbit.org editor
  • If you are in a classroom, adjust the radio set group in the project to your assigned channel.
  • Enter and flash radio_tilt_receive_test into the cyber:bot that you will use to display the tilt data it’s receiving from the transmitter.

The goal is to be able to tilt the transmitting micro:bit, and verify matching data in the receive terminal, and on the receiver micro:bit’s LEDs. So, you will be tilting the transmitter while monitoring the receiver.

  • Open the terminal in the editor that’s connected to the receiving cyber:bot.
  • Tilt the transmitter micro:bit in various directions. 
  • Verify that the micro:bit on the receiving cyber:bot displays the direction you are tilting with its LEDs.
  • Verify that it displays the x, y, and needle measurements in the terminal.

How the Tilt Radio Tests Work

How radio_transmit_tilt_test Works

The project starts with importing modules. Since this project only measures tilt and transmits, it does not need to include the cyberbot extension.

The project uses radio set group to set the channel, message queue, and message length. As explained in the Cybersecurity: Radio Basics tutorial, the channel defaults to 7, but can be adjusted to an integer from 0 to 255. Classrooms typically assign pairs of students to different channels to avoid crosstalk. The sender and receiver have to be on the same channel for communication to work. 

Next, pause (1000) gives the editor time to establish the serial connection with the micro:bit before it has to display text from the micro:bit.

The main loop starts with statements from display_tilt_direction_with_leds that take the accelerometer x and y measurements and calculate/display the LED tilt direction needle. There are extra serial write statements for “Send:” and an empty line. Since the LEDs display the direction of the tilt like a compass needle, the direction variable’s name is changed to needle here.

Next, the x, y, and needle values are added to a dictionary named dictionary. This step is important because it reduces the work the receiver has to do. The receiver can just get the values that correspond to the ‘x’, ‘y’, and ‘needle’ keys.

After dictionary is populated, all that remains is to convert it to a string, send it through the radio, and delay 0.5 s before repeating the forever loop.

How radio_receive_tilt_test Works

The project starts in much the same way as the radio_transmit_tilt_test.

The main loop starts by copying any data the radio might have received to a variable named rLongString. When on radio receive() returns none, the project skips everything in the if rLongString… statement and continues waiting for a signal. When on radio receive() returns a string from the transmitter micro:bit, all the statements in the if rLongString… statement get executed. First, convert string (rLongString) to dictionary converts the string that was received back to a dictionary. Then dictionary search sets the x, y, and needle variables using the ‘x’, ‘y’, and ‘needle’ keys. 

Now, that the receiver has variables with the transmitter micro:bit’s measurements, it can display them in the terminal and with the LEDs. As with the transmitter, these statements are similar to what’s in display_tilt_direction_with_leds with extra serial write line statements for “Receive:” and an empty line, the variable for displaying the tilt direction is needle instead of cardinal direction.

Tilt Control Forward & Backward

Now that one micro:bit can radio-transmit tilt info to another, let’s start reducing pause times and adding statements to make the cyber:bot move based on the tilt data it receives. 

Rapid Radio-Transmit Tilt Data

To make the tilt controlled robot responsive, it’s important to speed up the forever loop’s repeat rate. The changes are simple, just remove serial write statements and reduce pause (500) to pause (50). This will help prevent delays between tilting the controller and the cyber:bot’s response. Without the serial write statements, plan to use the LED displays to verify radio communication between the tilt controller and the cyber:bot.

Example project: radio_tilt_transmit_rapid

  • If you are in a classroom, adjust the radio set group in the project to your assigned channel.
  • Enter and flash radio_tilt_transmit_rapid into the micro:bit that you will use to measure and transmit tilt data. 
  • Verify that the tilt direction needle still displays.

How radio_tilt_transmit_rapid Works

The radio_tilt_transmit_rapid project is almost identical to radio_tilt_transmit_test from the previous activity. The only differences are that the serial write statements were removed and the pause (500) at the end of the loop was changed to pause (50) to make it more responsive.

Why not just completely remove the pause call? Probably the most important reason is to not flood the airwaves with unnecessary radio activity. The pause (50) call reduces the radio transmissions to around 20 times per second. The difference between letting the micro:bit transmit as fast as it can and repeating with a 50 ms pause will not be noticeable as you tilt the micro:bit to make the cyber:bot move.

Rapid Radio-Receive Tilt Plus Forward/Backward Control

The radio_tilt_bot_fb_only receiver project has statements added that will make the cyber:bot roll forward and backward based on the y-axis tilt measurement from the transmitter.
For best results, the receiver project should repeat at top speed, so all serial write and pause statements have been removed. 

Example project: Rapid Radio-Receive Tilt Plus Forward/Backward Control

  • Use the +Extensions button to add the cyberbot extension to your project. If you don’t remember how to do this, see the Add extensions to your micro:bit page.
  • Set the receiver cyber:bot board PWR switch to 1.
  • If you are in a classroom, adjust the radio set group in the project to your assigned channel.
  • Enter and flash radio_tilt_bot_fb_only into the micro:bit that’s in the receiver cyber:bot. 

  • Tilt the micro:bit transmitter and verify that the receiver cyber:bot displays a copy of the needle. This “micro:bit transmitter” will also be called the “tilt micro:bit”.
  • Hold the micro:bit tilt transmitter level, with the LEDs upward and the USB connector pointing toward you. (At this point, there is nothing to tell you that you are holding it level, the needle will still point in some direction. The holding level feature is coming soon.)
  • Set the cyber:bot board PWR switch to 2.
  • Tilt the micro:bit transmitter slightly away from you, and verify that the cyber:bot rolls forward.
  • Tilt the micro:bit transmitter slightly toward you, and verify that the cyber:bot rolls backward.
  • Set the PWR switch back to 1.

How It Works

The radio_tilt_bot_fb_only project is also almost identical to radio_tilt_receive_test from the previous activity. One difference is that the pause (500) was not reduced to 50; it was completely removed. Without the pause, the receiver project will recheck for radio data at top speed. The only thing limiting the responsiveness is that the transmitter has 50 ms sleep calls, so it’s only transmitting every 20 ms or so.

Some statements were also added to the if… block after the x, y, and needle variables are unpacked. 

First set fb to (y / 10) takes the y tilt value that could hold a value in the -1024 to 1024 range and scales it down to -102 to 102, which is a perfect range for servo control. The fb variable name is shorthand for forward/backward. 

Next variables for velocity-left (vL) and velocity-right (vR) are set with the value stored in fb. Let’s say you tilt the micro:bit away from you and that the fb value might be around 50. To make the cyber:bot roll forward, vL can be 50, but vR has to be -50 to make the right wheel turn the opposite direction. That’s why set vR to (0 – fb).

Now that the vL and vR variables store equal and opposite values based on your y-axis tilt, they can be used to set the left (P18) and right (P19) servo speeds.

Adding a Stop Range

You might have noticed that it was difficult to hold the tilt transmitting micro:bit to make the cyber:bot stay still. We can fix that by adding a stop range to the tilt values. 

The projects will check if the micro:bit accelerometer’s y-axis is close to zero. The transmitter micro:bit will display a diamond to indicate that it’s nearly level in the forward/backward direction. The receiver project will also make the cyber:bot stay still when the diamond indicator is displayed.

Transmitter Displays Stop Range

The only thing that needs to be added to the transmitter radio_tilt_transmit_rapid project is an if… block that displays one of two things:

  • A diamond if the y-axis tilt is less than +/- 80
  • The tilt direction needle if the y-axis reports larger values.

Let’s try it!

Example project: radio_tilt_controller_w_stop_range

  • Set your tilt controlled cyber:bot’s 3-position switch to 1 so that it doesn’t move around during this test.
  • If you are in a classroom, adjust the radio set group in the project to your assigned channel.
  • Enter and flash radio_tilt_controller_w_stop_range into the micro:bit that you will use to measure and transmit tilt data. 
  • Verify that the tilt direction needle still displays, except for when you hold it close to level. Then, it should display a diamond.

How radio_tilt_controller_w_stop_range Works

The radio_tilt_controller_w_stop_range project is just radio_tilt_transmit_rapid with an if…else… statement added. 

When the absolute value of y is greater than 80, it displays the tilt direction needle, just like it has up to this point. But, if the y value is anywhere in the -80 to 80 range, it instead displays a small diamond to tell you that your forward/backward tilt is pretty close to level.

The if absolute of (y) block returns the positive-only version of any value y might store. So, if y stores -20, absolute of (y) returns 20. If y stores 20, absolute of (y) doesn’t change anything and just returns 20. So, if absolute of (y) > 80 is a concise way to check if y is outside the -80…80 range. Another way to check if y is outside that range would be if y > 80 or y < -80.

Receiver Full Tilt Control & Stop Range

In addition to displaying the diamond when the y-axis tilt is close to level, the radio_tilt_bot_fb_with_stop_range project also makes the cyber:bot stay still.

Example project: radio_tilt_bot_fb_with_stop_range

  • If you are in a classroom, adjust the radio set group in the project to your assigned channel.
  • Make sure the PWR switch is set to 1 first.
  • Enter and flash radio_tilt_bot_fb_with_stop_range into the micro:bit that’s in the receiver cyber:bot. 

  • Tilt the micro:bit transmitter and verify that the receiver cyber:bot displays a copy of the needle.
  • Hold the micro:bit tilt transmitter level, with the LEDs upward and the USB connector pointing toward you.
  • Verify that both the transmitter and receiver micro:bits display a diamond.
  • Set the cyber:bot board PWR switch to 2.

While still holding the transmitter micro:bit level, does the cyber:bot stay still?

As you tilt the tilt transmitter away from and then toward you, does it make the cyber:bot roll forward and backward?

  • Set the PWR switch back to 1.

How It Works

Here is the portion of radio_tilt_bot_fb_with_stop_range that’s different from the previous radio_tilt_bot_fb_only that it’s based on. 

Keep in mind that fb is y / 8, so instead of looking for y being outside the +/- 80 range, this program checks if fb is outside the +/- 8 range. When the absolute value of fb is greater than 8, the project displays the tilt needle and sets the vL and vR variables just like it did in the previous radio_tilt_bot_fb_only project. But when fb falls inside the -8 to 8 range, it displays the diamond and sets vL and vR to 0. Whenever the else block sets vL and vR to zero, it makes the servos stop spinning.

Add Left/Right Tilt Control

Up to this point, the transmitter and receiver projects support forward, backward, and stop tilt control. 

Adding left/right control will complete the radio tilt-controlled cyber:bot functionality.

Update the Receiver cyber:bot project

The transmitter micro:bit should still be running the same project from the previous activity. That’s radio_tilt_controller_w_stop_range.

Now for the new cyber:bot receiver project!

Example project: radio_tilt_bot_fb_lr_with_stop_range

  • Set the receiver cyber:bot board PWR switch to 1.
  • If you are in a classroom, adjust the radio set group in the project to your assigned channel.
  • Enter and flash radio_tilt_bot_fb_lr_with_stop_range into the micro:bit that’s in the receiver cyber:bot. 

  • Set the cyber:bot board PWR switch to 1.
  • Repeat the needle/diamond display tests from the previous activity.
  • Set the cyber:bot board PWR switch to 2.
  • Now, tilt the micro:bit transmitter in the directions shown in the table, and verify that the cyber:bot moves as expected:

 

Tilt the micro:bit transmitter

Verify the cyber:bot maneuver

Level Stay still
Slightly away from you Forward slowly
Further away from you Forward faster
Slightly toward you Slowly backward
Further toward you Faster backward
Away from you and to the left Curve forward and to the left
Away from you and to the right Curve forward and to the right
Toward you and to the left Curve backward and to the left
Toward you and to the right Curve backward and to the right

How the Receiver Works

The radio_tilt_bot_fb_lr_with_stop_range project is just another development step from the previous activity. Here are the changes that were made to radio_tilt_bot_fb_with_stop_range to add the left/right control.

Remember how the project sets fb to y /10 to reduce the range of values from -1024…1024 to -102 to 102? Well, since the x-axis measurements also come in a range of -1024 to 1024, the project can also divide those by 10. That’s what set lr to (x / 10) does, and lr is shorthand for left/right.

After setting up vL and vR with fb and –fb, the lr component can be added in to cause turns. The statement if(fb < 0): set lr to (0 – lr) changes the sign of the lr variable if you are tipping the tilt transmitter toward you. That’s because the rules for wheel rotation directions for turning reverse when the robot is backing up.

Let’s try an exercise called variable tracing. Variable tracing is the process of stepping through each block after setting variable values and checking what each statement does with those values. Some software development environments offer an automated version of this, but here, it is a mental exercise to help better understand how the statements correctly control the wheel speeds. The variable values are calculated in comments to the right of the statements.

Example: Tilt the micro:bit away from you and to the left. 

Assume the y variable is 400, and the x variable is 200. 

Example: Tilt the micro:bit toward you and to the right. 

Assume the y variable is -400, and the x variable is -200. 

DISCUSSION FORUMS | PARALLAX INC. STORE

About | Terms of Use | Feedback: learn@parallax.com | Copyright©Parallax Inc. 2024


Source URL:https://learn.parallax.com/courses/cybersecurity-radio-tilt-control_makecode/
Links