1 of 56

Introduction to Coding

by Bob Cook, GA

2 of 56

Install Chrome web browser from click-here, unless you have a ChromeBook.

Type web store in Google Chrome search window.

Type Sphero edu in �Web Store search window.

Install and Launch App.

3 of 56

Robots

A robot is a machine—especially one programmable by a computer— capable of carrying out a complex series of actions automatically. Robots can be guided by an external control device or the control may be embedded. Robots may be constructed to take on human form, but most robots are machines designed to perform a task with no regard to how they look.

Robots have replaced humans in performing repetitive and dangerous tasks that humans prefer not to do, or are unable to do because of size limitations, or that take place in extreme environments, such as outer space or the bottom of the sea.” [Wikipedia]

The Sphero computer on board is a 75 MHz ARM Cortex M4.

4 of 56

Sphero Edu Application (click to play the video)

5 of 56

To launch from the Desktop, click the Sphero Edu icon.�Create/Sign-in to account. First, practice how to Drive.

6 of 56

Hold computer next to a robot. Choose the one with the most bars.�Flash colors to verify connection.�AIM first!!�Explore all the Driving options.

ALWAYS AIM FIRST!!

7 of 56

Programming, or coding, allows you to control the colors and motion of a robot by creating a list of actions, which can be replayed over and over.

Programs and Activities created by

Sphero and the Community.

8 of 56

9 of 56

Color

Color seems like a simple concept. The three kinds of photo-receptors in the human eye respond most to yellow, green and violet light. The difference in the signals received enables the brain to differentiate a wide range of colors, being most sensitive to yellowish-green light and to variations in hues in the green-to-orange region.

The most common computer color model is RGB, which combines Red, Green and Blue weights to encode a color. Typically, the values are encoded as 0 to 255 with (0, 0, 0) as black and (255, 255, 255) as white. Note that the range of numbers that can be stored in a computer storage byte (8 bits) is 0 to 255. The Sphero environment implements a color-picker that inserts the RGB numbers automatically.

Check out the following web link for RGB color values.

10 of 56

Code a program to display colors. Drag and drop blocks from Controls and Lights.

11 of 56

  1. LED (light-emitting diode is the main light).
  2. “back LED” is only blue, but can vary in brightness from 0 (off) to 255.
  3. Alt-Click pops a menu to delete or dup a block.
  4. Drag the blocks to join them together.
  5. Now drag the blocks to separate them again.
  6. Finally, put the blocks together, connect a robot,�then click START. It is ok to leave the robot in the�cradle as we are not moving the robot.
  7. Try changing the color, then restart the program.
  8. Use the “delay” block from Controls to show�two colors with a pause of 2 seconds between.
  9. Add the “strobe” and “fade” blocks to the code,�one at a time, then experiment with the options�until you are familiar with their capabilities.

12 of 56

Learning to Code poop

Coding is like any other science. You MUST learn the special vocabulary words, such as LED, delay, strobe or fade. You MUST learn the rules!! For example, having a negative brightness is illegal. In some cases, a program with an illegal setting will lock up or “crash” a device.

Finally, you must learn a science’s notation. Sphero supports block-programming pictures and the more advanced JavaScript text.

The goal of these lessons is to walk a students through Sphero’s vocabulary, rules and notation. Programming is a separate topic in which a student takes a word problem and breaks it down into coding steps that implement a solution.

13 of 56

  1. Learn about Sounds by using�the “play” and “speak” blocks.
  2. Sound is played on the host�computer so be sure that�the volume is up and that�a headphone is active.
  3. The BB-8, if you have�one, has special Star�Wars sounds.
  4. Type any text in a�“speak” block to play it.
  5. The “continue” option is�used when the sound�should overlap the next�action, e.g. fading in the�example.

14 of 56

Angles and Heading

Assuming you AIM the robot with the blue tail light�facing you, then a 0° heading is forward, 90° is right, 270°�is left, and 180° is backward. The little circle °�superscript indicates a zero-degree angle.�An angle is the figure formed by two rays, called�the sides of the angle, sharing a common endpoint,�called the vertex of the angle.

