Python lego spike prime

Обновлено: 16.05.2024

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Mindstorms / SPIKE Prime / SPIKE Essential

This repository is a collection of useful information about the Lego Mindstorms Robot Inventor (51515), Lego SPIKE Prime (45678) and Lego SPIKE Essential (45345).

Large Hub Hardware

This applies to both the SPIKE Prime and Mindstorms Robot Inventor large hubs.

Small Hub Hardware

This applies to the SPIKE Essential small hub.

Part Description
CPU ?
Internal storage ?
Wireless connectivity Bluetooth supporting 1 BT and 4 BLE connections (IC: ?).
Wired connectivity Micro USB cable.
Display 1 RGB LED (Driver IC: ?).
Motor Drivers 2 motor outputs (Driver ICs: 1 x ?).
Battery Management Lithium ion battery management (IC: ?).
Accerometer Three-axis accelerometer (IC: LSM6DS3TR).
Gyroscope Three-axis gyroscope (IC: LSM6DS3TR).
Ports 2 LPF2 ports = 2 normal speed (115kB).

Connecting to a hub

To connect to the hub you have two options, a micro USB cable or bluetooth. Both options create a serial connection between the hub and the computer. At the hub end of this serial connection is a micropython REPL (Read Evaluate Print Loop). You can use this REPL to run python commands just like you would in the python interpreter on your computer.

To connect on Linux you will normall use:

  • /dev/ttyACM0 for USB connections.
  • /dev/rfcomm0 for bluetooth connections.

Note: If you press and hold the left button then press the center button to power up the hub, it will startup bypassing the runtime on the hub.

I have found bluetooth on linux to be not that reliable and often have to follow this process:

Then I can use rfcomm to create the bluetooth serial port /dev/rfcomm0 :

An attempt to create an application that can communicate with a hub to allow for remote control / sending of scripts / sensor logging without needing any of the LEGO apps.

This is a disassembler/decompiler that uses the mpy-tool from the micropython repository to disassemble mpy files from the hub filesystem.

Dumps of the micropython filesystem on the Lego hub using rshell.

Long version numbers are from running the help(hub) command on the board. Short versions numbers are from the version.py files where available.

Dump Description
v0.5.01.0000-42a938e Initial filesystem (Purchased on: 28/05/2020) (Box Version: 29).
v1.0.00.0027-64837e9 Additional filesystem in 1.0.0 on Windows (Extracted from app.asar).
v1.0.00.0030-b228d30 Filesystem from 1.0.0 on Windows (Extracted from app.asar).
v1.0.00.0033-268c151 Filesystem from 1.1.4 on Windows (Extracted from app.asar).
v1.0.03.0034-c3879ab Updated filesystem using 1.2.0 on Windows(Updated on: 02/07/2020).
v1.0.06.0034-b0c335b Updated filesystem using 1.2.1 on Windows (Updated on: 17/07/2020).
v1.1.01.0000-6b4a939 Updated filesystem using 1.3.0 on Windows (Updated on: 01/09/2020).
v1.1.01.0000-6b4a939 Updated filesystem using 1.3.1 on Windows (Updated on: 20/10/2020).
v1.1.01.0002-3e5a121 Updated filesystem using 1.3.2 on Windows (Updated on: 03/11/2020).
v1.1.01.0002-3e5a121 Updated filesystem using 1.3.3 on Windows (Updated on: 18/12/2020).
v1.1.01.0002-3e5a121 Updated filesystem using 1.3.4 on Windows (Updated on: 17/03/2021).
v1.2.01.0101-edc1be7 Updated filesystem using 2.0.0 on Windows (Updated on: 25/08/2021).
v1.2.01.0101-edc1be7 Updated filesystem using 2.0.1 on Windows (Updated on: 25/08/2021) [UNCHANGED].
v1.3.00.0000-e8c274a Updated filesystem using 2.0.3 / 2.0.4 on Windows (Updated on: 03/11/2021).
v1.3.00.0000-e8c274a Updated filesystem using 2.0.5 on Windows (Updated on: 09/05/2022) [UNCHANGED].
v1.3.00.0000-e8c274a Updated filesystem using 2.0.6 on Windows (Updated on: 09/05/2022) [UNCHANGED].
Dump Description
v1.0.00.0070-51a2ff4 Initial filesystem (Purchased on: 27/09/2021) (Box Version: 143).

