Sphero BOLT JavaScript coding

Sphero / Robootika ja programmeerimine

Share on Social Networks

Share Link

Use permanent link to share in social media

Share with a friend

Please login to send this presentation by email!

Embed in your website

Select page to start with

9. JavaScript programs are written in a text language.

5. Sphero Edu Application (click to play the video)

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

1. Introduction to JavaScript Coding by Bob Cook, GA VIDEO

46. Sphero Knows Function Reuse (Search Programs for “Storytelling”) Make a copy for yourself, then click JavaScript to select a text function and then to copy it into your program. VIDEO

7. ALWAYS AIM FIRST!! 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.

8. 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.

16. 1. Click back-arrow to return to the Demo program’s page. 2. Click the robot’s name to Sleep when not in use or to turn off when returned to the charging cradle for the day. 3. Firmware updates will occur automatically several times a year.

60. 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 3D plot shows how velocity (blue line) changes as an acceleration force is applied at different intervals. 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.

38. 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 JavaScript code for any “block” program is displayed by a menu option. 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 call at the points of use.

37. Variable Assignments Variables “remember” values from one part of a program to another. To update a variable, use assignment to set a new value. Assignment Statement Rules variable = variable; variable = constant; variable = expression; variable++; or ++variable; //shorthand for variable = variable + 1; variable--; or ---variable; //shorthand for variable = variable - 1;

3. 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.

27. Sphero Square Pattern 6. Click on Sensor Data to view a record of a robot’s sensor data. “Location” records movement. 7. Observe the rounded corners. The physical world has affected the abstract solution. It takes the Sphero about a second to rotate the drive wheels to a new position. 8. Try inserting “await delay(2)” after each “roll”. 9. Observe the improvement. Measure how well the robot performs at higher and lower speeds, and with different durations.

15. Code a program to display a color. 1. Read the manual to learn the syntax and semantics of Lights. 2. Copy and Paste an example from the manual , then try it and study it. 3. Then change the example to prove that you understand the concepts. Choose robot with the most bars. Observe that the light flashes so fast that it is hard to tell if the code worked and that the Stop button must be pressed to end the program.

13. Learning to Code 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 JavaScript text coding as well as the simpler picture, or block, coding. The goal of these lessons is to walk a students through Sphero’s vocabulary, rules and notation. Programming is an advanced topic in which a student takes a word problem and breaks it down into coding steps that implement a solution while balancing implementation options, such as data structures and algorithms.

18. Syntax and Semantic Errors 1. Always copy correct code, then modify for a new purpose. Avoid typing! 2. The system will notify you of mistakes with a position marker ^ and a message. 3. Sometimes, the message part may be useless or even misleading. 4. Check both the syntax and semantics where the marker ^ indicates. 5. Try deleting, changing or adding characters to your code to explore error messages. 6. Type ctrl-z to undo any recent change.

67. Local versus Global Name Scope The scope of a name is all the places that it can be accessed. Rules : A name is known only in the function in which it is var-defined (local scope). A var-name defined outside a function (global scope) is know in all functions in which the name is not re-defined. In the next example, players alternate turns. A “turn” variable is incremented on every turn. An odd value indicates player one, even player two. The “turn” variable cannot be declared inside a function because local-scope variables become undefined on function return. Thus, “turn” must be defined as a global-scope variable. Rule : Declare variables and functions before they are used.

2. Why learn JavaScript? ● Popular programming language used to animate web pages ● Easy to learn ● Prepare for a life-long computer career Why Sphero? ● Learn two valuable careers in one -- robotics and coding ● Code lights, sound and motion instead of numbers and letters ● Buy a toy, computer, and learning application all in a single package

34. More about Simple-Loop Pattern for (var loop1=0; loop1 < 4; ++loop1) { } //end loop1 1. Observe that the “variable” loop1 changes value, in sequence, from 0 to the upper-limit-number minus 1; e.g. 0 1 2 3 in the example. 2. Remember that a variable’s name can be used as a substitute for any number. 3. Thus, any sequence that can be matched to 0 1 2 ... can be calculated using a loop’s variable name. Example: 0 1 2 3 0° 90° 180° 270° How to calculate one from the other? * is the multiply symbol in JavaScript 0*90=0 1*90=90 2*90=180 3*90=270