Blue AIM Dot

For Sphero, Ray 1 is drawn�from the center of the Sphero�to the 0° position on the sphere.��Ray 2 is the heading, or the�direction the Sphero should travel.

Listen to the Khan Academy lesson onangles and do the practice.

15 of 56

  1. Learn about Movements blocks by trying “roll”, “stop”,�and “spin”. A BB-8 can play iconic Star Wars Droid�animations that combine movement, lights and sound.
  2. Use low power for experiments.
  3. AIM first!!
  4. Remove robot from�cradle and set on�the floor.
  5. Be aware that if the�robot hits an obstacle�hard enough, it will lose�its AIM.
  6. Pick up the robot.�You can feel it trying to right itself if you twist it; that is stabilization in action. When stabilization is false and you power the motors, the robot will not balance, resulting in possible unstable behaviors like wobbly driving, or even jumping off the ground if you set the power very high.

16 of 56

Move Sphero in a Square Pattern (click to play the lesson)

17 of 56

Learn about Simple Loops (click to play the lesson)

  • Refactor is a common term used by developers to refer to improvements in the way code is written while still making sure it performs the same actions.

18 of 56

Challenges

  1. Code the robot to go forward, flash a light, and go backward.
  2. Code the robot to travel a square that is 2 feet on a side.
  3. Code the robot to flash Red, Green, Blue, White, each for one second.
  4. Code the robot to display the primary colors and to speak each name.
  5. Code the robot to sing the A B C song then try it out with kindergarten kids.
  6. Put the robot inside an upside-down paper cup. Tape a marker to the side. Put paper on the floor and code the robot to draw a figure or to write a name.
  7. Put a tape measure on the floor, then code the robot to stop at one-foot intervals and flash a light each time for a distance of five feet.
  8. Code the robot to travel in a triangle shape.
  9. Tape a sheet of construction paper to the floor and mark a start line. Have every student code the bot to land on the paper, but no trial runs! Then have every kid run their code and measure the closest approach.

19 of 56

Activities

  1. Draw a maze on the floor with tape then time students who drive the course.
  2. Set up a large oval race track. Mark a different erasable marker dot on each bot. Have a four-lap race with two or more bots.
  3. Copy Hot Potato to a bot and play the game with a group of kids.
  4. Draw a big circle with tape on the floor. Put all the bots inside then have the kids play Sumo Wrestling. Any bot that travels outside the circle is “out”.
  5. Set up a target circle or separate target areas with point values. Two teams of multiple students each, take turns trying to score by landing on points. Limit each play to a fixed number of seconds.
  6. Draw a big circle with tape on the floor. Scatter LEGOs or other objects within the circle, possibly with different point values. Students have a fixed time limit to move as many objects as possible outside the circle.

20 of 56

Variables

The next level of coding introduces the terms “constant” and “variable” names. Coders can choose a name, associate (or assign) a value to that name, then the name can be used in any other block in place of a number.

A constant is a name for which the assigned value never changes. One use of constants is to parameterize a program. Assume that the color “Red” is used multiple times in a program. By defining a constant name and using the name instead of “Red”, the color can be updated by simply re-assigning a different color to the name. The change is much easier than tracking down all uses of “Red”.

A variable is a name for which the assigned value changes during execution.

Name Assign value

21 of 56

When learning to code, study blocks by observing their actions. Some blocks, like variables, do not have observable actions. Make hidden things visible by using the “speak” block to say their values.

There are four choices for Sphero values and hence�variables: String ( “hello” ), Number ( -6 or 11.003 ),�Boolean ( true or false), and Color ( use Color Picker ).

Rule: variable names must begin with a letter.

Rule: a variable can only be set to a value that matches� its creation setting. Note that the shape (square� etc.) enforces matching i.e. a square peg only goes� in a square hole.

22 of 56

The “speak” block only says Strings. How to “speak” the other values?

Use “build string” from�the Operators tab.