Mindstorms Robot Inventor

Dump Description
v0.5.01.0002-f75d82d Initial filesystem (Purchased on: 16/10/2020).
v1.0.06.0034-b0c335b Updated filesystem using 4.0.4-dev.99999 on Windows (Updated on: 20/10/2020).
v1.0.06.0034-b0c335b Updated filesystem using 10.0.3 on Android (Updated on: 29/11/2020).
v1.2.01.0103-d08b6fe Updated filesystem using 10.1.0 on Android (Updated on: 05/05/2021).
v1.3.00.0203-71f6a41 Updated filesystem using 10.2.0 on Android (Updated on: 19/08/2021).
v1.4.01.0000-594ce3d Updated filesystem using 10.3.0 on Android (Updated on: 13/12/2021).

Dumps of the firmware on the Lego hub using the micropython REPL.

The lines below will output a number of bytes of the firmware starting at the provided location, or false if past the end.

The first versions of the firmware on the device do not have the firmware library. To dump these you have to use the DFU tool after booting the device into DFU mode.

To boot the device into DFU mode:

  1. Turn the hub off and disconnect the USB wire from your computer.
  2. Hold down the bluetooth button and plug in the USB wire to your computer.
  3. Keep holding the bluetooth button until it starts flashing in a cycle (pink-green-blue-off).
  4. The hub is now in DFU mode.
  5. The dfu-util program can be used to extract the firmware, see the script below.

Long version numbers are from running the help(hub) command on the board. Short versions numbers are from the version.py files where available.

Dump Description
v0.5.01.0000-42a938e MISSING Initial firmware (Purchased on: 28/05/2020) (Box Version: 29).
v1.0.00.0027-64837e9 MISSING Additional firmware in 1.0.0 on Windows (Extracted from app.asar).
v1.0.00.0030-b228d30 Firmware from 1.0.0 on Windows (Extracted from app.asar).
v1.0.00.0033-268c151 Firmware from 1.1.4 on Windows (Extracted from app.asar).
v1.0.03.0034-c3879ab Updated firmware using 1.2.0 on Windows (Updated on: 02/07/2020).
v1.0.06.0034-b0c335b Updated firmware using 1.2.1 on Windows (Updated on: 17/07/2020).
v1.1.01.0000-6b4a939 Updated firmware using 1.3.0 on Windows (Updated on: 01/09/2020).
v1.1.01.0000-6b4a939 Updated firmware using 1.3.1 on windows (Updated on: 20/10/2020) [UNCHANGED].
v1.1.01.0002-3e5a121 Updated firmware using 1.3.2 on Windows (Updated on: 03/11/2020).
v1.1.01.0002-3e5a121 Updated firmware using 1.3.3 on windows (Updated on: 18/12/2020) [UNCHANGED].
v1.1.01.0002-3e5a121 Updated firmware using 1.3.4 on Windows (Updated on: 17/03/2021) [UNCHANGED].
v1.2.01.0101-edc1be7 Updated firmware using 2.0.0 on Windows (Updated on: 25/08/2021).
v1.2.01.0101-edc1be7 Updated firmware using 2.0.1 on Windows (Updated on: 25/08/2021) [UNCHANGED].
v1.3.00.0000-e8c274a Updated firmware using 2.0.3 / 2.0.4 on Windows (Updated on: 03/11/2021).
v1.3.00.0000-e8c274a Updated firmware using 2.0.5 on Windows (Updated on: 09/05/2022) [UNCHANGED].
v1.3.00.0000-e8c274a Updated firmware using 2.0.6 on Windows (Updated on: 09/05/2022) [UNCHANGED].
Dump Description
v1.0.00.0070-51a2ff4 MISSING Initial firmware (Purchased on: 27/09/2021) (Box Version: 143).

