1 of 26

Gyro Drive on Spike Prime�using Python

Introduction

2 of 26

2025 Python Gyro Drive – �Starting Homework

  • If you plan to use these tools, you must review the following information from W3Schools BEFORE you view this presentation.
    • The W3Schools website allows you to test your knowledge in real time, on the website, with a Python interpreter.
  • Python Syntax
  • Python Comments
  • Python Variables, Python Lists
  • Python if…else
  • Python While Loops, Python For Loops
  • Python Functions
  • Most don’t have a HUB! Use the Spike Prime Hub Knowledge Base website for Hub Python elements.

https://spike.legoeducation.com/essential/help/lls-help-python#lls-help-python

  • There is much more to Python than you will learn as you go. This is a great start.

3 of 26

2025 Gyro Drive

  • Originally developed by Frank Larkin, First Mid-Atlantic First Lego League Director in 2022 - 2024 on Spike Prime using Blocks
  • Adapted to Spike Prime using MicroPython in 2025
    • This solution does not use native Spike HUB distance calculations, acceleration, or angle navigation.
    • Instead, it reads the sensors, does the math and applies power to the motors.
    • The math is elementary (line number and averages) enough for our FLL Challenge target audience.
  • We encourage students to “walk the code” to understand programming.
    • This will impress judges and allow students to answer with confidence.

4 of 26

What is Python?

  • Python (programming language) Wikipedia
  • Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation.
  • While not as fast as other languages, Python consistently ranks as one of the most popular, easy to learn programming languages and has gained widespread use in the machine learning community.
  • Spike Prime incorporates a version of Python called MicroPyton.
    • As the name suggests it is for micro processors.

5 of 26

MicroPython

  • MicroPython is a slightly modified Python compiler and runtime that runs on the bare-metal. MicroPython strives to be as compatible as possible with standard Python (known as Cpython) so that if you know Python, you already know MicroPython. On the other hand, the more you learn about MicroPython the better you become at Python.
  • With MicroPython you can get some really cool projects and running in no time.
  • Big Win!! Unlike Spike BlockCode, since this is just text, you can copy and paste code between programs!!!!! 🤯
  • FYI: the name Python comes from the British comedy series Monty Python's Flying Circus.

6 of 26

Gotta Have New Features

  • get_yaw: Enables users to navigate their FLL Challenge robots accurately.
    • Uses the Spike yaw sensor to accurately navigation to requested angles.
    • This function “spoofs” the yaw so it allows the use of +/-180o or +/-360o (540o)compasses. �Allowing you to turn to and drive at 180o or 360o headings!!! Your welcome!!!
        • Simple math, great for kids to see how this is done. We will have a deep dive on this.
  • gyro_spin_to_angle allows robot to spin to an angle.
        • You can control the spin speed and direction (left/right) if you need to avoid objects.
  • gyro_drive the robot with several options and overrides
    • Option: drive by: what you want to use to decide how far or long you drive.
      • distance accurately in centimeters, calculates drive acceleration making distance more accurate and repeatable
      • time in seconds. Why? Back away from an object you may hang on.
      • sonar, accurately approach an object using the distance sensor.
    • Overrides: Overrides are used in tandem with the options.
      • drive until robot detects a specific waypoint color on the playing field.
      • drive until a timeout is reached. Maybe it took too long? What do you do now?
    • All methods update the Drive.result_code. You then decide what to do.
  • gyro_drive_settings - Class dedicated to all the gyro drive settings.
  • gyro_drive_tests - Class designed to test you robot for accuracy and repeatability.
  • spinny - Class for running motors for attachments with accuracy.
    • Define as many as you like.

7 of 26

Coding Show Off vs. Readable

  • Stress readable code to your teams
    • The single letter a can be a variable, but accuracy is easier to understand.
    • Clean commenting is always good, while no commenting can cause misunderstanding
  • Professionals like to get it all on one line. They think it is cool!

yaw = (motion_sensor.tilt_angles()[0]/10) * -1 # kids may say “Ok I’m done, I cannot understand this.”

  • Break them out in steps to tell the story of what is happening.

robot_angles = motion_sensor.tilt_angles() # get all tilt angles, returns a tuple!! Google: Tuple

yaw = robot_angles[0] # pull out [0] (first one), yaw is decidegrees. Example: -907

yaw = yaw/10 # convert to degrees float (decimal) -90.7

yaw *= -1 # flip sign to match Spike Prime Blocks, left -, right + 90.7

8 of 26

Program Layout

  • The Spike Prime IDE (Interactive Development Environment) allows you to key in the Python commands�just like any text-based programming�language. You may need to enable it…
    • Help, Settings, General, Enable Python
  • Click New Project
  • Click the Python option
  • Hit Create

9 of 26