The empty string block�can be set to a prefix or left blank. The white pencil icon�pops a dialog to add a value blank, which can be filled with�a direct number or a variable name block.

The little trash can icon over the blanks can be clicked�to delete an item.

Rule: Multiple values of any type can be mixed and are joined� in the order listed on a single “build string” block.

23 of 56

Enter the program and Start it�without change.

Now change the variable names�and their values one at a time.

Change the first three “build string”s�to just one with three parts.

Now insert a new “speak word” in�the middle. Then change the first�set block from Hello to a different�string. Observe that both uses of�the variable word are now updated.�Cool!

24 of 56

Built-in Variables, click the Sensors tab

back LED

brightness 0-255

distance

since program start in centimeters

heading

in degrees 0-359. Spin block does not set heading if Speed is zero.

main LED

color

speed

target robot speed-255 to +255

time elapsed

since program start in seconds

Insert a roll block with a speed and heading then Start the program. Remember to AIM. The robot will “speak” the result of the “roll”. Measure the distance.

25 of 56

Operators

The Sphero is lots more than flashing lights and sound. It contains a�powerful arithmetic processor. Common operators are addition ( + ),�subtraction ( - ), multiplication ( * ), division ( / ), power of ( ^ ), and�remainder after division ( % ).

Substitution Rule: Any block that computes a value (number or�Boolean) can be substituted in any other block that has a matching�number (oval) or Boolean (hexagon) slot.

Again, use the “speak” block to experiment with the calculations�performed by an Operator block.

26 of 56

Experiment with different numbers, both integer ( 6 -8 ) and real ( 1.5 -0.3 ).�Real numbers are referred to as “floats” in some blocks.

27 of 56

Expressions

  1. Rules: Operator blocks can be nested. The innermost blocks are calculated first.
  2. Example: 3 + num1 * 4
  3. Code num1 * 4 + 3 and speak the answer.
  4. Code (3 + ( 5 - num1 )) and speak the answer.
  5. Add a new Number variable named “squareSide” and set it to 10.�Code squareSide ^ 2 and speak the answer as Area of Square.
  6. Add a new Number variable named “temperatureF” and set it to 212.�Code ((temperatureF - 32) * 5 / 9) and speak the answer as degrees Centigrade.
  7. Add a new Number variable named “radius” and set it to 10.�Code ((radius * 2) * 3.14156) and speak the answer as Circle Circumference.

28 of 56

Square Turn Challenge

  1. Remember the earlier two video exercises: 1) travel in a square and 2) use a loop block to travel in a square?
  2. Create a “degrees” variable, which is initialized to zero.
  3. Re-code the program to use the new variable.
  4. Remember that the Sphero maintains the same 0° orientation no matter which way it turns or how it rolls with different headings; therefore each turn requires a heading that is 90° larger than the previous turn. The “heading” variable maintains the current direction of travel.

29 of 56

Comparison Operators

We learned about Number operators that calculate a Number result, such as add, on two Numbers. The Comparison operators return a Boolean�(true or false) result that indicates whether the first Number is�greater, less etc. in relation to the second Number.

Comparator

Boolean Result

Comparator

Boolean Result

3.5 === (2.1+1.4)

equal true

7 === 8

false

8 !== 7

not equal true

3.5 !== 3.5

false

8 < 7

less than false

7.5 < 8

true

9.65 <= 9.65

less than or equal true

9.65 < 10

true

8 > 7.5

greater than true

7.5 > 8

false

8.3 >= 7

greater than or equal true

8.3 >= 8.3

true

30 of 56

Moving until a Comparator is True

  1. The builtin variables can be compared�to determine when a condition is�met, such as traveling a certain�distance.
  2. Use “loop until” to keep the robot�going until a comparison is true.

distance

since program start in centimeters

heading

in degrees 0-359. Spin block does not set heading unless Reset AIM.

speed

-255 to +255

time elapsed

since program start in seconds

Travel 24 inches. Experiment with different speeds, forward and backward. Observe that speed is measured by turns of the two drive wheels, which do not always match the external world view, particularly at higher speeds.