44. 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 9? Simple. Just change the “loop” block to 3 or 9. But what if we need to use coldWater twice, once with a count of 3 and once with a count of 9? The solution is to add a parameter, which is then referenced in the function’s loop-statement to achieve different purposes. Argument Parameter

62. 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 roll (clockwise rotation). 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 0° by increments of 10°, delays briefly, then speaks the current yaw value in degrees.

14. 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 .

29. Learn about Simple Loops 6. If we only knew the “heading” of the robot, we could just change the heading by 90° each time the loop repeats the code. 7. The JavaScript/Sphero feature getHeading() retrieves the target heading angle, in degrees, and can be used any place that a number is allowed. 8. Copy the example to roll in 4 directions. Remember that the “heading” changes value as the robot turns. 9. Oops! Observe that the robot turns right, not straight, to start rolling. The correction is to insert a “setHeading(270);” statement after line1 and before line 2. The effect will be that the initial heading will be set to 270° + 90° = 360° = 0°. Now the two programs are identical, but using the pattern is simpler, and much more flexible. Change to draw a pentagon.

33. A variable is a name for which the assigned value changes during execution. var counter = 10; //name can be set to many different values Rule: Constant and variable names must start with a letter, underscore _, or dollar sign $ and contain those characters as well as digits (0-9). Because JavaScript is case sensitive, a name with an uppercase "A" through "Z" does not match the same name with a corresponding lowercase letter "a" through "z". When learning to code, study code options by observing their actions. Variables may not have observable actions. Make hidden things visible by using the “speak” block to say their values. Trying to speak anything but a string will not work! However, the phrase “”+22 will convert any value to words.

11. Semantics -- the meaning of sentences ● last two sentences in the previous example do not make sense. ● The semantics of a language define the meanings or actions, of sentences. ● "blue" and "the" are both adjectives, but cannot be used interchangeably ● New programmers often fail because they use language features without knowing their effect. ● Always try out new language statements in a separate test program before adding to a larger program.

17. 1. “Code a program to display a color” caused a color to display briefly and then the robot paused waiting for the Stop button to be pressed. 2. Better problem description: Code a program to display a color for 2 seconds and then exit. How to wait for 2 seconds? How to exit a program? Look at the Controls section in the Manual. setMainLed() changes the color of the main LED (Light-Emitting Diode) light, or the full matrix on Sphero BOLT. Set using RGB (red, green, blue) values on a scale of 0 to 255. For example, a green color is coded as setMainLed({ r: 90, g: 255, b: 90 }) await delay(4) delays execution of any additional code for a number of seconds. exitProgram() ends a program, the same as tapping the Stop button.

39. What is a Function? A Function is a name that stands for a list of JavaScript statements. When a function call is encountered during execution, control transfers to the function’s list. When the end of a function’s list is reached, execution transfers back to the point of call. The most common use of functions is the getter/setter pattern, which get and set the values of variables that are “private” to the Sphero runtime. A “getter” function can be substituted anywhere that a number is legal. The previous examples have used getHeading, setHeading, getRandomColor, setMainLed, and setBackLed. As you start to type a name, the environment prompts you with a list of known matches.

21. 1. Learn about Sounds by using the “play” and “speak” options. 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 the “speak” option to convert text to speech. 5. The “continue” option is used when the sound should overlap the next action, e.g. fading in the example. Ambient sounds are typically played with the “continue” option to set a “location vibe” for a program. 6. Sounds can be played on the Sounds manual page.

35. 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 ( % ). Again, use the “speak” block to experiment with the calculations performed by an Operator block. Experiment with different integers and reals (floats). 3 + 4 = 7 8 - 5 = 3 6.1 * 4 = 24.4 56 / 7 = 8 2 ** 3 = 8 56 % 9 = 2