Mindstorms Robot Inventor

Dump Description
v0.5.01.0002-f75d82d Initial firmware (Purchased on: 16/10/2020).
v1.0.06.0034-b0c335b Updated firmware using 4.0.4-dev.99999 on Windows (Updated on: 20/10/2020).
v1.0.06.0034-b0c335b Updated firmware using 10.0.3 on Android (Updated on: 29/11/2020) [UNCHANGED].
v1.2.01.0103-d08b6fe Updated firmware using 10.1.0 on Android (Updated on: 05/05/2021).
v1.3.00.0203-71f6a41 Updated firmware using 10.2.0 on Android (Updated on: 19/08/2021).
v1.4.01.0000-594ce3d Updated firmware using 10.3.0 on Android (Updated on: 13/12/2021).

A recreation of the spike prime hardware using python to allow testing and debugging python scripts on a PC.

The aim is to create a script to dump the functions of the real hardware and then mock them to allow local development.

Currently there is two main scripts one to simulate running micropython scripts on a hub and one to push micropython scripts to a real connected hub. The simulator uses a mocked implementation of the micropython modules available on the phyical hub that redirect actions to the simulator gui.

File Description
simulator.py A python3 gui based simulator for the Lego hub.
run.py A python3 script to run a micropython script on a connected Lego hub.
upload.py A python3 script to upload a micropython script to a connected Lego hub.

Specification pdfs for internal parts of the Lego components.

File Description
stm32f413 The microprocessor inside the hub.

SPIKE Prime and Mindstorms Robot Inventor

File Description
large-hub The main SPIKE Prime hub.
large-hub-rechargeable-battery Rechargeable lithium ion battery pack for the hub, capacity 2100 mAH.
medium-angular-motor Medium motor with integrated absolute orientation sensor, accuracy +- 3 degrees.
large-angular-motor Large motor with integrated absolute orientation sensor, accuracy +- 3 degrees.
force-sensor Measures touch, tap, and force up to 10N (About 1Kg) at an accuracy of 0.65N.
distance-sensor Measures depth to 2m (fast to 30cm) with 1mm resolution. Has 4 white LED outputs.
color-sensor Measures 8 colours, reflectivity, and ambient light. Has 3 white LED outputs.
File Description
small-hub The smaller SPIKE Essential hub.
small-hub-rechargeable-battery Rechargeable lithium ion battery pack for the hub, capacity 620 mAH.
small-angular-motor Small motor with integrated absolute orientation sensor, accuracy +- 3 degrees.
color-light-matrix 3x3 RGB Light matrix with individual segment control.
color-sensor Measures 8 colours, reflectivity, and ambient light. Has 3 white LED outputs.

Where documents, code, graphics, binary or any other files have been created by me they are licensed under the MIT license. Other files that have been pulled from the firmware or filesystem of LEGO products remain licensed by LEGO.

Чем раньше ты начнешь изучать правильный язык, тем больше шансов, что он тебе поможет в жизни. Сегодня это одинаково верно, как для иностранных, так и для языков программирования. Поэтому на информатике многие продвинутые школьники стремятся изучать именно тот язык, который используется в крупных IT компаниях.

Смотрите вы ролики на Youtube или размещаете свои фотографии в Instagram, храните свои файлы в Dropbox, значит пользуетесь еще и Python. Питон (правильнее звучит «пайтон», но так его прозвали в России) используется при создании многих крупных интернет-ресурсов и находится в зените своей популярности. А еще на нем решаются задачи по программированию в ЕГЭ по информатике.