Program Layout - Default

  • This is the default when you would start a new Python project.
  • We will use a modified version removing commands like async, await and runloop.run.
    • These processes will not be used as these are advanced concepts that do not support navigation as well as gyro_drive, get_yaw and other processes do.
    • Example: Can only track angles to +/-100o
      • Cannot track past +/-180o
  • You will load a prepackaged Gyro Drive code you get from github.

from hub import light_matrix

import runloop

async def main():

# write your code here

await light_matrix.write("Hi!")

runloop.run(main())

10 of 26

Program Layout - Several Sections

  • Everything above the main function definition is considered global.
  • All gyro drive code and your code and will be in the same file.
  • You can put all your code in one file or make copies and put code in separate files with gyro drive code.
    • Bonus: You can also launch using the color sensor.
  • If you develop on one or more computers, go through all the tests we provide to come up with you robot’s standard settings.
  • Build your separate code then combine into one program to use at the competition.

Imports

Globals

Enum Classes Definition

Main function

Gyro Drive Setup

Run Tests

Execute Your Code

Define Your Code

gyro_drive_settings class

gyro_drive methods

gyro_drive_test

class definition

spinny class

definition

main() call

11 of 26

Program Layout - Imports

  • Allows you to bring other code objects into your project.
  • Spike Prime allows you to bring in MicroPython objects
    • We will use the time object to know how many seconds have passed for various processes. For you developers, this is different than the full Python time version.
    • Want to learn, Google, Google and Google!!!
  • Spike provides objects used to control the robot.
    • Again, we are importing the things we want to use.
    • The grayed-out ones (light and button) were used but are no longer used in the deployed code.
  • Unlike regular computer-based Python, you cannot create your custom imports. YET!!!!
    • If you Google this topic, some have directions on how to do this. Unfortunately, these do not work, as they were older versions. But I still have hope.
  • This Import feature is one of the reasons Python is so popular and flexible. (IMHO)

12 of 26

Program Layout – �Spike Knowledge Base

  • Spike provides Knowledge Base to detail all of their objects.
    • You access it by pulling out the tab on the right side of the screen. Then read through the materials.
  • Getting Started
    • This is a discussion of getting started with the Spike Python basics.
    • It shows you how to write code to make the robot move. Again, we will not cover some of their processes.
  • API - Application Programming Interface
    • These are the modules that control or give access to the different features in the hub.
  • A deep dive in that will not be wasted time!!!

13 of 26

Program Layout : �Global and Enum

  • global Drive – This makes the Drive definition global in scope.
    • Right now, it is just a global “handle”.
  • Enum allows us to associate a name with a value.
    • These improve readability.
    • These are global as they are above the main function
  • The class log_level: is creating a new object
    • It’s several entries that represent an enum.
    • Note the emun definitions are tabbed in 4 spaces. Tabbing is Python’s way of indicating what belongs with/under the object.
    • Remember, the goal is to improve readability.

14 of 26

Program Layout : �Enums Deep Dive

  • log_level - used in logging.
    • Logged messages show on the console.
    • OFF means the logging will not display
  • motor_velocity:
    • Indicates the maximum velocity of a �lego motor.
    • You can add others if you like.
    • It improves the readability of the code.
  • results:
    • These are the result codes that gyro drive �methods will set when a function completes.
  • When coding, type the name then . and �you see the list.
    • The name is displayed in the code but ,�the numerical value is passed when used.

15 of 26

Program Layout : �Enums Deep Dive

  • Spike provides enums too
    • These are used extensively. They are available in the Spike Knowledge Base online or in the Spike Python app.
  • port Constants
    • These are used to help identify a port. (see below)
    • We could pass a number 0-5, meaning A-F.
    • But enums support readability
  • Notice the motor_velocity enum (max velocity of various LEGO motors)
    • We defined these at top of the code. Visible to all. (easy to read!)

16 of 26

Program Layout : �main function definition

  • Functions (small code chunk) starts with def or definition.
  • Note that items under def main(): are Tabbed in. This is Python indicating they are part of the function.
  • global Drive - declared above, can now be seen under the main() function. But here Drive still has no values, yet!!!!
  • Drive = gyro_drive_settings()
    • Drive is now a global version of the instantiated (created)�gyro_drive_settings class. Walk the code to see what it does!
    • This class allows you to set the code to work �with your specific robot design.
    • Just typing Drive. shows you all the settings�variables and methods. �

17 of 26

Program Layout :�main function definition

  • These tools support a simple form of logging.
    • This has several reporting levels. log_level is an enum defined above. We can now change the default setting to whatever we want. Here, it is turned it OFF. You can change these settings anywhere in the code.
  • linegraph feature allows us to plot variables.
    • Question: The way the code is written, will linegraph be used Yes/No and why?
  • motor_pair.pair(): This method sets up a motor pair. This allows us to control the 2 drive motors with 1 command.
    • We are using motor.PAIR_3. These are 2 others if you want to “pair” motors. Read up on this in Spike KB.�

18 of 26

Program Layout : �Creating the spinny classes

  • Here we instantiate our spinny classes
    • A spinny is used to spin motors for arms, lifters or other spinny requirements.
  • Here we are instantiating or creating them.
    • Most of this should be somewhat easy to read and understand because of the enums and the variable names.
  • These will be commented in the code you get. Uncomment and set them up for your robot.
    • You may only need one, leave the second commented or delete it.

19 of 26

Program Layout : �gyro_drive_tests class

  • The gyro_drive_tests class has several tests to get your robot dialed in and test it capabilities.
    • These will be #commented out in the code you get.
    • The actual class is defined below here outside of main.
    • We will discuss the details of the calls in a different presentation.
  • Notice the return statement. It will tell the code to break out of the main function and stop the program.
    • It is now #commented out
    • If it was not commented out, all the main code below will be grayed out. This is the Spike UI is telling you that code is not visible to be executed.
  • Question: How can you tell these are still in the main method?

20 of 26

Program Layout : �Your functions are called

  • We are still in the main method, so we are tabbed in one tab stop
  • These are calls to separate functions you can create and name for what they do.
    • The actual functions are defined below here outside of main.
  • Let’s assume we are working on m1_Attach_the_left() �This could be the call for your first mission
    • You comment out the others so they will not run. When m1 runs and then is finished…
      • You will drop past the commented lines
      • Then you hit return. The program breaks out of the main function and ends.
  • When ready you can save all of this to slot 1 on your robot.
  • Repeat for all your missions

21 of 26

Program Layout : �Your mission functions

  • Now we want to work on m2 so we comment out m1 and uncomment m2.
    • m2_go_to_center(): This is an example call for your second mission. You make up your own.
    • m3 and m4 are commented so they show green
  • When ready, you can save these to different slots on the robot.
  • If you have another set of students working on the other missions when they are ready, you can copy and paste their code into the primary computer in the function you want.
  • When you return from here, you exit the main function. The program stops.
  • Notice we are at the end of the main function.

22 of 26

Program Layout : �Your function definitions

  • Notice we are not tabbed in?
    • The Main function definition is ended. We are now below the Main function.
  • Your code is defined here…
    • Like all functions, each starts with def
    • Commenting is always helpful.
  • You can define any of your own custom reusable methods below here.
  • If this is the primary computer…
    • You can define other mission functions that are being worked on another computer just to leave a space for it.
    • If you add pass at the bottom, Python will know you are going to update it later.

23 of 26

Bonus Idea!!!!: �Run Program by Color

  • This will allow you to run your program by using a color sensor to select the program.
    • Problem: The color_sensor_port is set to defaulted to -1.
    • You set the id. Example: Drive.color_sensor_port = port.D
      • port.D is a Spike enum (remember readability!!!)
  • You set the robot where you want. Then press the start button.
    • The loop starts, (130) and the power button ring turns orange. (131)
    • We read the color sensor into the variable called reading.
    • reading is color.UNKNOWN (-1) we keep looping.
      • color is another Spike enum.
  • If we read a color!!!!
    • What happens?
  • Bonus questions:
    • Why are there sleep(1) in there after the color is read?
    • Why is the return grayed out at the bottom?
    • If the robot is now driving and it hits a color what happens?

24 of 26

Bonus Idea!!!!: �Run Program by Color

  • If the reading == color.BLUE (“is equivalent to color.BLUE”)
    • Turn the Power button ring to BLUE.
    • sleep(1) - We wait a second to get fingers out of the way.�You can make it longer 2 might be better.
    • Run the m2 function.
      • We stay here until it returns.
    • We then go back to the loop, and the Power ring turns orange again.
      • The Main program is still running. �We keep looping until another color is presented.
  • New Idea! You may use a different color and method to reset your arms to their starting positions. How can you do that?
  • If a robot is brought back and the program has not been completed, you must stop it and start it again to get back to the loop.

25 of 26

See the problem?

  • This is a screenshot of the code that has a problem.
  • Where did the problem occur?
    • Hover over the error, the�UI shows…�
    • The code does not line up with the code above and below.
    • To fix this we just delete the space before sleep(1)
  • The UI will show you where it starts. Many other items are now highlighted so you look for where it started.
  • It is best to use the Tab key when indenting.
    • Even though you pressed Tab, the UI will use spaces.
    • Notice the UI will show you lines where the indents start.
  • Once you are on an indented line and hit return, �the cursor will move to that tabbed in position.

26 of 26

Gyro Drive on Spike Prime�using Python

Good luck and have fun!!!