Modify the program to use the other three variables.

31 of 56

Running a Program until Stopped by the Host

  1. Use “loop forever” to run a program�until the Stop button is clicked.
  2. Observe that the Spin block can be used to travel�in a curve or a circle. The example spirals out/in.

Infinite Spriral Pro�by ChrisLe5512

32 of 56

Other Useful Operators (Use “speak” to explore furth\er.

Convert real numbers to integers e.g. round(2.5) is 3.

Calculate a random integer or real number in a given range.

Trigonometric functions calculated in degrees. Click here to review.

33 of 56

Control “if then” Conditional Test

The true or false check in �the “loop until” is referred to as a conditional test. Instead of testing continually as in the “loop”, it is often desirable just to perform a single test. Consider the following code that chooses a random integer 1, 2 or 3. Then uses three conditional tests to convert the three numbers into three colors.

If the Condition is true, the list of actions is executed; otherwise they are ignored.

34 of 56

Control “if then else” Conditional Test

The second form, the “if then else” block executes the “then” block list if the condition is true or the “else” block list if the condition is false.

Add a “loop forever” block and copy the blocks into the loop. Execute the code.

Modify the program to “speak” three different phrases instead of flashing colors.

35 of 56

Movement Direction

Sphero uses the Cartesian coordinate system to track�movement. Review xy coordinates at Khan Academy https://www.khanacademy.org/math/basic-geo/basic-geo-coord-plane/coordinate-plane-4-quad/v/the-coordinate-plane

As mentioned earlier, Sphero records distance in centimeters (abbreviated cm.).�However, there is also a location sensor that calculates the�distance traveled from the robot’s starting point (0,0) in the�X Y and TOTAL directions. Observe that if a line is drawn�from the current x,y point to 0,0, a right triangle is formed.�The “total” location value is the length of the triangle’s�hypotenuse. Write a program to travel in the X direction,�then the Y. Now measure both XY distances and the�hypotenuse, then compare to the location values.

36 of 56

Velocity

Sphero’s “roll” block has slots for heading (in degrees), speed (cm/sec) and time in seconds. Speed is a synonym for velocity. If the robot’s speed is 10 cm/sec and it travels for 10 seconds, you would expect it to travel a distance of 10 cm/sec x 10 sec,�or 100cm (observe that the sec in the denominator of the speed fraction is canceled by the sec in the numerator of the time fraction).

Sphero “rolls” based on a speed that�represents the hypotenuse of a right triangle.�The speed actually has a speed component�both in the X direction and in the Y �direction. XY speeds can be positive or�negative, which is useful in comparisons�to determine direction. See next example.

Sphero achieves roll velocity gradually.

37 of 56

Write a Program to Speak Sphero’s Direction

When coding, write and test a bit at a time. DO NOT code the whole thing, then test. I tried this program, but it didn’t work as expected. The robot is going right only if xvel>yvel AND xvel>0. The AND Comparator is the symbol &&. A (Boolean && Boolean) is true only if both operands are true. Another common Boolean Comparator is OR (|| on Sphero). A (Boolean || Boolean) is true only if either operand, or both, are true.

38 of 56

Speak Direction

Code the listed program and try it out. Try moving Sphero straight forward and straight right for best results.

Add the “going left” and “going backward” cases to the code.

39 of 56

Acceleration

The Sphero’s velocity is measured in cm/sec. In order for a robot to achieve a velocity of 100cm/sec from a rest position (0cm/sec), something must happen to “accelerate” the robot. The Sphero computer controls the motors to achieve the “speed” listed in the “roll” block.

Sphero acceleration is measured at any instant by querying an accelerometer sensor. The “total” value is measured in Gs (or the down force of Earth’s gravity 9.8m/s2). Look at the graph, which shows the change in�velocity of a falling body at 1 sec. intervals.

Acceleration is measured both in the XY direction and�also up and down (the Z direction). Location cannot be�measured in the Z direction because the motors can’t�propel the robot in that direction. But you can throw a robot in the Z direction.

40 of 56

Acceleration

The “total” value is always positive and represents the hypotenuse with one side from 0,0,0 to x,y,0 and the second side from x,y,0 to x,y,z.

The x,y,z values can range from -8 to +8 Gs. The next program tries to display a color to reflect the direction of the current acceleration.

41 of 56

Blink Acceleration

Experiment with the x-axis, y-axis, z-axis, total, and vertical options.

42 of 56

Roll Pitch Yaw Orientation

The sensors discussed so�far measure distance,�location and acceleration.

The Orientation sensor�measures the degrees of rotation�for forward-backward (pitch) and�side-to-side (yaw), as well as�the roll (clockwise). Be aware that any, or all, of these rotations can occur even if there is no motion in any direction.

The next example updates the heading from 00 by increments of 100, delays briefly, then speaks the current yaw value in degrees.

43 of 56

Speak Yaw Orientation

44 of 56

Roll Yaw Spin Rate

The gyroscope�sensor measures�the angular velocity�(in degrees/second)�of a Sphero robot.

A gyroscope is used�in an aircraft, for example, to indicate the rate of rotation around the aircraft’s roll axis. As an aircraft rolls, the gyroscope measures non-zero values until the aircraft levels out, whereupon it would read a zero value.

45 of 56

Blink Light on Yaw Rate

Light glows brighter with higher spin velocity

Experiment with the different gyroscope options.

46 of 56

Events

One of the problems with testing for conditions is that they may be true only for a short time. Sphero defines three blocks that perform reliable tests for three useful conditions. The event blocks stand alone and are executed when the event occurs, then the main program continues from the point where it was interrupted.

Rule: “loop forever” should never be used in an “on” event’s code list.

Event

Explanation

On collision

Sphero hits an obstacle and is bounced back by a hand or foot

On freefall

Sphero is dropping from a height

On landing

Only triggered if “freefall” occurs first

47 of 56

On freefall and landing

Works best for throw and catch.

48 of 56

On collision (copy of Sphero Pong)

Two people bat (gently) the ball back�and forth. The receiver has to tap the�ball away to trigger the “collision” event.

49 of 56

Functions

The Sphero App has built-in program reuse, just use the search by keyword or tag and then apply filter options, such as “Likes”. However, what if only a part of the program is needed? It can be error-prone to try to extract just a piece of a large program.

The solution is to construct programs so that the useful pieces are isolated as Functions, which can be reliably copied from one program to another.

A further benefit of function-oriented coding is that a function can be reused multiple times by just placing a single function block at the points of use.

50 of 56

What is a Function?

A Function is a name that stands for a block list. When a function block is encountered during execution, control transfers to the function’s block list. When the end of a function’s block list is reached, execution transfers back to the point of call.

51 of 56

SpeakAndBlink Function Example

52 of 56

Sphero Knows Function Reuse (Search Storytelling Functions)

Make a copy for yourself.

53 of 56

Use Storytelling Functions

  1. Choose one of the� functions
  2. Right-click or�Alt-click to Copy
  3. Right-click on any�block to Paste onto �canvas of a test �program.
  4. Insert the�Function-Name�block in the test
  5. Try test program
  6. Explore some of the other 39 Storytelling Functions

54 of 56

Parameters and Arguments

The ColdWater function in the example spins the motors nine times. What if we needed a different count, such as 3 or 12? Simple. Just change the “loop” block.

But what if we need to use ColdWater twice, once with a count of 3 and once with a count of 12?

The solution is to “Add a block label” named count followed by an “Add number” parameter.

55 of 56

Parameters and Arguments

Parameters

Arguments

A parameter is part of a function definition that expands the function’s utility.

An argument is part of a function-use block that specifies values that control a function’s block list.

Be aware that the two terms are often used interchangeably in the literature.

56 of 56

Functions that Return Values

  1. Define a unique variable name to store the return value.
  2. Pick a name that obviously ties it to the function.
  3. After calling the function, the variable will be set.
  4. Complex expressions, which are used more than once, are often clearer if defined as a function.