О том, какие преимущества есть у языка и как его можно изучать с помощью нового конструктора LEGO SPIKE Prime рассказывает Татьяна Кочерова, методист лаборатории инженерных образовательных проектов Центра Педагогического Мастерства г. Москвы, учитель информатики и робототехники АНО «Школа ЦПМ».


В нашей школе любят экспериментировать, поэтому у меня не просто информатика, а программирование с элементами робототехники. Мы работаем в паре с другим преподавателем Сергеем Мустафиным, который занимается с детьми робототехникой углубленно в рамках дополнительного образования.

С оборудованием LEGO Education знакома почти двадцать лет и использовала практически все наборы. Сейчас мои ученики — пяти- и шестиклассники. Поэтому новый LEGO SPIKE Prime, рассчитанный именно на среднюю школу, пришелся для нас кстати.

До этого я использовала Scratch, так как это среда специально создана для обучению принципам кода, чтобы в ней легко разбирались дети. Но дети быстро растут! Поэтому решили переводить учеников на текстовый язык Python. Именно SPIKE подходит идеально для решения поставленной задачи, так как работает на двух языка — Scratch и Python. Такой удобный мостик получился для моих ребят. Они очень быстро и плавно перешли с одной среды на другую.

При знакомстве с набором LEGO SPIKE Prime и использовании языка Scratch все оказалось просто: дети взяли новый конструктор, открыли знакомую программу, нужно было буквально пару вводных фраз, и у них сразу начали двигаться конструкции, куда-то что-то уехало со стола, пришлось даже ловить. С питоном немного иначе. На первых занятиях некоторые сначала испугались: «Ого, такой серьезный язык». Но потом разобрались, что на самом деле у страха глаза велики. На уроках программирования на скретче они уже изучили такие понятия как «переменные величины» и действия с ними, основные алгоритмические конструкции, например, «операторы условия», а также узнали, какие бывают циклы. Поэтому учить синтаксис Python даже с нуля все же проще.

Важно помнить, что дети получают не просто «мертвые» знания, Python пригодится для тех, кто будет сдавать ЕГЭ по информатике, а если ребенок не планирует идти в IT-сферу, то он будет понимать, как работают современные программы, которыми он пользуется регулярно, а значит, сможет написать свою.

Сейчас, на мой взгляд, языки программирования также классный мотиватор для изучения английского. Я всегда говорю все команды на русском языке, например: «Сделайте вот это». Синтаксис они должны выучить сами. Не произношу команды языка на английском, потому что могу навредить своим произношением (в школе изучала немецкий).

Однажды, несколько лет назад, в одном из классов дети увлеклись на уроке до такой степени, что бегали к учителям английского и выясняли, почему в программировании слово «цвет» — «color» пишется без буквы «u». Те объяснили, что это слово — американизм, да еще жаргон. То есть дети были настолько увлечены, что копались в принципе наименования команд.

В питоне тоже очень интересно, и ученики начинают задавать какие-то вопросы, это заставляет их думать. А иногда они превосходят в своих знаниях учителя. Например, сейчас у меня есть ученик, который, знает Python даже лучше, чем я его. Так он все время «гоняет» меня, потому что ему, например, не нравится мое слово «апостроф». Он поправляет меня: «Скажите: «одинарная кавычка». Поэтому я сдаюсь и компромиссно говорю «апостроф или одинарная кавычка». Но его комментарии на уроке бесценны как для меня так и для ребят в классе. Он может быстрее меня ответить на вопрос, дав пояснение к теме урока с примером на понятном его одноклассникам уровне. Такие дети позволяют развиваться, держат педагога в тонусе.

Как учитель информатики, который преподавал разные языки, в том числе Паскаль и С++, могу уверенно сказать, что Python — более «свободный» для детей. К тому же Питон любят такие гиганты как Яндекс и Google, это модный, современный язык, в отличие от того же Паскаля, который морально устарел.