56. Velocity Sphero’s “roll” function has argument 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 the requested roll-velocity gradually, not instantaneously.

20. Copy code for new features, then modify to explore 1. Even though the example shows all the new options at once, they were added and tested one at a time. 2. Change the values and colors to explore further. 3. set back LED to brightest blue 4. set main LED to a random color 5. fade (transition) from green to blue over 3 seconds 6. strobe (blink) red 15 times over 3 seconds set seconds here set number of blinks in two places

32. Constant 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, Boolean or string. 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”. const Color = { r:255, g:0, b:0}; setMainLed(Color); Name Assign value

59. 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” function. Acceleration is a force that changes velocity. 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/s 2 ). 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.

54. Movement Location from the Origin 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-plan e-4-quad/v/the-coordinate-plane As mentioned earlier, Sphero can calculate the total distance traveled from the starting position in centimeters (abbreviated cm.). However, there is also a location sensor that calculates the distance from the robot’s starting point (0,0) to the current position in the X Y directions. Observe that if a line is drawn from the current x,y position 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 a certain distance in a diagonal direction. Now measure both XY distances and the hypotenuse, then compare to the location values.

12. Do-Nothing Sphero JavaScript Program async function startProgram ( ) { // Write code here } Syntax: { } must match up Semantics: Words are case sensitive -- Async or startprogram will produce an error Syntax: multiple blanks are allowed except within words or multiple symbols, such as // Syntax: English, or other language, comment to describe how code works single-line: // any characters from the // to the end of the line are ignored multi-line: /* any characters, even across multiple lines, are ignored up until the asterisk-slash combo */

31. 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.

28. Learn about Simple Loops ● 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. 1. Observe that the code turns the robot 90 ° at each step. Any regular polygon will have a similar step angle. What if we wanted to draw an octagon or decagon? That’s a lot of repeated code? 2. The solution is to use a simple-loop pattern. A pattern is code that can be duplicated with simple changes to implement a more complicated solution. 3. Always try out new features in the simplest possible code. The code below shows the simple-loop pattern, which repeats the code between the { and the } 4 times. 4. To use the pattern, simply change 4 to the desired number of repetitions. 5. Execute and then change the code to learn about loops.

36. Expressions 1. Rules: Operators can be nested inside parentheses ( ). Always add parentheses to expressions with multiple operators to control the order of evaluation. 2. Example: var num1 = 6; (3 + (num1 * 4)) 3. Code ((3 + num1) * 4) and speak the answer. Remember “” + (...) to convert. 4. Code (3 + ( 5 - num1 )) and speak the answer. 5. Add a new variable named “squareSide” and set it to 10. Code squareSide ** 2 and speak the answer as Area of Square. 6. Add a new variable named “temperatureF” and set it to 212. Code ((temperatureF - 32) * 5 / 9) and speak the answer as degrees Centigrade. 7. Add a new variable named “radius” and set it to 10. Code ((radius * 2) * 3.14156) and speak the answer as Circle Circumference.

45. Parameters and Arguments A parameter is part of a function definition that expands the function’s utility. An argument is part of a function call 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 (Never async!!) Rule: Use the “return expression;” statement to return a value from a function. If the function is used in an expression and the function does not execute a “return value” statement, the value “undefined” is returned. Functions that return values cannot contain any references to “await” Sphero functions. The “return;” statement can be used to exit a function that does not return a value. Arguments Parameters

4. 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.

30. 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.

42. User-defined Functions ● Create to make a useful list of statements easy to use for others ● Create when you find yourself typing the same code over and over. This differs from loop-creation in that loop code is repeated one group of statements after another. Statement-lists in functions are used repeatedly, but in different parts of the cod Rules : “Name” must begin with a letter, _ or $. The word “async” must be added only if the “Statements” contain an “await”. function [async] Name() { Statements }; var Name = [async] function( ) { Statements };

68. Events One of the problems with if-testing for conditions is that they may be true for only a short time. Sphero defines six functions that perform reliable tests for six useful conditions. The event functions stand alone and are executed when the event occurs, then, after the event code completes, 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 gyromax Spinning greater than 5.5 revolutions per second or the 2,000° limit. On [not] charging Putting/removing from the cradle or [un] plugging from the computer

53. Jump Explosion async function startProgram() { await explosion(2); // Write more code here exitProgram(); } async function explosion(duration) { await Sound.Effects.Explosion.play(false); setMainLed({ r: 255, g: 157, b: 0 }); await rawMotor(255, 255, duration); setMainLed({ r: 255, g: 15, b: 0 }); await fade({ r: 255, g: 26, b: 0 }, { r: 0, g: 0, b: 0 }, duration/2); }

26. Move Sphero in a Square Pattern, returning to the origin 1. A square figure has 4 equal-length sides in which each corner is a 90 ° angle. 2. Always implement complicated code in parts. What is simpler than 4 movements? Answer: Just one. 3. Code the robot to roll forward (0 °) for one second. Always choose slow speeds, such as 60, when developing code. Higher durations will travel forward. 4. One of my common errors is to forget the “await” prefix, when required. 5. Now add three more “roll” statements. Remember that angles are relative to the origin by default.

64. Yaw Left-Right 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. async function startProgram() { await speak('spin clockwise', true); await delay(0.5); await speak(buildString('yaw spin is', getGyroscope().yaw, 'degrees per second'), true); exitProgram(); }

55. Movement Location The location where the robot is in space (x,y) relative to the origin is measured in centimeters. This is not the distance traveled during the program, it is the offset from the origin (program start). Again, the accuracy is variable. getLocation().x is the right (+) or left (-) distance from the origin of the program start, in centimeters. getLocation().y is the forward (+) or backward (-) distance from the origin of the program start, in centimeters. Math.sqrt((getLocation().x ** 2) + (getLocation().y ** 2)) is the positive, total distance from the origin of the program. async function startProgram() { await roll(45, 60, 2); // positive right diagonal direction await speak("x "+getLocation().x+" y "+getLocation().y+" total "+ Math.sqrt((getLocation().x ** 2) + (getLocation().y ** 2)), true); // Write more code here exitProgram(); }

10. What is a Programming Language? language -- collection of sentences defined by a grammar and its vocabulary . vocabulary -- accepted words e.g. fbx not ok in English, $%# not ok in JavaScript grammar -- rules to create a sentence. A JavaScript program is one long sentence. Example Grammar Sentence -- Adjective Noun Verb Adjective Adjectives -- the a blue red white Nouns -- cat dog bird Verbs -- is eats Example Sentences the cat is red ← makes sense a bird is white ← makes sense blue dog eats the ← does not make sense a cat eats a ← does not make sense

66. Function Variables Programs so far have used numbers, Booleans, strings and color values. In JavaScript, functions can also be treated as data values that can be assigned to variables. The variable name can then be used as a synonym for its function value. async function speak1() { await speak("number 1", true); } async function speak2() { await speak("number 2", true); } async function startProgram() { var action = speak1; while (true) { if (getRandomInt(1, 2) === 1) { action = speak1; } else { action = speak2; } await action(); } }

71. On freefall and landing async function onFreefall() { setMainLed({ r: 6, g: 30, b: 255 }); await speak('helppp', true); } async function onLanding() { setMainLed({ r: 255, g: 1, b: 0 }); await speak('terra firma', true); } async function startProgram() { registerEvent(EventType.onFreefall, onFreefall); registerEvent(EventType.onLanding, onLanding); setStabilization(true); setMainLed({ r: 255, g: 250, b: 249 }); } Works best for moderately-high throw and catch.

70. GyroMax Example Spin the robot quickly to trigger a GyroMax event. async function onGyroMax() { setMainLed({ r: 255, g: 0, b: 0 }); await speak("gyromax", true); await delay(1.0); } async function startProgram() { setStabilization(false); registerEvent(EventType.onGyroMax, onGyroMax); setBackLed(255); while (true) { setMainLed({ r: 255, g: 255, b: 255 }); await delay(0.5); } //while true }

48. Moving until a Comparison is False 1. The builtin functions can be compared against to determine when a condition is met, such as traveling a certain distance. 2. Use a “while” loop to keep the robot going until a comparison is false. It repeats until the (Boolean) is false. getDistance() since program start in centimeters getHeading() in degrees 0-359. Spin block does not set heading if Speed is zero. getSpeed() -255 to +255 getElapsedTime() since program start in seconds Travel 36 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.

23. The JavaScript environment prompts you with the available options when a name is followed by a dot ( . ). async function startProgram() { await Sound.play(true); await Sound.ScienceFiction.play(true); await Sound.Animal.Cat.play(true) // Write more code here exitProgram(); } await speak(“Any sentence”, true) will speak a string of characters (enclosed by a pair of “) from your host device using a text-to-speech engine, in any language supported by your device. The wait/continue playback (true/false Boolean) delay option is handled the same as the Sound command. For example, to speak a sentence, use await speak(“Hello New York”, true) Punctuation in a sentence can be omitted. Unique Star Wars Droid Sounds are available using DroidName.Sound.Category.SoundName.play() . The droid names are written as BB8 , BB9E , and R2D2 and they can only be played on the intended Droid. The wait Boolean is not available. For example, to play the R2-D2 Burnout sound use R2D2.Sound.General.Burnout.play()

40. Some of the Sphero Getter/Setter Functions Description Getter Setter brightness 0-255 getBackLed() setBackLed(99); since program start in centimeters getDistance() in degrees 0-359. Spin block does not set heading if Speed is zero. getHeading() setHeading(270); color getMainLed() setMainLed({ r: 90, g: 255, b: 90 }); random color getRandomColor() target robot speed-255 to +255 getSpeed() setSpeed(60); since program start in seconds getElapsedTime()

24. 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 on angles and do the practice .

63. Speak Yaw Orientation async function startProgram() { var head = 0; while (true) { setHeading(head); await delay(0.5); await speak(buildString('yaw is', getOrientation().yaw, 'degrees'), true); head = head + 10; await delay(0.025); } } Provides the tilt angle along a given axis measured by the Gyroscope, in degrees. getOrientation().pitch is the forward or backward tilt angle, from -180° to 180°. getOrientation().roll is the spin (twist) angle, from -90° to 90°. getOrientation().yaw is the left or right tilt angle, from -180° to 180°.

19. More Color Options setBackLed() sets the brightness of the back aiming LED, aka the "Tail Light". This LED is limited to blue only, with a brightness scale from 0 to 255. For example, use setBackLed(255) to set the back LED to full brightness. setMainLed(getRandomColor()) chooses a random color value from the full spectrum of 0-255 on each color channel. On Sphero BOLT, this command sets all 64 pixels on the LED matrix to the specified color. The “fade” option changes the main LED lights from one color to another over a period of seconds. For example, to fade from green to blue over 3s, use: await fade ({ r: 0, g: 255, b: 0 }, { r: 0, g: 0, b: 255 }, 3) The “strobe” option repeatedly blinks the main LED lights. The period is the time, in seconds, the light stays on during a single blink; cycles is the total number of blinks. The time for a single cycle is twice the period (time for a blink plus the same amount of time for the light to be off). Another way to say this is the period is 1/2 (or 0.5 as a decimal fraction) the time it takes for a single cycle. So, to strobe (or blink) green 15 times in 3 seconds, use: await strobe ({ r: 255, g: 57, b: 66 }, (3 / 15) * 0.5, 15) / is the JavaScript division operator; * is the multiplication operator

57. 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) expression is true only if both operands are true. Another common Boolean Comparator is OR (|| on Sphero). A (Boolean || Boolean) expression is true only if either operand, or both, are true. async function startProgram() { var xVelocity, yVelocity; while (true) { await speak("Move Sphero in any direction.", true); await delay(0.5); xVelocity = getVelocity().x; yVelocity = getVelocity().y; if (xVelocity > 0) { await speak("Moving right.", true); } else if (yVelocity > 0) { await speak("Moving forward.", true); } } // while true // Write more code here exitProgram(); }

52. Miscellaneous Motor Functions resetAim() resets the heading calibration (aim) angle to use the current direction of the robot as 0°, within a range of 0-360°. For example, use resetAim(90) to use the current right facing direction of the robot as 0°. setStabilization() turns the stabilization system on and off. Stabilization is normally on to keep the robot upright. When setStabilization(false) and you power the motors, the robot will not balance, resulting in possible unstable behaviors like wobbly driving, or even jumping if you set the power very high. When stabilization is off you can't use setSpeed to set a speed because it requires the control system to be on to function. Some use cases to turn stabilization off are: 1. Jumping: Set Motor Power to max values and the robot will jump off the ground! 2. Gyroscope: where you want to to isolate the Gyroscope readings rather than having the robot auto balance. await rawMotor() controls the electrical power sent to the left and right motors independently, on a scale from -255 to 255 where positive is forward, negative is backward, and 0 is stopped. This is different from setSpeed because rawMotor sends an "Electromotive force" to the motors, whereas setSpeed is a target speed measured by the encoders. For example, to set the raw motor to full power for 4s, making the robot jump off the ground, use await rawMotor(255, 255, 4) . Jumping will lose the current heading. rightMotorPwm() and leftMotorPwm() control the electrical power sent to the left and right motors independently, on a scale from -255 to 255. If you set both motors to full power the robot will jump because setStabilization(false) when using this command. Motor Power is different from setSpeed because rawMotor sends an "Electromotive force" to the motors, whereas setSpeed is a target speed measured by the encoders.

25. await roll() combines heading(0-360°), speed(-255-255), and duration (in seconds) to make the robot roll with one line of code. For example, to have the robot roll at 90°, at a speed 200 for 2s, use await roll(90, 200, 2). A negative speed rolls backwards. stopRoll() sets the speed to zero to stop the robot, however, it does not apply any braking so “stop” is somewhat of a misnomer. await spin() spins the robot for a given number of degrees over a duration (in seconds), with 360° being a single revolution. async function startProgram() { await speak("Spinning in a circle", false); await spin(360, 3); // Write more code here exitProgram(); } 1. Learn about Movements 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 to avoid slamming into obstacles. 3. AIM first!! Remove robot from cradle and set on the floor. 4. Be aware that if the robot hits an obstacle hard enough, it will lose its AIM. 5. 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 may show instability.

22. Sound Options await Sound.Category.SoundName.play(true) plays a sound from your host device. When a sound is played, if you use the true Boolean option, the program waits until the sound plays completely before continuing. Change to false to go to the next command immediately. If you want to use timing different than the wait/continue options, you can follow a true with a delay() command so the subsequent logic is delayed for the given duration. You can randomize all sounds by not declaring a Category and SoundName , such as await Sound.play(true) . If you declare a Category but leave the SoundName blank it will randomize in the given category, such as await Sound.Animal.play(true) Categories Ambience Mechanical Animal Personality Effects ScienceFiction Game Sports Water Storytelling EightBit Menu RobotTalk

47. Comparison Operators We learned about Number operators that calculate a Number result, such as add on two Numbers. The Comparison operators return a Boolean result (true or false) that indicates whether the first Number is greater than, less than 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

50. Control “if” Conditional Test The true or false check in the “while” loop 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 “if” actions are executed; otherwise they are ignored. async function startProgram() { var choice = 0; while (true) { choice = getRandomInt(1, 3); if (choice === 1) { setMainLed({ r: 255, g: 0, b: 0 }); } if (choice === 2) { setMainLed({ r: 0, g: 255, b: 0 }); } if (choice === 3) { setMainLed({ r: 0, g: 0, b: 255 }); } //end if choice await delay(1); } // end while true // Write more code here exitProgram(); }

58. Speak Direction Code the listed program and try it out. Try moving Sphero straight forward and straight right for best results. Be sure to AIM first. Add the “Moving left” and “Moving backward” cases to the code. async function startProgram() { var xVelocity, yVelocity; while (true) { await speak("Move Sphero in any direction.", true); await delay(0.5); xVelocity = getVelocity().x; yVelocity = getVelocity().y; if (xVelocity > 0 && xVelocity > yVelocity) { await speak("Moving right.", true); } else if (yVelocity > 0 && yVelocity > xVelocity) { await speak("Moving forward.", true); } } // while true // Write more code here exitProgram(); }

43. User Function Example async function startProgram() { await roller(); await coldWater(); await roller(); await coldWater(); // Write more code here exitProgram(); } async function roller() { await roll(0, 60, 1); }; var coldWater = async function() { await Sound.Water.Bubbles.play(false); for (var _i0 = 0; _i0 < 9; ++_i0) { setMainLed({ r: 28, g: 31, b: _i0 * 30 }); await rawMotor(-93, 93, 0.1); await rawMotor(93, -93, 0.1); await delay(0.025); } setMainLed({ r: 0, g: 0, b: 0 }); }; The “roller” function rolls the robot forward for one second. The “coldWater” function plays bubbles, changes light color and gyrates. The “startProgram” code is much easier to understand and change through the use of functions. We have not explained the “rawMotor” function, but we don’t need to in order to use “coldWater”.

69. On collision (copy of Sphero Pong) var turn = 0; async function startProgram() { setMainLed({ r: 255, g: 255, b: 255 }); registerEvent(EventType.onCollision, onCollision); await delay(1); setMainLed({ r: 61, g: 255, b: 0 }); setSpeed(80); } Two people bat (gently) the ball back and forth. The receiver has to tap the ball away to trigger the “collision” event. async function onCollision() { await Sound.EightBit.Blurp.play(false); setMainLed({ r: 255, g: 45, b: 0 }); stopRoll(); await delay(0.5); turn = turn + 1; if (turn % 2 === 1) { setHeading(getRandomInt(150, 210)); } else { setBackLed(0); setHeading(getRandomInt(-30, 30)); } setSpeed(80); setMainLed({ r: 61, g: 255, b: 0 }); }

65. Blink Light on Yaw Rate Light glows brighter green with higher spin velocity in a clockwise direction; brighter red with a higher spin velocity in a counter-clockwise direction. Provides the rate of rotation around a given axis from -2,000° to 2,000° per second. getGyroscope().pitch is the rate of forward or backward spin, from -2,000° to 2,000° per second. getGyroscope().roll is the rate of left or right spin, from -2,000° to 2,000° per second. getGyroscope().yaw is the rate of sideways spin, from -2,000° to 2,000° per second. Experiment with the different gyroscope options. async function startProgram() { setStabilization(false); while (true) { // positive is counter-clockwise // negative is clockwise // maximum value is 2000 degrees/second if (getGyroscope().yaw > 1) { // 2000 deg/sec divided by 255 = 7.84 // 255 is the maximum color value // results in a value between 0.0 and 255 // thus, red gets brighter as spin increases setMainLed({ r: (getGyroscope().yaw / 7.84), g: 0, b: 0 }); } else { setMainLed({ r: 0, g: (getGyroscope().yaw / -7.84), b: 0 }); } await delay(0.25); } //while true }

51. Control “if -- else if -- else” Conditional Tests The second form, the “if -- else if -- else” statements, execute the “if” tests until one is found that is true, then its actions are performed. If none of the conditions are true, the “else” actions are performed. As many “else if” sections as needed (or none) may be added to code any number of tests. Copy the statements. Execute the code. Modify the program to “speak” four different phrases instead of flashing colors. async function startProgram() { var choice = 0; while (true) { choice = getRandomInt(1, 4); if (choice === 1) { setMainLed({ r: 255, g: 0, b: 0 }); } else if (choice === 2) { setMainLed({ r: 0, g: 255, b: 0 }); } else if (choice === 3) { setMainLed({ r: 0, g: 0, b: 255 }); } else { setMainLed({ r: 0, g: 255, b: 255 }); } //end if choice await delay(1); } // end while true // Write more code here exitProgram(); }

49. Running a Program until Stopped by the Host 1. Use “while(true)” to run a program until the Stop button is clicked. 2. Observe that the spin function can be used to travel in a curve or a circle. The example spirals out, then in. Infinite Spriral Pro by ChrisLe5512 async function startProgram() { var spin_time = 1; setSpeed(64); await delay(0.25); while (true) { setMainLed({ r: 0, g: 255, b: 0 }); for (var _i0 = 0; _i0 < 4; ++_i0) { // spin larger curves await spin(180, spin_time); spin_time = spin_time * 1.25; await delay(0.025); } //end for _i0 for (var _i1 = 0; _i1 < 4; ++_i1) { setMainLed({ r: 255, g: 4, b: 19 }); // spin smaller curves await spin(180, spin_time); spin_time = spin_time / 1.25; await delay(0.025); } //end for _i1 await delay(0.025); } //end while true // Write more code here exitProgram(); }

61. Blink Acceleration Blink red if acceleration is increasing in the positive or negative x direction. Blink green if acceleration is decreasing in the positive or negative x direction. Remember that increasing acceleration is like stepping on the gas pedal, no matter what direction a car is driving. Negative acceleration is like stepping on the brake. Experiment with the x-axis, y-axis, z-axis, total, and vertical options. async function startProgram() { while (true) { if (getAcceleration().x > 0.5) { setMainLed({ r: 255, g: 0, b: 0 }); await delay(0.5); } else if (getAcceleration().x < -0.5) { setMainLed({ r: 0, g: 255, b: 0 }); await delay(0.5); } else { setMainLed({ r: 255, g: 255, b: 255 }); await delay(0.5); } if getAccel } //while true } g = 9.80665 m/s^2. getAcceleration().x is the left-to-right acceleration, from -8 to 8 g's. getAcceleration().y is the forward-to-back acceleration, from of -8 to 8 g's. getAcceleration().z is the upward-to-downward acceleration, from -8 to 8 g's. Math.sqrt((getAcceleration().x ** 2) + (getAcceleration().y ** 2) + (getAcceleration().z ** 2)) is the combined vector acceleration of all 3 axes, from 0 to 14 g's. getVerticalAcceleration() is the upward or downward acceleration regardless of the robot's orientation, from -8 to 8 g's.

41. Some of JavaScript’s standard functions (see more in any manual) sqrt(x) returns the square root of x round(x) rounds x to the nearest integer value floor(x) rounds x down to the nearest integer value ceiling(x) rounds x to the nearest integer value trunc() returns integer part of x by removing fractional digits abs(x) returns the absolute value of x, removing the sign sign(x) returns +1 for positive x, -1 for negative, and 0 for zero random() returns a random number between 0 and 1 getRandomInt(min, max) returns a random integer between, and including, the given min/max values getRandomFloat(min, max) returns a random float between two values sin(x) returns the sine of x radians Review here . cos(x) returns the cosine of x radians tan(x) returns the tangent of x radians exp(x) returns the value of e to the x power hypot(x, y, ..., n) returns the square root of the sum of squares of its arguments log(x) returns the natural logarithm (base e) of x log10(x) returns the base 10 logarithm of x toRadians(x) returns radians equal to x degrees min(x, y, ..., n) returns the number with the lowest value max(x, y, ..., n) returns the number with the highest value pow(x, y) returns the value of x to the power of y Math.E returns the base of natural logarithms (~ 2.718) Math.PI returns PI (~ 3.14159) // used to control format of spoken numbers v. toExponential() returns a string of v in exponential notation v. toFixed(x) returns a string of v with x digits after the 5.xxx v. toPrecision(x) returns a string of x characters from v


  • 1507 Total Views
  • 1223 Website Views
  • 284 Embeded Views


  • 0 Social Shares
  • 0 Dislikes

Share count

  • 0 Facebook
  • 0 Twitter
  • 0 LinkedIn
  • 0 Google+

Embeds 2

  • 8 uus.insplay.eu
  • 5