Introduction to Coding
by Bob Cook, GA
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.
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.
Sphero Edu Application (click to play the video)
To launch from the Desktop, click the Sphero Edu icon.�Create/Sign-in to account. First, practice how to Drive.
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!!
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.
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.
Code a program to display colors. Drag and drop blocks from Controls and Lights.
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.
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.
Move Sphero in a Square Pattern (click to play the lesson)
Learn about Simple Loops (click to play the lesson)
Challenges
Activities
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
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.
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.
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!
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.
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.
Experiment with different numbers, both integer ( 6 -8 ) and real ( 1.5 -0.3 ).�Real numbers are referred to as “floats” in some blocks.
Expressions
Square Turn Challenge
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 |
Moving until a Comparator 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.
Running a Program until Stopped by the Host
Infinite Spriral Pro�by ChrisLe5512
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.
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.
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.
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.
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.
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.
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.
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.
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.
Blink Acceleration
Experiment with the x-axis, y-axis, z-axis, total, and vertical options.
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.
Speak Yaw Orientation
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.
Blink Light on Yaw Rate
Light glows brighter with higher spin velocity
Experiment with the different gyroscope options.
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 |
On freefall and landing
Works best for throw and catch.
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.
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.
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.
SpeakAndBlink Function Example
Sphero Knows Function Reuse (Search Storytelling Functions)
Make a copy for yourself.
Use Storytelling Functions
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.
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.
Functions that Return Values