Я все время говорю, что Python — это змей, который заползет, окружит вас и вы не сможете вырваться из его объятий.

За что я люблю робототехнические конструкторы? За то, что это программирование, которое можно потрогать руками. Если раньше я пыталась на уроке информатики объяснить детям, для чего нужно то или иное знание, им казалось, что я требую от них что-то непонятное. С наборами школьники говорят: «В этом легче разобраться. Видишь, что происходит».

Союз LEGO Education плюс Питон — это бомба для учителя информатики, настоящий козырь для увлечения детей. Лет десять назад я провела эксперимент: у меня было три группы в параллели 8 класса, и в каждой я дала разный язык программирования. В одной был Паскаль, в другой — С++ и в третьей — наборы LEGO Education и Robolab. Когда две группы приходили и узнавали, что сегодня на уроке они изучают программирование, то сникали, а в последней, когда видели, что ставят желтые наборы на стол, кричали: «Ура, Лего!». Они бежали программировать и все делали с огромным удовольствием. Поэтому неудивительно, что я так загорелась Спайком, когда увидела, насколько это универсальный набор для уроков.

Мы попросили школу купить нам SPIKE Prime и стали с коллегой думать, как нам связать программу. Сергей Мустафин преподает на наборе LEGO Education EV3, и планировал переходить на текстовый язык. Теперь у детей есть два разных робототехнических набора, связанных единым языком программирования — Python. Важно помнить, что, когда они закончат обучение на Спайке, то смогут уйти в любое другое направление.

На уроках я использую и российские наборы, но в прошлом году мы столкнулись с проблемой не самого лучшего качества пластмассы — то шурупчики вылетают, то еще что-то. Дети маленькие, они начинают переживать, переспрашивать, что у них не так. С российским набором школьникам был необходим постоянно учитель рядом, а сейчас я практически не трачу времени на техническое сопровождение. Ребята же, открывая набор Спайк, получают не только яркий, приятный на ощупь, продуманный до мелочей от системы хранения до создания робототехнических моделей, интуитивно понятный учебный комплект, но и заряд положительных эмоций, способствующих созданию ситуации успеха.

Сейчас своим ученикам я хочу показать с помощью SPIKE Prime, что все, что их окружает, они могут сами создать своими руками, а не только пользоваться готовым. Например, шагомер. Мы привыкли, что у нас есть гаджет, который все считает, так вот пусть соберут свой гаджет! Для этого в SPIKE есть акселерометр, они могут измерить длину своего шага, настроить под свои параметры, подсчитать, какое расстояние они пройдут пусть и в рамках одного урока. Хочется сделать с ними какую-нибудь игру, я еще не совсем придумала, как она будет реализована. Идей в голове много, я только в начале пути освоения набора, и пока он полностью оправдывает мои надежды.


Заветная для многих преподавателей желтая коробка!

За что я ценю SPIKE Prime:

1. Очень удобное сопровождение для учителя. Можно придумывать задания самому, можно опираться на чужой опыт: есть масса готовых уроков, рассчитанных на 45 минут.
2. Аккумулятор идет в комплекте. Я не трачу свое время на то, чтобы зарядить оборудование, подготовить его, зарядка идет во время программирования и это очень удобно.
3. Самодостаточность. В наборе есть все, что нужно для реализации любой учебной задачи — бери и работай.
4. Выбор языка. Каждый сам определяет — Scratch или Python, а это здорово именно для программирования.

Хотите использовать на уроках SPIKE Prime? Уже получили новый набор, но не знаете, как лучше его использовать? Есть идеи, что с ним можно сделать интересного?
Приходите на Всероссийскую конференцию пользователей «SPIKE Prime» — «Первые шаги», 29 октября, онлайн, бесплатно.

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

These are some basic programs that are useful if you are building and programming the LEGO SPIKE PRIME. We use this code for competing in the FLL. If there are any bugs or you have any questions please notify us. We strongly recommend that you use VS Code for your programming, the instructions for doing so are below. You can however also paste this into the SPIKE or MINDSTORMS software.

Programs and Features included

  • follows line until specified color/distance is reached
  • acceleration/braking
  • dynamic PID control for smooth driving
  • turns until specified color/angle is reached
  • acceleration/braking
  • different turning styles (on the spot/curve)
  • drives in a straight line until specified distance/color is reached
  • accelerating/braking
  • dynamic PID control for smooth driving
  • alignment with lines
  • parallel code execution for turning motors while driving

Necessary extensions/Programs for use in VS Code:

Visual Studio Code Python Lego Spike Prime/Mindstorms Robot Inventor Extension by Peter Staev

Fully charged battery voltage

When the battery is fully charged the voltage is 8300.

Click the button LEGO Hub: Disconnected on the left hand side of the blue bottom bar. A dropdown menu will open at the top of the screen, try out all the COM options it gives you until you are connected. Note: You have to have previously connected to the hub in the Spike or Mindstorms software first.

How to upload a program to the hub:

Press CTRL SHIFT P and select LEGO Hub: upload program from the dropdown menu. Choose Python: regular. Choose the slot you want the program to be saved in on the hub.

How to start a program:

Press CTRL + SHIFT + P and select LEGO Hub: start program from the dropdown menu. Select the slot of the program you want to start on the hub. Note: This step can be skipped if you have autostart activated.

How to enable preocompiling:

To precompile the main.py on the PC go to the extension page and select the extension then click on the settings symbol and activate Lego Spike Prime Mindstorms: Compile Before Upload. This will allow the program to start faster

For further info on working with Spike Prime in VS Code see:

This program uses features of extensions that use unofficial and undocumented APIs. They can change without notice. Functions tested on Windows connecting to a LEGO MINDSTORMS Spike Prime Hub.

LEGO and MINDSTORMS are registered trademarks of the LEGO Group. SPIKE is trademark of LEGO Group.

About

These are the programs we use every day as a team for programming the LEGO SPIKE PRIME for competitions such as the First Lego League. Feel free to use this code and tag us on social media if you do so

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

LEGO SPIKE Prime / MINDSTORMS Robot Inventor Extension

This extension helps you connect to the SPIKE Prime or MINDSTORMS Robot Inventor brick and perform various operations on it.

status

Shows the connections status right in the status bar

connect


Clicking on the status will either connect or disconnect (if already connected). Support connecting to USB and Bluetooth (see Known Issues for limitations).

slot-selection


Once connected you can start a running program by choosing its slot. For each slot if a program is present you will see its name next to the slot number:

type-selection

You can upload two types of programs with this extension:

This is more or less the same as a python project, created with the Mindstorms or SPIKE prime apps. But allows you to use your favorite code editor and its extensions instead of the built in one.

This gives you access to an async code execution and event notifications that are provided by built in event loop that runs on the brick. The event loop is used to run Scratch programs and I haven't found any other way to access it from standard python type programs.

The advanced programs mus follow a specific template in order for them to execute correctly:

You can check what advanced functions found so far here.

Automatic upload/start of a python file

During active development you will be uploading a program over and over again so going through all the prompts for type and slot is not very convenient. You can skip those prompts and automatically start the program after uploading by adding a specific comment line as first in your program.

For example, if I want the program to be uploaded as an advanced python program to slot 5 and autostart it once the upload is finished the comment should be the following

  • When using Bluetooth and you have many programs stored on the brick it stops responding to querying slot info. You should eiher use USB connection or avoid using commands that query slot info - for example you can completely avoid them by using the automatic upload comment in your python files.

Thanks to sanjayseshan/spikeprime-tools and bricklife for figuring out currently available JSON RPC that the brick supports.

This extension uses unofficial and undocumented APIs. They can change without notice. Functions tested on a Mac connecting to a MINDSTORMS Robot Inventor Hub FW Version 1.0.6.34 with runtime version 2.1.4.13

LEGO and MINDSTORMS are registered trademarks of the LEGO Group. SPIKE is trademark of LEGO Group.

About

Helps you connect and work with Lego's SPIKE Prime/MINDSTORMS Robot Inventor hubs


In my previous post, I introduced how to set a mission for LEGO Spike Prime and implement the task with LEGO Spike programming blocks. As I mentioned before, Lego Spike Prime supports MicroPython pretty well. Most of the programming blocks could find corresponding Python functions.

In this post, I will demonstrate how to “translate” my previous programming blocks into Python code. I will also show an issue encountered when writing Python code and a way to work around it.

The programming blocks and mission setting could be found at this post. Since the programming blocks are long, I will not list them here again.

“main” Function

The whole program just uses the default template of LEGO Spike Python project. It imports all the necessary libraries at the beginning of the file.

Just like the programming blocks shown on the left, the “main” function of Python code contains several functions which divide the whole working process into several sub segments. I will introduce them one by one.


“Start_off” function

The program initiates two colour sensors and one distance sensor at the beginning. In “start_off” function, most of the code has corresponding programming blocks, so it is pretty convenient to “translate” programming blocks into the Python code. MotorPair objects are used to control 2 motors simultaneously in opposite directions. Please note that “wait until” block could not be translated directly since Python has not such kind of loop statement. I need to use “while” loop to replace it and make proper adjustment to make code run well.


“start_line_sensing” Function

The distance sensor sometimes will return None type, which I believe is a bug of the current MicroPython version. To workaround this problem, we need to check if the retrieved value of “get_distance_cm” is equal to None. Otherwise, since None type is different from float type, the system will throw out a runtime error and the whole program will stop.

The Python code here realizes the same functionality as block programming. It uses proportional line following method to control the movement of the motors.


“move_clip” Function

This function is simple. It just drives a single motor which connects to Port F to run clockwise or counter-clockwise for a certain degree.


“send_to_destination” Function

This function will send an object to the destination. The code is similar to the above “start_line_sensing” function. It uses proportional line following method to trace the black line until color sensor on Port E identifies color red, which is the edge of the destination.


“return_to_base” Function

This function returns the vehicle robot to the starting place. However, after using Motor object to control Port B and Port D motor, the program stops unexpectedly. It seems the problem happens when using MovePair and Motor objects to control the same ports. It is a bug of the current MicroPython version.

Continue…

To workaround this problem, I should only use MovePair objects to control the two motors. The following is a method to implement it.

Update of “return_to_base” Function

In the following code, Motor object related code has been replaced with a function called “run_until_touching_red_line”. Except this, all the other code is the same as the previous version. I will explain “run_until_touching_red_line” function below.


“run_til_touching_red_line” Function

This function sets two variables “motor_b_status” and “motor_d_status” which represent the move/stop status of Port B motor and Port D motor. Color sensor E and C are mounted to the side of Port B and Port D motor, respectively. In while loop, when colour sensor E identifies red colour, it will set the “motor_b_status” to 0, meaning that the motor B on its side should stop running.

After that, the program checks the value of “motor_d_status”. If “motor_d_status” is 0, meaning that the other motor has stopped running, the program knows that it could stop both motors by calling motor_pair.stop() and exiting the while loop. If “motor_d_status” is equal to 1, the program will call motor_pair.start_tank(0,30), so that only the motor D on the other side keeps moving.

The same logic applies when colour sensor C identifies red colour. Through using the two variables “motor_b_status” and “motor_d_status”, MotorPair function could specify the speed of each motor correctly.

continue…

That is all the MicroPython code in order to accomplish the same mission done by programming blocks. If you are keen to try it yourself, you could copy the above code into Python canvas and check how it works. Enjoy the coding and have fun!

Читайте также: