Only this pageAll pages
Powered by GitBook
Couldn't generate the PDF for 128 pages, generation stopped at 100.
Extend with 50 more pages.
1 of 100

English

Loading...

TRIK Studio

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

TRIK Studio Junior

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

INTEGRATIONS

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

TRIK controller

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

About TRIK Studio

TRIK Studio — free robot programming environment.

It allows you to solve problems using both visual and textual programming languages.

A distinctive feature of TRIK Studio is an interactive simulation mode. You don't need to have a constructor to learn how to program.

TRIK Studio — universal software for teaching programming basics. It provides a smooth transition from diagrams to text languages.

Supported platforms

TRIK Studio supports 4 platforms:

  • TRIK controller.

  • LEGO EV3.

  • LEGO NXT 2.0.

  • Pioneer Kit.

Download

You can download the latest version of TRIK Studio on the website trikset.com.

Recommended system requirements

  • RAM: 4 GB or more.

  • Operating system:

    • 64-bit Microsoft Ⓡ Windows 10.

    • Ubuntu 16.04 and later.

    • macOS 10.12 Sierra and later.

TRIK Studio can be run on computers with different versions of operating systems and with less memory. For example, TRIK Studio 3.2.0 works with legacy versions of Microsoft Ⓡ Windows, on macOS 10.9 Mavericks, and on many versions of GNU/Linux. However, for later versions, compatibility with legacy operating systems is not guaranteed, so check compatibility before installing if your system does not meet the recommended requirements.

TRIK help

TRIK help — a guide for working with the free robot programming environment TRIK Studio. You can find the open-source TRIK Studio code in our repository at GitHub.

The help also describes how TRIK Studio interacts with supported platforms:

  • TRIK controller.

  • LEGO EV3.

  • LEGO NXT.

  • Pioneer Kit.

Getting started and creating a project

Create a new project and launch an existing one

Main window

After starting TRIK Studio, you will see the start page that displays the of TRIK Studio, quick access to recent projects, and buttons for and .

Project creation

To create a new project, click the "New project" button on the TRIK Studio home page.

Or select File → New project from the .

A window opens with a new program in the visual programming language:

Read about programming in a visual language in the article:

Read about creating a new text program in the article:

Launch an existing project

To start an existing project, click the "Open project" button on the TRIK Studio start page.

Or in the , select File → Open....

By default, TRIK Studio searches for files in the *.qrs format or the last open format (for example, *.js). If you need an existing project in a different format, select the desired format (for example, *.py) or All files (*.*).

How do I replace the "Character movement" image?

This article is automatically translated from Russian by Google Translator.

You can change the "Character movement" image in the TRIK Studio Junior settings.

1. Choose Settings → Preferences ... in the

2. Choose the "Robots" tab in the opened window, click the "Browse" button next to the "2D Robot Image" field and select the desired image.

3. Press "OK".

Adding and removing blocks in TRIK Studio Junior

Adding and removing blocks in TRIK Studio Junior is the same as in TRIK Studio:

Syntax of expressions in the blocks in TRIK Studio Junior

The syntax for expressions in blocks in TRIK Studio Junior is similar to the syntax for expressions in TRIK Studio blocks:

Property editing in TRIK Studio Junior

Editing element properties in TRIK Studio Junior is similar to editing element properties in TRIK Studio:

Array

An array is one of the types of TRIK Studio language that stores a set of values ​​(array elements) identified by an index. The numbering of indices in the array starts at 0.

Arrays can be created explicitly using the following expressions (the next lines are equivalent):

a = {1; 2; 3; 4};
a = {1, 2, 3, 4};

Or with explicit indices:

a = {[0] = 1, [10] = 2, [20] = 3};

You can use arrays without creating them. For example, like this:

a[1] = 1;
a[2] = 2;

In this case, "empty spaces" in the array (indices that did not have an explicit assignment) will be filled with default values:

  • 0 — for real and integer;

  • false — for boolean;

  • empty lines for arrays of strings.

Array values ​​can also be used without curly braces if used as the return value. For example, this expression will return an array of numbers 1 and 2:

a = 1;
b = 2;
a, b 

This is implemented in order to interpret the enumerations of values ​​(for example, the ports of motors in the block "Motors forward") as arrays. Therefore, wherever you use a comma-separated value notation, you can use an array.

Constants

TRIK Studio has only one built-in constant. It can be used in the same way as sensor variables, but its value cannot be changed.

pi

3.14159265358979

Represents the ratio of the circumference of a circle to its diameter, determined by the constant π.

Antivirus conflicts

Some antiviruses recognize TRIK Studio as a threat, which prevents TRIK Studio from working correctly.

Below are the instructions for solving similar antivirus problems:

  • Avast antivirus blocks TRIK Studio. What to do?

Class «battery»

This article is automatically translated from Russian by Google Translator.

Provides access to information about the battery or power supply unit.

readVoltage

Returns the current-voltage of the battery (or power supply) in volts.

Syntax

brick.battery().readVoltage();
brick.battery().readVoltage();

Adding and removing blocks
Syntax of expressions in the blocks
Property editing
How to find out the version of TRIK Studio
About TRIK Studio
version
opening an existing project
creating a new one
main menu
main menu
Visual programming
Textual programming
main menu

WinSCP

WinSCP — an SFTP and SCP protocol graphical client for Windows. Using it, you can exchange files between the TRIK controller and the computer using the SCP protocol.

Run WinSCP from TRIK Studio

To start the utility go to the menu Tools → External tools → WinSCP.

Connect to the TRIK controller in WinSCP

1. In the directory with TRIK Studio installed, go to the winscp folder and run WinSCP.exe.

2. Fill in the next fields:

  • File protocol: SCP

  • Host name: controller IP address.

  • User name: root.

Leave the Password field blank.

3. Press the "Login" button.

4. If "Warning" window is opened, press «Yes».

This warning occurs when WinSCP connects to a new SSH server.

5. On the left side of the application, the file system of your computer will be, on the right - the file system of the TRIK controller.

How to find out the version of TRIK Studio Junior

The TRIK Studio Junior version is displayed in the window title.

And also on the start page.

TRIK Studio Junior settings

Settings window

To open TRIK Studio preferences press the corresponding item in the main menu:Settings → Preferences....

The interface of the settings window in TRIK Studio Junior is the same as the interface of the settings in TRIK Studio:

Links between blocks in TRIK Studio Junior

This article is automatically translated from Russian by Google Translator.

Links between blocks in TRIK Studio indicate the control flow of interpretation between blocks.

Example

Let it be necessary that after the delay the program ends immediately. To do this, connect the Timer and Final blocks with a link pointing from the "Timer" block to the program end block.

Creating and deleting links in TRIK Studio Junior is the same as in TRIK Studio:

Subprograms in TRIK Studio Junior

Any program in TRIK Studio can be saved as a subprogram and used in another program.

Working with subprograms in TRIK Studio Junior is similar to working with subprograms in TRIK Studio:

Exercises in TRIK Studio Junior

Exercise is a regular program in which you cannot modify some parts of a solution (blocks, sensors setup, world parameters). That is, any diagram can be saved as an exercise for students.

Exercises are created and loaded in TRIK Studio Junior in the same way as in TRIK Studio:

Sublime Text

TRIK Studio can be integrated with the external Sublime Text programming environment.

This will allow experienced TRIK Studio users to use all the features of professional text editors and their plugins:

  • static analyzers,

  • auto formatters,

  • color themes.

Read about how to integrate Sublime with TRIK Studio in the articles:

Programming TRIK with the visual programming language

For programming the TRIK controller with the visual language, TRIK Studio has specialized blocks, as well as sensor variables.

Read more about visual programming in the article

Working with graphs

If the program is launched in the interpretation mode on the robot or in the two-dimensional model, you can see the readings of the robot sensors on the graph in the .

The graph is scaled automatically so that the readings curve fits entirely in height.

From the drop-down list below you can select a sensor, the values ​​from which will be displayed on the graph.

When you hover over a point on the graph, the value at that point will be displayed.

To the right of the graph there are four buttons for working with it:

How to open robot settings

Robot settings in TRIK Studio can be opened in two ways.

Way 1

Using the toolbar button:

Way 2

1. Choose in the Settings → Preferences → Robots.

2. In the opened window open the tab "Robots".

How to change TRIK Studio interface language

Interface language can be changed in the TRIK Studio settings.

1. Choose Settings → Preferences ... in the

2. Choose the "Behaviour" tab in the opened window.

3. Select necessary language. Now TRIK Studio supports English, Russian and French.

“<System language>” means that the TRIK Studio interface language will be determined by the language of the operating system.

4. Press "OK".

5. Restart TRIK Studio to apply the changes.

Visual programming

A program in the TRIK Studio is represented as a sequence of the connected by the .

Each program corresponds to the , which may contain other . Diagrams are packaged in projects stored on the disk.

Main diagram

The main diagram is created when the . About adding and removing blocks to the , read the article:

Subprograms

The diagrams with subprograms are created automatically when you add the block "" to the scene. In this case, the subprogram is displayed by double-clicking on the "Subprogram" block on the scene.

Read more about subprograms in the article:

TRIK Studio language tokens

The language uses spaces, tabs, and line breaks outside of string literals only as separators between tokens — they do not affect the interpretation of expressions.

The language has the following keywords:

  • and

  • false

  • nil

  • not

  • or

  • true​

And the following :

String literals are written in either single or double-quotes. For example,

Integers are written either in decimal, octal, or hexadecimal. Hexadecimal numbers begin with the prefix 0x, octal numbers begin with the prefix 0. For example,

  • 3, 345 — decimal number

  • 0xff, 0xBEBADA — hexadecimal number

  • 07654321 — octal number

Real numbers are written either in conventional or exponential form. For example,

Comments begin with -- and continue to the end of the line. For example,

See the article about the syntax of expressions in the blocks:

Sensor variables

Besides , in TRIK Studio reserved variables are available that store the values ​​of the readings of sensors connected to the corresponding ports.

These values ​​can be assigned to variables and used in mathematical expressions.

Variables have the form

For example, sensorA1 for TRIK or sensor1 for Lego NXT.

A complete list of sensor variables is provided in sections for specific platforms:

  • .

  • .

  • .

External tools

PuTTY, WinSCP, TRIK Gamepad

Three external programs are available in TRIK Studio:

  1. .

  2. .

  3. .

To start the program, go to the menu Tools → External tools.

Avast antivirus blocks TRIK Studio. What to do?

This article is automatically translated from Russian by Google Translator.

Avast gives a message about a blocked file

If Avast antivirus gives a message about blocking the file when you install or run TRIK Studio, you should add the file to exceptions in the antivirus settings, or select "MORE OPTIONS"→"Open anyway".

Or wait for some time for this message and continue your job:

Avast does not display a threat message (file moved to virus chest)

It is possible that Avast may delete the TRIK Studio executable file or simply not display a threatening message when launching TRIK Studio. In this case: 1. Open the main window of Avast. 2. In the "Menu", select the "My Statistics" item.

3. Then "Threats in Virus Vault (Open Virus Vault)".

4. Hover the mouse cursor over the locked file entry and a drop-down menu button "..." appears on the right. Click it and select "More Options".

5. Then select "Restore and add to exceptions".

6. After these actions TRIK Studio should start and work normally.

TRIK Studio Junior interface

The TRIK Studio interface depends on the selected mode. TRIK Studio Junior, like , has two modes:

  1. It is intended for creating a robot control diagram and executing it in the generation mode.

  2. It is intended for executing and debugging a program on a 2D model.

The TRIK Studio Junior interface depends on the selected mode and coincides with the TRIK Studio interface:

Visual programming in TRIK Studio Junior

A program in the TRIK Studio Junior is represented as a sequence of the connected by the .

Each program corresponds to the , which may contain other . Diagrams are packaged in projects stored on the disk.

Main diagram

The main diagram is created when the . About adding and removing blocks to the , read the article:

Subprograms

The diagrams with subprograms are created automatically when you add the block "Subprogram" to the scene. In this case, the subprogram is displayed by double-clicking on the "Subprogram" block on the scene.

Read more about subprograms in the article:

PyCharm

TRIK Studio can be integrated with the external programming environment .

This will allow experienced TRIK Studio users to use all the features of professional text editors and their plugins:

  • static analyzers,

  • auto formatters,

  • color themes.

Read about how to integrate PyCharm with TRIK Studio in the article:

Uploading programs to several TRIK robots from Sublime Text

This article discusses the possibility of simultaneous loading of programs on a group of robots using the external text editor Sublime Text. The article is a continuation of the next material

Setting up

Download the file for Windows and place it in the folder where TRIK Studio is installed.

The manual was tested on Sublime Text 3 (Build 3211). You can download Sublime Text from the .

Before starting the program for the first time, you should log in to the TRIK controller via WinSCP. Instructions on how to do this are available . After that WinSCP will remember that it was allowed to establish a connection with this robot and will not require confirmation. This step must be repeated each time a new controller is connected.

1. Start Sublime Text.

2. Choose Tools → Build System → New Build System

3. A window with a text file will open. In it, you need to erase everything and insert the following code instead:

Where:

  • <path to scripts dir> — the full path to the folder with the programs to be loaded onto the robots,

  • <file with ip addresses> — the name of the.txt file that contains the IP addresses of the robots to upload the files.

  • There must be one IP address per line. The file must be in the same folder as the programs to be uploaded.

4. Specify your path to the send_files.cmd file instead of the one specified in the code.

Exapmple:

5. Save the file in the suggested directory <system directory>\Sublime Text 3\Packages\User under the nameTRIK_SEND.sublime-build.

6. ChooseTools → Build System and then in the list opened chooseTRIK_send.

7. To start sending programs to robots, just click Tools → Build or the corresponding key combination Ctrl+B. In order to return to , select Tools → Build System and select TRIK in the list that opens.

Connecting to the TRIK controller via Wi-Fi

The TRIK controller has a Wi-Fi module that can work in two modes:

  1. The access point mode, when the controller creates a new network, and we connect devices to it.

  2. The Wi-Fi client mode, when we connect the controller to an existing network.

To select a mode in the controller menu, select the Network item.

Read about connecting the controller to devices in different modes and the interaction of several controllers in the articles:

Connecting the TRIK controller to a computer and smartphone

Using access point and client modes

The TRIK controller can be connected to other devices in two ways:

  1. Using the TRIK controller as an access point (the controller creates a new network) and connects the devices to it.

  2. Using the TRIK controller in Wi-Fi client mode and connect the devices and the controller itself to an existing network.

Method 1. The controller in the Wi-Fi access point mode

In this mode, the controller creates a new network, so we can connect devices to it.

1. Select Network → Wi-Fi hotspot in the menu. The controller will distribute Wi-Fi, and the network parameters will appear on the screen:

  • Network name.

  • Password.

  • Controllers IP address.

2. When connecting a computer or smartphone to a Wi-Fi network, select the network and enter the password.

Method 2. The controller in the Wi-Fi client mode

In this mode, we connect the controller and devices to an existing Wi-Fi network.

To do this, in the controller's , we need to enter the name and password of the network to which we will connect the controller.

1. To launch the web interface, connect your computer or smartphone to the controller as an access point.

2. In the address bar of the browser, enter the IP address of the controller. The web interface will open.

3. In the "Wi-Fi client" field, enter the name and password of the network to which you want to connect the controller. Click the Save button.

4. Switch the controller to Wi-Fi client mode.

5. If the connection is successful, the controller's IP address will be displayed at the top of the screen next to the icon , and the network name will be highlighted in the list with the icon .

Connecting the TRIK controller to TRIK Studio

1. Connect the controller to the computer with TRIK Studio installed in either of .

2. In the TRIK Studio settings, go to the "Robots" section and select the TRIK platform in the "Platforms" window.

3. Enter the IP address of the controller in the "TCP Settings" field.

Also, the controller IP address can be specified on the toolbar:

4. Click "OK".

How to check the connection?

Try to a program to the controller.

What if there is no connection?

If there is no connection to the controller, TRIK Studio will show an error:

In this case check:

  1. Whether the IP address in TRIK Studio matches the IP address on the controller.

  2. Whether the TRIK controller displays its IP address. The IP address may not exist if the controller is connected to a Wi-Fi network in Wi-Fi client mode, but the router did not issue it. We recommend that you wait for a little or switch to the "Access Point" mode and back in the Wi-Fi client mode. It can also happen in Access Point mode. We recommend turning off the controller for a while and then restarting it.

Connecting devices to TRIK and working with them

This article is automatically translated from Russian by Google Translator.

The TRIK controller allows you to build a robotic model without limiting yourself in the choice of "equipment" for it.

It allows you to connect digital and analog sensors, external devices via i2c and UART protocols, has two video ports and a USB connector.

There are 6 ports for servo motors and 4 ports for power motors.

This section contains information on how to connect sensors, motors, cameras to the TRIK controller - it describes the process of testing the connected devices, their configuration, and effective use together with the TRIK Studio programming environment.

How to find out the firmware version of the TRIK controller?

1. Turn on the controller.

2. Go to More... → Version & Update.

3. The "OS version" is the controller firmware version.

Subprograms
Exercises
Running a 2D model in TRIK Studio from Sublime Text
Uploading programs to several TRIK robots from Sublime Text
Visual programming
sensor<port name>
constants
TRIK
LEGO EV3
LEGO NXT

Function include

This article is automatically translated from Russian by Google Translator.

Function description

Allows you to use functions implemented by the user in other files. It is supposed to write your own libraries.

As a passed parameter you must specify the full system path to the file with the required functions or the name of the file. In the second case, the file for a connection must be in the same directory as the main file in which include is called.

Function call

other_file.js
// Functions must be declared as global variables
sum = function(a, b) {
    return a + b;
}
include("other_file.js");
print(sum(1, 2));
+ - * / % ^ # & ~ | << >> // == ~= <= >= < > = ( ) { } [ ] ; : , . .. && ||
a = 'alo123'
a = "alo123"
3.0
3.1416 
314.16e-2
0.31416E1 
34e1​
a = 1; -- remark
operators
Syntax of expressions in the blocks
TRIK Studio
Editing mode
Debug mode
TRIK Studio interface
PyCharm
Running a 2D model in TRIK Studio from PyCharm
Connecting devices to TRIK and working with them
Testing devices connected to the TRIK controller
Configuring the operation of a USB camera with a TRIK controller
Capturing images with TRIK camera and using them in TRIK Studio
TRIK Studio settings
Links between blocks

Button

Description

Change the scale of the graph.

Clear the graph.

Export graph readings in .csv (comma-separated value) format. All readings of the selected sensor from the beginning of their recording are exported.

special window
{
"cmd": ["D:\\TRIKStudio\\send_filesl.cmd", “<path to scripts dir>”, "<file with ip addresses>"],
"selector": "source.js"
}
"cmd": ["C:\\TRIKStudio\\send_files.cmd", "C:\\Users\\Admin\\myfiles", "ip_addr.txt"]
send_files.cmd
official website
here
start the 2D model
Running a 2D model in TRIK Studio from Sublime Text
main menu
main menu
blocks
links
main diagram
diagrams (subprograms)
project is created
scene
Subprogram
Adding and removing blocks
Subprograms
PuTTY
WinSCP
TRIK Gamepad
blocks
links
main diagram
diagrams (subprograms)
project is created
scene
Adding and removing blocks in TRIK Studio Junior
Subprograms in TRIK Studio Junior
web interface
two ways
upload
Connecting the TRIK controller to a computer and smartphone
Connecting the TRIK controller to TRIK Studio
Interaction of TRIK controllers

TRIK Studio language types

Unlike Lua, the TRIK Studio language is statically-typed, that is, the type of each expression and each variable must be known at compile time. Moreover, the language does not require (and does not even allow!) to explicitly write the types of variables. It uses automatic type inference for the use of variables.

For example, environment "understands" from the expression a = 1 that type of a is integer.

Type

Description

Boolean (logic) type

Can be one of two values: true or false.

Real

Uses IEEE 754 64-bit binary64 representation (allows to store values up to 1.7E+308).

Integer

Uses 32-bit signed representation (allows to store values in a range from -2 147 483 648 to 2 147 483 647).

String

Allows storing character strings of arbitrary length in UTF-8 encoding.

Null type

It has only a one-nil value and means the absence of any other value type.

Allows storing an arbitrary number of values ​​of an arbitrary (but for each value in the same array of the same) type, including other arrays, and access values ​​by index.

See the article about the syntax of expressions in blocks:

Textual programming

Creating a new text program, generating diagrams in code and supported programming languages

The text-based programming mode allows you to edit the program generated from the diagram before downloading it to the robot or write the program in text form from scratch.

Create a new text program

1. Create a diagram containing the "Initial Node" and "Final Node" blocks.

2. Select a real robot mode.

3. Click on the “Generate Code” button. After that, an empty program template that contains all the necessary declarations will appear.

Generate code from the diagram

1. Select the real robot mode.

2. Press the "Generate code" button.

When the diagram is regenerated, manual changes will not be lost if the text file is saved. The result of the new generation will be saved to another file.

Supported programming languages

The supported text programming language is platform-dependent. One platform can have multiple target text languages.

Attention! Available generators depend on the installed plug-ins.

TRIK controller

For the TRIK platform, generation is possible in:

  • Python.

  • JavaScript.

Lego EV3 controller

Experts in EV3 can look at the code generated in the internal language of EV3 using the "Generate into EV3 byte code" button. Theoretically, it can be edited and run for execution or even used for EV3 text programming, but it is inconvenient to do this - the language was created to automatically generate, rather than write programs.

Lego NXT controller

For Lego NXT, generation in C language is supported using the ECRobot library.

Geoscan Pioneer quadcopter

For the quadcopter Geoscan Pioneer, generation in Lua is possible.

About TRIK Studio Junior

This article is automatically translated from Russian by Google Translator.

TRIK Studio Junior is a free programming environment with the "Character movement" for elementary grades.

The environment has a common interface with the TRIK Studio programming environment for robots, which allows for a continuous learning process, starting from elementary grades.

Features of TRIK Studio Junior

1. Loops, subprograms, arrays, mathematical and logical operators support.

2. Wide range of characters.

3. Support for exercise creation with auto-check for self-study and homework.

4. Just like TRIK Studio, TRIK Studio Junior has an interactive simulation mode. You don't need to have a constructor to learn how to program.

Since the interface and work in TRIK Studio Junior in many respects coincides with the interface and work in TRIK Studio, some articles in this section will provide links to similar articles in the TRIK Studio help section.

What is "Character movement"

"Character movement" — an object that understands and executes the commands of the algorithm. In TRIK Studio Junior, you can change the artist's image.

Download TRIK Studio Junior

You can download the latest version of TRIK Studio on the website trikset.com.

Recommended system requirements

  • RAM: 4 GB or more.

  • Operating system:

    • 64-bit Microsoft Ⓡ Windows 10.

    • Ubuntu 16.04 and later.

    • macOS 10.12 Sierra and later.

Getting started and creating a project in TRIK Studio Junior

Main window

After starting TRIK Studio Junior, you will see the start page that displays the version of TRIK Studio Junior, quick access to recent projects, and buttons for opening an existing project and creating a new one.

Project creation

To create a new project, click the "New project" button on the TRIK Studio Junior home page.

Or select File → New project from the main menu.

A window opens with a new program in the visual programming language:

Read about programming in a visual language in the article:

Launch an existing project

To start an existing project, click the "Open project" button on the TRIK Studio start page.

Or in the main menu, select File → Open....

By default, TRIK Studio Junior searches for files in the *.tsj format.

Running a 2D model in TRIK Studio from Sublime Text

This article discusses setting up and using the Sublime Text external programming environment to call programs in the TRIK Studio 2D model.

This will allow experienced TRIK Studio users to use all the features of professional text editors and their plugins: static analyzers, auto formatters, color themes.

It also describes how to automatically run the program on several fields, which can be useful for participants in competitions with automated verification systems.

Preparation

It is assumed that the user is writing a program in an external editor and would like to run this program on one or more fields. Fields can be presented both in the .xml format (more details in the article "2D model tuning"), and in the.qrs format.

  1. Download run_2d_model.cmd file for Windows or run_2d_model.sh for Linux and place it in the folder where TRIK Studio is installed.

  2. Place the fields on which you want to test the program in a separate folder. If the fields are in .xml format, create an empty default.qrs project in this folder.

Setting up Sublime Text

The instruction was tested on Sublime Text 3 (Build 3211). You can download Sublime Text on the official website.

1. Open Sublime Text.

2. ChooseTools → Build System → New Build System.

3. A window with a text file will open. You need to erase everything in it and paste the following code instead, where <path to field dir> is the full path to the folder with the fields:

{
"cmd": ["D:\\TRIKStudio\\run_2d_model.cmd", “<path to fields dir>”, "$file"],
"selector": "source.js",
"encoding": "windows-1251"
}

4. Edit this file:

  • For Linux, substitute your path to the run_2d_model.sh file instead of the one specified in the code. For example: "cmd": ["/home/admin/TRIKStudio/run_2d_model.sh", “/home/admin/fields/”, "$file"]

  • For Windows, substitute your path to the run_2d_model.cmd file instead of the one specified in the code. For example: "cmd": ["D:\TRIKStudio\run_2d_model.cmd", "D:\Users\Admin\fields", "$file"]

5. Save this text file in the suggested directory <system folder>\Sublime Text 3\Packages\User under the name TRIK.sublime-build.

6. Open your source code in Sublime Text. To launch it, just click Tools → Build or the corresponding key combination (Ctrl + B).

For the proposal to add this functionality, the TRIK project team thanks Alexander Zhuravlev, the participant of the NTI IRS Olympiad 2018-2020.

About the TRIK controller

The TRIK controller is an educational robotics platform developed by a team of experienced engineers specifically for robotics.

TRIK Studio supports this platform.

The TRIK controller has a color touchscreen display, programmable buttons and a Wi-Fi module that can operate in two modes.

The TRIK controller is compatible with a wide range of peripheral devices, including all the necessary equipment for controlling DC motors and servo drives, as well as for receiving and processing information from digital and analog sensors, microphones, and video modules.

The TRIK controller supports various ways of connecting via Wi-Fi, connecting and working with external devices.

For detailed information about the TRIK controller, see the manufacturer's website.

TRIK controller programming

To program the TRIK controller, select "TRIK" in the TRIK Studio settings in the "Robots" tab.

Use specialized and common blocks to write programs in a visual language. Read more about visual programming in the article

Read about text programming in the article

An example of solving a problem on the interaction of two robots

The task

Send message "5" from one robot and receive it on another.

Please note that the task can only be solved in real robot mode.

Solution

To solve the problem, you have to:

  1. Write a message transmission algorithm for the leading robot.

  2. Write a message reception algorithm for the second robot.

  3. Connect robots to a single network.

  4. Run programs on robots.

Message transmission algorithm

1. Switch TRIK Studio to the real robot mode.

2. Enter a message variable for the message and initialize it by assigning it the number 5 in the "Expression" block.

3. Add "Send message" and "End" blocks. In the properties of the "Send message" block, specify the onboard number of the robot to which you want to send the message and the variable containing the message.

The complete algorithm

Message reception algorithm

1. Switch TRIK Studio to the real robot mode.

2. Add the "Receive message" block. In the block properties, specify the variable in which you want to write a message sent from another robot. The variable can be named whatever you want. Set the "Wait for message" property to true.

3. After the message has arrived, display it on the robot's screen for 3 seconds, and then finish the algorithm. To do this, add blocks "Print Text", "Timer" and "End". In the properties of the "Print text" block, check the Calculate box and specify true in the "Update image" field.

The complete algorithm

TRIK controller programming in Python and JavaScript

This article is automatically translated from Russian by Google Translator.

Creating a text program

Read the article about creating a new text program and generating a diagram to code:

Programming in Python and JavaScript

The functionality of the runtime environment is accessed through predefined objects and functions.

Objects

Object

Description

Represents the TRIK controller and provides access to the robot's devices.

Represents methods of controlling the execution of the script and provides access to operating system functions.

It implements communication between robots in the network by means of the mailbox mechanism.

Serves to work with the remote control.

Provides management of parallel threads.

Functions

Function

Description

Returns a one-dimensional array of bytes containing the pixels of the rgb32-formatted image taken from the camera.

Allows you to use functions implemented by the user in other files. It is assumed for writing your own libraries. As a passed parameter you must specify the full system path to the file with the required functions.

Class «accelerometer»

This article is automatically translated from Russian by Google Translator.

Represents the accelerometer of the TRIK controller.

Method

Description

Returns the current sensor reading as an array of three elements corresponding to the sensor readings along each axis.

Signal

Description

The signal sent by the sensor when new data is ready.

read

Returns the current sensor reading as an array of three elements corresponding to the sensor readings along each axis.

Syntax

brick.accelerometer().read();
brick.accelerometer().read();

newData

The signal sent by the sensor when new data is ready.

Class «led»

This article is automatically translated from Russian by Google Translator.

Provides control of the LED on the body of the robot.

Method

Description

Turns the LED on in "red" mode.

Turns the LED on in the "green" mode.

Turns the LED on in the "orange" mode.

Turns off the LED.

red

Turns the LED on in "red" mode.

Syntax

brick.led().red();	
brick.led().red();

green

Turns the LED on in the "green" mode.

Syntax

brick.led().green();	
brick.led().green();

orange

Turns the LED on in the "orange" mode.

Syntax

brick.led().orange();
brick.led().orange();

off

Turns off the LED.

Syntax

brick.led().off();
brick.led().off();

How to find out the version of TRIK Studio

The TRIK Studio version is displayed in the window title.

And also on the start page.

Syntax of expressions in the blocks

To declare variables and set certain values ​​for them, the “” block is used.

For mathematical expressions — "" block.

Also, mathematical expressions, including those that change the values ​​of variables, can be used almost everywhere where you can specify a value.

Blocks and their properties that do not allow the use of mathematical expressions are described in the section .

All variables in the program are global, i.e. their values ​​can be used in any block in the program.

TRIK Studio language

The language used inside the blocks is based on and largely follows its syntax. Nevertheless, there are significant differences, so a full description of the language used in TRIK Studio is given here.

Examples of expressions

Declaration of several variables in one block "":

The same using blocks:

Proportional controller for driving along the line using two light sensors for the TRIK platform:

An example of using to set the ports of the “Motors forward” block. An array is created with the name a, the port M3 is assigned to the zero element, the first is M1, then the contents of the first element of the array are changed to M4, then the resulting array is transferred to the “Ports” property of the “Motors forward” block:

Property editing

In TRIK Studio, there are two ways to edit property values ​​of blocks and links between them:

  1. .

  2. .

Attention! Editing the properties of the block is carried out only using the context menu.

Using Property Editor panel

When a block, link, or element is selected, all the properties of the current element are displayed on the panel.

The property editor is a table. In the left column, the property name of the element is displayed, in the right - its value.

You can change the value of any property by clicking on the corresponding cell in the right column and entering the desired value.

For properties that allow only a specific set of values, for example, the “Port” property of the "" block, when you try to edit them, a drop-down menu will appear where the desired value is selected:

Property editing on the diagram

To edit properties directly on the diagram:

  1. Hover over the value of the desired property.

  2. Double-click the left mouse button to activate editing properties.

  3. Enter the desired value.

  4. Click on any place in the scene.

Attention! This approach can serve as a source of errors, because it allows you to enter an arbitrary text value of the property, including the incorrect one. Be careful.

Screenshot of the TRIK controller screen

Using the web interface, as well as the PuTTY and WinSCP utilities

A screenshot of the TRIK controller screen can be taken in two ways:

  1. Using the .

  2. With the .

Using the web interface

1. Connect to the controller via Wi-Fi using any .

2. Log in to the by typing the IP address of the controller in the browser.

3. Make sure that the image or text you want to take a screenshot of is displayed on the controller screen.

4. Select the Image menu item in the web interface and click the Make Screenshot button.

5. After that, the screenshot will appear in the list. If this does not happen, you need to refresh the page (F5 or Ctrl-R).

6. To download the screenshots you've taken, click the Download All button.

With the PuTTY and WinSCP utilities

1. Connect to the controller via Wi-Fi using any .

2. Open TRIK Studio.

3. Run the PuTTY utility. To do this, in the main menu open Tools -> Third-Party Programs -> PuTTY.

4. Wait for the connection process to complete.

5. Make sure the controller displays the image or text you want to screenshot.

6. Enter the fbgrab image.png command, where image is an arbitrary name for the saved image.

7. If successful, the following text will be displayed in the console:

Resolution: 240x320 depth 16 Converting image from 16 Now writing PNG file (compression -1)

8. Run the utility. To do this, open Tools → Third-Party Programs → WinSCP in the main menu.

9. If you see a "Warning" window, click "Yes".

10. Select in the left window the directory where you want to save the snapshot. Drag the created image from the right window to the left.

Launching and uploading programs to the TRIK controller

To work with the TRIK controller in the TRIK Studio settings, go to the section and select the TRIK platform.

There are several options for executing programs for the TRIK controller:

  • Step-by-step diagram interpretation with a simulation of robot behavior on a 2D model.

  • Uploading the program to the robot and its further autonomous execution without communication with the computer.

Interpretation with a simulation of robot behavior

In the robot's 2D model mode, commands are not transmitted to the robot but are executed step-by-step by the virtual robot displayed on the screen. For more information, see the article .

1. Turn on 2D model mode.

2. Click on the "Run" button.

3. The 2D model window will open and the program will start running.

4. When you switch to edit mode, you can track the steps of the program.

Uploading to the controller

From TRIK Studio, you can upload a program to a robot in order to execute it autonomously later without connection to a computer. 1. the TRIK controller to TRIK Studio. 2. Click on the "Upload Program" button.

3. To run the program on the controller go to the "Files" menu, select the desired program and press the "Enter" button.

Class «colorSensor»

This article is automatically translated from Russian by Google Translator.

The camera in color sensor mode.

init

Turns the camera on and initializes it in color sensor mode.

Syntax

The boolean parameter defines whether to display the image from the camera:

  • true — output,

  • false — do not output

read

Returns an array with the coordinates of the dominant color in the RGB color scale in the specified area of the frame.

The frame is divided into squares by a grid, by default 3 by 3, the dimensionality of the grid can be set in model-config.xml on the robot. Squares are indexed from 1. That is, (1, 1) is the upper-left edge of the frame, (2, 2) is its center.

The return value is an array of three elements from 0 to 255, indexed from 0. The zero element contains the intensity of red (0 - none at all, 255 - very much), the first - the intensity of green, the second - the intensity of blue. For example, (0, 0, 0) is black, (255, 255, 255) is white, (255, 0, 0) is red.

Syntax

As a parameter, it is necessary to specify the indices of the square x and y.

stop

Turns off the camera and stops the sensor.

Syntax

Syntax of expressions in the blocks
Array
Textual programming
brick
script
mailbox
gamepad
Threading
getPhoto
include(“path”)
read
newData
red
green
orange
off

Method

Description

init​

Turns the camera on and initializes it in color sensor mode.

read​

Returns an array with the coordinates of the dominant color in the RGB color scale in the specified area of the frame.

stop

Turns off the camera and stops the sensor.

brick.colorSensor("video1").read(x, y);
brick.colorSensor("video1").read(x, y);
brick.colorSensor("video1").stop();
brick.colorSensor("video1").stop();
brick.colorSensor("video1").init(True);
brick.colorSensor("video1").init(true);
Blocks in TRIK Studio Junior
How do I replace the "Character movement" image?
Exercises in TRIK Studio Junior
How do I replace the "Character movement" image?
How to find out the version of TRIK Studio Junior
Visual programming
Textual programming
Variable Initialization
Expression
"Common blocks"
Lua 5.3
Types
Tokens
Operators
Sensor variables
Constants
Built-in functions
Expression
"Variables Initialization"
arrays
"Variable Initialization" block
"Expression" block
Using Property Editor panel
Directly on the diagram
Subprogram
Property Editor
Wait for IR distance sensor
web interface
PuTTY and WinSCP utilities
method
web interface
method
WinSCP
"Robots"
"2D Model"
Connect

Adding and removing blocks

Add blocks to the scene

You can add blocks to the scene in TRIK Studio in three ways:

  1. Drag and drop the corresponding icons from the palette of elements onto the diagram.

  2. Using mouse gesture.

  3. When creating a new connection between blocks using a linker.

Drag and drop from the palette

Left-click on the necessary block located in the Palette panel. Without releasing the mouse button, move the block onto the scene.

Use mouse gestures

Draw on the scene a special image of the block with the Right mouse button. The block appears in the center of the drawn image.

Gestures can be drawn with a few strokes. The gesture input ends if the strokes have not been drawn for some time (you can set the time in the settings window on the Behavior tab).

Available conditional images can be found in two ways:

1. In the "Mouse Gestures" window, which opens through the main menuTools → Mouse gestures.

2. In the tooltip that appears when you hover over a block in the Palette panel.

Add block when creating a new connection

  1. Start creating a connection using the linker (a colored circle to the right of the block that appears after the block is selected) and release the left mouse button when the cursor is on an empty section of the diagram.

  2. In the menu that appears, select "Create new element". A new menu with blocks will appear.

  3. Select the block you need.

Delete block

Deleting a block from the scene is possible in two ways:

  1. Select the block with the left mouse button and then click the "Delete" button on the keyboard.

  2. Right-click on the block and select "Delete" in the menu that appears.

Delete several blocks

1. Select the necessary blocks in one of the following ways.

1.1. Hold down the "Ctrl" button and right-click the necessary blocks.

1.2. Right-click on an area in the scene with the necessary blocks.

2. Delete the selected blocks in one of the following ways.

2.1. Press the “Delete” button on the keyboard.

2.2. Right-click on any selected block and select "Delete" from the menu that appears.

Replace block

To replace the block on the scene:

1. Right-click on the block and select "Replace by..." in the menu that appears.

2. Select the block that you want to put instead of from the list.

Links between blocks

Links between blocks in TRIK Studio indicate the control flow of interpretation between blocks.

Example

Let it be necessary that after the delay the program ends immediately. To do this, connect the Timer and End blocks with a link pointing from the "Timer" block to the program end block.

Create links

Links can be created in two ways:

  1. Using mouse gesture.

  2. Using linkers.

Using mouse gestures

Hover over a block, hold down the right mouse button and draw a line to the second block. The line shape can be arbitrary. It is important that it starts strictly on one block and ends on the second.

If you move the mouse cursor over the link, gray markers are displayed at its ends. By pulling on one of these markers, you can control the link. To attach one of the ends of the connection to the block, you need to pull the corresponding gray marker and release it on the block of interest.

Using linkers

The Linker is a colored circle to the right of the block that appears after the block is selected. When you click on this circle and move the mouse with the left button pressed, the link begins to stretch out of the element.

If you drop this relationship on an existing element, these elements will be connected.

If you release the left mouse button when the cursor is on an empty section of the diagram, a menu with the following items will appear:

  • Delete

  • Create new element

When you select the "Delete" menu item, the created link will be deleted.

When you hover over the menu item "Create a new element" a new menu appears, listing all the possible elements to create. When you select one of these items on the diagram, the corresponding element will be created and join the current link.

Delete links

Links are removed in the same way as blocks.

Add a new block on the link

If you need to add a new block between two linked blocks, drag a block from the Palette panel to the link. Release the mouse button when you hover over a link (not a block).

Create breakpoints

Links in TRIK Studio can be broken lines. To add a breakpoint, move the mouse cursor over the link, click the left mouse button and drag the gray marker that appears.

If the breakpoint of the connection is positioned so that it and the two nearest to it will be located approximately on one straight line, this will lead to the destruction of this breakpoint and smoothing of the broken line in this place.

Subprograms

Any program in TRIK Studio can be saved as a subprogram and used in another program.

Subprograms can be saved to a local collection or exported to a separate file for transfer to other computers.

To work with the collection of subprograms, use the menu item Tools → Subprograms:

  1. Export to file.

  2. Import from file.

  3. Save to collection.

  4. Load from the collection.

  5. Clear collection.

Export to file

Use the export of subprograms to a file to transfer them to other computers. If you plan to use the subprograms on your computer, then use the option Save to collection.

To export subprograms from an open project to a separate qrs file, select Tools → Subprograms → Export to file in the main menu.

All subprograms from the current project will be exported to this file.

Import from file

To load previously-stored subprograms, select Tools → Subprograms → Import from file in the main menu.

Attention! If the imported file contains subprograms with the same names as in the current project, then the subprograms from the project will be replaced by imported ones.

Save to collection

To transfer subprograms to other computers, use the export function.

To save routines from the current project, select Tools → Routines → Save to Collection from the main menu.

Then select the subprograms you want to save and click OK.

Attention! If there are subprograms with the same names in the collection, they will be overwritten.

Load from collection

To load subprograms from the collection, select Tools → Subprograms → Download from the collection from the main menu.

Then select the subprograms that you want to import into the current project, and click OK.

Clear collection

To delete all subprograms saved in the collection, select Tools → Subprograms → Clear collection in the main menu.

The collection of subprograms is stored in the user directory and is not lost when uninstalling or reinstalling TRIK Studio.

Exercises

Creation and upload of exercises

Exercise is a regular program in which you cannot modify some parts of a solution (blocks, sensors setup, world parameters). That is, any diagram can be saved as an exercise for students.

Exercise creation

1. Draw a field on the scene using the world editing panel, if it is necessary for your task.

2. Create a diagram.

3. Remove all or part of the blocks from the diagram. The Initial Node block must have remained on the scene.

4. Choose Tools → Save as task… in the main menu.

5. In the opened dialog, select the restrictions for the exercise.

Name

Description

1

2d model world is read-only

Forbids editing walls and colored lines in a two-dimensional model.

2

Sensors are read-only

It prohibits changing the configuration of sensors, as well as their position and direction in a two-dimensional model.

3

2D robot model position is read-only

Forbids to move the robot "manually."

4

Motors to wheels binding are read-only

Forbids changing motors in the settings of a two-dimensional model.

5

2D model simulation settings are read-only

It prohibits changing the noise settings of sensors and motors, as well as the physical engine in a two-dimensional model.

6. Click “OK” and select the path to save the exercise.

7. After saving, the exercise will automatically open in TRIK Studio, where you can make sure that the selected options are not available for editing.

Exercise load

Loading a saved exercise takes place as a regular program. For example, using the File Panel.

TRIK Studio shortcuts

The table below shows the default shortcuts. You can change the keyboard shortcut for actions in the settings of TRIK Studio.

Action

Shortcut

Switching TRIK Studio modes

Switch to

Ctrl+1

Switch to

Ctrl+2

Working with diagram

Show all text

Ctrl+Shift+T

Increase scene scaling

Ctrl+=

Decrease scene scaling

Ctrl+-

Redo

Ctrl+Shift+Z

Undo

Ctrl+Z

Find

Ctrl+F

Find and replace

Ctrl+H

Working with project

Close all tabs

Ctrl+Shift+W

Close current tab

Ctrl+W

Create project

Ctrl+N

Open project

Ctrl+O

Save project

Ctrl+S

Save project as

Ctrl+Shift+S

Upload program to the robot

Ctrl+U

Show/hide error panel

Alt+1

Show/hide console

Alt+2

Running a 2D model in TRIK Studio from PyCharm

This article is automatically translated from Russian by Google Translator.

This article deals with setting up and using the external programming environment PyCharm to call programs in the 2D model of TRIK Studio.

This will allow experienced TRIK Studio users to use all the features of professional text editors and their plugins: static analyzers, auto formatters, color themes.

It also tells how to automatically run the program on several fields, which can be useful for participants of competitions with automated checking systems.

Preparation

It is assumed that the user is writing a program in an external editor and would like to run this program on one or more fields. Fields can be presented both in the .xml format (more details in the article "2D model tuning"), and in the.qrs format.

  1. Download run_2d_model.cmd file for Windows or run_2d_model.sh for Linux and place it in the folder where TRIK Studio is installed.

  2. Place the fields on which you want to test the program in a separate folder. If the fields are in .xml format, create an empty default.qrs project in this folder.

Setting up PyCharm

Instructions tested on PyCharm Professional Edition (2019.3). You can download PyCharm from the official website.

1. Open the source code folder in PyCharm with File → Open.

2. ChooseFile → Settings or press the key combination «Ctrl+Alt+S».

3. ChooseTools → External tools and click on the «+».

4. In the Name field, enter the desired name of the tool, for example, «run_2d_model». In the Program field, type your path to the file run_2d_model.cmd. In the Arguments type the parameters $FileDir$ and $FileName$ or chooseInsert Macros and select the desired parameters from the list. In the Working Directory type$FileDir$ or chooseInsert Macros and select the desired parameter. Click the OK button.

5. To run the code, select Tools→ External tools and run_2d_model (or its name, chosen earlier).

6. To add "hotkeys" select File → Settings or press the key combination «Ctrl+Alt+S». In the menu that appears, select the tab Keymap and go to the created external tool. Click on run_2d_model right mouse button, select Add Keyboard Shortcut.

7. In the window that opens, enter the desired key combination to call the Toolbox and click «ОК».

8. Now you just have to press the selected combination (in this case Shift+B, but it is possible to choose any other) to run the code.

If an error occurs, select Settings → Tools → Terminal and enter your path to the cmd.exe file (shell path). Then click Apply.

Running a 2D model in TRIK Studio from VSCode

This article discusses setting up and using the VSCode external programming environment to call programs in the TRIK Studio 2D model.

This will allow experienced TRIK Studio users to use all the features of professional text editors and their plugins: static analyzers, auto formatters, color themes.

It also describes how to automatically run the program on several fields, which can be useful for participants in competitions with automated verification systems.

Preparation

It is assumed that the user is writing a program in an external editor and would like to run this program on one or more fields. Fields can be presented both in .xml format (for more details, see the article "2D model tuning"), and in .qrs format.

  1. Download run_2d_model.cmd for Windows or run_2d_model.sh for Linux and place it in the folder where TRIK Studio is installed.

  2. Place the fields on which you want to test the program in a separate folder. If the fields are in .xml format, create an empty default.qrs project in this folder.

The manual was tested on the January 2020 release (version 1.42). You can download VSCode from the official website.

Setting up VSCode

1. Create a folder where the source code file will be placed.

2. Open this folder in VSCode with File → Open Folder.

3. ChooseTerminal → Configure Tasks.

4. If there were no tasks before, then selectCreate tasks.json file from template → Others in the drop-down menu . The file tasks.jsonwill be opened. If tasks were created earlier, it will open right after point 3.

5. Delete everything from this file and paste this code, where <path to field dir>is the full path to the folder containing fields:

{
"version": "2.0.0",
	"tasks": [ {
		"label": "Run TRIK 2D model",
		"type": "shell",
		"command": "/home/admin/TRIKStudio/run_2d_model.sh" <path to fields dir> script.js",
		"windows": {
			"command": "D:\\TRIKStudio\\run_2d_model.cmd  <path to fields dir> script.js"
		},
		"group": "test",
		"presentation": {
			"reveal": "always",
			"panel": "new"
		}
	}]
}

6. Depending on your operating system, edit the filetasks.json:

  • For Linux, in the line corresponding to the "command" field, specify the path to the edited run_2d_model.shand specify your source code file as the third argument. This file should be located in the folder that we opened with VSCode. Example: "command": "/home/admin/TRIKStudio/run_2d_model.sh /home/admin/fields/ script.js"

  • For Windows, in the line corresponding to the

    "windows": { "command" field, specify the path to the edited run_2d_model.shand specify your source code file as the third argument. This file should be located in the folder that we opened with VSCode. Example: "command": "D:\TRIKStudio\run_2d_model.cmd D:\Users\Admin\fields script.js"

7. Save the filetasks.json.

8. Now select Run TRIK 2D modelin the dropdown menu Terminal → Run Task or press the corresponding keyboard shortcut (Ctrl+Shift+B) to run your code.

For the proposal to add this functionality, the TRIK project team thanks Alexander Zhuravlev, the participant of the NTI IRS Olympiad 2018-2020.

Uploading programs to several TRIK robots from VSCode

This article discusses the possibility of simultaneous uploading of programs on a group of robots using an external text editor VSCode. The article is a continuation of the next material

Setting up

Download the send_files.cmd file for Windows and place it in the folder where TRIK Studio is installed.

The manual was tested on the January 2020 release (version 1.42). You can download VSCode from the official website.

The first time the program is launched, confirmation from the user is required to establish a connection with the robot.

To allow the connection, enter Y or Yes at the command line.

1. Open the folder with the files you want to send in VSCode using File → Open Folder.

2. SelectTerminal → Configure Tasks.

3. If there were no tasks before, then select Create tasks.json file from template → Others from the drop-down menu. The tasks.json file will be opened. If tasks were created earlier, it will be opened right after step 2.

4. Remove everything from this file and paste this code:

{
    "version": "2.0.0",
        "tasks": [ {
            "label": "Send files",
            "type": "shell",
            "windows": {
                "command": "C:\\TRIKStudio\\send_files.cmd  <path to scripts dir> <file with ip addresses>"
            },
            "group": "test",
            "presentation": {
                "reveal": "always",
                "panel": "new"
            }
        }]
}

Where:

  • <path to scripts dir> is the full path to the folder with programs that must be uploaded on robots,

  • <file with ip addresses> is the name of the .txt file that contains the ip-addresses of robots for downloading files. One ip-address per line.

5. In the line corresponding to the "windows": {"command" field specify the path to the send_files.cmd file. The file with the IP addresses of the robots must be in the same folder as the programs to be sent. For example:

"command": "C:\TRIKStudio\send_files.cmd C:\Users\Admin\myfiles ip_addr.txt"

6. Save the file tasks.json.

7. Now select Send filesin the dropdown menu Terminal → Run Taskor press the corresponding keyboard shortcut (Ctrl+Shift+B) to upload programs to the robots.

Interaction of TRIK controllers

TRIK controllers can interact with each other, which makes it possible to solve problems of transferring messages between robots.

For the interaction of controllers, it will be necessary to select a master controller — the one to which we will connect the rest of the controllers. And also connect all controllers to one network. This can be done in two ways:

1. Using the existing network.

2. By creating a Wi-Fi access point on one of the controllers.

Method 1. Interaction using an existing Wi-Fi network

1. Select a master controller and connect it to an existing Wi-Fi network in client mode.

2. In the web interface of the master controller, in the "Interaction of robots" field, specify the tail number (usually for the master it is 01, but any other is possible) and its IP address.

3. Connect all other controllers to the same Wi-Fi network in client mode.

4. Specify for each of them in your web interfaces in the "Interaction of robots" field the tail number (different from the others) and the IP address of the master controller.

Also, the flight number and IP address of the master controller can be specified on the controller in the Interaction menu item.

4. On all controllers go to the Interaction menu item and click the "Connect" button. The icon should appear in the upper right corner of the controller screens.

Method 2. Interaction using a Wi-Fi access point on one of the controllers

Actions with the master controller

1. Select a master controller and share Wi-Fi from it using access point mode (select Network → Wi-Fi access point in the menu).

2. Next, return to the main menu screen and select Interaction.

3. Specify the tail number (usually for the master it is 01, but any other is possible) and its IP address.

Actions with other controllers

4. Connect the rest of the controllers to the master using the Wi-Fi client mode. To do this, in the web interface of each controller, in the "Wi-Fi client" fields, specify the name and password of the network of the master controller.

5. Open the web interface using the IP address displayed on the controller in Wi-Fi client mode.

6. Specify for each of the controllers in their web interfaces in the "Interaction of robots" field the tail number (different from others) and the IP address of the master controller.

Also, the flight number and IP address of the master controller can be specified on the controller in the Interaction menu item.

Action with all controllers

7. On all controllers go to the Interaction menu item and click the "Connect" button. An icon should appear in the upper right corner of the controller screens.

Class «objectSensor»

This article is automatically translated from Russian by Google Translator.

Camera in object sensor mode. Captures a contrasting object in the center of the frame and returns its coordinates and size in the frame.

Method

Description

Detects the dominant color in the center of the frame and remembers it as the color of the object.

Switches the camcorder on and initializes it in object sensor mode.

Returns an array with the X coordinate of the object center relative to the center of the frame, the Y coordinate of the object center relative to the center of the frame, and the relative size of the object.

Turns off the camera and stops the sensor.

detect

Detects the dominant color in the center of the frame and remembers it as the color of the object. After that, the "read" method starts to return data for the object.

Syntax

brick.objectSensor().detect();
brick.objectSensor().detect();

init

Switches the camcorder on and initializes it in object sensor mode. The boolean parameter determines whether to display the image from the camera (true — display).

Syntax

brick.objectSensor().init(true);
brick.objectSensor().init(True);

The boolean parameter defines whether to display the image from the camera:

  • true — output,

  • false — don't output.

read

Returns an array that contains the following data in its cells:

  • In the zero cell, the X-axis coordinate of the object center relative to the center of the frame (-100 to 100, -100 is the center of the object on the edge of the frame on the left);

  • The Y-coordinate of the object's center relative to the frame center (from -100 to 100, -100 is the center of the object on the frame edge at the top);

  • The second cell is the relative size of the object, a number from 0 to 100 (100 - the object occupies almost the entire frame, 0 - the object is not on the frame).

Syntax

brick.objectSensor().read();
brick.objectSensor().read();

stop

Turns off the camera and stops the sensor.

Syntax

brick.objectSensor().stop();
brick.objectSensor().stop();

Class «sensor»

This article is automatically translated from Russian by Google Translator.

Represents a sensor (analog or digital) connected to ports A1, ..., A6, D1, D2.

Method

Description

Returns the current reading of the sensor (digital or analog) connected to this port.

Returns the current raw reading of the sensor (digital or analog) connected to this port.

read

Returns the current reading of the sensor (digital or analog) connected to this port. The present value is returned, depending on the port configuration, which is described in the file model-config.xml in the trik folder on the robot.

For example, the IR distance sensor returns a value in centimeters.

Syntax

var data1 = brick.sensor(sensorName).read();
var data2 = brick.sensor("sensorName").read();
data1 = brick.sensor(sensorName).read();
data2 = brick.sensor("sensorName").read();

readRawData

Returns the current raw reading of the sensor (digital or analog) connected to this port. The range of values depends on the specific sensor and does not take into account the configuration of the robot (the physical readings of the sensor are returned, e.g. the delay of the received ultrasonic signal).

Syntax

var data1 = brick.sensor(sensorName).readRawData();
var data2 = brick.sensor("sensorName").readRawData();
data1 = brick.sensor(sensorName).readRawData();
data2 = brick.sensor("sensorName").readRawData();

Class «motor»

This article is automatically translated from Russian by Google Translator.

Provides control of the robot motor (power or servo motor) connected to ports M1, ..., M4, S1, ..., S6.

brake

Blocking of motors for braking for a specified time in milliseconds.

Syntax

As a parameter, you must specify the time in milliseconds.

power

Returns the current motor power (-100 to 100).

Syntax

powerOff

Turns the motor off.

Syntax

setPower

Turns on the motor with the specified power.

Syntax

As a parameter, you must specify the power. The power is set in the range from -100 ("full reverse") to 100 ("full forward"). 0 corresponds to a force break, i.e. the motor stops, it is blocked and remains energized.

Object «Threading»

This article is automatically translated from Russian by Google Translator.

Provides management of parallel threads.

joinThread

Waiting for the specified flow to complete.

Syntax

As a parameter, it is necessary to specify thread id.

killThread

Finishes the execution of the specified flow.

Syntax

The thread id must be specified as a parameter.

receiveMessage

Queries the received message.

Syntax

If wait is true, it waits until a message arrives.

sendMessage

Sends a message to the specified stream.

Syntax

As parameters, it is necessary to specify thread id and message.

startThread

Runs the function passed as a parameter in a separate thread.

Warning! This creates a new copy for all global variables. So if the value of a variable change in one thread, it stays the same in another thread.

Syntax

As parameters, it is necessary to specify thread id and function.

Class «encoder»

This article is automatically translated from Russian by Google Translator.

Represents power motor encoders connected to ports E1, E2, E3, E4.

read

Returns the current encoder reading in degrees on the specified port.

Syntax

As a parameter, you must specify the port.

Example

reset

Resets the current encoder reading to 0.

Syntax

As a parameter, you must specify the port.

Example

readRawData

Returns the current encoder reading in "ticks" on the specified port.

Syntax

Example

PuTTY

PuTTY — a client program for working with network protocols. You can connect to the using the SSH and Serial protocols.

Launching PuTTY from TRIK Studio

To run PuTTY, go to Tools → External tools → PuTTY.

Connection to the TRIK controller in PuTTY

1. Connect the controller to the computer via .

2. In the TRIK Studio settings on the tab, write down the IP address of the controller, which is displayed on the main screen of the controller.

3. Launch PuTTY from TRIK Studio by selecting Tools → External tools → PuTTY from the main menu.

4. In the window that opens, enter the root login. Leave the Password field blank.

editor mode
debug mode
detect
init
read
stop
read
readRawData

Method

Description

brake

Blocking of motors for braking for a specified time.

power

Returns the current motor power.

powerOff

Turns the motor off.

setPower

Turns on the motor with the specified power.

var pow1 = brick.motor(motorName).power();
var pow2 = brick.motor("motorName").power();
pow1 = brick.motor(motorName).power();
pow2 = brick.motor("motorName").power();
brick.motor(motorName).powerOff();
brick.motor("motorName").powerOff();
brick.motor(motorName).powerOff();
brick.motor("motorName").powerOff();
brick.motor(motorName).setPower(power);
brick.motor("motorName").setPower(power);
brick.motor(motorName).setPower(power);
brick.motor("motorName").setPower(power);
brick.motor(motorName).brake(durationMs);
brick.motor("motorName").brake(durationMs);
brick.motor(motorName).brake(durationMs);
brick.motor("motorName").brake(durationMs);

Method

Description

joinThread

Waiting for the specified flow to complete.

killThread

Finishes the execution of the specified flow.

receiveMessage

Queries the received message.

sendMessage

Sends a message to the specified stream.

startThread

Runs the function passed as a parameter in a separate thread.

Threading.killThread("threadId");
Threading.receiveMessage(wait);
Threading.sendMessage("threadId", "message");
Threading.startThread("newThreadId", "functionName");
Threading.joinThread("threadId");

Method

Description

read

Returns the current encoder reading in degrees on the specified port.

reset

Resets the current encoder reading to 0.

readRawData

Returns the current encoder reading in "ticks" on the specified port.

brick.encoder(portName).reset();
brick.encoder("portName").reset();
brick.encoder(portName).reset();
brick.encoder("portName").reset();
brick.encoder(E1).reset();
brick.encoder("E2").reset();
brick.encoder(E1).reset();
brick.encoder("E2").reset();
brick.encoder(portName).readRawData();
brick.encoder("portName").readRawData();
brick.encoder(portName).readRawData();
brick.encoder("portName").readRawData();
brick.encoder(E1).readRawData();
brick.encoder("E2").readRawData();
brick.encoder(E1).readRawData();
brick.encoder("E2").readRawData();
brick.encoder(portName).read();
brick.encoder("portName").read();
brick.encoder(E1).read();
brick.encoder("E2").read();
brick.encoder(portName).read();
brick.encoder("portName").read();
brick.encoder(E1).read();
brick.encoder("E2").read();

Built-in functions

In mathematical expressions, you can use the functions available for any platform.

Function

Description

time()

Returns the time in milliseconds since the program started.

sin(angle)

The sine of the angle, where "angle" is the angle in degrees.

cos(angle)

The cosine of the angle, where "angle" is the angle in degrees.

ln(a)

The logarithm, where "a" is a number.

exp(a)

Exponent ("e" in the degree of argument "a").

asin(a)

Arcsine, where "a" is a number.

acos(a)

Arccosine, where "a" is a number.

atan(a)

Arctangent, where "a" is a number.

atan2(a1, a2)

The arctangent of a1 / a2 with division check by 0.

sgn(a)

Sign. Returns 1 if the argument “a” is positive, -1 if it is negative, and 0 if the argument is zero.

sqrt(a)

The square root of the argument "a". If the argument is negative, the variable will be assigned the value “NaN” (Not A Number).

abs(a)

The absolute value of number "a".

ceil(a)

Rounds up the passed argument "a" to the nearest integer.

floor(a)

Rounds down the passed argument "a" to the nearest integer.

random(a)

A random number between 0 and the passed argument “a”.

Running a 2D model in TRIK Studio from VSCode
An example of solving a problem on the interaction of two robots
TRIK controller
Wi-Fi
Robots

Function getPhoto

This article is automatically translated from Russian by Google Translator.

Function description

The function returns a one-dimensional array of bytes containing the pixels of an rgb32-formatted image taken from the camera (image size 160x120). This function can be used to solve marker recognition problems.

Function call

var pic = getPhoto();

Work example

Let's look at an example of converting a frame taken with a camera to grayscale and black-and-white color formats.

Take a picture and display the result with the show function.

// take a frame in rgb32 format
var pic = getPhoto();
brick.display().show(pic, total_height, total_width, "rgb32");
script.wait(2000);
# take a frame in rgb32 format
pic = getPhoto();
brick.display().show(pic, total_height, total_width, "rgb32");
script.wait(2000);

Rwsult:

Implementing the grayscale function

function grayScale(sPic){
	bufPic = [];
	for(var i = 0; i < total_height; i++)
		for(var j = 0; j < total_width; j++){
			var x = i * total_width + j;
			var p = sPic[x];
			var r = (p & 0xff0000) >> 16;	// take the value of the red component
			var g = (p & 0xff00) >> 8;	// take the value of the green component
			var b = (p & 0xff);		// take the value of the blue component
			p = r * 0.299 + g * 0.587 + b * 0.114; // component Y of YUV
			bufPic[x] = p; 
		}
	return bufPic;
}
def grayScale(sPic):
	bufPic = [];
	for i in range(total_height):
		for j in range(total_width):
			x = i * total_width + j;
			p = sPic[x];
			r = (p & 0xff0000) >> 16;	# take the value of the red component
			g = (p & 0xff00) >> 8; # take the value of the green component
			b = (p & 0xff); # take the value of the blue component
			p = r * 0.299 + g * 0.587 + b * 0.114; # component Y of YUV
			bufPic.append(p); 
	return bufPic;

Converts the image to black and white and outputs it to the display:

var pic = grayScale(pic);

brick.display().show(pic, total_height, total_width, "grayscale8");
script.wait(2000);
pic = grayScale(pic);

brick.display().show(pic, total_height, total_width, "grayscale8");
script.wait(2000);

Result:

Implementing the image binarization function

// Binarization - converting the image to black and white
function binarization(treshold, sPic){
	bufPic = []
	for(var i = 0; i < sPic.length; i++){
		bufPic[i] = sPic[i] > treshold ? 255 : 0;
	}
	return bufPic;
}
# Binarization - converting the image to black and white
def binarization(treshold, sPic):
	bufPic = []
	for i in range(len(sPic)):
		bufPic.append(255 if sPic[i] > treshold else 0);
	return bufPic;

Translates the image to black and white and outputs it to the display:

var pic = binarization(80, pic);
brick.display().show(pic, total_height, total_width, "grayscale8");
script.wait(2000);
pic = binarization(80, pic);
brick.display().show(pic, total_height, total_width, "grayscale8");
script.wait(2000);

Result:

An example of a program using the getPhoto function.

TRIK controller firmware

Instructions for Windows, Linux and Ubuntu

Choose your operating system:

Windows

1. Download the latest . 2. Download and install .

Attention! You will need administrator permissions to install and use DiskImager.

3. Remove the microSD card from the TRIK controller. 4. Insert it into your computer using a card reader. 5. Start DiskImager. To change the language, select About → Language in the menu.

6. Select the disc letter to write.

7. Click the «Restore drives from» button.

8. In the window that appears, filter the files by type .xz and select the downloaded file.

9. Click "Open".

10. Wait for the operation to complete.

Linux

1. Download the latest . 2. Remove the microSD card from the TRIK controller. 3. Insert it into your computer using a card reader. 4. If the SD card has the correct partition table (the first partition is at least 2 GB, ext4 file system), then go to step 18. 5. Get superuser (root) rights:

6. Look at the devices that are currently connected to the computer:

7. Unmount all SD card partitions using the umount command.

Example:

8. Select the inserted microSD card:

Example:

9. View the current partition table using the p command.

10. Remove any existing partitions using the d command.

11. Make sure all partitions are removed:

12. Create a new partition using the n command.

13. Leave all parameters, except the size, by default - press Enter. Specify +2G for the query “Last sector, + sectors or + size {K, M, G}”.

14. Create a partition on the remainder of the SD card using the n command. Leave all parameters as default.

15. Check with the p command what happened.

16. Apply changes using the w command.

17. Format partitions with mkfs.ext4 commands.

Example:

18. Unmount the first partition using the umount command.

Example:

19. Unpack the downloaded firmware image using the Archive Manager. 20. Copy the unpacked image to the SD card using the dd command.

Example:

Ubuntu

Instructions for version 14.04 and older.

1. Download the latest . 2. Remove the microSD card from the TRIK controller. 3. Insert it into your computer using a card reader. 4. Open the location of the downloaded firmware image in the file manager. 5. Call the context menu by right-clicking on the archive and select the first item "Open" in" Create bootable disk ". 6. From the drop-down menu, select the drive to which you want to burn the firmware. Then click the "Start Recovery" button.

Object «mailbox»

This article is automatically translated from Russian by Google Translator.

It implements communication between robots in the network by means of the mailbox mechanism.

connect

Connects to the robot with a given IP address on a given port (or default port), gives it its on-board number, and registers with the "mailbox" network.

Syntax

As parameters, you must specify the IP address of the robot and the port. If no port is specified, the default port is used.

Example

hasMessages

Returns true if the robot received a new message.

Syntax

myHullNumber

Returns the onboard number of the robot.

Syntax

newMessage

Sends a message after receiving a message.

Syntax

The first parameter is the sender's onboard number, the second is the message itself.

receive

Gets a new message or blocks script execution until the message arrives.

Syntax

send

Sends the specified message to the robot with the specified board number (or all robots).

Syntax

As a parameter, you must specify the on-board number of the robot to which you want to send the message and the message. If no on-board number is specified, the message is sent to all robots registered in the network.

Example

Class «keys»

This article is automatically translated from Russian by Google Translator.

Used to operate the buttons on the robot's remote control.

buttonPressed

Sent when the button with the specified code is pressed or released.

Syntax

The first parameter is the code of the button, the second - 1 if the button is pressed, 0 if released.

isPressed

Returns true if the button with the specified code is currently pressed. Possible options:

  • KeysEnum.Left (code105),

  • KeysEnum.Up (code 103),

  • KeysEnum.Down (code 108),

  • KeysEnum.Enter (code 28),

  • KeysEnum.Right (code 106),

  • KeysEnum.Power (code 116),

  • KeysEnum.Esc (code 1).

Syntax

reset

Resets memorized button presses.

Syntax

wasPressed

Returns whether or not a button with the specified code was pressed, reset the remembered presses for that button. Possible options:

  • KeysEnum.Left (code 105),

  • KeysEnum.Up (code 103),

  • KeysEnum.Down (code 108),

  • KeysEnum.Enter (code 28),

  • KeysEnum.Right (code 106),

  • KeysEnum.Power (code 116),

  • KeysEnum.Esc (code 1).

Syntax

Class «lineSensor»

This article is automatically translated from Russian by Google Translator.

Camera in line sensor mode.

detect

Detects the dominant color in the vertical bar in the center of the frame and remembers it as a line color. Then the "" method starts returning data for that line.

Syntax

init

Turns the camera on and initializes it inline sensor mode. The boolean parameter determines whether to display the image from the camera (true - display).

Syntax

The boolean parameter defines whether to display the image from the camera:

  • true — output,

  • false — don't output.

read

Returns an array with the following data in its cells:

  • the zero cell is the X coordinate of the line center relative to the center of the frame (from -100 to 100, -100 is the center of the line on the edge of the frame on the left);

  • in the first cell - the probability of crossing (the number from 0 to 100, showing how many points of the line color are in the horizontal stripe in the frame center);

  • the second cell - the relative size of the line, a number from 0 to 100 (100 - the line occupies almost the whole frame, 0 - the line is absent in the frame).

Syntax

stop

Turns off the video camera and stops the sensor.

Syntax

Method

Description

buttonPressed

Sent when the button with the specified code is pressed or released.

isPressed

Returns true if the button with the specified code is currently pressed.

reset

Сбрасывает запомненные нажатия кнопок.

wasPressed

Returns whether or not a button with the specified code was pressed, reset the remembered presses for that button.

brick.keys().isPressed(KeysEnum.Up);
brick.keys().isPressed(KeysEnum.Up);
brick.keys().reset();
brick.keys().reset();
brick.keys().wasPressed(KeysEnum.Up);
brick.keys().wasPressed(KeysEnum.Up);
brick.keys().buttonPressed.connect(lambda code, value: brick.stop() if code == KeysEnum.Up else print(code));
brick.keys().buttonPressed.connect(function(code, value){if (code==KeysEnum.Up)brick.stop() ; });

Method

Description

detect

Detects the dominant color in the vertical bar in the center of the frame and remembers it as a line color.

init

Turns the camera on and initializes it inline sensor mode.

read

Returns an array with the X coordinate of the center of the line relative to the center of the frame, the probability of a crossover, and the relative size of the line.

stop

Turns off the video camera and stops the sensor.

brick.lineSensor().read();
brick.lineSensor().read();
brick.lineSensor().stop();
brick.lineSensor().stop();
read
brick.lineSensor().detect();
brick.lineSensor().init(True);
brick.lineSensor().detect();
brick.lineSensor().init(true);

TRIK Studio language operators

  1. Binary operators.

  2. Unary operators.

  3. Assignment operator.

  4. Return operator.

  5. Empty operator.

Binary operators

​Title

​Title

​Title

+

Addition

Applicable to real and integer values. The result is an integer if both arguments are integer, otherwise real.

-

Subtraction

Applicable to real and integer values. The result is an integer if both arguments are integer, otherwise real.

*

Multiplication

Applicable to real and integer values. The result is an integer if both arguments are integer, otherwise real.

/

Division

Applicable to real and integer values. The result is real.

//

Integer division

Applicable to integer values. The result is an integer.

^

Power

Applicable to real and integer values. The result is real.

%

Remainder of the division

Applicable to integer values. The result is an integer.

&

Bitwise "and"

Applicable to integer values. The result is an integer.

|

Bitwise "or"

Applicable to integer values. The result is an integer.

>>, <<

Bitwise left and right shift

Applicable to integer values. The result is an integer.

..

Concatenation

Applicable to string values. The result is a string.

>=, >, <, <=

Comparison operations

Applicable to integer and real values. The result is boolean.

==

Equality check

Applicable to any type of value. The result is boolean.

~=, !=, '~=', '!='

Inequality check

Applicable to any type of value. The result is boolean. All notations are equal.

and, &&

Logical "and"

Applicable to integer, real and boolean types. The result is boolean. All notations are equal.

or, ||

Logical "or"

Applicable to integer, real and boolean types. The result is boolean. All notations are equal.

Unary operators

​Title

​Title

​Title

-

Arithmetic unary minus

Applicable to integer and real values. The result is an integer or real (depending on the type of argument).

~

Bitwise "not"

Applicable to integer values. The result is an integer.

not

Logical "not"

Applies to boolean, integer, real, and string values, the result is boolean (0 or an empty string is considered false, everything else is true).

#

Length operator

Applicable to string values. The result is an integer.

Assignment operator

It has the following form:

variable1, variable2, …, variableN = expression1, expression2, …, expressionN

In its simplest form variable = expression.

Return operator

It is written as an expression and should be at the end of the statement block.

Empty operator

Written as ;.

Example

A statement block with two assignment operators and a return operator:

a, b = 1, 2; -- assignment operator and empty operator
c = 3; -- assignment operator and empty operator
a + b + c -- return operator
sudo -i
fdisk -l
umount /dev/{first SD card partition}
umount /dev/{second SD card partition}
...
umount /dev/sdb1
fdisk /dev/{device}
fdisk /dev/sdb
p
d
p
n
Command (m for help): n
Partition type:
     p     primary (0 primary, 0 extended, 4 free)
     e     extended
Select (default p):
Partition number (1-4, default 1):
First sector (4096-784932712):
Last sector, +sectors or +size{K,M,G}: +2G
Command (m for help): n
Partition type:
     p     primary (0 primary, 0 extended, 4 free)
     e     extended
Select (default p):
Partition number (1-4, default 1):
First sector (4096-784932712):
Last sector, +sectors or +size{K,M,G}:
p
w
mkfs.ext4 /dev/{раздел}
mkfs.ext4 /dev/sdb1
mkfs.ext4 /dev/sdb2
sudo umount /dev/{first partition}
sudo umount /dev/sdb1
sudo dd bs=4M if=trik-base-v2-trikboard.ext4 of=/dev/{first partion}
sudo dd bs=4M if=trik-base-v2-trikboard.ext4 of=/dev/sdb1
Windows
Linux
Ubuntu
firmware image
DiskImager
firmware image
firmware image
Installing DiskImager

Method

Description

connect

Connects to the robot with a given IP address on a given port (or default port), gives it its on-board number, and registers with the "mailbox" network.

hasMessages

Returns true if the robot received a new message.

myHullNumber

Returns the onboard number of the robot.

newMessage

Sends a message after receiving a message.

receive

Gets a new message or blocks script execution until the message arrives.

send

Sends the specified message to the robot with the specified board number (or all robots).

mailbox.hasMessages()
mailbox.hasMessages();
x = mailbox.myHullNumber()
var x = mailbox.myHullNumber();
mailbox.newMessage.connect(lambda sender, message: print(message))
mailbox.newMessage.connect(function(sender, message) { print(message); });
message = mailbox.receive()
var message = mailbox.receive();	
mailbox.send("message")
mailbox.send(boardNumber, "message")
mailbox.send("message");
mailbox.send(boardNumber, "message");
mailbox.send(1, "Hello") # Sending a message to a robot with board number 1
mailbox.send(1, "Hello"); // Sending a message to a robot with board number 1
mailbox.connect("ipAddress");
mailbox.connect("ipAddress", port);
mailbox.connect("192.168.0.20", 8889);

Sensory variables for the TRIK controller

This article is automatically translated from Russian by Google Translator.

Sensor variables are reserved variables for getting readings of the sensors connected to the corresponding ports.

These values can be assigned to variables and used in mathematical expressions.

Variable changes can be tracked as you go through the program in the variable table.

Variable

Description

An array of three elements containing accelerometer readings on the X, Y, and Z-axis.

buttonDown

buttonUp

buttonEnter

buttonEsc

buttonPower

buttonLeft

buttonRight

State of the buttons on the TRIK controller body: "Down", "Up",

"Enter", "Esc", "Power",

"Left", "Right".

Possible values: 0 — button not pressed. 1 — button pressed.

The color sensor readings by the camcorder in the center of the frame are the intensity of red, green, and blue, respectively.

They are only updated when the color sensor is turned on and initialized.

Possible values: 0 ... 255

encoder1 encoder2 encoder3 encoder4

Encoder readings on ports E1, E2, E3, E4 respectively.

gamepadButton1

...

gamepadButton5

The state of the buttons on the remote control from 1 to 5 respectively.

0 — the button is not pressed. 1 — button is pressed.

gamepadConnected

Remote control connection status.

0 — remote control is not connected. 1 — the remote control is connected.

The coordinates of pressing the active areas on the remote control.

Each variable stores an array of two elements corresponding to the coordinate of the press point.

Possible values: From (-100, -100) to (100, 100).

(-101, -101) — if there is no press.

gamepadPad1Pressed gamepadPad2Pressed

The state of the click on the left and right area of the remote control respectively. The coordinates of pressing can be found out with the help of the variables and . Possible values: 1 — the active area on the remote control is pressed. 0 — the active area on the remote control is not pressed.

gamepadWheel

Tilt value of the remote control (if it is connected and the "steering wheel" is enabled on it).

Possible values: -100 ... 100. -101 — if there is no data on the "rudder" position.

-100 — extreme left position. 100 — extreme right position.

An array of three elements containing the gyroscope readings on the X, Y, and Z-axis respectively.

The array of three elements containing the camera readings in the line sensor mode. The values are updated when the line sensor is enabled and initialized.

objectSensorX objectSensorY

The coordinates of the object detected by the video camera in relation to the center of the screen. The values are updated when the sensor is on and initialized.

Possible values: -100 to 100 (relative to the center of the frame).

objectSensorSize

The size of the object recognized by the video camera. The value is updated when the object sensor is activated and initialized.

Possible values: 0 to 100.

100 - object occupies the whole frame.

sensorA1 ... sensorA6

Readings of the sensors connected to the corresponding analog ports.

sensorD1 sensorD2

Readings from sensors connected to the corresponding digital ports.

accelerometer

An array of three elements containing accelerometer readings on the X, Y, and Z axis, respectively.

Example

x = accelerometer[0]; -- X-axis accelerometer readings
y = accelerometer[1]; -- Y-axis accelerometer readings
z = accelerometer[2]; -- Z-axis accelerometer readings

colorSensorR, colorSensorG, colorSensorB

The color sensor readings by the camcorder in the center of the frame are the intensity of red, green, and blue, respectively. They are only updated when the color sensor is turned on and initialized.

Possible values

From 0 to 255.

Example

r = colorSensorR; -- red intensity
g = colorSensorG; -- green intensity
b = colorSensorB; -- blue intensity

gamepadPad1, gamepadPad2

The coordinates of pressing the active areas on the remote control.

Each variable stores an array of two elements corresponding to the coordinate of the click point.

Possible values

From (-100, -100) to (100, 100), (-100, -100) - top left corner of the active area. (-101, -101) - if there is no click.

gyroscope

An array of three elements containing the gyroscope readings on the X, Y, and Z-axis respectively.

Пример

x = gyroscope[0]; -- X-axis gyroscope readings
y = gyroscope[1]; -- Y-axis gyroscope readings
z = gyroscope[2]; -- Z-axis gyroscope readings

lineSensor

An array of three elements containing camera readings inline sensor mode. The values are updated when the sensor is on and initialized.

lineSensor[0]

The deviation of the line from the screen center from -100 (leftmost line position in the frame) to 100 (rightmost line position).

lineSensor[1]

Crossing probability is defined as the percentage of points inside the horizontal stripe in the center of the frame that is recognized as a line, from 0 (no such points) to 100 (all points in the horizontal strip are recognized as a line).

lineSensor[2]

Relative line size, that is, the number of points in the frame defined as a line, from 0 (no line in the frame) to 100 (the whole frame is recognized as a line).

VSCode

TRIK Studio can be integrated with the external VSCode programming environment.

This will allow experienced TRIK Studio users to use all the features of professional text editors and their plugins:

  • static analyzers,

  • autoformatter,

  • color themes.

Read about how to integrate VSCode with TRIK Studio in the next articles:

TRIK Studio main menu

The main menu of TRIK Studio contains a set of basic operations and environment settings:

File

  • New project — create a new project.

  • Recent projects — open one of the recently used projects.

  • New diagram — create a new chart in the current project.

  • Open… — open a saved project. Projects are stored on disk in files with the .qrs extension.

  • Save — save the current project.

  • Save as… — save the current project to the selected location. Subsequent saves will be made to the selected file.

  • Save diagram as a picture… — save the current image on the scene to disk.

  • Print — print a chart or text using the standard print dialog.

  • Quit — exit the program.

  • Restore default settings and Quit — restore the default settings and exit the program.

Edit

  • Undo — cancel a completed action.

  • Redo — make a canceled action again.

  • Copy — copy the selected item.

  • Paste — insert the selected item.

  • Cut — cut the selected item.

  • Find... — open the search dialog for the project.

  • Find and replace — open the project search dialog and replace.

View

  • Zoom in — zoom in on the scene.

  • Zoom out — to reduce the scale of the scene.

  • Panels — enable/disable the display of various windows.

  • To main page — go back to the main page.

Tools

Attention! Items in this menu may appear and disappear depending on the program configuration.

  • Mouse gestures — open a tab with a list of available mouse gestures (see the "" section).

  • Run — start execution of the diagram currently displayed in interpretation mode (the item is available only in interpretation mode).

  • 2D model — switch the interpretation mode to a two-dimensional model.

  • Real robot — switch the interpretation mode to control the real robot via Wi-Fi, Bluetooth, or USB, depending on the used and the settings for connecting to the robot.

  • Robot settings — open the settings window of the robot model with which you work in TRIK Studio (for more details see the "" section in the article ").

  • Save as task… — save the current diagram and two-dimensional model as an exercise for students. In an exercise, you cannot modify some parts of a solution. For example, the location of objects in a two-dimensional model or the configuration of sensors. Selecting this menu item opens a dialog in which you can select the parts to be frozen (for more information about exercises, see the article ").

  • Subprograms — subprograms management (for more details see the article ").

  • Generate code — open a tab with the generated code corresponding to the current diagram and the selected text language (this item may look like "Generate JavaScript code", "Generate Python code", "Generate C code", etc.). The code is not downloaded to the robot and is not executed, but can be edited and downloaded later.

  • Upload program — only generate code and upload to the robot without executing.

  • Upload and execute program — generate the code corresponding to the current diagram, load it and execute on the robot.

  • Stop robot — interrupt the execution of the program and send the robot commands to turn off the motors.

  • Connect — establish a connection with the robot. The robot must be turned on. The item is available only if the selected mode of working with the robot requires a constant connection (for example, interpretation of the program via Bluetooth or Wi-Fi).

Settings

  • Preferences… — open the TRIK Studio environment settings window (see the article "").

  • Show grid — enable/disable grid on the scene.

  • Show alignment — enable/disable the display mode for vertical and horizontal guidelines for positioning objects relative to each other.

  • Switch on grid — enable/disable automatic grid alignment.

  • Switch on alignment — enable/disable vertical and horizontal guidelines for positioning blocks relative to each other.

  • Show all text — enable/disable displaying all block properties directly on the diagram. If the text below the blocks is disabled, properties can be viewed and edited in the property editor at the top left.

Help

  • Small help — open help.

  • About TRIK Studio — view brief information about TRIK Studio.

  • Open logs — open a folder with log files.

  • Check for updates — get information from the Internet about the availability of a new version of the environment or any of the plug-ins, and run auto-updates if necessary.

TRIK controller web interface

This article is automatically translated from Russian by Google Translator.

The web interface of the TRIK controller allows:

  • Change Wi-Fi settings on the controller.

  • Configure the interaction of several controllers.

  • Change the configuration of sensors, motors, and encoders.

  • Change the configuration of microelectromechanical systems (gyroscope and accelerometer).

  • Start video broadcasting from the controller's camera.

  • Download the log files.

  • View the programs loaded on the controller.

  • Take screenshots of the controller screen and download them.

  • Take screenshots from the camera connected to the controller and download them.

Running the web interface

‌To start the web interface:

  1. Connect the TRIK controller to the computer in any of the .

  2. Enter the IP address of the controller in the address bar of your browser.

The IP address of the controller is displayed on the screen after connecting to the network.

Web interface menu

The web interface menu contains the following items:

  1. Network

  2. Ports

  3. MEMS

  4. Video

  5. Logs

  6. Programs

  7. Images

Network

On the "Network" tab, you can:

  • Set the Wi-Fi network parameters for the controller in access point mode.

  • Change the Wi-Fi access point name for the controller in point mode.

  • Set the controller's board number and the master controller's IP address for .

  • Set the controller's board number and the master controller's IP address for controller communication.

Ports

On the "Ports" tab you can:

  • Select the type of power motors to be connected for each port.

  • Select the type of connected servomotors for each port.

  • Select the type of analog sensors to be connected for each port.

  • Select the type of encoders used in the motors for each port, as well as the positive direction of the motor shaft position for each port.

  • Select the type of digital encoders to be connected for each port.

  • Configure the ports for connecting video cameras.

After changing the settings, press the "Save" button at the bottom of the screen and confirm the action.

Power Motors

Under "Power Motors" you can select the type of power motors to be connected for each port.

Servo motors

Under "Servomotors" you can select the type of servomotors to connect for each port.

Analog sensors

Under "Analog Sensors" you can select the type of analog sensors to be connected for each port.

Encoders

Under "Encoders" you can select the type of encoders used in the motors for each port, as well as the positive motor shaft position reference direction for each port.

Distance sensors

Under "Distance sensors" you can select the type of digital sensors to be connected for each port.

Video1 / Video2

Video ports and video cameras connected to them can operate in the following modes:

  • colorSensor3x3 - color sensor mode.

  • lineSensor - line sensor mode with color detection.

  • photo - the camera is used for capturing photos and video stream.

  • edgeLineSensor - line sensor mode with edge detection (works on inverse lines).

MEMS

The MEMS (microelectromechanical systems) tab allows:

  • Enable or disable the gyroscope or accelerometer.

  • Select the refresh rate and range of the accelerometer and gyro in "Advanced Settings".

To change the configuration, press the "Save" button and confirm the action.

Video broadcast

The "Video broadcasting" tab allows you to watch video from the camera installed on the controller.

To start it, you need to add the "Start video broadcasting" block to the robot's control from the remote control.

Logs

The Logs tab displays the controller logs, which can be downloaded for later sending to the service.

User scripts

The "User scripts" tab displays the programs loaded on the controller.

You can remove all programs through the controller interface.

Images

The "Images" tab contains images taken with the connected camera, as well as screenshots of the controller screen.

In the tab you can:

  • Take a of the controller screen.

  • View and download images received from the controller either individually or all together.

  • Delete all existing images (selective deletion is not available).

LOG

The icon allows you to download log files. Read more in the article "Actions in case of TRIK Studio or TRIK controller malfunction" in the section "".

Running a 2D model in TRIK Studio from VSCode
Uploading programs to several TRIK robots from VSCode
mailbox.connect("ipAddress")
mailbox.connect("ipAddress", port)
mailbox.connect("192.168.0.20", 8889)
accelerometer
colorSensorR
colorSensorG
colorSensorB
gamepadPad1
gamepadPad2
gamepadPad1
gamepadPad2
gyroscope
lineSensor
File
Edit
View
Tools
Settings
Help
Adding blocks with mouse gestures
platform
Robots
"TRIK Studio settings
"Exercises
"Subprograms
TRIK Studio settings
possible ways
Wi-Fi client
Wi-Fi access
controller communication
program
support
screenshot
Collecting logs on TRIK controller

TRIK Studio settings

Settings window

To open TRIK Studio preferences press the corresponding item in the main menu:Settings → Preferences....

The left bar contains the next tabs:

  • Behaviоur.

  • Miscellaneous.

  • Editor.

  • Robots.

  • Shortcuts.

The right bar contains the fields to edit for the current tab. "Import" and "Export" buttons at the bottom of the window allow you to save the current settings to a file and upload it on another computer.

Behaviour

User Interface

  • Language — environment language. After the change, a restart of TRIK Studio is required. The setting "<System language>" means that the language will be determined by the current language of the operating system.

Automatics

  • Autosave — the option to enable or disable autosave of an open project, as well as set the autosave interval in seconds.

  • Gestures — enable or disable recognition engine for mouse gestures.

  • Delay after gesture — the time period of the system expectation between the finishing of a mouse gesture and its execution. Delay allows you to draw a gesture in a few strokes. The value is indicated in milliseconds.

  • Check for updates on start — connect at startup with the update server and start auto-update if necessary.

Touch

  • Touch mode — enable user interface optimization for touch screens.

Widgets

  • Dockable mode — detaches windows for free alignment.

Miscellaneous

Graphics

  • Antialiasing — the line drawing mode with smoothing improves the appearance of diagrams due to a slight decrease in the speed of the system.

Other

  • Show splashscreen — enable / disable the display of the splashscreen with the TRIK Studio logo at startup.

  • Limit recent projects list — controls how many projects to show in the "Recent projects" menu item File.

Images

Set of icons to use to display the diagram.

Toolbars

  • Size — configure the size of the buttons on the toolbar.

Editor

Font

  • Use some of system fonts — replace the font for displaying labels on the diagram with one of the fonts installed in the system. The sizes of the labels on the blocks are set rigidly, so changing the font can lead to the crawl of the labels on each other, but you can experiment.

Grid

  • Show grid — display the alignment grid on the scene of the diagram editor.

  • Activate grid — align blocks on a grid.

  • Show alignment — display alignment lines on the scene of the diagram editor. Alignment lines appear when a block is on the same horizontal or vertical line with another block, and help align the blocks in the scene.

  • Activate alignment — align the blocks along the alignment lines.

  • Width — thickness of alignment lines. Adjustable depending on the brightness of the monitor or projector.

  • Cell size — size of one cell. The default size is selected so that the block covers four cells.

Node Elements

  • Drag area — the size of the area, pulling which you can change the size of the block "Comment".

Edge

  • Line mode — mode of drawing links on the diagram.

    • broken — links are drawn as broken lines with break points that are added by the user.

    • square —connections are drawn as broken lines, each segment of which is parallel to the coordinate axes. Break points in this case are automatically added by the system.

    • curve — connections are drawn as smooth curves, the curvature of which can be set by the user.

  • Loop edges indent — indent size for loop connections.

Embedded Linkers

  • Size — size of the built-in linker, i.e. a circle next to a block in a diagram that creates relationships between elements (for more details see the article "Connections between the blocks").

  • Indent — indent of the built-in linker from the block icon.

Palette

  • Representation — choice between the mode of displaying icons and names or only icons in the palette.

  • Count of items in a row — the number of icons per line of the palette with the selected "Icons" mode.

Robots

The composition of this tab depends on the installed plug-ins and on the currently selected platform. Typical tab items are described below.

Robotics construction kit

The robotics kit for which programs are written in the TRIK Studio. The list of all available blocks in the palette and available actions on the toolbar depends on this option.

Robot model

Choosing the type of execution model for the selected constructor. In most cases, this is a 2D model or a real robot, but for some robotics kits one of the models may not be available, in this case this item would not be displayed.

2D robot image

The appearance of the robot in a 2D model.

Connection settings

Kit-specific settings for connecting to the robot, such as the IP address for TRIK controllers or the COM port of the Bluetooth connection for Lego NXT controllers. If a connection in the selected mode is not required, the item would not be displayed.

External tools settings

Kit-specific settings for programs not supplied with TRIK Studio, which must be installed on the computer. For most operating modes, additional installed programs are not needed, so the corresponding items are not displayed in the window.

Sensor settings

The section indicates which sensors are connected to the ports of the robot.

Uploading & Running

  • Running after uploading — run the program immediately after downloading it to the robot or not. Applicable only for some modes of some kits (for example, for Lego NXT in generation mode).

Graphics watcher update interval

  • Sensors — interval in milliseconds after which a new point with a sensor reading is added.

  • Autoscaling — the interval in milliseconds after which the graph automatically changes its scale to optimally display the values.

  • Text info — the interval in milliseconds after which the labels with values ​​are updated on the chart.

Shortcuts

This tab allows you to set or change hotkeys for the most commonly used actions. To do this, select the cell corresponding to the action, and in the "Combination" line at the bottom of the window, press the desired key combination.

The "Clear" button removes the key combination from the cell.

All hotkeys installed by default, you can find in the article:

Export settings

TRIK Studio allows you to export the current settings to a file for uploading them to another computer. To do this, click the "Export" button at the bottom of the window.

Import settings

TRIK Studio allows you to import settings from a previously exported file. To do this, click the “Import” button at the bottom of the window and select the desired .ini file.

Object «script»

This article is automatically translated from Russian by Google Translator.

Represents methods of controlling script execution and accessing operating system functions.

Method

Description

Sets the end-of-run flag for an event-driven program.

Returns a random number from the specified range.

Считывает всё содержимое указанного файла в массив строк.

Deletes the specified file.

Sets the event-oriented program flag.

Выполняет переданную в качестве параметра команду консоли операционной системы.

Returns the time stamp - the number of milliseconds elapsed since the beginning of January 1, 1970 GMT.

Creates and returns a timer.

Suspends script execution for the number of milliseconds passed.

Writes a string to a file.

quit

Sets the end-of-run flag for an event-driven program. As soon as the current event handler completes, the script execution will end.

Syntax

script.quit();	
script.quit();

random

Returns a random number from the specified range.

Syntax

script.random(min, max);
script.random(min, max);

The range boundaries must be specified as parameters.

Example

var a = script.random(0, 10); // random number from 0 to 10
a = script.random(0, 10); # random number from 0 to 10

readAll

Reads the entire contents of the specified file into a string array.

Syntax

script.readAll('fileName');
script.readAll('fileName');

As a parameter, you must specify the name of the file with the extension.

Example

var lines = script.readAll('input.txt'); // reads the text file input.txt
lines = script.readAll('input.txt'); # reads the text file input.txt

removeFile

Deletes the specified file.

Syntax

script.removeFile('fileName');
script.removeFile('fileName');

As a parameter, you must specify the name of the file with the extension.

Example

script.removeFile('file.txt'); // delete file file.txt
script.removeFile('file.txt'); # delete file file.txt

run

Sets the event-oriented program flag. When the script finishes, it is not unloaded from memory but continues to wait for events to occur until one of the handlers calls the "quit" method.

Syntax

script.run();
script.run();

system

Executes the command transmitted.

Syntax

script.system();
ript.system();

As a parameter, you must specify the operating system console command.

Example

script.system("reboot");
script.system("reboot");

time

Returns the time stamp - the number of milliseconds elapsed since the beginning of January 1, 1970 GMT.

Syntax

script.time();
script.time();

timer

Creates and returns a timer (class QTimer) that sends a timeout signal every n milliseconds.

Syntax

script.timer(n);
script.timer(n);

n is passed as a parameter.

Example

script.timer(1000);
script.timer(1000);

wait

Suspends script execution for the number of milliseconds passed.

Syntax

script.wait(msCount);
script.wait(msCount);

The number of milliseconds is passed as a parameter.

Example

script.wait(1000); // stop the execution of the script for one second
script.wait(1000); # stop the execution of the script for one second

writeToFile

Writes a string to a file.

Syntax

script.writeToFile('fileName', 'text');
script.writeToFile('fileName', 'text');

The file name and the line to be written should be specified as parameters.

Example

script.writeToFile('output.txt', 'Hello, world'); // write "Hello, world" in the output.txt file
script.writeToFile('output.txt', 'Hello, world'); # write "Hello, world" in the output.txt file

Object «gamepad»

This article is automatically translated from Russian by Google Translator.

Serves to work with the programmable control panel "TRIK Gamepad".

Method

Description

Returns true if a button with the specified number was pressed on the remote control.

Returns whether the control area on the remote control is currently pressed.

If the specified control area on the remote is pressed, returns the current x-coordinate of the press.

If the specified control area on the remote is pressed, returns the current y-coordinate of the press.

Sent when the user moves his finger away from the control area with the specified number.

Resets the memorized events from the remote control.

If "steering" (events from the device's accelerometer) is enabled on the remote control, it returns the current remote control tilt.

Sent when the remote control has the "steering wheel" (events from the device's accelerometer) on and the user has turned the device.

Signal

Description

Sent when the user has pressed one of the five buttons at the bottom of the remote control.

Sent when the remote control is connected to the robot.

It is sent when the remote control is turned off.

Sent when the user taps or moves their finger over the control area on the remote.

button

Sent when the user has pressed one of the five buttons at the bottom of the remote control.

buttonWasPressed

Returns true if a button with the specified number was pressed on the remote control. Resets the memorized press for this button.

Syntax

gamepad.buttonWasPressed(buttonNumber);
gamepad.buttonWasPressed(buttonNumber);

As a parameter, you must specify the number of the button - from 1 to 5.

Example

gamepad.buttonWasPressed(5);
gamepad.buttonWasPressed(5);

connected

Sent when the remote control is connected to the robot.

disconnect

It is sent when the remote control is turned off.

isPadPressed

Returns whether the control area on the remote control is currently pressed. The control areas are numbered 0 and 1.

Syntax

gamepad.isPadPressed(padId);
gamepad.isPadPressed(padId);

As a parameter, you must specify the number of the control area - 0 or 1.

Example

gamepad.isPadPressed(1);
gamepad.isPadPressed(1);

pad

Sent when the user taps or moves their finger over the control area on the remote.

padX

If the specified control area on the remote is pressed, returns the current x-coordinate of the press.

Syntax

gamepad.padX(padId);
gamepad.padX(padId);

As a parameter, you must specify the number of the padId control area.

padY

If the specified control area on the remote is pressed, returns the current y-coordinate of the press.

Syntax

gamepad.padY(padId);
gamepad.padY(padId);

As a parameter, you must specify the number of the padId control area.

padUp

Sent when the user moves his finger away from the control area with the specified number.

Syntax

gamepad.padUp.connect( function(padId, x, y) { brick.stop(); });
gamepad.padUp.connect(lambda padId, x, y: brick.stop());

Parameters:

  • padId — control area number.

  • x, y — the coordinates of the last known click from -100 to 100. The coordinate (-100, -100) corresponds to the upper left corner of the control area.

reset

Resets the memorized events from the remote control.

Syntax

gamepad.reset();
gamepad.reset();

wheel

If "steering" (events from the device's accelerometer) is enabled on the remote control, it returns the current remote control tilt.

Tilt is coded from -100 to 100, with -100 being the leftmost "rudder" position and 100 being the rightmost position.

Syntax

gamepad.wheel();
gamepad.wheel();

wheelEvent

Sent when the remote control has the "steering wheel" (events from the device's accelerometer) on and the user has turned the device.

Syntax

gamepad.wheelEvent.connect( function(percent) { brick.motor("E1").setPower(percent); });
gamepad.wheelEvent.connect(lambda percent: brick.motor("E1").setPower(percent));

As a parameter it is necessary to specify a number from -100 to 100, -100 corresponds to the leftmost position of the "rudder", 100 - to the rightmost position.

pic = getPhoto();

Connecting and working with the video module

This article is automatically translated from Russian by Google Translator.

Both video modules and USB webcams can be connected to the TRIK controller.

Connecting

The video module connects to the video1 or video2 port, the USB webcam connects to the USB port.

Connect the video module to the video2 (or video1) port so that the red plug pin is on the right.

Using

The camera in TRIK Studio can be run in three modes:

  1. As a line sensor.

  2. As objects sensor.

  3. As a color sensor.

Write an algorithm to initialize the video camera:

After the camera is initialized, a video broadcast with additional graphic elements will appear on the display.

Warning! By default, the Line Sensor mode will be enabled. To change the mode of use, go to the properties of the "Initialize Camera" block and change the mode to the desired one.

LineSensor

The camera as a line sensor is needed to solve the problem of driving on the line, as well as on a discontinuous line.

In order to enable the camera as a line sensor, you must change the camera mode in the "Initialize Camera" block properties, to Line Sensor. The Line Sensor mode has a variable.

Example

Task. Write an algorithm for moving the robot along a line using a camera.

Algorithm writing

1. Initialize the variable k - the proportionality factor to be used in the proportional regulator for the robot's motion.

2. Initialize the camera as a line sensor.

Warning! The "Wait for button to be pressed" block is necessary so that the camera has time to turn on. When the image from the camera appears on the robot's screen, you can proceed to the next step.

3. Detect the camera on the object.

4. Write a controller for motion. Use the "Line Sensor to Variable" block, which writes a reading of the object's deviation from the center of the screen along the X-axis (from -100 to 100) to a variable specified in the properties. In other words, it is a dynamic error.

General view of the algorithm

Running the algorithm on a real robot

1. Run the program on the robot.

2. Wait for the camera to turn on.

3. In Line Sensor mode, the screen will display 4 purple guides. Aim the camera at the line so that the right edge of the line falls in the corridor between the two right guides and the left edge between the two left guides.

4. Press the Up button on the controller to detect an object (line).

Note that the video is streamed to the screen in 240×140 px format, which is exactly half of the screen.

The line must fill with yellow dots, as in the picture, to know that detection has occurred:

5. Press the Down button.

ObjectSensor

The camera as an object sensor is required for object recognition and tracking tasks. In order to enable the camera as a line sensor, you must change the camera mode, in the properties of the "Initialize Camera" block, to Object Sensor. The Object Sensor mode has sensor variables: .

Example

Task. Write an algorithm for object recognition using a camera.

Attention! The robot must output to the console the coordinates of the object center and its diameter in pixels.

Algorithm writing

1. Initialize the camera as an object sensor.

Warning! The "Wait for the button to be pressed" block is necessary so that the camera has time to turn on. When the camera image appears on the robot's screen, you can proceed to the next step.

2. Detect the camera on the object.

3. Write a loop with a condition to exit the program by pressing Esc on a false branch.

4. On the true branch, add a function to assign the coordinates of the center of the object and the diameter in pixels, to the variables a, b, c.

5. Next, add the variables a, b, c to the console and end the loop with the "Timer" block:

General view of the algorithm

Running the algorithm on a real robot

1. Run the program on the robot.

2. Wait for the video camera to turn on.

3. Position the robot so that the camera is facing a small square on the object. Press the Up button on the controller to detect the object.

To understand that detection has occurred, the object must fill with yellow dots, as in the picture:

4. Press the Down button on the controller.

ColorSensor

The camera as a color sensor is necessary for color recognition tasks.

In order to enable the camera as a line sensor, you must change the camera mode, in the properties of the "Initialize Camera" block to Color Sensor.

Color Sensor mode has sensor variables of three colors (red, green, blue): .

In Color Sensor mode, the camera divides the frame into 9 zones and returns the average color value of the center zone.

Example

Write an algorithm for recognizing green and red using a camera. The robot should output to the console the color it sees.

Note that the problem can only be solved on a real robot.

Algorithm writing

1. Initialize the camera as a color sensor.

Warning! The "Wait for button to be pressed" block is necessary so that the camera has time to turn on. When the camera image appears on the robot's screen, you can proceed to the next step.

2. Add the function of assigning touch variables to variables a, b.

3. Write a condition that will distinguish between red and green. Given that red is colorSensorR = 255 , and green is colorSensorG = 255 .

Algorithm

Running the algorithm on a real robot

1. Execute the program on the robot. 2. Wait for the video camera to turn on. 3. Position the robot so that the camera is pointing at the color you want to recognize.

4. Press the Up button on the controller to start color recognition. The robot should display the color the camera is pointing at (Green, Red).

Class «gyroscope»

This article is automatically translated from Russian by Google Translator.

Represents of the TRIK controller. At rest, the average value of the gyroscope output is not zero and is called a bias or bias error.

The parameter is determined by many factors and can vary, for example, depending on the ambient temperature.

In order for the gyroscope to work properly it is necessary to subtract the zero offset from the incoming values. This can be calculated using the "" method.

Since calibration takes a long time, if you run the model frequently, you can do it once, then store the value in a variable with "", and call "" instead of calibration when you run the program.

calibrate

Calculates a zero offset within a specified time and initializes the gyroscope with this parameter, resets the current tilt angles. The recommended calibration time is 10-20 seconds.

Syntax

Parameter:

  • msec — time in milliseconds.

calibrationFinished

The signal sent by the sensor after the end of the calibration.

getCalibrationValues

Returns an object that contains the necessary zero-offset data.

Syntax

isCalibrated

Returns true if calibration is complete, false otherwise.

Syntax

newData

The signal sent by the sensor when it has new data ready.

read

Returns an array of seven elements:

  • 0−2 — angular velocities on the three axes (in milligrades/seconds),

  • 3 — a time of the last measurement (in microseconds),

  • 4−6 — tilt angles on the three axes (in milligrads).

Syntax

readRawData

Returns an array of three elements with angular velocities on the three axes.

Syntax

setCalibrationValues

Sets the object containing the necessary parameters about the zero offset.

Since calibration takes a long time, if you run the model frequently, you can do it once, then store the value in a variable with "", and call "setCalibrationValues" instead of calibration when you run the program.

Syntax

Parameter:

  • values — object containing bias data.

quit
random
readAll
removeFile
run
system
time
timer
wait
writeToFile
buttonWasPressed
isPadPressed
padX
padY
padUp
reset
wheel
wheelEvent
button
connected
disconnect
pad

Method

Description

calibrate

Calculates a zero offset within a specified time and initializes the gyroscope with this parameter, resets the current tilt angles.

getCalibrationValues

Returns an object that contains the necessary zero-offset data.

isCalibrated

Returns true if calibration is complete, false otherwise.

read

Returns an array of seven elements: angular velocities on the three axes, time of the last measurement, tilt angles on the three axes.

readRawData

Returns an array of three elements with angular velocities on the three axes.

setCalibrationValues

Sets the object containing the necessary parameters about the zero offset.

Сигнал

Описание

calibrationFinished

The signal sent by the sensor after the end of the calibration.

newData

The signal sent by the sensor when it has new data ready.

brick.gyroscope().calibrate(msec);
brick.gyroscope().calibrate(msec);
brick.gyroscope().getCalibrationValues();
brick.gyroscope().getCalibrationValues();
brick.gyroscope().isCalibrated();
brick.gyroscope().isCalibrated();
brick.gyroscope().read();
brick.gyroscope().read();
brick.gyroscope().readRawData();
brick.gyroscope().readRawData();
brick.gyroscope().setCalibrationValues(values);
brick.gyroscope().setCalibrationValues(values);
the gyroscope
calibrate
getCalibrationVaules
setCalibrationValues
getCalibrationVaules
TRIK Studio shortcuts

Video module

USB webcam

lineSensor
objectSensorSize, objectSensorX, objectSensorY
colorSensorR, colorSensorG, colorSensorB

TRIK Studio interface

TRIK Studio modes

The TRIK Studio interface depends on the selected mode. TRIK Studio has two modes:

  1. Editing mode It is intended for creating a robot control diagram and executing it in the generation mode.

  2. Debug mode It is intended for executing and debugging a program on a 2D model or in interpretation mode on a real robot.

Switching between modes

There are three ways to switch modes:

  1. Keyboard shortcuts Ctrl+1 / Ctrl+2.

  2. Mode switching panel.

  3. Status bar.

Editing mode

TRIK Studio in edit mode has the following interface elements:

  • Editor window/scene

  • Main menu

  • File panel

  • Edit panel

  • View panel

  • Interpreter panel

  • Generators panel

  • "Others" panel

  • Panel for switching between editor and debug mode

  • Property editor panel

  • Sensor settings

  • Palette (set of blocks for diagrams creation)

  • Variables panel

  • Status bar

Editor window/scene

The scene displays the diagram and allows you to edit it.

Read about creating a new project and working with the diagrams in the articles:

Editor mode also displays the current executable block when interpreting diagrams.

Main menu

The main menu of TRIK Studio contains a set of basic operations and environment settings:

  • File

  • Edit

  • View

  • Tools

  • Settings

  • Help

For more information, see the article:

File panel

The "File" panel repeats the main operations available from the "File" menu.

Create a new project. Open a saved project. Save the current project.

Edit panel

Cancel the operation. Repeat the operation.

View panel

The View panel contains buttons that allow you to scale diagrams.

Zoom in / out.

You can also zoom the scene using:

  1. Hold down the Ctrl key and roll the mouse wheel.

  2. Keyboard shortcut Ctrl+= и Ctrl+-.

Interpreter panel

The Interpreter panel contains the commands for starting and stopping the execution of a program, buttons for switching interpretation modes between a two-dimensional model and a real robot, as well as a button for opening robot settings available from the Tools menu.

When working with a real robot in interpretation mode, this panel also contains a "Connect" button.

Run program. Stop program. 2D model mode. Real robot mode. Robot settings.

Generators panel

The commands in this panel change depending on the program configuration.

The Generators panel contains commands for generating code and loading the program to the robot.

Generate code. Upload program to the robot.

"Other" panel

"Other" panel may contain various information depending on the chosen platform.

For example, for the TRIK kit this panel displays the IP address of the controller to which you are connecting.

Panel for switching between editing and debugging modes

The panel for mode switching displays the current TRIK Studio mode and allows you to switch between editing and debugging modes.

Editor. Debug.

Property editor panel

The property editor is used to display and edit the property values ​​of selected objects (blocks, links).

About working with the property editor see article:

Sensors settings panel

Sensor settings allow you to specify which sensors are used on which port. The same can be done from the robot settings dialog.

Available set of sensors depends on the selected platform in the settings on the Robots tab.

Palette panel

The Palette panel contains a set of available blocks and the relationships between them, which can be added to the diagram.

  1. The composition of the palette may vary depending on the platform selected in the settings.

  2. Blocks that are not available in the selected execution model (2D model or on a real robot) are highlighted in gray.

How to add and remove blocks to the scene in TRIK Studio read in the article:

Variables panel

Displays the list of variables used when executing the diagram with their current values, including sensor variables. When executed in the interpretation mode on a two-dimensional model or a real robot, they are taken from the robot in real-time. Not used in the generation mode.

Status bar

The status bar displays the current TRIK Studio mode (editing or debugging) and allows you to switch between modes. To switch between them, just click on the status bar.

Debug mode

The elements of the TRIK Studio interface in debug mode repeat the elements in edit mode, except for the editor window, property editor panels and palette. Instead of these elements, the next elements are displayed:

  • 2D model window

  • Error panel

  • Robot settings panel

  • Plots panel

2D model window

The 2D model window opens if a 2D model is selected as the program execution mode.

The window allows you to set the environment in which the robot will be executed, set the robot sensors and observe how the program written in edit mode will work.

Read more about the 2D model in the article:

In the Interpretation and Generation modes for the real robot, this window is not displayed, an executable diagram is displayed instead.

Robot settings panel

The robot settings panel displays the type of controller and robot parameters that depend on the selected platform.

Opening robot settings panel

Error panel

In the case of syntactic and semantic errors in the TRIK Studio, a window with the corresponding messages appears.

To view the block where the error occurred, click on the message.

Plots panel

The Plots window displays the values sent by the sensors in real-time.

Read more in the article:

Getting started and creating a project
Adding and removing blocks
TRIK Studio main menu
Property editing
Adding and removing blocks
2D model
Working with graphs

Object «brick»

This article is automatically translated from Russian by Google Translator.

The object "brick" represents the TRIK controller and provides access to the robot devices.

Method

Description

Provides access to the accelerometer.

Provides access to battery information.

Provides access to the color sensor by the camera.

Provides access to the display of the robot.

Provides access to the encoder on the specified port.

Get a photo from the camera as an array of bytes.

Provides access to the gyroscope.

Provides access to the buttons on the body of the robot.

Play the audio file.

Provides access to the LED on the body of the robot.

Provides access to the line sensor by the camera.

Provides access to the motor on the specified port.

Provides access to the object sensor by the camera.

Pronounce the string passed as a parameter (in Russian or English).

Provides access to the sensor on the specified port.

Stops all motors and active sensors, and removes what is drawn on the display.

accelerometer

Provides access to the accelerometer (class "Accelerometer").

Syntax

brick.accelerometer();
brick.accelerometer();

battery

Provides access to battery information (class "Battery").

Syntax

brick.battery();
brick.battery();

colorSensor

Provides access to the color sensor by the camera (class "ColorSensor").

Syntax

brick.colorSensor("video1");
brick.colorSensor("video1");

display

Provides access to the display of the robot (class "Display").

Syntax

brick.display();
brick.display();

encoder

Provides access to the encoder on the specified port (class "Encoder").

Syntax

brick.encoder(portName);
brick.encoder("portName");
brick.encoder(portName);
brick.encoder("portName");

As a parameter, you must specify the port.

Example

brick.encoder(E1); // encoder call on port E1
brick.encoder("E2"); // encoder call on port E2
brick.encoder(E1); # encoder call on port E1
brick.encoder("E2"); # encoder call on port E2

getStillImage

Get a photo from the camera as an array of bytes.

Syntax

brick.getStillImage();
brick.getStillImage();

gyroscope

Provides access to the gyroscope (class "Gyroscope").

Syntax

brick.gyroscope();
brick.gyroscope();

keys

Provides access to the buttons on the robot body (class "Keys").

Syntax

brick.keys();
brick.keys();

led

Provides access to the LED on the robot body (class "Led").

Syntax

brick.led();
brick.led();

lineSensor

Provides access to the line sensor by the camera (class "LineSensor").

Syntax

brick.lineSensor();
brick.lineSensor();

motor

Provides access to the motor (power or servomotor) on the specified port (class "Motor").

Syntax

brick.motor(motorName);
brick.motor("motorName");
brick.motor(motorName);
brick.motor("motorName");

As a parameter, you must specify the port.

Example

brick.motor(M1) // motor call on port M1
brick.motor("M2") // motor call on port M2
brick.motor(M1) # motor call on port M1
brick.motor("M2") # motor call on port M2

objectSensor

Provides access to the object sensor by the camera (class "ObjectSensor").

Syntax

brick.objectSensor();
brick.objectSensor();

playSound

Play the audio file.

Syntax

brick.playSound("filename");
brick.playSound("filename");

As a parameter, you must specify the name of the file with an absolute path or the path relative to the folder trik on the controller.

Warning! The file must be pre-loaded on the controller.

Example

brick.playSound("media/sound.mp3"); // Play the sound.mp3 file in the media folder
brick.playSound("media/sound.mp3"); # Play the sound.mp3 file in the media folder

say

Say the line (in Russian or English).

Syntax

brick.say(string);
brick.say(string);

As a parameter, you must specify a string in English or Russian.

Example

brick.say("Привет, я ТРИК");
brick.say("Привет, я ТРИК");

sensor

Provides access to the sensor on the specified port (class "Sensor").

Syntax

brick.sensor(portName);
brick.sensor("portName");
brick.sensor(portName);
brick.sensor("portName");

As a parameter, you must specify the port.

Example

brick.sensor(A1) // call a sensor on port A1
brick.sensor("A2") // call a sensor on port A2
brick.sensor(A1) # call a sensor on port A1
brick.sensor("A2") # call a sensor on port A2

stop

Stops all motors and active sensors, and removes what is drawn on the display.

Syntax

brick.stop();
brick.stop();

TRIK controller menu

The TRIK controller menu contains six sections:

  1. File Manager — start and remove programs.

  2. Testing — testing of devices connected to the TRIK controller.

  3. Network Config— connecting the TRIK controller to other devices.

  4. Comm settings — the interaction of several TRIK controllers.

  5. Language — language selection.

  6. More... — programming the controller, system settings, and information about the firmware version.

Use the controller buttons to navigate the menu.

"Up", "Down", "Right", "Left" — move through the menu. "Enter" (checkmark) — select a menu section. "Exit" (cross) — exit from the submenu.

File Manager

The "File Manager" section is intended for viewing, launching, and deleting programs uploaded to the controller.

Starting the program

Press the Enter button (checkmark) to start the program.

Deleting the program

To delete the program, press the "Right" button and confirm the deletion.

Deleting all programs

To remove all programs, select "Delete all ..." and confirm the removal.

Testing

On the TRIK controller, using this menu item, you can test the connected devices:

  1. Analog sensors.

  2. Servos.

  3. Power motors.

  4. Digital sensors.

  5. Encoders.

  6. Gyroscope.

  7. Accelerometer.

For more details, see the article

Network Config

This section is about setting up the connection of the controller to a computer or smartphone.

In the "Network" item, you can connect the controller to a computer or smartphone in two modes:

  1. Wi-Fi access point.

  2. Wi-Fi client.

For more details, see the article

Comm settings

At the "Comm settings" section, you can configure the parameters for the interaction of the controllers.

For more details, see the article

Language

This section allows you to select the language of the TRIK controller menu.

1. Select the language you want and press Enter. 2. Once the warning about the controller restart appears, press the Enter button again. 3. After restarting, the language will change to the selected one.

More...

The "More..." menu item contains the next sub-items:

  1. Programming.

  2. System settings.

  3. Version

Programming

Section "Programming" is intended for writing a program on the controller from ready-made commands.

  1. Add commands to the algorithm using the "<new command>" item.

  2. After the completion of the algorithm, select the "Run program" item.

  3. To clear the list, use the "Clear list" menu item.

Add command

The "<add command>" item allows you to add a command to the end of the algorithm.

Select a command using the Up and Down buttons and press Enter.

By adding commands to the list, you can get the final program.

When adding the "Motors forward" command to the algorithm, you must specify the power.

When adding a Timer command to the algorithm, you must specify the timeout in milliseconds.

Run program

The "Run program" item allows you to execute the written algorithm.

Clear list

The "Clear list" item allows you to delete the algorithm you wrote before.

System settings

In this subsection, you can choose what will be displayed in the Files folder:

  • Scripts folder. In this case, only programs uploaded from TRIK Studio will be displayed.

  • File system.

Version

In this subsection, you can see the firmware version and the mac-address.

accelerometer
battery
colorSensor
display
encoder
getStillImage
gyroscope
keys
playSound
led
lineSensor
motor
objectSensor
say
sensor
stop

.
Testing devices connected to the TRIK controller
Connecting to the TRIK controller via Wi-Fi
Interaction of TRIK controllers

2D model

Interactive simulation mode is a distinctive feature of TRIK Studio. In that mode, the commands are executed for the virtual robot model displayed on the screen. For TRIK, Lego EV3 and Lego NXT kits the model is a three-wheeled cart.

TRIK three-wheeled cart

Initially, the robot is in an infinite empty space, and the user has the opportunity to set different scene objects like walls, draw colored lines and areas on the floor.

At the same time, the work of the majority of the real robot sensors is emulated. For example, touch sensor, ultrasonic distance sensor, color and light sensors for NXT, compass, and gyroscope for EV3, infrared and ultrasonic distance sensors, touch sensor and light sensor for TRIK, and many others.

A two-dimensional model may have devices that are not available on a real robot. For example, the ability to draw colored lines with a marker on the floor. The appearance and set of devices of the two-dimensional model depend on the chosen platform.

The two-dimensional model mode is useful for debugging programs in the absence of a real robot.

2D model window

To open the 2D model window, press the button on the toolbar or choose in settings "2D model".

2D model elements:

  • Tools for editing world model

  • Grid

  • Ruler

  • "Return to start" button

  • "Start/Stop" button

  • Panel for interpretation speed control

  • Model settings

    • Display emulator and buttons of the robot

    • Ports control

    • Motors control

    • Robot physics settings

    • Model parameters

  • Robot popup menu

Tools for editing world model

Editing the model of the world is carried out using the corresponding panel.

Name

Description

Shortcut

Cursor

Switch to selection mode.

1

Wall

Add a wall to the scene.

When added with the Shift key pressed, the wall is placed either at a right angle or at an angle of 45 ° relative to the borders of the window. The wall is displayed in the form of a "brick" line. When such a line is touched by a touch sensor or when it enters the range of a distance sensor, the sensor is triggered. A robot cannot drive through a wall.

2

Can

Add a can to the scene.

3

Ball

Add a ball to the scene. When the robot touches it, the ball bounces some distance.

4

Line

Add a straight line to the scene.

When added with the Shift key pressed, the line is placed either at a right angle or at an angle of 45 ° relative to the borders of the window. Light and color sensors located on a virtual robot can respond to the line.

You can the color and thickness of the line.

5

Curve

Add a line with curvature on the scene. Light and color sensors located on the virtual robot can respond to the line. You can the color and thickness of the line.

6

Ellipse

Add an ellipse to the scene.

Light and color sensors located on the virtual robot can respond to the ellipse.

You can the color and thickness of the borderline as well as the color of the filling.

7

Rectangle

Add a rectangle to the scene.

Light and color sensors located on the virtual robot can respond to the rectangle.

You can the color and thickness of the borderline as well as the color of the filling.

8

Stylus

Draw a line using the mouse.

Light and color sensors located on the virtual robot can respond to the drawn line.

You can the color and thickness of the line.

9

Add an image on the floor of the scene.

Depending on the mode of the image, light and color sensors located on the virtual robot can respond to the image.

0

Editor of lines, stylus, and ellipse

When a line, Bézier curve, stylus, rectangle, or ellipse is selected, a pop-up window appears that allows you to adjust their color and thickness.

The ellipse and rectangle tools have the ability to paint over the inner area with the specified color. You can also edit the size, shape, and position of the selected geometric objects.

Working with background

In addition to various geometric objects on the scene, it is possible to load an image from a file using the Image tool.

If you select an image, you can move it, resize it and configure the following parameters:

The image will not be included in the save file. When you open the current project on another computer or rename the file with the picture, the image in the 2D model disappears.

The picture will be packed into the project. Attention, this might significantly increase the size of the save file.

The image will be in the foreground. The robot can detect this image using sensors.

The image will be in the background. The robot does not see this image.

Change image... Replaces the image with the one selected through the dialog window.

Model settings panel

To open the settings panel, click the button to the right of the scene:

This panel contains:

  • Display emulator

  • Sensors control panel

  • Motors control panel

  • Robot physics control

  • Model settings

Display emulator

The emulator of the robot screen allows displaying colored primitives on the screen. The emulator of the buttons to emulate buttons clicking (by clicking on the corresponding button on the robot).

Sensors control panel

The port control panel allows you to change the configuration and location of the sensors of the robot model.

For each port, you can select the sensor of interest, and it will automatically be added to the scene.

When you change the configuration of the sensors from the settings, the sensors in the two-dimensional model are automatically adjusted. In this case, it will be considered that the sensor is connected to the robot. That is, when the robot icon moves, the sensors will move with it, even if they are at some distance from the robot model.

A gray cone is displayed next to the ultrasound or infrared sensor, indicating the area in which the sensor will detect obstacles.

Rotate and move sensors

For each port, you can select the sensor of interest, and it will automatically be added to the scene. Added sensors are always mounted on the robot, they can be moved and rotated.

When rotating with the Shift key pressed, the sensor rotates either at a right angle or at an angle of 45° relative to the borders of the window.

Motors control panel

The motor control panel allows you to specify which of the motor ports will correspond to the left and right wheels.

Robot physics control

  • Realistic physics more accurately emulate the forces acting on the robot: it turns when it collides with a wall, accelerates with acceleration, etc.

  • Realistic sensors — enable/disable emulation of inaccurate sensors.

  • Realistic engines — enable/disable emulation of inaccurate motor control.

Model settings

Displays the parameters of the robot model:

  • wheel diameter,

  • robot height,

  • robot width,

  • robot mass.

Context menu

Also, the functions of the two-dimensional model are available when you click the right mouse button on the scene.

Menu item

Description

Hand dragging mode

Allows you to move the scene with the robot, walls, and lines when clicking and dragging to a free section of the scene.

Multiselection mode

Allows you to select a group of walls, lines, and other parts of the world when you click and drag to a free section of the scene.

Save world model...

Saving the world model as an XML file, which can then be loaded and used in another project.

Load world model…

Load a previously saved model of the world.

Clear items

Delete all walls and color lines. The robot remains on the scene.

Clear floor

Delete all colored lines drawn by the robot marker. Other elements remain on the scene.

Grid

Turn on the grid on the scene and snap the walls to its nodes. The slider allows you to adjust the size of the grid.

Panel to control simulation speed

The speed control panel allows you to set the simulation speed.

When choosing a low speed, one second of model time corresponds to a few seconds of real-time, when choosing a high speed - vice versa.

The current model time elapsed since the launch of the program is also displayed here. It may differ from real-time (depending on the speed settings and computer capabilities).

Ruler

The ruler shows the distance on the scene, in centimeters (relative to the size of the robot).

"Return to start" button

The "Return to start" button sets the robot to its initial position, which is set by the red cross on the scene.

The cross can be rotated around its axis, highlighting it and dragging the end of the arrow that appears. This sets the initial direction of the robot.

When added with the Shift key pressed, the cross arrow is placed either at a right angle or at an angle of 45° relative to the borders of the window.

"Start/Stop" buttons

Run program.

Stop program.

Pop-up robot menu

A pop-up menu for controlling the robot appears when clicking on the robot.

Item

Description

Robot following

When the mode is on, the scene automatically moves, exposing the robot to the center if it moves beyond the boundaries of the visible area.

Return robot

Return the robot to its original position, indicated by a red cross.

Change marker thickness

Change the thickness of the trace left by the robot when drawing with a marker.

Common blocks

The list of available blocks depends on the chosen robotics kit and on the robot model (real robot or 2D model simulation). Blocks unavailable for the current kit are not shown at all, and blocks inaccessible for this model within the same platform are shown in gray and are not available for dragging onto the scene.

Common blocks for all platforms are presented below. A program using only these blocks will be executed on any platform without any changes.

A list of blocks specific to a particular robotics kit can be found in the relevant sections:

  • TRIK

  • LEGO EV3

  • LEGO NXT

  • Geoscan Pioneer Quadcopter

List of common blocks

Icon

Name

Description

The starting point for program execution.

Each diagram should have only one such block. There should not be any incoming links in it, and there should be only one outgoing link from this element.

The process of diagram interpretation begins with this block.

End of the program.

If the program consists of several parallel execution sections, reaching this block completes the corresponding execution section.

This block cannot have outgoing links.

A block for declaring a new variable and setting a value for it.

Separation of program execution in accordance with a given condition.

Indicates merging of two branches of a conditional statement. It does not perform any actions but is useful for ensuring the structure of the program.

A loop that is executing so far some condition is true, indicated before it begins. This condition is checked before the loop body is executed, so the body may not be satisfied even once (if the condition is false from the very beginning).

Block that provides the execution of a sequence of blocks several times.

A condition with several alternatives.

Counts the value of the specified expression. Initialization of variables is also allowed.

Subprogram execution.

Block divides program execution into several threads.

Block merging parallel tasks.

Finishes the task with the identifier specified in the "Task" property. Must be applied from another task.

A block for assigning a specified variable to a random integer from a given interval.

Block for adding arbitrary text to the diagram as a comment.

Block for setting the delay. The delay time is set in the Delay parameter in milliseconds.

Start drawing with a marker of a given color on the floor. When the robot moves in a two-dimensional model, a colored line will remain behind it.

Finish drawing with a marker.

Initial Node

Initial Node

The starting point for program execution.

Each diagram should have only one such block. There should not be any incoming links in it, and there should be only one outgoing link from this element.

The process of diagram interpretation begins with this block.

Final Node

Final Node

End of the program.

If the program consists of several parallel execution sections, reaching this block completes the corresponding execution section.

This block cannot have outgoing links.

Variable Initialization

Variable Initialization

A block for declaring a new variable and setting a value for it. The same operation can be performed using the Expression block, but this block makes the program more clear.

Properties

Property

Description

Value

An expression is specified that defines the initial value of the variable.

Variable

The variable name is specified.

Condition

Condition

Separation of program execution in accordance with a given condition.

This block must have two outgoing connections, at least one of which must have the value of the Condition parameter set: true or false.

Properties

Property

Description

Condition

A logical expression is indicated (for more details, see the article ""), based on the value of which the further path of the diagram execution will be selected.

End if

End if

Indicates merging of two branches of a conditional statement. It does not perform any actions but is useful for ensuring the structure of the program. It does not perform any actions but is useful for ensuring the structure of the program. If you adhere to the rule that all branches of the "Condition" or "Switch" operators converge on such a block, this will significantly increase the chances that the generator will be able to generate code in text language without goto statements.

Pre-conditional Loop

Pre-conditional Loop

A loop with a precondition is a loop that is true so far for some condition specified before it starts. This condition is checked before the loop body is executed, so the body may not be satisfied even once (if the condition is false from the very beginning).

Properties

Property

Description

Condition

The logical expression is specified (for more details, see the article ""), based on the value of which the further path of the diagram interpretation will be selected.

Loop

Loop

Block that provides the execution of a sequence of blocks several times. The number of repetitions is set by the value of the Iteration parameter. The block must have two outgoing connections, one of which must be marked with the value “body” (that is, the value of the “Condition” parameter the connection must have “body”). Another connection coming from the “Cycle” block should remain unmarked: it will go through when the program passes through the “Loop” block the specified number of times. Infinite loops and loops of the form while / do and while are organized without using this block, looping the control flow using links. An exit from such a loop is carried out using the “Condition” block.

Switch

Switch

A condition with several alternatives.

In the "Expression" parameter, you can specify an arbitrary expression (for more details, see the section "Syntax of expressions"), based on the value of which the further path of the diagram interpretation will be selected.

This block must have several outgoing links. All relations, except one, should be marked with an elementary value (string, number, etc.), which can take an expression (the value is simply written in the Condition property of the connection). One of the links should not be marked: it jumps if the expression is not equal to any of the listed values.

Expression

Expression

Evaluate the value of the specified expression. Initialization of variables is also allowed.

For more information about the syntax of valid expressions for the Expression parameter, see the section "Expression syntax".

Subprogram

Subprogram

Subprogram execution. Subprograms are used to keep repeating program fragments on a separate diagram. When adding this block to the diagram, you will be prompted to enter the name of the subprogram, after which double-clicking on the block will be able to go to the diagram corresponding to this subprogram. An additional palette with all the subprograms will also appear. Subprograms from it can be dragged onto the scene and used as normal blocks. The appearance, name, and properties of the block can be changed using the context menu.

Properties

Changing the properties of this block does not perform in the "Properties Editor" panel, but using the "Change Properties" item in the context menu. To call the context menu, right-click on the block "Subprogram".

In the window that opens, you can:

  • Change subprogram name.

  • Add and change subprogram parameters by specifying a name, type, and value.

  • Change the picture on the icon of your subprogram.

  • Change subprogram icon background.

Fork

Fork

A block divides program execution into several threads. For example, you can simultaneously wait for the sensor to trigger and the time interval to expire. A block must have at least two outgoing connections. In order to be able to further refer to parallel tasks generated by this block (for example, in the "Kill thread" block or in the "Join" block), you need to give the names of the tasks. This is done on outgoing connections, in the Condition property. The name of the task can be any string, but one of the names should be the name of the task that is included in this block. The name of the main program is main.

Join

Join

Block for merging parallel tasks.

It blocks the execution of the program until the execution of all parallel tasks included in this block reaches this block.

A block must have at least two incoming links. On the outgoing connection (in the “Condition” property) there must be an identifier for the task, which will continue after the block has completed.

Kill thread

Kill thread

Finishes the task with the identifier specified in the "Task" property. Must be applied from another task.

Random Initialization

Random Initialization

A block for assigning a specified variable to a random integer from a specified interval using the From and To properties.

Comment

Comment

Block for adding arbitrary text to the diagram as a comment.

Used to explain a specific block or section of a diagram. May be associated with the block, which he explains.

When the program is executed, the block is not taken into account.

Timer

Timer

Block for setting the delay. The delay time is set in the Delay parameter in milliseconds.

Marker Down

Marker Down

Start drawing with a marker of a given color on the floor. When the robot moves in a two-dimensional model, a colored line will remain behind it.

The block is available only in the two-dimensional model mode.

Marker Up

Marker Up

Finish drawing with a marker.

The block is available only in the two-dimensional model mode.

Class «display»

This article is automatically translated from Russian by Google Translator.

Provides access to the display of the robot.

Screen size: 240*320 pixels.

addLabel

Print the specified text on the screen, starting from the specified coordinate. If there was already text in the specified coordinates, it will be replaced by the new text.

The changes on the display will occur only after calling the method "".

Parameters:

  • text — display text,

  • x, y — screen coordinates.

Example

clear

Clear the drawing window.

drawArc

Draw an arc of an ellipse inscribed into a rectangle with the upper left corner at specified coordinates and having a given width and height. The changes on the display will occur only after calling the method "".

Parameters:

  • x, y — the coordinates of the upper left corner of the rectangle on the screen,

  • l — rectangle width,

  • h — rectangle height,

  • from — initial angle bounding the arc,

  • to — finite angle bounding the arc.

Example

drawEllipse

Draw an ellipse inscribed into a rectangle with the upper left corner at specified coordinates and having a given width and height. The changes on the display will occur only after calling the method "".

Parameters:

  • x, y — coordinates of the upper left corner of the rectangle,

  • l — rectangle width,

  • h — rectangle height.

Example

drawLine

Draw a line with the beginning and the end at the given coordinates. The changes on the display will occur only after calling the method "".

Parameters:

  • x0, y0 — line origin coordinates,

  • x1, y1 — line end coordinates.

Example

drawPoint

Draw a point at given coordinates. The changes on the display will occur only after calling the method "".

Parameters:

  • point coordinates x, y.

Example

drawRect

Draw a rectangle with the upper left corner at the specified coordinates and having the specified width and height. The changes on the display will occur only after calling the method "".

Parameters:

  • x, y — coordinates of the upper left corner of the rectangle,

  • l — rectangle width,

  • h — rectangle height.

Example

hide

Close and clear the drawing window.

redraw

Redraw the window to draw. The changes to the display will only happen after this method is called.

removeLabels

Remove from the screen all text added to it by calls to the "" method.

setBackground

Set the screen background to the color you specify.

Available colors:

  • white,

  • red, darkRed,

  • green, darkGreen,

  • blue, darkBlue,

  • cyan, darkCyan,

  • magenta, darkMagenta,

  • yellow, darkYellow,

  • gray, darkGray, lightGray,

  • black.

As a parameter, you must specify the color.

Example

setPainterColor

Set the color of the brush used to draw the graphical primitives.

Available colors:

  • white,

  • red, darkRed,

  • green, darkGreen,

  • blue, darkBlue,

  • cyan, darkCyan,

  • magenta, darkMagenta,

  • yellow, darkYellow,

  • gray, darkGray, lightGray,

  • black.

As a parameter, you must specify the color.

Example

setPainterWidth

Set the thickness of the brush used to draw the graphical primitives, in pixels.

As a parameter, you must specify the thickness d.

Example

show

Display the image generated in the one-dimensional array on the controller.

Parameters:

  • array — a one-dimensional integer array with dimensions width×height

  • width и height — the width and height of the image, respectively

  • The format in which each element of the array is represented should be passed as the format parameter. The formats currently supported are: «rgb32», «grayscale8», «rgb888».

Example

Examples of using show() on an image taken with.

showImage

Display the image previously loaded on the robot.

The name of the image file (in BMP, GIF, JPG, JPEG, PNG, PBM, PGM, PPM, TIFF, XBM, XPM formats) must be specified as a parameter, the path is specified either as absolute or relative to the trik folder.

Example

Method

Description

addLabel

Print the specified text on the screen, starting from the specified coordinate.

clear

Clear the drawing window.

drawArc

Draw an arc of an ellipse inscribed into a rectangle with the upper left corner at specified coordinates and having a given width and height.

drawEllipse

Draw an ellipse inscribed into a rectangle with the upper left corner at specified coordinates and having a given width and height.

drawLine

Draw a line with the beginning and the end at the given coordinates.

drawPoint

Draw a point at given coordinates.

drawRect

Draw a rectangle with the upper left corner at the specified coordinates and having the specified width and height.

hide

Close and clear the drawing window.

redraw

Redraw the window to draw. The changes to the display will only happen after this method is called.

removeLabels

Remove from the screen all text added to it by calls to the "addLabel" method.

setBackground

Set the screen background to the color you specify.

setPainterColor

Set the color of the brush used to draw the graphical primitives.

setPainterWidth

Set the thickness of the brush used to draw the graphical primitives, in pixels.

show

Display the image generated in the one-dimensional array on the controller.

showImage

Display the image previously loaded on the robot.

brick.display().addLabel("text", x, y);
brick.display().addLabel("text", x, y);
brick.display().addLabel('Hello, world!', 1, 1);
brick.display().addLabel('Hello, world!', 1, 1);
brick.display().clear();
brick.display().clear();
brick.display().drawArc(x, y, l, h, from, to);
brick.display().drawArc(x, y, l, h, from, to);
brick.display().drawArc(0, 0, 10, 10, 20, 50);
brick.display().drawArc(0, 0, 10, 10, 20, 50);
brick.display().drawEllipse(x, y, l, h);
brick.display().drawEllipse(x, y, l, h);
brick.display().drawEllipse(0, 0, 10, 10);
brick.display().drawEllipse(0, 0, 10, 10);
brick.display().drawLine(x0, y0, x1, y1);
brick.display().drawLine(x0, y0, x1, y1);
brick.display().drawLine(0, 0, 10, 10);
brick.display().drawLine(0, 0, 10, 10);
brick.display().drawPoint(x, y);
brick.display().drawPoint(x, y);
brick.display().drawPoint(10, 10);
brick.display().drawPoint(10, 10);
brick.display().drawRect(x, y, l, h);
brick.display().drawRect(x, y, l, h);
brick.display().drawRect(0, 0, 10, 10);
brick.display().drawRect(0, 0, 10, 10);
brick.display().hide();
brick.display().hide();
brick.display().redraw();
brick.display().redraw();
brick.display().removeLabels();
brick.display().removeLabels();
brick.display().setBackground("color");
brick.display().setBackground("color");
brick.display().setBackground("red");
brick.display().setBackground("red");
brick.display().setPainterColor("color");
brick.display().setPainterColor("color");
brick.display().setPainterColor("red");
brick.display().setPainterColor("red");
brick.display().setPainterWidth(d);
brick.display().setPainterWidth(d);
brick.display().setPainterWidth(5);
brick.display().setPainterWidth(5);
brick.display().show(array, width, height, format)
brick.display().show(array, width, height, format)
//rgb32
var photo = getPhoto();
brick.display().show(photo, 160, 120, "rgb32");
script.wait(5000);

//rgb888
pic = []
photo = getPhoto();
l = photo.length;
for (i = 0; i < l; i++) {
    var p = photo[i];
    pic.push((p&0xff0000)>>16);
    pic.push((p&0xff00)>>8);
    pic.push((p&0xff));
}
brick.display().show(pic, 160, 120, "rgb888");
script.wait(5000);                            

//grayscale8                                   
pic = []                                      
photo = getPhoto();
l = photo.length;                             
for (i = 0; i < l; i++) {                     
        var p = photo[i];                     
        pic.push(((p&0xff0000)>>18) + ((p&0xff00)>>10) + ((p&0xff)>>2));                
}                                             
                                              
brick.display().show(pic, 160, 120, "grayscale8");
script.wait(5000);
#rgb32
photo = getPhoto();
brick.display().show(photo, 160, 120, "rgb32");
script.wait(5000);

#rgb888
pic = []
photo = getPhoto();
l = len(photo);
for i in range(l):
    p = photo[i];
    pic.append((p&0xff0000)>>16);
    pic.append((p&0xff00)>>8);
    pic.append((p&0xff));

brick.display().show(pic, 160, 120, "rgb888");
script.wait(5000);                            

#grayscale8                                   
pic = []                                      
photo = getPhoto();
l = len(photo);                             
for i in range(l):                    
    p = photo[i];                     
    pic.append(((p&0xff0000)>>18) + ((p&0xff00)>>10) + ((p&0xff)>>2));                
                                         
                                              
brick.display().show(pic, 160, 120, "grayscale8");
script.wait(5000);
brick.display().showImage("imagePath");
brick.display().showImage("imagePath");
brick.display().showImage("media/trik_smile_sad.png");
brick.display().showImage("media/trik_smile_sad.png");
redraw
redraw
redraw
redraw
redraw
redraw
addLabel
getPhoto()
adjust
adjust
adjust
adjust
adjust
Image
Initial Node
Final Node
Variable Initialization
Condition
End if
Pre-conditional loop
Loop
Switch
Expression
Subprogram
Fork
Join
Kill thread
Random Initialization
Comment
Timer
Marker Down
Marker up
Expression Syntax
Syntax of expressions

Connecting to the TRIK controller using UART

This article is automatically translated from Russian by Google Translator.

In addition to connecting the TRIK controller to the computer using Wi-Fi, it can be connected via a USB to UART interface converter based on the chip CP2102:

The connection algorithm is described below.

  1. Installing drivers

  2. Setting up the COM port

  3. Modem installation

  4. Modem setup

  5. Creating a network connection

  6. Setting up a network connection

  7. Connecting to the controller

1. Installing drivers

1. Download the drivers from the converter manufacturer's official website: silabs.com. 2. Unpack the archive and run the driver installer corresponding to your operating system (32 or 64 bit).

3. After the installation is complete, connect the USB to the UART converter to the computer (without the controller). Wait until the device is detected.

4. Check in the "Device Manager" if the driver has been installed correctly.

5. If the CP2102 USB to UART Bridge Controller shows an exclamation mark in Device Manager, as in the example below, then the device driver is not installed. Repeat the installation procedure, or contact a technician.

If the device is not on the Device Manager list, check if the USB port is working and if the device is correctly inserted into the USB port. If the device is connected correctly, the red "POWER" LED on the device should light up.

2. Setting up the COM port

1. In the "Device Manager" call the properties of Silicon Labs CP210x USB to UART Bridge (COMx).

On the "Port Settings" tab, set:

  • Bits per second: 115200.

  • Flow Control: No.

With the "Advanced" button you can select the number of the COM port, if necessary:

3. Modem installation

Open Windows Control Panel any way

1. From the Control Panel, select the Phone & Modem section.

2. Enter any phone code for the city and press "OK".

3. On the "Modems" tab, click the "Add" button.

4. Select "Do not detect my modem, I will select it from list" and click "Next".

5. Select "Standard Modem Types" → "Communications cable between two computers" and click "Next".

6. Select the previously specified port (COM3 in our example), then click "Next" and "Done".

4. Modem setup

1. Once again, from the Control Panel, select Phone & Modem and click the Modems tab. 2. Select "Communications cable between two computers (COM3)" and click "Properties".

3. Press "Change settings" button on General tab, elsewere, the necessary settings will not be available

4. The "Modem" tab should correctly display the COM port (COM3).

  • Set Port Speed: 115200

5. On "Advanced" tab press "Change Default Preferences..." button

6. On "General" tab, set:

  • Port Speed: 115200.

  • Flow Control: None.

Then click OK - OK.

5. Creating a network connection

Open Parameters("All Settings") → "Network & Internet" → "Dial-Up" → "Set up a new connection".

or Control Panel → "Network and Sharing Center" → "Set up a new connection on network"

Select "Connect to the Internet - Set up a broadband or dial-up connection to the Internet" and click "Next".

Setup connection anyway

Select "Dial-up"

4. Enter 1 in the "Number to Dial" field, fill the connection name, and click "Connect".

Leave the username and password fields blank

5. Wait for some time, then select "Set up the connection anyway".

6. Click Close.

6. Setting up a network connection

1. Open "Network Connections" (Control Panel → "Network and Sharing Center → "Change adapter settings" or Parameters ("All Settings") → "Network & Internet" → "Change adapter options").

2. Go to the properties of the created connection.

3. On the General tab, select "Communications cable between two computers (COMx)" and click "Configure".

4. Select the following option:

  • Select max. speed: 115200

  • Uncheck the "Hardware flow control" box.

  • Click OK.

5. On the "Options" tab, check boxes according to the picture below and click the "PPP Settings..." button.

6. Uncheck "Enable software compression" and click "OK".

7. On the "Network" tab, the "IPv4" protocol must be enabled. IPv4 options → Automatic (by default)

7. Connecting to the controller

1. Remove the USB to the UART converter from the USB connector. 2. Turn on the controller. 3. Connect the USB to the UART converter to the appropriate port on the controller.

3. Connect the USB to UART converter to the computer.

4. Open Parameters ("All Settings") → "Network & Internet" → "Dial-up". Click on the connection and click the "Connect" button.

5. Click "Dial"

6. If everything is done correctly, the "RXD" and "TXD" lights on the inverter should flash.

And the connection status should change to active.

7. Open the Phone Connection Status window.

8. Click the Details button.

9. The IPv4 address must be 10.0.5.1 .

10. If this is correct, you can access the web interface at 10.0.5.2.

11. Or specify the IP address 10.0.5.2 in the corresponding TRIK Studio window to control the controller.

Blocks in TRIK Studio Junior

This article is automatically translated from Russian by Google Translator.

TRIK Studio Junior blocks consist of four categories:

  1. Algorithms — blocks to describe algorithms.

  2. Actions — blocks that perform any action on the "Character movement": commands to drive forward, turn, play sound, and others.

  3. Waiting — blocks waiting for an event to occur: certain sensor readings, pressing a button, etc.

  4. Drawing — blocks displaying graphics and text on the screen.

Algorithms

Icon

Name

Description

The starting point for program execution.

Each diagram should have only one such block. There should not be any incoming links in it, and there should be only one outgoing link from this element.

The process of diagram interpretation begins with this block.

End of the program.

If the program consists of several parallel execution sections, reaching this block completes the corresponding execution section.

This block cannot have outgoing links.

A block for declaring a new variable and setting a value for it.

Separation of program execution in accordance with a given condition.

Indicates merging of two branches of a conditional statement. It does not perform any actions but is useful for ensuring the structure of the program.

A loop that is executing so far some condition is true, indicated before it begins. This condition is checked before the loop body is executed, so the body may not be satisfied even once (if the condition is false from the very beginning).

Block that provides the execution of a sequence of blocks several times.

A condition with several alternatives.

Counts the value of the specified expression. Initialization of variables is also allowed.

Subprogram execution.

Block divides program execution into several threads.

Block merging parallel tasks.

Finishes the task with the identifier specified in the "Task" property. Must be applied from another task.

A block for assigning a specified variable to a random integer from a given interval.

Block for adding arbitrary text to the diagram as a comment.

Initial Node

Initial Node

The starting point for program execution.

Each diagram should have only one such block. There should not be any incoming links in it, and there should be only one outgoing link from this element.

The process of diagram interpretation begins with this block.

Final Node

Final Node

End of the program.

If the program consists of several parallel execution sections, reaching this block completes the corresponding execution section.

This block cannot have outgoing links.

Variable Initialization

Variable Initialization

A block for declaring a new variable and setting a value for it. The same operation can be performed using the Expression block, but this block makes the program more clear.

Properties

Property

Description

Value

An expression is specified that defines the initial value of the variable.

Variable

The variable name is specified.

Condition

Condition

Separation of program execution in accordance with a given condition.

This block must have two outgoing connections, at least one of which must have the value of the Condition parameter set: true or false.

Properties

Property

Description

Condition

A logical expression is indicated (for more details, see the article ""), based on the value of which the further path of the diagram execution will be selected.

End if

End if

Indicates merging of two branches of a conditional statement. It does not perform any actions but is useful for ensuring the structure of the program. It does not perform any actions but is useful for ensuring the structure of the program. If you adhere to the rule that all branches of the "Condition" or "Switch" operators converge on such a block, this will significantly increase the chances that the generator will be able to generate code in text language without goto statements.

Pre-conditional Loop

Pre-conditional Loop

A loop with a precondition is a loop that is true so far for some conditions specified before it starts. This condition is checked before the loop body is executed, so the body may not be satisfied even once (if the condition is false from the very beginning).

Properties

Property

Description

Condition

The logical expression is specified (for more details, see the article ""), based on the value of which the further path of the diagram interpretation will be selected.

Loop

Loop

Block that provides the execution of a sequence of blocks several times. The number of repetitions is set by the value of the Iteration parameter. The block must have two outgoing connections, one of which must be marked with the value “body” (that is, the value of the “Condition” parameter the connection must have “body”). Another connection coming from the “Cycle” block should remain unmarked: it will go through when the program passes through the “Loop” block the specified number of times. Infinite loops and loops of the form while / do and while are organized without using this block, looping the control flow using links. An exit from such a loop is carried out using the “Condition” block.

Switch

Switch

A condition with several alternatives.

In the "Expression" parameter, you can specify an arbitrary expression (for more details, see the section "Syntax of expressions"), based on the value of which the further path of the diagram interpretation will be selected.

This block must have several outgoing links. All relations, except one, should be marked with an elementary value (string, number, etc.), which can take an expression (the value is simply written in the Condition property of the connection). One of the links should not be marked: it jumps if the expression is not equal to any of the listed values.

Expression

Expression

Evaluate the value of the specified expression. Initialization of variables is also allowed.

For more information about the syntax of valid expressions for the Expression parameter, see the section "Expression syntax".

Subprogram

Subprogram

Subprogram execution. Subprograms are used to keep repeating program fragments on a separate diagram. When adding this block to the diagram, you will be prompted to enter the name of the subprogram, after which double-clicking on the block will be able to go to the diagram corresponding to this subprogram. An additional palette with all the subprograms will also appear. Subprograms from it can be dragged onto the scene and used as normal blocks. The appearance, name, and properties of the block can be changed using the context menu.

Properties

Changing the properties of this block does not perform in the "Properties Editor" panel, but using the "Change Properties" item in the context menu. To call the context menu, right-click on the block "Subprogram".

In the window that opens, you can:

  • Change subprogram name.

  • Add and change subprogram parameters by specifying a name, type, and value.

  • Change the picture on the icon of your subprogram.

  • Change subprogram icon background.

Fork

Fork

A block divides program execution into several threads. For example, you can simultaneously wait for the sensor to trigger and the time interval to expire. A block must have at least two outgoing connections. In order to be able to further refer to parallel tasks generated by this block (for example, in the "Kill thread" block or in the "Join" block), you need to give the names of the tasks. This is done on outgoing connections, in the Condition property. The name of the task can be any string, but one of the names should be the name of the task that is included in this block. The name of the main program is main.

Join

Join

Block for merging parallel tasks.

It blocks the execution of the program until the execution of all parallel tasks included in this block reaches this block.

A block must have at least two incoming links. On the outgoing connection (in the “Condition” property) there must be an identifier for the task, which will continue after the block has completed.

Kill thread

Kill thread

Finishes the task with the identifier specified in the "Task" property. Must be applied from another task.

Random Initialization

Random Initialization

A block for assigning a specified variable to a random integer from a specified interval using the From and To properties.

Comment

Comment

Block for adding arbitrary text to the diagram as a comment.

Used to explain a specific block or section of a diagram. May be associated with the block, which he explains.

When the program is executed, the block is not taken into account.

Actions

Icon

Name

Description

Sends the message to the parallel thread with the identifier given.

Saves the code of the button pressed on the robot to the specified variable.

Moves the "Character movement" forward by the specified number of cells.

Moves the "Character movement" back by the specified number of cells.

Turns "Character movement" to the right.

Turns "Character movement" to the left.

Speak through the speaker the phrase passed as an argument.

Set the specified controller's LED color.

Send Message To Thread

Send Message To Thread

Sends the message to a parallel task with a specified identifier (the identifier must be specified while creating the task in the "Fork" block).

The message can be arbitrary.

Get Button Code

Get Button Code

Assigns the pressed button code to a specified variable.

The "Waiting" property allows you to wait for the button to be pressed. If the button is not pressed, the variable will be set to -1.

Forward

Forward

Moves the "Character movement" forward by the specified number of cells.

The "Number of cells" property allows you to set the number of cells the "Character movement" should move by.

Backward

Backward

Moves the "Character movement" back by the specified number of cells. The "Number of cells" property allows you to set the number of cells the "Character movement" should move by.

Turn right

Turn right

Turns "Character movement" to the right.

Turn left

Turn left

Turns "Character movement" to the right.

Say

Say

Use the speaker to say the phrase passed as the block argument.

LED

LED

Set the specified LED color on the controller.

Waiting

Icon

Name

Description

Block for setting the delay. The delay time is set in the Delay parameter in milliseconds.

Wait for a message from another parallel task.

Wait for the user to enter a value.

Wait until the specified button on the robot is pressed.

Timer

Timer

Block for setting the delay. The delay time is set in the Delay parameter in milliseconds.

Receive Message From Thread

Receive Message From Thread

Wait for a message from another parallel task.

The message text will be assigned to the specified variable.

The "Wait for message" property allows you to specify what to do if the message queue is empty: wait for a new message to arrive or continue working by assigning an empty string to the variable.

The message is automatically converted to the same type as the receiver variable. For example, if you send a number as a string, it will be accepted as a number.

User input

User input

Wait for the user to enter a value. The value will be assigned to the specified variable.

Properties

The block has three properties:

Property

Description

Variable

Variable name.

Default

Default variable value.

Text

Text field description.

Example

Block

Execution

Wait for Button

Wait for Button

Wait until the specified button on the robot is pressed.

Drawing

Icon

Name

Description

Erase everything that is drawn on the screen.

Start drawing with a marker of a given color on the floor. When the robot moves in a two-dimensional model, a colored line will remain behind it.

Finish drawing with a marker.

Print the specified string at the specified location on the robot's screen. The default value of the "Text" property is interpreted as a pure string, so it will be displayed that way.

Specify the color to draw simple graphical shapes on the robot's screen.

Specify the line width used to draw simple graphical figures on the robot's screen.

Draw a dot on the screen at the specified coordinates.

Draw a line segment on the screen. Segment ends are given as parameters to the block.

Draw a rectangle on the screen. The coordinates of the upper left corner, the width, and the height of the rectangle are specified as parameters.

Draw an ellipse inscribed in a given rectangle on the screen.

Draw an arc on the screen, given the coordinates of the rectangle in which it will be inscribed, and the angles (in degrees) of its beginning and end on the circle. If the beginning and the end coincide, the circle will be drawn.

Draw a smiley face on the screen.

Draw a sad smiley face on the screen.

Set the screen background color.

Clear Screen

Clear Screen

Erase everything that is drawn on the screen.

Marker Down

Marker Down

Start drawing with a marker of a given color on the floor. When the robot moves in a two-dimensional model, a colored line will remain behind it.

The block is available only in the two-dimensional model mode.

Marker Up

Marker Up

Finish drawing with a marker.

The block is available only in the two-dimensional model mode.

Print Text

Print Text

Prints the specified string at the specified location on the robot's screen.

Properties

Property

Value

Evaluate

True — print the variable or expression value.

False — print as text.

Text

Text or variable/expression to be printed.

Redraw

True — redraw the screen. False — do not redraw.

X, Y

The text beginning coordinates.

How to print a text?

To print a text:

  1. Put your text into the Text property.

  2. Uncheck the Evaluate checkbox.

How to print a variable value?

To print a variable value:

  1. Put the variable name into the Text property.

  2. Check the Evaluate checkbox.

Painter Color

Painter Color

Specify the color to draw simple graphical shapes on the robot's screen.

Painter Width

Painter Width

Specify the width of the line used to draw simple graphical figures on the robot's screen.

Draw Pixel

Draw Pixel

Draw a dot on the screen at the specified coordinates.

Draw Line

Draw Line

Draw a line segment on the screen. Segment ends are given as parameters to the block.

Draw Rectangle

Draw Rectangle

Draw a rectangle on the screen. The coordinates of the upper left corner, the width, and the height of the rectangle are specified as parameters.

Draw Ellipse

Draw Ellipse

Draw an ellipse inscribed in a given rectangle on the screen.

Draw Arc

Draw Arc

Draw an arc on the screen, given the coordinates of the rectangle in which it will be inscribed, and the angles (in degrees) of its beginning and end on the circle. If the beginning and the end coincide, the circle will be drawn.

Smile

Smile

Draw a smiley face on the screen.

Sad Smile

Sad Smile

Draw a sad smiley face on the screen.

Background Color

Background Color

Sets the screen background color.

Initial Node
Final Node
Variable Initialization
Condition
End if
Pre-conditional loop
Loop
Switch
Expression
Subprogram
Fork
Join
Kill thread
Random Initialization
Comment
Expression Syntax
Syntax of expressions
Send Message To Thread
Get Button Code
Forward
Backward
Turn right
Turn left
Say
LED
Timer
Receive Message From Thread
User input
Wait for Button
Clear Screen
Marker Down
Marker up
Print Text
Painter Color
Painter Width
Draw Pixel
Draw Line
Draw Rectangle
Draw Ellipse
Draw Arc
Smile
Sad Smile
Background Color

TRIK specific blocks

TRIK specific blocks consist of three categories:

  1. Actions - blocks that perform any action on the controller: turning on the motors, playing sounds, etc.

  2. Waiting - blocks waiting for an event to occur: certain sensor readings, pressing a button, etc.

  3. Drawing - blocks displaying graphics and text on the screen.

For blocks common for all platforms see the article

Action blocks

Icon

Name

Description

Sends the message to the parallel thread with the identifier given.

Saves the code of the button pressed on the robot to the specified variable.

Plays a sound with specified frequency and duration on the controller.

Play the specified sound file on the controller.

Turn on the motors at the specified ports with the specified power.

Turn on the motors in reverse mode at the specified ports with the specified power.

Turn off the motors at the specified ports.

Reset the motors revolutions count for the specified ports.

Set the servos rotation angle on the specified ports to the specified position.

Speak through the speaker the phrase passed as an argument.

Set the specified controllers LED color.

The block has a logical parameter "Code". If it's True, the content of the "Command" parameter translates directly into the program code. Otherwise, an OS' CLI call will be pulled.

Turn on the video camera on the controller in one of the three modes.

Turn off the camera.

Fixes the image in the center of the frame and initializes the line sensor or object sensor with it.

Places the current line sensor reading into the specified variable.

Starts a video broadcast on the robot.

Stops the video feed from the robot's camera.

Sends the message to the robot with the board number specified.

Writes a given message to a file.

Deletes a file.

Sets the gyroscope angle to zero at the current position.

Send Message To Thread

Send Message To Thread

Sends the message to a parallel task with a specified identifier (the identifier must be specified while creating the task in the "Fork" block).

The message can be arbitrary.

Get Button Code

Get Button Code

Assigns the pressed button code to a specified variable.

The "Waiting" property allows you to wait for the button to be pressed. If the button is not pressed, the variable will be set to -1.

Play Tone

Play Tone

Plays a sound with specified frequency and duration on the controller.

Play Sound

Play Sound

Plays an audio file on the controller.

The file must be pre-loaded on the controller. The path to the file is relative to the trik folder on the controller. You can download the file to the controller, for example, using the WinSCP program.

Motors Forward

Motors Forward

Turn on the motors on the given ports with the given power.

The ports are specified by lines M1, M2, M3, and M4, separated by commas. The power specified as a percentage by a number from -100 to 100. If the value is negative, the motors will be reversed.

Motors Backward

Motors Backward

Turn on the motors in reverse mode on the given ports with the given power.

Parameters are similar to the "motors forward" block.

Stop Motors

Stop Motors

Stop the motors on the specified ports.

The ports are specified by lines M1, M2, M3, and M4, separated by commas.

Clear Encoder

Clear Encoder

Reset the motors revolutions count on the specified ports.

The ports are specified by lines E1, E2, E3, and E4, separated by commas.

Angular Servo

Angular Servo

Set the servos rotation angle on the specified ports to the specified position (from -90 to 90 degrees).

The ports are specified by comma separated values.

Say

Say

Use the speaker to say the phrase passed as the block argument.

LED

LED

Set the specified LED color on the controller.

System Call

System Call

The block has a logical parameter "Code". If it's True, the content of the "Command" parameter translates directly into the program code. Otherwise, an OS' CLI call will be pulled.

Initialize Camera

Initialize Camera

Enable the video camera on the controller in one of three modes:

  1. Line Sensor - detects a color line in the center of the frame and subsequently returns the deviation of the center of the line from the center of the frame as a number in the range from -100 (left) to 100 (right).

  2. Object sensor - detects a contrasting object in the center of the frame and later returns the coordinates of its center and diameter in pixels.

  3. Color sensor - returns the dominant color in the center of the frame as its coordinates in the RGB color scale.

Detect by Camera

Detect by Camera

Captures the image in the center of the frame and initializes a line sensor or object sensor with it. The camera must be switched on in the appropriate mode with the "Initialize Camera" block.

Line Detector into Variable

Line Detector inti Variable

Places the current line sensor reading in the specified variable.

The camera must be switched on inline sensor mode by the "Initialize Camera" block and initialized by the "Detect by camera" block.

Enable Video Streaming

Enable Video Streaming

Starts a video broadcast on the robot.

The video can be viewed on the TRIK control panel or in a browser at the address {robots ip-address}:8080/?action=stream/.

Send message

Send message

Sends the message to the robot with the board number specified.

The robot must be on the same network as the robot sending the message and registered as master or slave using Settings → Messages on the robot. If there is more than one robot with the given board number in the network, all of them will receive the message.

Write to File

Write to File

Writes the given expression to a file.

The path can be absolute or relative to the folder containing trik-studio.exe.

The file can be retrieved from the controller, e.g. with the WinSCP program for Windows or SCP for Linux.

Remove File

Remove File

Deletes a file. The path can be absolute or relative to the folder containing trik-studio.exe.

Stop Camera

Stop Camera

Turn off the camera.

Disable Video Streaming

Disable Video Streaming

Stop the video feed from the robot's camera.

Calibrate Gyroscope

Calibrate Gyroscope

Sets the gyroscope angle to zero at the current position..

Waiting Blocks

Icon

Name

Description

Wait for a message from another parallel task.

Wait for the user to enter a value.

Wait until the value returned by the gyro sensor on the specified port is greater or less than the one specified in the "degrees" parameter.

Wait for the touch sensor to operate on the specified port.

Wait until the value returned by the light sensor on the specified port is greater or less than the one specified in the "percents" parameter.

Wait until the distance returned by the ultrasonic distance sensor is greater or less than the one specified in the "distance" parameter..

Wait until the distance returned by the infrared distance sensor is greater or less than the one specified in the "distance" parameter..

Wait until the revolutions counter reading on the specified port is greater or less than the "Tacho limit" value.

Wait until the specified button on the robot is pressed.

Wait for the message in the mailbox. When the message is received, it will be assigned to the specified variable.

Wait for the button to be pressed on the remote control connected to the robot.

Wait for one of the two active areas of the RC to be pressed.

Wait for the desired tilt of the RC.

Wait until the RC is disconnected from the robot. If the RC is not connected, the program will continue running.

Wait for the RC to connect to the robot. If the RC is already connected, the program will continue running.

Receive Message From Thread

Receive Message From Thread

Wait for a message from another parallel task.

The message text will be assigned to the specified variable.

The "Wait for message" property allows you to specify what to do if the message queue is empty: wait for a new message to arrive or continue working by assigning an empty string to the variable.

The message is automatically converted to the same type as the receiver variable. For example, if you send a number as a string, it will be accepted as a number.

User input

User input

Wait for the user to enter a value. The value will be assigned to the specified variable.

Properties

The block has three properties:

Property

Description

Variable

Variable name.

Default

Default variable value.

Text

Text field description.

Example

Block

Execution

Wait for Gyroscope

Wait for Gyroscope

Wait until the value returned by the gyro sensor on the specified port is greater or less than the one specified in the "degrees" parameter..

Wait for Touch Sensor

Wait for Touch Sensor

Wait for the touch sensor to operate on the specified port.

Wait for Light

Wait for Light

Wait until the value returned by the light sensor on the specified port is greater or less than the one specified in the "percents" parameter. Parameters:

  • "Percents" - value to compare with the value returned by the light sensor.

  • "Port" - the port to which the light sensor is connected.

  • "Read value" - the operation that will be used to compare with the value of the "Percents" parameter.

Wait for Ultrasonic Distance

Wait for Ultrasonic Distance

Wait until the distance returned by the ultrasonic distance sensor is greater or less than the one specified in the "distance" parameter (distance is set in centimeters, from 0 to 300).

Parameters:

  • "Distance" - value to compare with the value returned by the distance sensor.

  • "Port" - the port to which the distance sensor is connected.

  • "Read value" - the operation to be used for comparison with the value of the Distance parameter.

Wait for Infrared Distance

Wait for Infrared Distance

Wait until the distance returned by the infrared distance sensor is greater or less than the one specified in the "distance" parameter.

By default, the distance on ports A1 and A2 is set in centimeters (from 0 to 100). It is not recommended to connect other sensors to these ports as incorrect values may be read.

Another parameter is the number of the port to which the distance sensor is connected. The last parameter specifies the operation to be used for comparison with the distance.

Wait for Encoder

Wait for Encoder

Wait until the revolutions count reading on the specified port is greater or less than the Tacho limit value.

Wait for Button

Wait for Button

Wait until the specified button on the robot is pressed.

Wait for Message

Wait for Message

Wait for the message in the mailbox. When the message is received, it will be assigned to the specified variable.

The Wait for message property allows you to specify what to do if the message queue is empty: wait for a new message to arrive or continue working by putting an empty string into the variable.

The message is automatically converted to the type corresponding to the receiver variable type, i.e. you can, for example, send a number as a string and accept it as a number.

Wait Gamepad Button

Wait Gamepad Button

Wait for the button to be pressed on the remote control connected to the robot. The buttons are numbered from 1 to 5.

Wait Pad Press

Wait Pad Press

Wait for one of the two active areas of the RC to be pressed. The coordinates of the click can be obtained with the "gamepadPad" sensory variables.

Wait for Gamepad Wheel

Wait for Gamepad Wheel

Wait for the desired tilt of the RC.

The tilt is only registered if the remote is in "steering" mode, the tilt angle is coded with numbers from -100 (maximum left) to 100 (maximum right).

Another parameter specifies the operation that will be used to compare with the Angle parameter value.

Wait for Gamepad Disconnect

Wait for Gamepad Disconnect

Wait until the RC is disconnected from the robot. If the RC is not connected, the program will continue running.

Wait for Gamepad Connect

Wait for Gamepad Connect

Wait for the RC to connect to the robot. If the RC is already connected, the program will continue running.

Drawing Blocks

Icon

Name

Description

Specify the color to draw simple graphical shapes on the robot's screen.

Specify the line width used to draw simple graphical figures on the robot's screen.

Draw a dot on the screen at the specified coordinates.

Draw a line segment on the screen. Segment ends are given as parameters to the block.

Draw a rectangle on the screen. The coordinates of the upper left corner, the width, and the height of the rectangle are specified as parameters.

Draw an ellipse inscribed in a given rectangle on the screen.

Draw an arc on the screen, given the coordinates of the rectangle in which it will be inscribed, and the angles (in degrees) of its beginning and end on the circle. If the beginning and the end coincide, the circle will be drawn.

Draw a smiley face on the screen.

Draw a sad smiley face on the screen.

Set the screen background color.

Print the specified string at the specified location on the robot's screen. The default value of the "Text" property is interpreted as a pure string, so it will be displayed that way.

Erase everything that is drawn on the screen.

Painter Color

Painter Color

Specify the color to draw simple graphical shapes on the robot's screen.

Painter Width

Painter Width

Specify the width of the line used to draw simple graphical figures on the robot's screen.

Draw Pixel

Draw Pixel

Draw a dot on the screen at the specified coordinates.

Draw Line

Draw Line

Draw a line segment on the screen. Segment ends are given as parameters to the block.

Draw Rectangle

Draw Rectangle

Draw a rectangle on the screen. The coordinates of the upper left corner, the width, and the height of the rectangle are specified as parameters.

Draw Ellipse

Draw Ellipse

Draw an ellipse inscribed in a given rectangle on the screen.

Draw Arc

Draw Arc

Draw an arc on the screen, given the coordinates of the rectangle in which it will be inscribed, and the angles (in degrees) of its beginning and end on the circle. If the beginning and the end coincide, the circle will be drawn.

Smile

Smile

Draw a smiley face on the screen.

Sad Smile

Sad Smile

Draw a sad smiley face on the screen.

Background Color

Background Color

Sets the screen background color.

Print Text

Print Text

Prints the specified string at the specified location on the robot's screen.

Properties

Property

Value

Evaluate

True — print the variable or expression value.

False — print as text.

Text

Text or variable/expression to be printed.

Redraw

True — redraw the screen. False — do not redraw.

X, Y

The text beginning coordinates.

How to print a text?

To print a text:

  1. Put your text into the Text property.

  2. Uncheck the Evaluate checkbox.

How to print a variable value?

To print a variable value:

  1. Put the variable name into the Text property.

  2. Check the Evaluate checkbox.

Clear Screen

Clear Screen

Erase everything that is drawn on the screen.

Common blocks
Send Message To Thread
Get Button Code
Play Tone
Play Sound
Motors Forward
Motors Backward
Stop Motors
Clear Encoder
Angular Servo
Say
LED
System Call
Initialize Camera
Stop Camera
Detect by Camera
Line Detector into Variable
Enable Video Streaming
Disable Video Streaming
Send message
Write to File
Remove File
Calibrate Gyroscope
Receive Message From Thread
User input
Wait for Gyroscope
Wait for Touch Sensor
Wait for Light
Wait for Ultrasonic Distance
Wait for Infrared Distance
Wait for Encoder
Wait for Button
Wait for Message
Wait Gamepad Button
Wait Pad Press
Wait for Gamepad Wheel
Wait for Gamepad Disconnect
Wait for Gamepad Connect
Painter Color
Painter Width
Draw Pixel
Draw Line
Draw Rectangle
Draw Ellipse
Draw Arc
Smile
Sad Smile
Background Color
Print Text
Clear Screen

2D model tuning

Defines walls. Used as a container, has no attributes. In addition to creating a virtual world of robots in TRIK Studio, you can do more flexible customization by editing an XML file: specify the location of objects, color, width, and other parameters more precisely.

First, you need to create an XML file for the virtual model.

2D model coordinate system

In the 2D model window the axes located as follows:

Attention! One cell has dimensions of 17.5 × 17.5 centimeters or 50 × 50 pixels.

An XML file creation

To create an empty XML file you should use your OS' standard tools such as Notepad in Windows or whatever.

To save the world model created in TRIK Studio:

  1. Switch to the 2D model mode.

  2. Go to the "Debug mode".

  3. Right-click on the scene and choose "Save world model..." in the context menu.

  4. Specify the location and file name to save.

Editing an XML file

Open a saved XML file in a text editor. Notepad++, for example.

The XML file contains tags and attributes.

Tags

Tag is a markup language element. There is the start (opening) and end (closing) tags. The text contained between the start and end tags is displayed and placed according to the properties specified in the start tag.

Example:

<walls> <!-- start (opening) tag -->
     <wall begin="200:-200" id="{a3ede76b-1d7e-4c72-9ed4-08d8ea9af4bf}" end="200:150"/>
</walls> <!-- end (closing) tag -->

Attributes

Attributes are tag properties that provide additional text formatting capabilities. They are recorded as a combination of "attribute name-value". Text values are enclosed in quotation marks.

In the above example, the attributes are:

begin="200:-200" id="{a3ede76b-1d7e-4c72-9ed4-08d8ea9af4bf}" end="200:150"

The simplest virtual world model without objects in .xml the format is as follows:

The simplest virtual model
<?xml version='1.0' encoding='utf-8'?>
<root>
    <world>
        <background/>
        <walls/>
        <skittles/>
        <balls/>
        <colorFields/>
        <images/>
        <regions/>
    </world>
    <robots>
        <robot direction="0" id="trikKitRobot" position="0:0">
            <sensors/>
            <startPosition direction="0" id="{name}" y="25" x="25"/>
            <wheels left="M4###output###М4###" right="M3###output###М3###"/>
        </robot>
    </robots>
</root>

Robots

The following tags are available for describing robots:

Tag

Description

Defines a robot on stage. Used as a container and must contain a element.

Adds a robot to the scene. Can be used as a container.

Defines sensors on a robot. Used as a container.

Sensors ports configuration.

Defines the starting position of the robot.

Motor ports configuration.

<robots>...</robots>

Defines a robot on stage. Used as a container, has no attributes.

<robots>
     <robot id="trikKitRobot" position="0:0" direction="0">
</robots>

<robot>...</robot>

Adds a robot to the scene. Can be used as a container.

Attention! You can not add multiple robots to the scene.

Attributes

Attribute

Description

direction="0″

The direction of the robot, which can be adjusted by clicking on the robot and pulling the arrow.

position="x:y"

The position of the robot, where x and y is the position of the upper left point of the square of the robot in the .

id="trikKitRobot"

Unique ID.

Example:

<robot id="trikKitRobot" position="0:0" direction="0">

<sensors>...</sensors>

Defines sensors on a robot. Used as a container, has no attributes.

<sensors>
     <sensor type="kitBase::robotModel::robotParts::Motor" direction="0" port="M4###output###JM4$$$D$$$4###" position="75:25"/>
</sensors>

<sensor/>

Sensors ports configuration.

Attributes

Attribute

Description

position="x:y"

The position of the sensor, where x and y is the position of the center point of the square of the sensor in the .

direction="0″

The direction of the sensor, which can be adjusted by clicking on the sensor and pulling the arrow.

port="A1###input######sensorA1"

The port to which the sensor is connected.

type="trik::robotModel::parts::TrikInfraredSensor"

Type of connected sensor.

There are 5 types of sensors for TRIK and 9 types of sensors for EV3:

Sensor

Description

TrikSonarSensor

Ultrasonic distance sensor

TrikLineSensor

Line sensor.

TrikLightSensor

Light sensor.

TrikTouchSensor

Touch sensor.

TrikInfraredSensor

Infrared distance sensor.

Sensor

Description

RangeSensor

Range sensor.

TouchSensor

Touch sensor.

Ev3Gyroscope

Gyroscope.

LightSensor

Light sensor.

ColorSensorGreen

Color sensor (green).

ColorSensorFull

Color sensor (detection).

ColorSensorBlue

Color sensor (blue).

ColorSensorRed

Color sensor (red).

ColorSensorPassive

Color sensor (passive).

Example:

<sensor position="75:25" direction="0" port="A1###input###А1###sensorA1"
type="trik::robotModel::parts::TrikInfraredSensor"/>

<startPosition/>

Defines the starting position of the robot.

Attributes

Attribute

Description

id="{name}"

Unique ID.

direction="0″

The direction of the robot, if you click on the "return" button. To adjust, click on the cross and pull the arrow.

x="25″

The x-axis position in the .

y="25″

The y-axis position in the .

Example:

<startPosition id="{7a326d25-82f4-4eb4-9b42-1e75576f35a4}" direction="0" x="25" y="25"/>

<wheels/>

Motor ports configuration.

Attributes

Attribute

Description

left="M4###output###М4###"

The port to which the left engine is connected.

right="M3###output###М3###"

The port to which the right engine is connected.

Example:

<wheels left="M4###output###М4###" right="M3###output###М3###"/>
<wheels left="B###output###В###" right="C###output###С###"/>

Objects

The following tags are available for describing objects:

Tag

Description

walls

Defines walls. Used as a container, has no attributes.

skittles

Defines skittles. Used as a container, has no attributes.

balls

Defines balls. Used as a container, has no attributes.

colorFields

Defines the elements that you can draw (line, Bezier curve, rectangle, ellipse, elements drawn with a stylus). Used as a container, has no attributes.

images

Specifies the inserted image. Used as a container, has no attributes.

regions

Defines regions. Used as a container, has no attributes.

Adds a wall.

Adds a skittle.

Adds a ball.

Adds a ball.

Adds a Bezier curve.

Adds a rectangle.

Adds an ellipse.

Detects the stylus on the scene. Used as a container.

Allows you to draw arbitrary shapes using the stylus.

Allows you to add regions to the scene.

<wall>

Adds a wall to the scene.

Attributes

Attribute

Description

id="{name}"

Unique ID.

begin="x:y"

The beginning of the wall, where x and y is the position of the starting point in the .

end="x:y"

The end of the wall, where x and y is the position of the starting point in the .

Example:

<wall id="{wall1}" begin="50:-50" end="250:-50"/>

<skittle>

Adds a skittle to the scene.

Attributes

Attribute

Description

markerY="44″

The position on which the skittle will stand along the Y-axis if you click on the "return" button.

markerX="220″

The position on which the skittle will stand along the X-axis if you click on the "return" button.

id="{name}"

Unique ID.

y="44″

Y-axis position.

x="220″

X-axis position.

Example:

<skittle rotation="0" id="{skittle1}" markerY="44" startRotation="0" x="220" y="44"
markerX="220"/>

<ball>

Adds a ball to the scene.

Attributes

Attribute

Description

markerY="169″

The position on which the ball will fall along the Y-axis if you click on the "return" button.

markerX="-18″

The position on which the ball will fall along the X-axis if you click on the "return" button.

id="{name}"

Unique ID.

y="169″

Y-axis position.

x="-18″

X-axis position.

Example:

<ball rotation="0" id="{ball1}" markerY="169" startRotation="0" x="-18" y="169" markerX="-18"/> 

<line>

Adds a line to the scene.

Attributes

Attribute

Description

begin="x:y"

The beginning of the line, where x and y is the position of the starting point in the .

end="x:y"

At end of the line, where x and y is the position of the starting point in the .

id="{name}"

Unique ID.

stroke-width="6″

Line width.

fill="#ff000000″

The line fills color.

fill-style="none"

Fill style. In this case, this attribute does not make sense, because the line is always smooth.

stroke-style="solid"

Line style. There are 5 styles:

  • solid — solid;

  • dot — dotted line;

  • dash — dash line;

  • dashdot — dash-dot;

  • dashdotdot — dash-dot line with two points.

stroke="#ff000000″

Line color.

Example:

<line stroke-width="6" fill-style="none" end="250:-50" id="{line1}" stroke-style="solid"
fill="#ff000000" stroke="#ff000000" begin="50:-50"/>

<cubicBezier>

Adds a Bezier curve.

Attributes

Attribute

Description

cp1="x:y"

Marker defining the curve bend.

cp2="x:y"

Marker defining the curve bend.

stroke-style="solid"

Style of the Bezier curve. The styles of the Bezier curve are similar to the line styles.

begin="x:y"

The beginning of the Bezier curve, where x and y is the position of the starting point in the .

end="x:y"

The end of the Bezier curve, where x and y is the position of the starting point in the .

id="{name}"

Unique ID.

fill-style="none"

Fill style. In this case, this attribute does not make sense, because the line is always smooth.

stroke-width="6″

The width of the Bezier curve.

stroke="#ff000000″

Bezier curve fills color.

fill="#ff000000″

Bezier curve color.

Example:

<cubicBezier id="{cubicBezier1}" fill-style="none" stroke-width="6" end="-106.577:134.894"
begin="-112.95:-192.25" fill="#ff000000" cp1="-142.95:-192.25" cp2="17.0502:-192.25"
stroke="#ff000000" stroke-style="solid"/>

<rectangle>

Adds a rectangle.

Attributes

Attribute

Description

stroke-style="solid"

Style of the rectangle. The styles of the rectangle are similar to the line styles.

begin="x:y"

The beginning of the rectangle, where x and y is the position of the starting point in the .

end="x:y"

The end of the rectangle, where x and y is the position of the starting point in the .

id="{name}"

Unique ID.

fill-style="none"

Fill style. The default value is "none". The filled rectangle should be set to "solid".

fill="#ff000000″

Border color.

stroke-width="6"

Border width.

stroke="#ff000000″

Fill color.

Example:

<rectangle stroke-width="6" fill-style="none" end="344:511" id="{rectengle1}" 
stroke-style="solid" fill="#ff000000" stroke="#ff000000" begin="285:229"/>

<ellipse>

Adds an ellipse.

Attributes

Attribute

Description

stroke-style="solid"

Style of the ellipse. The styles of the rectangle are similar to the line styles.

begin="x:y"

The beginning of the ellipse, where x and y is the position of the starting point in the .

end="x:y"

The end of the ellipse, where x and y is the position of the starting point in the .

id="{name}"

Unique ID.

fill-style="none"

Fill style. The default value is "none". The filled ellipse should be set to "solid".

stroke-width="6″

Border width.

fill="#ff000000″

Border color.

stroke="#ff000000″

Fill color.

Example:

<ellipse stroke-width="6" fill-style="none" end="-178:300" id="{ellipse1}" 
stroke-style="solid" fill="#ff000000" stroke="#ff000000" begin="-260:7"/>

<stylus>

Defines a stylus for drawing.

Attributes

Attribute

Description

stroke-style="solid"

Style of the stylus. The styles of the stylus are similar to the line styles.

id="{name}"

Unique ID.

fill-style="none"

Fill style. In this case, this attribute does not make sense, because shapes drawn with a stylus are always homogeneous.

stroke-width="6″

Stilus width.

fill="#ff000000″

Stylus color.

stroke="#ff000000″

Fill color.

Example:

<stylus stroke-width="6" fill-style="none" id="{stylus_name}" stroke-style="solid" 
fill="#ff000000" stroke="#ff000000">

<stylusLine>

Allows you to draw arbitrary shapes using the stylus. This block of code consists of many segments.

Attributes

Attribute

Description

stroke-style="solid"

Shape style. The styles of the shape are similar to the line styles.

id="{name}"

Unique ID.

fill-style="none"

Fill style. In this case, this attribute does not make sense, because shapes drawn with a stylus are always homogeneous.

stroke-width="6″

Stilus width.

fill="#ff000000″

Stylus color.

stroke="#ff000000″

Fill color.

Example:

<stylusLine stroke-width="6" fill-style="none" end="-334:259" id="{name1}" stroke-style="solid"
fill="#ff000000" stroke="#ff000000" begin="-334:260"/>
<stylusLine stroke-width="6" fill-style="none" end="-333:258" id="{name2}" stroke-style="solid"
fill="#ff000000" stroke="#ff000000" begin="-334:259"/>
<stylusLine stroke-width="6" fill-style="none" end="-333:254" id="{name3}" stroke-style="solid"
fill="#ff000000" stroke="#ff000000" begin="-333:258"/>

<region>

Allows you to add regions to the scene. There are 2 types of regions:

  • rectangle

  • ellipse

Attributes

Attribute

Description

filled="true"

Fill. The default value is true.

type="rectangle"

Region type.

height="300″

The height of the region (in the case of an ellipse, this is the height of the rectangle that describes the ellipse).

width="300″

The width of the region (in the case of an ellipse, this is the width of the rectangle that describes the ellipse).

text="Finish"

The text will be displayed in TRIK Studio.

textX="0″

The position is of the text relative to the lower-left corner along the X-axis.

textY="0″

The position is of the text relative to the lower-left corner along the Y-axis.

x="1300″

The position of the beginning of the region (upper left corner) along the X-axis (in the case of an ellipse, this is the coordinate along the X-axis of the upper left corner of the rectangle describing the ellipse).

y="-200″

The position of the beginning of the region (upper left corner) along the Y-axis (in the case of an ellipse, this is the coordinate along the Y-axis of the upper left corner of the rectangle describing the ellipse).

visible="false"

Visibility in TRIK Studio.

id="finish"

Unique ID.

color="#ff0000″

Fill and borders color.

Example:

<regions>
            <region filled="true" type="rectangle" height="300" width="300" textX="0" 
text="Finish" textY="0" x="1300" y="-200" visible="true" id="Start" color="#ff0000"/>
</regions>

2D model setup example

The "Barcode" task

You need to draw a barcode. The barcode consists of white and black lines of the same thickness. The black line specifies 1 in a binary number, and the white one 0. The first black line in the robot path is the first bit of the number.

The barcode lines order: 1001011011.

World creation

In this task, the lines should be the same thickness and length. It’s very difficult to draw lines by hand using the Line or Stylus tool, so edit the lines manually:

1. Draw 10 lines on the scene.

2. Save the model of the world.

3. Open the resulting XML file in any convenient editor. Pay attention to the code block with the<line...>tag.

4. For convenience, name each line black1-black5 and white1-white5. You can do this in the "id" attribute. Name the lines in the order shown above.

5. Specify the line thickness "50" in the stroke-widthattribute.

6. Assign the color to each line: #ff000000 is black, #ffffffff is white. You can do this in the attribute fill. Assign colors so that you get a barcode.

7. Set the position of each line in the beginand endattributes without gaps, so that you get a smooth barcode.

The result

Adding restrictions to the 2D Model

It is possible to add restrictions by to prepare for students.

There are three types of restrictions:

  1. Time restrictions. For example, a time limit to complete a task or a specific action in a specific time frame.

  2. Spatial. For example, adding regions ("Start", "Finish") or prohibiting/forcing a robot, its sensor, or some moving object to be at a certain time in a certain place.

  3. Device restrictions. For example, a limitation on the set of sensors or on the behavior of devices.

Constraint description structure

The main tagwhich contains all the restrictions is used to describe them. Used as a container. Restrictions are described inside the tag, each inner tag must be one of four:

<constraints>...</constraints>

The main tag containing all restrictions. Used as a container.

<timelimit/>

Time limit. Mandatory.

Attributes

Syntax:

<constraint>...</constraint>

A constraint with an arbitrary condition. If the condition is violated a specified error message will be displayed. Can be used as a container. Has one child tag: <conditions>...</conditions>.

Attributes

Syntax:

<event>...</event>

The main tool for setting dynamic constraints. Used as a container.

An event is just a pair (, ).

Attributes

Syntax:

<init>...</init>

Unconditional event executing before the program starts.

Example:

Conditions

Now lets talk about the conditions in the and elements. Conditions are set using the tag if only one of the is tested, or the tag if a compound condition is tested.

<condition>...</condition>

The condition being checked is described inside this tag.

Example:

<conditions>...</conditions>

Used to create compound conditions. The logical bond is the mandatory attribute. The bond may be and or or. Negation is specified by the <not> tag without attributes. Other <conditions> elements may also appear among subexpressions.

Attributes:

Syntax:

Atomic conditions

Atomic condition is one of the following elements:

<equals>...</equals>

Equals. The functional symbols value comparison operation. Can be used as a container.

Syntax:

<notEqual>...</notEqual>

Not equal. The functional symbols value comparison operation. Can be used as a container.

Syntax:

<greater>...</greater>

Greater. The functional symbols value comparison operation. Can be used as a container.

Syntax:

<less>...</less>

Less. The functional symbols value comparison operation. Can be used as a container.

Syntax:

<inside/>

Sets spatial constraints.

Attributes

Syntax:

<settedUp/> and <dropped/>

Checks whether the event set up or not.

Attributes

Syntax:

Example:

The "check event" event conditions check that the other "Try move" event is set up and the "Go back" event is dropped. If both of them return "true" after the check the program successfully ends.

<timer/>

A predicate that starts to return "true" when the specified time has passed since the moment when this event was set, and up to that moment it returns "false".

Attributes

Syntax:

Example

Let's look at using <timer/> with different forceDropOnTimeout attribute values.

The "check region" event checks time and spatial limits. The first condition (timer) becomes true after 1000ms. Its value doesn't change after that. The second one (inside) checks that the robot is inside the "start_zone" region. When both conditions will be met simultaneously the program will end successfully.

1. Since the forceDropOnTimeout attribute is "false", the event will be still set up after a specified timeframe and wait for the second condition to be met.

2. Since the forceDropOnTimeout attribute is "true", the event will be dropped after the specified timeframe despite the presence of a second condition. Therefore, if the robot is not in the required region right after 1000 ms, then the success message will not be displayed even if the robot will be there after some time.

Variable types and arithmetic operations

<int/>, <double/>, <string>, <bool/>

Setting a constant.

Attributes

Syntax:

<variableValue/>

Variable value.

It is possible to take the property of any variable using a dot. For example, "rect.width" will return the width of the rectangle stored in "rect".

Attributes

Syntax:

<objectState/>

Get the object state.

Attributes

Syntax:

Example

<typeOf/>

Get the objects with specified ID meta-type. For example, the type of the wall object with id=777 will be wall.

Most often, this element will be needed to check the type of connected sensors and motors.

Attributes

Syntax:

<minus>..</minus>, <abs>...</abs>

Unary arithmetic operations for changing the sign and taking the modulus of a number.

Syntax:

Example:

<sum>, <difference>, <min>, <max>

Sum and difference of values. Minimum and maximum value.

Example:

Triggers

<trigger>...</trigger>

An action or a group of actions that will be performed one or many times after the event condition is met.

Syntax:

<fail/>

Display an error message. Finish checking the task.

Attributes

Syntax:

<success/>

The task is successfully done.

Attributes

Syntax:

<setter>...</setter>

Set the variable value.

Attributes

Example:

<setUp/>, <drop/>

Setting up or dropping an event.

Attributes

Example:

Sensor names

TRIK Robot Sensors

Lego EV3 Robot sensors

Additional robot properties

Working with the controller display

Example

Checking that the word “message” was displayed on the controller screen. The case is important.

Restrictions example

You need to start in the blue square then drive along the wall to the red one using the IR distance sensor.

Tag

Description

timelimit

Time limit.

constraint

A constraint with an arbitrary condition in violation of which a specified error will be generated.

event

The main tool for setting dynamic constraints. Used as a container.

init

An unconditional event that runs before the program starts executing.

<constraints>
     <!-- Time limit -->
     <timelimit value="30000"/>
     
     <!-- Conditional constraint. An error message will be shown at violation. -->
     <constraint checkOnce="true" failMessage="The robot must be at start before run!">
          <inside objectId="robot1" regionId="start_zone"/>
     </constraint>
     
     <!-- Initializing variable x with value 2 -->
     <init>
          <setter name="x">
               <int value="2"/>
          </setter>
      </init>

</constraints>

Attribute

Description

value="value"

Timeout in milliseconds after which the execution will be terminated and the "Time limit exceeded" error will be displayed.

<timelimit value="35000"/>

Attribute

Description

checkOnce="true"

Boolean attribute. If the value is true, then the restriction will be checked once at program startup. Is useful for one-time checks such as sensor layout etc.

failMessage="Error!"

An error message will be displayed when a restriction is violated.

<constraint checkOnce="true" failMessage="The robot must be at start before run!">
<!-- Checks if the IR distance sensor is connected to the A1 port -->
<constraint checkOnce="true" failMessage="The IR distance sensor must be connected to the robots A1 port!">
    <equals>
        <typeOf objectId="robot1.A1"/>
        <string value="twoDModel::robotModel::parts::RangeSensor"/>
    </equals>
</constraint>
<!-- Checks if the robot is inside the specified region for the entire program execution time-->
<constraint failMessage="The robot has left the allowed zone!">
    <inside objectId="robot1" regionId="warzone"/>
</constraint>

Attribute

Description

settedUpInitially="true"

An attribute that allows you to indicate whether the event is set up at the start of the program. The event can be set up or dropped. In the setup state, the event pulls its trigger if its condition is met, otherwise it's just ignored by the system.

The default value is false.

id="finish checker"

Events unique ID. The event can be referred by id from others. Optional.

dropsOnFire = "true"

A boolean attribute that indicates whether the event should continue to be set up after it is triggered or not. Optional. The default value is true.

<event id="finish checker" settedUpInitially="false">
	<condition>
		<inside objectId="robot1" regionId="finish"/>
	</condition>
	<trigger>
		<success/>
	</trigger>
</event>
<!-- Setting the "my_value" variable to the value of two-->
<init>
    <setter name="my_value">
        <int value="2"/>
    </setter>
</init>
<condition>
    <!-- The condition of equality of two values is described inside the tag -->
    <equals>
        <objectState object="robot1.display.smiles"/>
        <bool value="true"/>
    </equals>
</condition>

Attribute

Description

glue="and"

Logical bond.

<conditions glue="and">
   <!-- Condition1 -->
   <!-- Condition2 -->
   <!--    ...   -->
   <!-- ConditionN -->
</conditions>

<conditions glue="and">
   <not>
      <!-- Condition1 -->
   </not>
</conditions>

<conditions glue="and">
   <timer timeout="1000" forceDropOnTimeout="true"/>
   <conditions glue="or">
      <greater>
         <objectState object="robot1.display.labels.size"/>
         <int value="20"/>
      </greater>
      <less>
         <objectState object="robot1.display.labels.size"/>
         <int value="19"/>
       </less>    
    </conditions>
</conditions>

Tag

Description

equals, notEqual, greater, less

Value comparison operations.

inside

Sets spatial constraints.

settedUp and dropped

Checks whether an event is set up or not.

timer

Sets the time in ms after which the specified condition is considered true.

<equals>
	<objectState object="robot1.display.labels.first.text"/>
	<string value="finish"/>
</equals>
<notEqual>
	<objectState object="robot1.display.labels.first.text"/>
	<string value="finish"/>
</notEqual>
<greater>
	<objectState object="robot1.display.labels.size"/>
	<int value="0"/>
</greater>
<less>
    <objectState object="robot1.display.labels.size"/>
    <int value="10"/>
</less>

Attribute

Description

objectId="id"

Object ID.

regionId="id"

Region ID.

<!-- Limits the location of the "robot1" robot to the "start" zone -->
<inside objectId="robot1" regionId="start"/>

Attribute

Description

id="event1"

The ID of the event is checked

<!-- The "event1" event is set up condition -->
<condition>
    <settedUp id="event1"/>
</condition>

<!-- The "event2" event is dropped condition -->
<condition>
    <dropped id="event2"/>
</condition>
<event id="check event" settedUpInitially="true">
    <conditions glue="and">
        <settedUp id="Try move"/>
        <dropped id="Go back"/>
    </conditions>
    <trigger>
        <success/>
    </trigger>
</event>

Attribute

Description

timeout="1000"

The time interval after which this predicate will become true. Mandatory. The value must be a non-negative integer.

forceDropOnTimeout="true"

A Boolean attribute that allows you to drop the event that has this timer in a condition.

If set to true, the event will be dropped even if there are other active timers and unmet conditions. Optional. The default value is true.

<timer timeout="1000" forceDropOnTimeout="false"/>
<event id="check region" settedUpInitially="true">
    <conditions glue="and">
        <timer timeout="1000" forceDropOnTimeout="false"/>
        <inside objectId="robot1" regionId="start_zone"/>
    </conditions>
    <trigger>
        <success/>
    </trigger>
</event>
<event id="check region" settedUpInitially="true">
    <conditions glue="and">
        <timer timeout="1000" forceDropOnTimeout="true"/>
        <inside objectId="robot1" regionId="start_zone"/>
    </conditions>
    <trigger>
        <success/>
    </trigger>
</event>

Variable or operation

Description

int, double, string, bool

Integer, fractional, string, and boolean constants.

variableValue

Variable value.

objectState

Get the object state.

typeOf

Get the meta-type of the object with the specified identifier.

minus, abs

Unary arithmetic functions that have exactly one child, which must be an integer value.

sum, difference, min, max

Binary arithmetic functions that have exactly two child elements, each of them must be an integer.

Attribute

Description

value="0″

Constant value.

<int value="0"/>

<string value="finish"/>

Attribute

Description

name="my_value"

Variable name

<variableValue name="rotation"/>

Attribute

Description

object="robot1.display.labels.size"

Object ID

<objectState object="robot1.display.labels.first.text"/>
<!-- Assign to the "rotation" variable the robots rotation angle -->
<setter name="rotation">
     <objectState object="robot1.rotation"/>
 </setter>
<!-- Checking if the "rotation" value equals to the robots rotation angle -->
<equals>
   <variableValue name="rotation"/>
   <objectState object="robot1.rotation"/>
</equals>

Attribute

Description

objectId="id"

Objects unique ID.

<typeOf objectId="robot1.A3"/>
<minus>
    <objectState object="robot1.rotation"/>
</minus>

<abs>
    <objectState object="robot1.rotation"/>
</abs>
<!-- Modulus of the difference of the "rotation" variable and the robots rotation angle -->
<abs>
    <difference>
        <variableValue name="rotation"/>
        <objectState object="robot1.rotation"/>
    </difference>
</abs>
<!-- The difference of the "rotation" variable and the robots rotation angle -->
<difference>
       <variableValue name="rotation"/>
       <objectState object="robot1.rotation"/>
</difference>

<!-- The sum of the "counter" variable and one -->
<sum>
       <variableValue name="counter"/>
       <int value="1"/>
</sum>

Tag

Description

trigger

An action or a group of actions that will be performed one or many times after the event condition is met.

fail

Display an error message. Finish checking the task.

success

Display success message, finish the check.

setter

Set the variable value.

setUp, drop

Setting or dropping the event.

<trigger>
	<success/>
</trigger>

Attribute

Description

message="Wrong answer!"

Error message text

<fail message="Wrong answer!"/>

Attribute

Description

deffered="false"

Optional. The default value is "false". If set to "true" the trigger won't stop the program, I. e. the checker will wait until the program finishes and either reports the success if there were no errors, or otherwise, it will finish with an error. In other words, you won't get the error "The program has finished, but the task is not completed": the program will either terminate successfully or with a meaningful error like "Time limit exceeded".

<success/>

Attribute

Description

name="my_value"

Variable name

<!-- Creating the "total_score" variable with the value of zero -->
<setter name="total_score">
       <int value="0"/>
 </setter>

<!-- Addind 2 to the "total_score" -->
<setter name="total_score">
       <sum>
              <variableValue name="total_score"/>
              <int value="2"/>
       </sum>
</setter>

Attribute

Description

id="finish checker"

The ID of the event.

<!-- Set up the "finish checker" event -->
<triggers>
				<setUp id="finish checker"/>
</triggers>

Name

Description

twoDModel::robotModel::parts::RangeSensor

Distance sensor

trik::robotModel::twoD::parts::TwoDLightSensor

Light sensor

twoDModel::robotModel::parts::TouchSensor

Touch sensor

trik::robotModel::twoD::parts::LineSensor

Line sensor

Name

Description

twoDModel::robotModel::parts::RangeSensor

Distance sensor

twoDModel::robotModel::parts::LightSensor

Light sensor

twoDModel::robotModel::parts::TouchSensor

Touch sensor

twoDModel::robotModel::parts::ColorSensorRed

Color sensor (red)

twoDModel::robotModel::parts::ColorSensorGreen

Color sensor (green)

twoDModel::robotModel::parts::ColorSensorBlue

Color sensor (blue)

twoDModel::robotModel::parts::ColorSensorPassive

Color sensor (passive)

twoDModel::robotModel::parts::ColorSensorFull

Color sensor EVX/NXT (color)

twoDModel::robotModel::parts::ColorSensorAmbient

Color sensor EV3 (ambient)

ev3::robotModel::twoD::parts::GyroscopeSensor

Gyroscope

ev3::robotModel::twoD::parts::GyroscopeSensor

Compass

Property

Description

robot1.rotation

A current robot's rotation angle

robot1.x and robot1.y

Robots coordinate

robot1.led.color

LED color

robot1.marker.isDown

Checks if the robot has a marker and it draws a line on the field. Returns "true" or "false".

robot1.shell.lastPhrase

Get the last robots phrase.

Property

Description

robot1.display.sadSmiles

Checks if there is a sad smile on the controller display. Returns "true" or "false".

robot1.display.smiles

Checks if there is a happy smile on the controller display. Returns "true" or "false".

robot1.display.labels.first.text

Message (label) text that was displayed first.

robot1.display.labels.last.text

Message (label) text that was displayed last.

robot1.display.labels.size

Get the displayed label number.

<equals>
        <objectState object="robot1.display.labels.first.text"/>
        <string value="message"/>
</equals>
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <world>
      <background />
      <walls>
         <!-- The wall-->
         <wall id="{wall1}" end="300:150" begin="0:100" />
         <wall id="{wall2}" end="550:100" begin="300:150" />
         <wall id="{wall3}" end="650:200" begin="550:100" />
         <wall id="{wall4}" end="850:300" begin="650:200" />
         <wall id="{wall5}" end="1200:300" begin="850:300" />
         <wall id="{wall6}" end="1600:50" begin="1200:300" />
      </walls>
      <skittles />
      <balls />
      <colorFields />
      <images />
      <regions>
         <!-- Regions-->
         <region visible="true" id="finish" x="1300" color="#ff0000" text="Finish" type="rectangle" width="300" textX="0" textY="0" y="-200" filled="true" height="300" />
         <region visible="true" id="start_zone" x="-50" color="#0000ff" text="Start" type="rectangle" width="150" textX="0" textY="0" y="100" filled="true" height="-150" />
         <region visible="false" id="warzone_1" x="-50" color="#ffff00" text="warzone1" type="rectangle" width="650" textX="0" textY="0" y="-50" filled="true" height="200" />
         <region visible="false" id="warzone_2" x="600" color="#ffff00" text="warzone2" type="rectangle" width="250" textX="0" textY="0" y="0" filled="true" height="250" />
         <region visible="false" id="warzone_3" x="850" color="#ffff00" text="warzone3" type="rectangle" width="750" textX="0" textY="0" y="50" filled="true" height="250" />
      </regions>
   </world>
   <robots>
      <!-- Robot description -->
      <robot id="trikKitRobot" position="0:0" direction="0">
         <sensors>
            <sensor port="A1###input###А1###sensorA1" position="75:25" type="trik::robotModel::parts::TrikInfraredSensor" direction="45" />
            <sensor port="M3###output###JM3$$$C$$$3###" position="75:25" type="kitBase::robotModel::robotParts::Motor" direction="0" />
            <sensor port="M4###output###JM4$$$D$$$4###" position="75:25" type="kitBase::robotModel::robotParts::Motor" direction="0" />
         </sensors>
         <startPosition id="{ee2c46c1-23fc-4cda-98f4-77d9de775305}" x="25" y="25" direction="0" />
         <wheels left="M3###output###М3###" right="M4###output###М4###" />
      </robot>
   </robots>
   <constraints>
      <!-- Time limit (30 seconds) -->
      <timelimit value="30000" />
      <!-- Spatial restriction of the start region. Checks once at the program start -->
      <constraint checkOnce="true" failMessage="The robot must be inside the blue square at the start!">
         <inside regionId="start_zone" objectId="robot1" />
      </constraint>
      <!-- Sensors type and presence restriction -->
      <constraint checkOnce="true" failMessage="Only the IR distance sensor must be connected to the A1 port">
         <conditions glue="and">
            <equals>
               <typeOf objectId="robot1.A1" />
               <string value="trik::twoDModel::robotModel::parts::RangeSensor" />
            </equals>
            <equals>
               <typeOf objectId="robot1.A2" />
               <string value="undefined" />
            </equals>
            <equals>
               <typeOf objectId="robot1.A3" />
               <string value="undefined" />
            </equals>
            <equals>
               <typeOf objectId="robot1.A4" />
               <string value="undefined" />
            </equals>
            <equals>
               <typeOf objectId="robot1.A5" />
               <string value="undefined" />
            </equals>
            <equals>
               <typeOf objectId="robot1.A6" />
               <string value="undefined" />
            </equals>
            <equals>
               <typeOf objectId="robot1.D1" />
               <string value="undefined" />
            </equals>
            <equals>
               <typeOf objectId="robot1.D2" />
               <string value="undefined" />
            </equals>
         </conditions>
      </constraint>
      <!-- Robot ride control -->
      <constraint failMessage="The robot tried to move out of the permitted area!">
         <conditions glue="or">
            <inside regionId="warzone_1" objectId="robot1" />
            <inside regionId="warzone_2" objectId="robot1" />
            <inside regionId="warzone_3" objectId="robot1" />
         </conditions>
      </constraint>
      <!-- An event that checks if the robot has entered the finish area -->
      <event settedUpInitially="true">
         <condition>
            <timer timeout="100" forceDropOnTimeout="true" />
         </condition>
         <trigger>
            <setUp id="finish checker" />
         </trigger>
      </event>
      <!-- Event reporting the successful finish -->
      <event id="finish checker" settedUpInitially="false">
         <condition>
            <inside regionId="finish" objectId="robot1" />
         </condition>
         <trigger>
            <success />
         </trigger>
      </event>
   </constraints>
</root>
Constraint description structure
Conditions
Atomic conditions
Variable types and arithmetic operations
Triggers
Sensor names
Additional robot properties
Working with the controller screen
Restrictions example
editing an XML file
exercises
<constraints>...</constraints>
condition
trigger
<constraint>
<event>
<condition>
atomic conditions
<conditions>
robots
robot
robot
sensors
sensor
startPosition
wheels
coordinate system
coordinate system
coordinate system
coordinate system
wall
skittle
ball
line
cubicBezier
rectangle
ellipse
stylus
stylusLine
region
coordinate system
coordinate system
coordinate system
coordinate system
coordinate system
coordinate system
coordinate system
coordinate system
coordinate system
coordinate system

Restrictions setting examples

This article is automatically translated from Russian by Google Translator.

Setting constraints is a unique feature of TRIK Studio designed for an automated check of tasks. This tool has many uses:

  • self-examination of homework by students,

  • accelerating the process of checking tasks by the teacher,

  • online competitions with automatic checking of the participants' solutions.

The TRIK Studio constraint language is a very powerful tool that allows you to check almost all aspects of program execution and robot behavior and may seem complicated at first glance. However, don't be upset - in this article we will walk you through the process of creating constrained tasks, ranging from simple constraints that cover most of the tasks to complex constraints, which can be useful for enthusiasts.

  • Restricting the program execution time and the "Start" and "Finish" zones

  • Examples analysis

    • Example 1. Drive from the "Start" zone to the "Finish" zone with a restriction of the movement zone

    • Example 2. Drive from the "Start" zone to the "Finish" zone with a stop

    • Example 3. Drive from the "Start" zone to the "Finish" zone along the wall with the sensors checking

    • Example 4. Counting intersections and displaying the result

    • Example 5. Kegelring

    • Example 6. Checking robot behavior

Restricting the program execution time and the "Start" and "Finish" zones

For those who are just starting to get acquainted with the TRIK Studio constraint language, we suggest starting with simple restrictions on the program run time, the "Start" and "Finish" zones. This is more than enough for most robotic tasks.

1. Define the following conditions and parameters for the task and the world model.

  • Optimal program execution time. If the program exceeds the timelimit, the checking system will generate an error "The program ran too long".

  • Start zone. The zone from which the robot must start executing the program, otherwise the checking system will generate an error.

  • Finish zone. The zone where the robot must arrive at the end of the program, otherwise the checking system will generate an error.

2. Edit the value of the <regions> tag in the world XML file to add the Start and Finish zones. By changing the x, y, width and height values, you can edit the location and size of the zones. To check the position of a zone, load the file into the virtual world model and check the location of the zones. After that, if necessary, you can make the "Start" and "Finish" zones invisible by setting the attribute visible="false".

<regions>
    <region type="rectangle" visible="true" color="blue" text="Старт" x="-450" y="-400" width="150" height="150" id="start_zone"/>
    <region type="rectangle" visible="true" color="green" text="Финиш" x="450" y="-400" width="150" height="150" id="finish_zone"/>
</regions>

3. Copy the <constraints> block template below into the XML file of the world for which you want constraints.

<constraints>
    <!-- Restriction on program runtime -->
     <timelimit value="300000"/>

    <!-- Restriction, which will be checked once before starting the program -->
    <constraint checkOnce="true" failMessage="Робот должен находиться в зоне старта перед запуском!">
        <inside objectId="robot1" regionId="start_zone"/>
    </constraint>
    
    <!-- An event that verifies that the robot is in the finish area at the end of the program -->
    <event id="finish checker" settedUpInitially="true">
        <condition>
            <inside objectId="robot1" regionId="finish_zone"/>
        </condition>
        <trigger>
            <success/>
        </trigger>
    </event>
</constraints>

4. Fill in the <timelimit value="300000"> tag. Specify what you think is the best execution time for the program. Note that the time is in milliseconds, i.e., 300000ms = 5 minutes, 120,000ms = 2 minutes, etc.

5. The constraint task is ready! Now you know how to check the start and end positions of the robot and the execution time of the program.

Examples analysis

Now let's break down the application of this technique to different tasks and consider options for more detailed checks.

Example 1. Drive from the "Start" zone to the "Finish" zone with a restriction of the movement zone

The task of passing the labyrinth. Having started in the blue square, it is necessary to pass to the finish area. In order to check that the user actually passes the labyrinth and not bypasses it, a spatial constraint is set.

Blue square - start area, red square - finish area, black rectangle - field that cannot be left by the robot

Below is the complete code to test this task.

<?xml version='1.0' encoding='utf-8'?>
<root>
	<!-- World Description -->
	<world>
		<trace/>
		<walls>
			<wall end="450:-400" id="" begin="-300:-400"/>
			<wall end="-300:200" id="" begin="-300:-250"/>
			<wall end="450:200" id="" begin="-300:200"/>
			<wall end="450:200" id="" begin="450:-250"/>
			<wall end="150:-100" id="" begin="150:-400"/>
			<wall end="300:50" id="" begin="300:-250"/>
			<wall end="450:-250" id="" begin="300:-250"/>
			<wall end="-150:-250" id="" begin="-300:-250"/>
			<wall end="0:-250" id="" begin="-150:-250"/>
			<wall end="-150:-100" id="" begin="150:-100"/>
			<wall end="150:50" id="" begin="-150:50"/>
			<wall end="150:200" id="" begin="150:50"/>
		</walls>
		<colorFields/>
		<!-- Defining regions (zones) on the world map -->
		<regions>
			<region type="rectangle" visible="true" color="blue" text="Старт" x="-450" y="-400" width="150" height="150" id="start_zone"/>
			<region type="rectangle" visible="true" color="green" text="Финиш" x="450" y="-400" width="150" height="150" id="finish_zone"/>

			<region id="warzone" type="rectangle" filled="false" color="black" visible="true" x="-450" y="-400" width="1050" height="600"/>
		</regions>
	</world>
	<robots>
		<robot id="trikKitRobot" direction="0" position="-401:-351">
			<sensors>
				<sensor type="kitBase::robotModel::robotParts::Motor" direction="0" port="M4###output###JM4$$$D$$$4###" position="75:25"/>
				<sensor type="kitBase::robotModel::robotParts::Motor" direction="0" port="M3###output###JM3$$$C$$$3###" position="75:25"/>
				<sensor type="kitBase::robotModel::robotParts::Motor" direction="0" port="M2###output###JM2$$$B$$$2###" position="75:25"/>
				<sensor type="kitBase::robotModel::robotParts::Motor" direction="0" port="M1###output###JM1$$$A$$$1###" position="75:25"/>
			</sensors>
			<startPosition direction="0" x="-376" y="-326"/>
		</robot>
	</robots>
	<!-- Description of restrictions -->
	<constraints>
		<!-- Time limit of 5 minutes -->
		<timelimit value="300000"/> 
		
		<constraint checkOnce="true" failMessage="Робот должен находиться в зоне старта перед запуском!">
			<inside objectId="robot1" regionId="start_zone"/>
		</constraint>

		<!-- Restriction that verifies that the robot is in the allowed zone -->
		<constraint failMessage="Робот попытался объехать лабиринт!">
			<inside objectId="robot1" regionId="warzone"/>
		</constraint>

		<!-- An event that verifies that the robot is in the finish area at the end of the program -->
		<event id="finish checker" settedUpInitially="true">
			<condition>
				<inside objectId="robot1" regionId="finish_zone"/>
			</condition>
			<trigger>
				<success/>
			</trigger>
		</event>
	</constraints>
</root>

Let's take a closer look at how the check takes place.

1. Set a time limit for passing the task. This limit is mandatory. The time is specified in milliseconds.

<timelimit value="300000"/>

2. Set a constraint on the area where the robot should be before starting the program. According to the condition of the problem, it should be a blue square - the start area. This restriction will be checked once, at the beginning of the program, since the attribute checkOnce is true.

With the <inside> tag we set the spatial constraint. It has two attributes. In the first (objectId) we specify the id of the object whose location we want to check, in our case, it is a robot. In the second (regionId) we specify the id of the region in which our object should be located.

If the condition described in <inside> is not met, the program will be terminated with an error. For this, the <constraint> tag has an attribute failMessage, which allows you to specify the text of the error message.

<constraint checkOnce="true" failMessage="The robot must be in the launch area before starting!">
    <inside objectId="robot1" regionId="start_zone"/>
</constraint>

3. In order to verify that the user actually goes through the maze and not bypasses it, let's set another spatial constraint.

Let's edit the <regions> tag in the XML file of the world by adding the region with id = "warzone".

<region id="warzone" type="rectangle" filled="false" color="black" visible="true" x="-450" y="-400" width="1050" height="600"/>

This constraint will be checked at all times of program execution. In the <inside> tag we will specify the object id and the region id, in our case, it is the robot and the black rectangle limiting the maze.

If the robot is outside the specified region at any time, the program will terminate with an error, the text of which is specified in the failMessage attribute.

<constraint failMessage="The robot tried to go around the maze!">
    <inside objectId="robot1" regionId="warzone"/>
</constraint>

4. Now we have to check that the robot reaches the finish area.

To do this, let's create an event that will check if the robot is in the right zone or not. The attribute settedUpInitially="true" means that the event will be started (fired) immediately when the program starts.

In the <condition> tag we specify which condition to check. In our case the condition is the same as described above - we are checking that the robot is in the region with id = "finish". If that condition is true, then the user will see a message saying that the program was executed successfully. To do that, we write a child tag <success/> in the <trigger> tag.

<event id="finish checker" settedUpInitially="true">
    <!-- Condition-->
    <condition>
        <inside objectId="robot1" regionId="finish_zone"/>
    </condition>
    <!-- Trigger-->
    <trigger>
        <success/>
    </trigger>
</event>

Example 2. Drive from the "Start" zone to the "Finish" zone with a stop

The task is to pass forward and stop in the finish area.

This task is slightly different from Example 1 in that another condition is added for successful completion of the program - the robot must not only be in the finish area, but also stop.

Below is the complete code to test this task.

<?xml version='1.0' encoding='utf-8'?>
<root version="20190819">
    <world>
    <!-- Defining regions (zones) on the world map -->
		<regions>
            <region id="finish_zone" text="Finish" textX="0" width="200" height="150" color="green" x="320" y="-50" visible="true" type="rectangle" filled="true" textY="0"/>
            <region id="start_zone" text="Start" textX="0" width="100" height="-100" color="#0000ff" x="-20" y="70" visible="true" type="rectangle" filled="true" textY="0"/>
			
						<region type="rectangle" id="warzone" text="Поле, которое нельзя покидать" x="-20" y="-140" width="610" height="320" color="orange" visible="true"/>
		</regions>
    </world>
    <robots>
        <robot id="trikKitRobot" direction="0" position="0:0">
            <sensors>
                <sensor port="M3###output###М3###" direction="0" position="75:25" type="kitBase::robotModel::robotParts::Motor"/>
                <sensor port="M4###output###М4###" direction="0" position="75:25" type="kitBase::robotModel::robotParts::Motor"/>
                <sensor port="M1###output###М1###" direction="0" position="75:25" type="kitBase::robotModel::robotParts::Motor"/>
                <sensor port="M2###output###М2###" direction="0" position="75:25" type="kitBase::robotModel::robotParts::Motor"/>
            </sensors>
            <startPosition id="{888338bf-3f53-44a4-ac0a-8aeea2d036b2}" y="25" direction="0" x="25"/>
            <wheels left="M3###output###М3###" right="M4###output###М4###"/>
        </robot>
    </robots>
    <settings realisticMotors="false" realisticSensors="false" realisticPhysics="false"/>
    <!-- Setting restrictions -->
    <constraints>
        <!-- Time limit -->
        <timelimit value="10000"/>
    
        <!-- Zone restriction on the start of the ride. Checked once at the beginning of the program-->
        <constraint checkOnce="true" failMessage="Робот должен находиться в синем квадрате перед запуском!">
            <inside objectId="robot1" regionId="start_zone"/>
        </constraint>
	    
	    	<!-- The robot is in the tolerance zone -->
	    	<constraint failMessage="Робот покинул допустимую зону!">
	    		<inside objectId="robot1" regionId="warzone"/>
	    	</constraint>
    
        <!-- Event indicating the successful execution of the program (finish area + robot stopped) -->
        <event id="finish checker" settedUpInitially="true">
            <conditions glue="and">
                <inside regionId="finish" objectId="robot1"/>
                <equals>
                    <objectState object="robot1.M3.power"/>
                    <int value="0"/>
                </equals>
                <equals>
                    <objectState object="robot1.M4.power"/>
                    <int value="0"/>
                </equals>
            </conditions>
            
            <trigger>
                <success/>
            </trigger>
        </event>
    </constraints>
</root>

Now let's take a closer look at how the check takes place.

1. Let's set a time limit for passing the task.

<timelimit value="10000"/>

2. Let's set a constraint on the initial position of the robot. It will be checked once at the beginning of the program.

<constraint checkOnce="true" failMessage="The robot must be in the blue square before launching!">
    <inside objectId="robot1" regionId="start_zone"/>
</constraint>

3. Set a restriction on the area that the robot cannot leave.

<constraint failMessage="Робот покинул допустимую зону!">
    <inside objectId="robot1" regionId="warzone"/>
</constraint>

4. Now create an event that verifies that the robot is in the finish zone and that it has stopped in the finish zone and has not moved on.

The zone limit is set with the <inside> tag. In order to check that the robot has stopped, we need to check that the power on both motors is zero. To do this we use the <equals> tag. With the <objectState> tag we define the object whose value we want to compare. In our case this is the power of the motors, so we will write robot1.M3.power or robot1.M4.power in the attribute object, where M3 and M4 are the ports to which the motors are connected in the current configuration. And the value to be compared we write using the <int> tag and its value attribute.

Thus, this event checks three conditions: the robot is in the finish area, the power on motor M3 is zero and the power on motor M4 is also zero. If these conditions are met the user will be shown a message about the successful execution of the program.

<event id="finish checker" settedUpInitially="true">
    <!-- Compound condition -->
    <conditions glue="and">
        <inside regionId="finish" objectId="robot1"/>
        
        <equals>
            <objectState object="robot1.M3.power"/>
            <int value="0"/>
        </equals>
        
        <equals>
            <objectState object="robot1.M4.power"/>
            <int value="0"/>
        </equals>
    </conditions>
    
    <trigger>
        <success/>
    </trigger>
</event>

Example 3. Drive from the "Start" zone to the "Finish" zone along the wall with the sensors checking

Having started in the blue square, you must drive along the wall with the IR distance sensor to the red square.

Below is the complete code for checking this task.

<?xml version='1.0' encoding='utf-8'?>
<root version="20190819">
    <world>
        <walls>
            <wall stroke-width="10" end="-110:50" stroke="#ff000000" begin="-200:50" stroke-style="none" fill="#ff000000" id="{f148f786-7d73-4c42-a3aa-c7a29892d3d7}"/>
            <wall stroke-width="10" end="0:100" stroke="#ff000000" begin="-110:50" stroke-style="none" fill="#ff000000" id="{8f39faac-9392-4878-86e9-9fe5dbea0007}"/>
            <wall stroke-width="10" end="250:110" stroke="#ff000000" begin="0:100" stroke-style="none" fill="#ff000000" id="{bf465864-fa2e-4b59-ac65-e27bd85300d5}"/>
            <wall stroke-width="10" end="350:160" stroke="#ff000000" begin="250:110" stroke-style="none" fill="#ff000000" id="{ba5441dd-8dd8-4100-ad8b-66d634792e3f}"/>
            <wall stroke-width="10" end="400:260" stroke="#ff000000" begin="350:160" stroke-style="none" fill="#ff000000" id="{ca85b1de-8e9c-49e9-8c40-c2c49f43dcaa}"/>
        </walls>
        <skittles/>
        <balls/>
        <colorFields/>
        <images/>
        <regions>
            <region visible="true" type="rectangle" x="350" filled="true" y="50" width="150" height="200" id="good_zone3" color="#ffff00"/>
            <region visible="true" type="rectangle" x="-250" filled="true" y="-50" width="150" textY="0" height="100" text="Start" id="start_zone" textX="0" color="#0000ff"/>
            <region visible="true" type="rectangle" x="0" filled="true" y="0" width="400" height="150" id="good_zone2" color="#ffff00"/>
            <region visible="true" type="rectangle" x="400" filled="true" y="150" width="100" textY="0" height="100" text="Finish" id="finish" textX="0" color="#ff0000"/>
            <region visible="true" type="rectangle" x="-200" filled="true" y="-50" width="250" height="150" id="good_zone1" color="#ffff00"/>
        </regions>
    </world>
    <robots>
        <robot direction="0" position="-200:-25" id="trikKitRobot">
            <sensors>
                <sensor type="trik::robotModel::parts::TrikInfraredSensor" direction="69.6769" position="42:18" port="A1###input###А1###sensorA1"/>
                <sensor type="kitBase::robotModel::robotParts::Motor" direction="0" position="75:25" port="M4###output###М4###"/>
                <sensor type="kitBase::robotModel::robotParts::Motor" direction="0" position="75:25" port="M3###output###М3###"/>
                <sensor type="" direction="0" position="0:0" port="A5###input###А5###sensorA5"/>
                <sensor type="" direction="0" position="0:0" port="A6###input###А6###sensorA6"/>
            </sensors>
            <startPosition direction="0" x="-175" y="0" id="{84223544-d500-411a-9fdb-b382eb98d09f}"/>
            <wheels right="M3###output###М3###" left="M4###output###М4###"/>
        </robot>
    </robots>
    <settings realisticPhysics="false" realisticSensors="false" realisticMotors="false"/>
    <constraints>
        <!-- Time Limit. Mandatory Limit -->
        <timelimit value="40000"/>
        <!-- Check that a distance sensor is installed on port A1 -->
        <constraint checkOnce="true" failMessage="У робота должен быть установлен датчик расстояния на порт А1">
            <equals>
                <typeOf objectId="robot1.A1"/>
                <string value="twoDModel::robotModel::parts::RangeSensor"/>
            </equals>
        </constraint>
        <!-- Check that there are no sensors other than the distance sensor -->
        <constraint checkOnce="true" failMessage="У робота не должно быть датчиков, кроме датчика расстояния">
            <conditions glue="and">
                <equals>
                    <typeOf objectId="robot1.A2"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.A3"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.A4"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.A5"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.A6"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.D1"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.D2"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.F1"/>
                    <string value="undefined"/>
                </equals>
            </conditions>
        </constraint>

        <!-- Zone restriction on the start of the ride. Checked once at the beginning of the program -->
        <constraint checkOnce="true" failMessage="Робот должен находиться в синей зоне перед стартом!">
            <inside objectId="robot1" regionId="start_zone"/>
        </constraint>
        <!-- Checks that the robot is in a valid region for the duration of the program -->
        <constraint failMessage="Робот покинул допустимую зону!">
            <conditions glue="or">
                <inside objectId="robot1" regionId="good_zone1"/>
                <inside objectId="robot1" regionId="good_zone2"/>
                <inside objectId="robot1" regionId="good_zone3"/>
            </conditions>
        </constraint>
        <!-- Event that notifies of successful program execution -->
        <event id="finish checker" settedUpInitially="true">
            <condition>
                <inside objectId="robot1" regionId="finish"/>
            </condition>
            <trigger>
                <success/>
            </trigger>
        </event>
    </constraints>
</root>

Now let's take a closer look at how the check takes place.

1. Let's set a time limit for the task.

<timelimit value="40000"/>

2. According to the problem condition, the robot must have only the distance sensor connected (there must be no other sensors). To be sure of this, let's compare the value of the object on port A1 with the value of the distance sensor. For more information about the names of the sensors for different constructors, see the link.

<constraint checkOnce="true" failMessage="The robot must have a distance sensor installed on port A1">
    <equals>
        <typeOf objectId="robot1.A1"/>
        <string value="twoDModel::robotModel::parts::RangeSensor"/>
    </equals>
</constraint>

3. Let's check that no sensors are connected to the other ports. To do this, compare the value on each port with the "undefined" string.

<constraint checkOnce="true" failMessage="The robot should have no sensors other than the distance sensor">
    <conditions glue="and">
        <equals>
            <typeOf objectId="robot1.A2"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.A3"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.A4"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.A5"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.A6"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.D1"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.D2"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.F1"/>
            <string value="undefined"/>
        </equals>
    </conditions>
</constraint>

4. Let's set a constraint on the initial position of the robot. It will be checked once at the beginning of the program because the checkOnce flag is set.

<constraint checkOnce="true" failMessage="The robot must be in the blue square before launching!">
    <inside objectId="robot1" regionId="start_zone"/>
</constraint>

5. Let's set a restriction on the zone that the robot can't leave. In the previous examples, we considered a situation where the robot needed to stay in one zone. In this case, the allowed zone consists of several rectangles, so we need to check that the robot is in one of those zones. To do that we use the <conditions></conditions> tag with the glue = "or" attribute.

<constraint failMessage="The robot has left the tolerance zone!">
    <conditions glue="or">
        <inside objectId="robot1" regionId="good_zone1"/>
        <inside objectId="robot1" regionId="good_zone2"/>
        <inside objectId="robot1" regionId="good_zone3"/>
    </conditions>
</constraint>

6. Finally, let's create an event that will notify you if the robot is in the finish area.

<event id="finish checker" settedUpInitially="true">
    <condition>
        <inside objectId="robot1" regionId="finish"/>
    </condition>
    <trigger>
        <success/>
    </trigger>
</event>

Example 4. Counting intersections and displaying the result

Linear traffic with intersection counting: when entering an intersection, the robot should display the number of this intersection on the screen.

Below is the complete code for checking this task.

<?xml version='1.0' encoding='utf-8'?>
<root version="20190819">
    <world>
        <walls/>
        <skittles/>
        <balls/>
        <colorFields>
            <cubicBezier id="{6199f811-617a-463d-848f-39b28b918584}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="-174.411:98.5051" cp1="-173.503:9.71619" stroke-width="12" cp2="-184.608:-31.2306" fill="#ff000000" end="-103.03:-28.2828"/>
            <line id="{311aba08-eff0-4d50-98f1-fc7595e22b79}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="-97.2997:-28.5387" stroke-width="12" fill="#ff000000" end="353.7:-28.5387"/>
            <line id="{e4428c3f-4ef1-4214-b5be-9a22eb4f875e}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="-175.556:244" stroke-width="12" fill="#ff000000" end="-175.556:106.222"/>
            <line id="{c921474d-3f18-4f98-b3fd-c83fa6e712b8}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="-202.02:102.353" stroke-width="12" fill="#ff000000" end="-149.459:102.353"/>
            <line id="{5f4000d6-8494-45bb-8e0c-44a5779f3140}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="-49.8316:-64.6465" stroke-width="12" fill="#ff000000" end="-49.8316:11.4478"/>
            <line id="{c20e8d67-e66b-4cd1-a4d5-da909d32717a}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="48.2829:-65.5219" stroke-width="12" fill="#ff000000" end="48.2829:10.5724"/>
            <line id="{3abe2138-f488-429d-bb27-94b6a13c913e}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="146.599:-64.8485" stroke-width="12" fill="#ff000000" end="146.599:11.2458"/>
            <line id="{ccaf1f51-b4b8-4ed4-9110-cf08067e7bf4}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="249.63:-65.5219" stroke-width="12" fill="#ff000000" end="249.63:10.5724"/>
            <line id="{6866e178-6a20-4048-8eab-ed3554098cd4}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="460.157:66.3198" stroke-width="12" fill="#ff000000" end="460.157:260.178"/>
            <cubicBezier id="{47001b3d-8af4-432d-8e66-9cc7728f2a39}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="358.194:-28.399" cp1="438.051:-29.9289" stroke-width="12" cp2="457.133:13.7415" fill="#ff000000" end="459.881:62.7527"/>
            <cubicBezier id="{edb3034d-f57c-4349-a714-3439433d2db2}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="458.622:252.499" cp1="457.591:441.101" stroke-width="12" cp2="251.469:440.071" fill="#ff000000" end="249.408:304.03"/>
            <cubicBezier id="{ff2677c7-98f1-46e0-b17c-197a3d94e664}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="249.408:304.03" cp1="251.469:155.622" stroke-width="12" cp2="-10.3061:151.5" fill="#ff000000" end="-9.27549:302.999"/>
            <cubicBezier id="{c841736a-ce7b-4bc4-90bb-7bb72bb7dd99}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="-9.27549:302.999" cp1="-9.02218:404.61" stroke-width="12" cp2="-177.667:378.931" fill="#ff000000" end="-175.204:250.438"/>
            <line id="{34475443-f1cf-4718-bb44-bd4bfc7221bf}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="428.351:105.655" stroke-width="12" fill="#ff000000" end="489.769:105.655"/>
            <line id="{9e883af6-6280-4577-b0da-608011ca26ed}" stroke-style="solid" fill-style="none" stroke="#ff000000" begin="428.197:199.401" stroke-width="12" fill="#ff000000" end="489.615:199.401"/>
        </colorFields>
        <images/>
        <regions>
            <region id="region_1" type="rectangle" textX="0" width="80" textY="0" visible="true" y="0" text="1" filled="true" height="80" color="#0000ff" x="-215"/>
            <region id="region_2" type="rectangle" textX="0" width="80" textY="0" visible="true" y="-70" text="2" filled="true" height="80" color="#0000ff" x="-40"/>
            <region id="region_3" type="rectangle" textX="0" width="80" textY="0" visible="true" y="-70" text="3" filled="true" height="80" color="#0000ff" x="55"/>
            <region id="region_4" type="rectangle" textX="0" width="80" textY="0" visible="true" y="-70" text="4" filled="true" height="80" color="#0000ff" x="160"/>
            <region id="region_5" type="rectangle" textX="0" width="80" textY="0" visible="true" y="-70" text="5" filled="true" height="80" color="#0000ff" x="260"/>
            <region id="region_6" type="rectangle" textX="0" width="80" textY="0" visible="true" y="110" text="6" filled="true" height="80" color="#0000ff" x="420"/>
            <region id="region_7" type="rectangle" textX="0" width="80" textY="0" visible="true" y="210" text="7" filled="true" height="80" color="#0000ff" x="420"/>
            <region id="start_zone" type="rectangle" textX="0" width="80" textY="0" visible="true" y="130" text="Старт" filled="true" height="80" color="#ff0000" x="-215"/>
        </regions>
    </world>
    <robots>
        <robot id="trikKitRobot" position="-199.667:149.444" direction="-90">
            <sensors>
                <sensor type="kitBase::robotModel::robotParts::Motor" port="M3###output###М3###" position="75:25" direction="0"/>
                <sensor type="" port="A1###input###JA1###sensorA1" position="0:0" direction="0"/>
                <sensor type="" port="A2###input###JA2###sensorA2" position="0:0" direction="0"/>
                <sensor type="" port="LineSensorPort###input###TrikLineSensorPort###lineSensor" position="0:0" direction="0"/>
                <sensor type="kitBase::robotModel::robotParts::EncoderSensor" port="E3###input###M3$$$Е3###encoder3" position="75:25" direction="0"/>
                <sensor type="kitBase::robotModel::robotParts::EncoderSensor" port="E4###input###M4$$$Е4###encoder4" position="75:25" direction="0"/>
                <sensor type="trik::robotModel::parts::TrikLightSensor" port="A5###input###А5###sensorA5" position="54:42" direction="0"/>
                <sensor type="trik::robotModel::parts::TrikLightSensor" port="A6###input###А6###sensorA6" position="54:8" direction="0"/>
                <sensor type="kitBase::robotModel::robotParts::Motor" port="M4###output###М4###" position="75:25" direction="0"/>
            </sensors>
            <startPosition id="{9f3c8967-8967-4a0d-a118-ba8041db8a37}" y="174.444" direction="-90" x="-174.667"/>
            <wheels left="M3###output###М3###" right="M4###output###М4###"/>
        </robot>
    </robots>
    <settings realisticMotors="false" realisticSensors="false" realisticPhysics="true"/>
    <constraints>
        <timelimit value="50000"/>
        <constraint failMessage="The robot must be in the launch area before starting!" checkOnce="true">
            <inside regionId="start_zone" objectId="robot1"/>
        </constraint>
        <event id="id_1" settedUpInitially="true">
            <conditions glue="and">
                <inside regionId="region_1" objectId="robot1"/>
                <equals>
                    <objectState object="robot1.display.labels.last.text"/>
                    <string value="1"/>
                </equals>
            </conditions>
            <trigger>
                <setUp id="id_2"/>
            </trigger>
        </event>
        <event id="id_1_fail" settedUpInitially="true">
            <conditions glue="and">
                <inside regionId="region_1" objectId="robot1"/>
                <notEqual>
                    <objectState object="robot1.display.labels.last.text"/>
                    <string value="1"/>
                </notEqual>
            </conditions>
            <trigger>
                <fail message="Invalid intersection number! Please note that the junction number should be displayed as the last line"/>
            </trigger>
        </event>
        <event id="id_2" settedUpInitially="false">
            <conditions glue="and">
                <inside regionId="region_2" objectId="robot1"/>
                <equals>
                    <objectState object="robot1.display.labels.last.text"/>
                    <string value="2"/>
                </equals>
            </conditions>
            <trigger>
                <setUp id="id_3"/>
            </trigger>
        </event>
        <event id="id_3" settedUpInitially="false">
            <conditions glue="and">
                <inside regionId="region_3" objectId="robot1"/>
                <equals>
                    <objectState object="robot1.display.labels.last.text"/>
                    <string value="3"/>
                </equals>
            </conditions>
            <trigger>
                <setUp id="id_4"/>
            </trigger>
        </event>
        <event id="id_4" settedUpInitially="false">
            <conditions glue="and">
                <inside regionId="region_4" objectId="robot1"/>
                <equals>
                    <objectState object="robot1.display.labels.last.text"/>
                    <string value="4"/>
                </equals>
            </conditions>
            <trigger>
                <setUp id="id_5"/>
            </trigger>
        </event>
        <event id="id_5" settedUpInitially="false">
            <conditions glue="and">
                <inside regionId="region_5" objectId="robot1"/>
                <equals>
                    <objectState object="robot1.display.labels.last.text"/>
                    <string value="5"/>
                </equals>
            </conditions>
            <trigger>
                <setUp id="id_6"/>
            </trigger>
        </event>
        <event id="id_6" settedUpInitially="false">
            <conditions glue="and">
                <inside regionId="region_6" objectId="robot1"/>
                <equals>
                    <objectState object="robot1.display.labels.last.text"/>
                    <string value="6"/>
                </equals>
            </conditions>
            <trigger>
                <setUp id="id_7"/>
            </trigger>
        </event>
        <event id="id_7" settedUpInitially="false">
            <conditions glue="and">
                <inside regionId="region_7" objectId="robot1"/>
                <equals>
                    <objectState object="robot1.display.labels.last.text"/>
                    <string value="7"/>
                </equals>
            </conditions>
            <trigger>
                <success/>
            </trigger>
        </event>
    </constraints>
</root>

Let's take a look at how verification works.

1. After each intersection, set the zones where it will be checked that the correct intersection number is displayed. To do this, edit the value of the <regions> tag in the XML file of the world, adding there the necessary number of zones to check. By changing the values of x, y, width and height, you can edit the location and size of the zones. To check the position of a zone, load the file into the virtual world model and check the location of the zones. After that, if necessary, you can make zones invisible by setting the attribute visible="false".

<!-- Example zone -->
<region id="region_1" type="rectangle" textX="0" width="80" textY="0" visible="true" y="0" text="1" filled="true" height="80" color="#0000ff" x="-215"/>

2. After that, in the <constraints> block set the constraint check. First we will specify the limit on the execution time of the task.

<timelimit value="50000"/>

3. Let's set a constraint on the initial position of the robot.

<constraint failMessage="The robot must be in the launch area before starting!" checkOnce="true">
    <inside regionId="start_zone" objectId="robot1"/>
</constraint>

4. In each zone after the intersection, we will check that the correct number is displayed. To do this, specify the id of the desired region in the <inside> tag and check that the last displayed message (robot1.display.labels.last.text) equals the number of the passed intersection. After that, we will call the same events for the rest of the zones.

<event id="id_1" settedUpInitially="true">
    <conditions glue="and">
        <inside regionId="region_1" objectId="robot1"/>
        <equals>
            <objectState object="robot1.display.labels.last.text"/>
            <string value="1"/>
        </equals>
    </conditions>
    <trigger>
        <setUp id="id_2"/>
    </trigger>
</event>

5. We will display an error message if the wrong number is displayed. To do this, compare the message that was displayed with the expected correct value. If the messages don't match, the user will get the specified error message and the program will stop executing.

<event id="id_1_fail" settedUpInitially="true">
    <conditions glue="and">
        <inside regionId="region_1" objectId="robot1"/>
        <notEqual>
            <objectState object="robot1.display.labels.last.text"/>
            <string value="1"/>
        </notEqual>
    </conditions>
    <trigger>
        <fail message="Неверный номер перекрестка! Обратите внимание, что номер перекрестка должен выводиться последней строчкой"/>
    </trigger>
</event>

6. Set the event that will display a message about the successful execution of the program, if all the specified intersections are passed correctly.

<event id="id_7" settedUpInitially="false">
    <conditions glue="and">
        <inside regionId="region_7" objectId="robot1"/>
        <equals>
            <objectState object="robot1.display.labels.last.text"/>
            <string value="7"/>
        </equals>
    </conditions>
    <trigger>
        <success/>
    </trigger>
</event>

Example 5. Kegelring

The robot must push all pins outside the circle.

Below is the complete code for checking this task.

<?xml version='1.0' encoding='utf-8'?>
<root version="20190819">
    <world>
        <walls/>
        <skittles>
            <skittle markerY="0.107756" y="0.107756" rotation="0" startRotation="0" id="{skittle1}" x="-90.3433" markerX="-90.3433"/>
            <skittle markerY="62.9765" y="62.9765" rotation="0" startRotation="0" id="{skittle2}" x="-63.8519" markerX="-63.8519"/>
            <skittle markerY="62.963" y="62.963" rotation="0" startRotation="0" id="{skittle3}" x="62.3031" markerX="62.3031"/>
            <skittle markerY="-89.2259" y="-89.2259" rotation="0" startRotation="0" id="{skittle4}" x="-0.323222" markerX="-0.323222"/>
            <skittle markerY="89.0101" y="89.0101" rotation="0" startRotation="0" id="{skittle5}" x="-1.45453" markerX="-1.45453"/>
            <skittle markerY="-1.44107" y="-1.44107" rotation="0" startRotation="0" id="{skittle6}" x="88.1212" markerX="88.1212"/>
            <skittle markerY="-63.1785" y="-63.1785" rotation="0" startRotation="0" id="{skittle7}" x="62.3031" markerX="62.3031"/>
            <skittle markerY="-64.7408" y="-64.7408" rotation="0" startRotation="0" id="{skittle8}" x="-63.8519" markerX="-63.8519"/>
        </skittles>
        <balls/>
        <colorFields/>
        <images>
            <image imageId="{ed8c2ee9-a500-4993-b874-611ba6b78853}" id="{d91a151a-4519-4646-89fd-395c863b5e77}" isBackground="false" rect="0:0:-6:-6" position="0:0"/>
            <image imageId="{9275be02-a681-4b9f-981e-56bcb9f17cee}" id="{8f470550-4bb5-4b34-b46e-c349d686bd9a}" isBackground="false" rect="0:0:-6:-6" position="0:0"/>
            <image imageId="{229679a6-12a5-44d0-97d9-99f132ded1e2}" id="{5dcb114e-03d4-493b-9849-daf4cd364a2a}" isBackground="false" rect="0:0:-6:-6" position="0:0"/>
            <image imageId="{27036474-ec49-423d-9f20-141d0c7d1044}" id="{ebb8366d-61c7-422f-9460-865851d1e0f1}" isBackground="false" rect="0:0:-6:-6" position="0:0"/>
            <image imageId="{69f0b63a-2937-4b12-bad7-2e240210db2e}" id="{f7bd0d83-ae88-46c8-bd9e-95fd3c32c174}" isBackground="false" rect="0:0:-6:-6" position="0:0"/>
            <image imageId="{80069e12-f4e6-4d56-8487-d8d4dd9e5ce2}" id="{1345cda3-f2e1-49b9-ae6b-35b4aa2eb850}" isBackground="false" rect="0:0:-6:-6" position="0:0"/>
            <image imageId="{7904d24c-5993-4013-80b5-bc899c0daabf}" id="{116c53b9-aa2c-4a16-bf8c-d291629c416f}" isBackground="false" rect="0:0:-4:-4" position="0:0"/>
            <image imageId="{742a7dc4-05a6-47c2-87fc-d04f1b3f0be4}" id="{9ee0c06d-b9c0-4da8-8227-98ffdc24f0be}" isBackground="false" rect="-200:-201:399:401" position="0:0"/>
        </images>
        <regions>
            <region type="ellipse" filled="true" textY="0" y="-150" visible="true" width="300" text="Ring" id="warzone" x="-150" height="300" textX="0" color="#ff0000"/>
        </regions>
    </world>
    <robots>
        <robot direction="0" id="trikKitRobot" position="-25:-24.4321">
            <sensors>
                <sensor type="kitBase::robotModel::robotParts::EncoderSensor" direction="0" port="E1###input###M1$$$Е1###encoder1" position="75:25"/>
                <sensor type="trik::robotModel::parts::TrikLightSensor" direction="0" port="A5###input###А5###sensorA5" position="50:25"/>
                <sensor type="kitBase::robotModel::robotParts::EncoderSensor" direction="0" port="E2###input###M2$$$Е2###encoder2" position="75:25"/>
                <sensor type="trik::robotModel::parts::TrikLightSensor" direction="0" port="A3###input###А3###sensorA3" position="56:43"/>
                <sensor type="kitBase::robotModel::robotParts::Motor" direction="0" port="M2###output###М2###" position="75:25"/>
                <sensor type="trik::robotModel::parts::TrikInfraredSensor" direction="0" port="A1###input###А1###sensorA1" position="22:25"/>
                <sensor type="kitBase::robotModel::robotParts::Motor" direction="0" port="M1###output###М1###" position="75:25"/>
                <sensor type="kitBase::robotModel::robotParts::Motor" direction="0" port="M4###output###М4###" position="75:25"/>
                <sensor type="trik::robotModel::parts::TrikLightSensor" direction="0" port="A2###input###А2###sensorA2" position="56:5"/>
                <sensor type="kitBase::robotModel::robotParts::Motor" direction="0" port="M3###output###М3###" position="75:25"/>
                <sensor type="kitBase::robotModel::robotParts::EncoderSensor" direction="0" port="E3###input###M3$$$Е3###encoder3" position="75:25"/>
                <sensor type="kitBase::robotModel::robotParts::EncoderSensor" direction="0" port="E4###input###M4$$$Е4###encoder4" position="75:25"/>
            </sensors>
            <startPosition y="0.567901" direction="0" id="{2b1161e8-ba72-40ed-bf22-be49c2ab4cb9}" x="0"/>
            <wheels left="M4###output###М4###" right="M3###output###М3###"/>
        </robot>
    </robots>
    <settings realisticSensors="false" realisticPhysics="true" realisticMotors="false"/>
    <constraints>
        <timelimit value="60000"/>
        <constraint failMessage="Робот должен находиться в круге перед запуском!" checkOnce="true">
            <inside objectId="robot1" regionId="warzone"/>
        </constraint>
        <event settedUpInitially="true">
            <condition>
                <timer forceDropOnTimeout="true" timeout="100"/>
            </condition>
            <trigger>
                <setUp id="finish checker"/>
            </trigger>
        </event>
        <event id="finish checker" settedUpInitially="false">
            <conditions glue="and">
                <not>
                    <inside objectId="{skittle1}" regionId="warzone"/>
                </not>
                <not>
                    <inside objectId="{skittle2}" regionId="warzone"/>
                </not>
                <not>
                    <inside objectId="{skittle3}" regionId="warzone"/>
                </not>
                <not>
                    <inside objectId="{skittle4}" regionId="warzone"/>
                </not>
                <not>
                    <inside objectId="{skittle5}" regionId="warzone"/>
                </not>
                <not>
                    <inside objectId="{skittle6}" regionId="warzone"/>
                </not>
                <not>
                    <inside objectId="{skittle7}" regionId="warzone"/>
                </not>
                <not>
                    <inside objectId="{skittle8}" regionId="warzone"/>
                </not>
            </conditions>
            <trigger>
                <success/>
            </trigger>
        </event>
    </constraints>
</root>

Now let's look in more detail at how the check takes place.

1. Let's edit the XML file of the world by adding a circle zone to the <regions> tag.

<region type="ellipse" filled="true" textY="0" y="-150" visible="true" width="300" text="Ring" id="warzone" x="-150" height="300" textX="0" color="#ff0000"/>

2. Let's set a time limit for the task.

<timelimit value="60000"/>

3. Let's set a constraint on the initial position of the robot.

<constraint failMessage="Робот должен находиться в круге перед запуском!" checkOnce="true">
    <inside objectId="robot1" regionId="warzone"/>
</constraint>

4. Set an event that checks that all pins are outside the circle, and then displays a message that the program has been successfully executed.

<event id="finish checker" settedUpInitially="false">
    <conditions glue="and">
        <not>
            <inside objectId="{skittle1}" regionId="warzone"/>
        </not>
        <not>
            <inside objectId="{skittle2}" regionId="warzone"/>
        </not>
        <not>
            <inside objectId="{skittle3}" regionId="warzone"/>
        </not>
        <not>
            <inside objectId="{skittle4}" regionId="warzone"/>
        </not>
        <not>
            <inside objectId="{skittle5}" regionId="warzone"/>
        </not>
        <not>
            <inside objectId="{skittle6}" regionId="warzone"/>
        </not>
        <not>
            <inside objectId="{skittle7}" regionId="warzone"/>
        </not>
        <not>
            <inside objectId="{skittle8}" regionId="warzone"/>
        </not>
    </conditions>
    <trigger>
        <success/>
    </trigger>
</event>

Example 6. Checking robot behavior

In the start position the robot must be in the start area at a distance from the wall and a touch sensor must be connected to port A1. A successful pass is when the robot approaches the wall, touches it with the touch sensor, moves away from it, and so on 5 times.

The idea of the checking program is that at any given time either the event waiting for the robot to drive up to the wall or that it has gone back is triggered. Both of these events arm each other. When the robot returns to its original position, the iteration counter is incremented. There is an extra event that checks the counter value. It will display a message about the successful execution of the program when the value is five.

Below is the complete code for checking this task.

<?xml version='1.0' encoding='utf-8'?>
<root version="20190819">
    <world>
        <walls>
            <wall fill="#ff000000" stroke-width="0" stroke="#ff000000" begin="-68:-204" id="{6f8bd6be-2983-4b0b-bbf8-5a26d1ed1ef7}" end="-68:77" stroke-style="none"/>
        </walls>
        <skittles/>
        <balls/>
        <colorFields/>
        <images/>
        <regions>
            <region x="-270" textY="0" y="-110" text="Стартовое поле" id="start_zone" color="#0000ff" filled="true" width="80" visible="true" textX="0" type="rectangle" height="80"/>
            <region x="-280" textY="0" y="-230" text="Поле, которое нельзя покидать" id="warzone" color="#ffff00" filled="true" width="210" visible="false" textX="0" type="rectangle" height="285"/>
        </regions>
    </world>
    <robots>
        <robot position="-256:-103" id="trikKitRobot" direction="0">
            <sensors>
                <sensor port="A5###input###А5###sensorA5" position="0:0" type="" direction="0"/>
                <sensor port="M3###output###М3###" position="75:25" type="kitBase::robotModel::robotParts::Motor" direction="0"/>
                <sensor port="M4###output###М4###" position="75:25" type="kitBase::robotModel::robotParts::Motor" direction="0"/>
                <sensor port="A1###input###А1###sensorA1" position="75:25" type="trik::robotModel::parts::TrikTouchSensor" direction="0"/>
            </sensors>
            <startPosition x="-231" y="-78" id="{99807fe9-54b1-42d7-991b-2b9cf102abe7}" direction="0"/>
            <wheels left="M4###output###М4###" right="M3###output###М3###"/>
        </robot>
    </robots>
    <settings realisticPhysics="false" realisticMotors="false" realisticSensors="false"/>
    <constraints>
        <!-- Time limit of 30 seconds -->
        <timelimit value="300000"/>
        <!-- Check that a touch sensor is installed on port A1 -->
        <constraint checkOnce="true" failMessage="На порту А1 должен быть выставлен датчик касания">
            <equals>
                <typeof objectId="robot1.А1"/>
                <string value="twoDModel::robotModel::parts::TouchSensor"/>
            </equals>
        </constraint>
        <!-- Check that there are no sensors other than the touch sensor on port A1 -->
        <constraint checkOnce="true" failMessage="The robot should have no sensors other than the touch sensor on port A1">
            <conditions glue="and">
                <equals>
                    <typeOf objectId="robot1.A2"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.A3"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.A4"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.A5"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.A6"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.D1"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.D2"/>
                    <string value="undefined"/>
                </equals>
                <equals>
                    <typeOf objectId="robot1.F1"/>
                    <string value="undefined"/>
                </equals>
            </conditions>
        </constraint>
        <!-- Check that the robot is in the valid zone during the program run time -->
        <constraint failMessage="Робот покинул допустимую зону!">
            <inside objectId="robot1" regionId="warzone"/>
        </constraint>
		
		    <!-- The event that indicates that the robot has gone and starts the check chain -->
        <event id="First move" settedUpInitially="true">
            <condition>
                <greater>
                    <objectState object="robot1.M3.power"/>
                    <int value="0"/>
                </greater>
            </condition>
            <triggers>
                <setUp id="Touching wall"/>
                <setter name="counter">
                    <int value="0"/>
                </setter>
            </triggers>
        </event>

        <!-- Event that gives an error if the robot does not move in the first second -->
        <event id="Waiting for going forward too long" settedUpInitially="true">
            <conditions glue="and">
                <timer timeout="1000" forceDropOnTimeout="true"/>
                <settedUp id="First move"/>
            </conditions>
            <trigger>
                <fail message="The robot never went in the first second"/>
            </trigger>
        </event>

        <!-- An event that verifies that the robot has approached the wall (touch sensor triggered) and plunges a second -->
        <event id="Touching wall">
            <condition>
                <equals>
                    <objectState object="robot1.A1.value"/>
                    <int value="1"/>
                </equals>
            </condition>
            <trigger>
                <setUp id="Returned back"/>
            </trigger>
        </event>

        <!-- An event that checks that the robot has gone back, increments the iteration counter and re-arms the first -->
        <event id="Returned back">
            <condition>
                <inside objectId="robot1" regionId="start_zone"/>
            </condition>
            <triggers>
                <setUp id="Touching wall"/>
                <setUp id="Done?"/>
                <setter name="counter">
                    <sum>
                        <variableValue name="counter"/>
                        <int value="1"/>
                    </sum>
                </setter>
            </triggers>
        </event>

        <!-- An event that verifies that the number of iterations has reached 5 and thus the task is complete -->
        <event id="Done?">
            <condition>
                <notLess>
                    <variableValue name="counter"/>
                    <int value="5"/>
                </notLess>
            </condition>
            <trigger>
                <success/>
            </trigger>
        </event>
    </constraints>
</root>

Now let's take a closer look at how the check takes place.

1. Let's set a time limit for the task.

<timelimit value="40000"/>

2. According to the problem condition, the robot must have only the touch sensor connected (there must be no other sensors). To be sure of this, compare the value of the object on port A1 with the value of the touch sensor. For more information about the names of the sensors for different constructors, see this link.

<constraint checkOnce="true" failMessage="Touch sensor must be set on port A1">
    <equals>
        <typeof objectId="robot1.А1"/>
        <string value="twoDModel::robotModel::parts::TouchSensor"/>
    </equals>
</constraint>

3. Let's check that no sensors are connected to the other ports. To do this, compare the value on each port with the "undefined" string.

<constraint checkOnce="true" failMessage="The robot should have no sensors other than the touch sensor">
    <conditions glue="and">
        <equals>
            <typeOf objectId="robot1.A2"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.A3"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.A4"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.A5"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.A6"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.D1"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.D2"/>
            <string value="undefined"/>
        </equals>
        <equals>
            <typeOf objectId="robot1.F1"/>
            <string value="undefined"/>
        </equals>
    </conditions>
</constraint>

4. Set a restriction on the area that the robot cannot leave.

<constraint failMessage="Робот покинул допустимую зону!">
    <inside objectId="robot1" regionId="warzone"/>
</constraint>

5. Let's set an event that verifies that the robot has started to move forward. As a condition, we specify that the power applied to the motor on port M3 must be greater than zero. If this condition is fulfilled, two triggers are triggered. The first one triggers the event with id = "Touching wall", and the second one assigns the value zero to the variable counter.

Since the attribute settedUpInitially is set to true, the event will be triggered (activated) immediately at the program startup.

<event id="First move" settedUpInitially="true">
    <condition>
        <greater>
            <objectState object="robot1.M3.power"/>
            <int value="0"/>
        </greater>
    </condition>
    <triggers>
        <setUp id="Touching wall"/>
        <setter name="counter">
            <int value="0"/>
        </setter>
    </triggers>
</event>

6. Let's define an event that will show an error in case after 1000ms (=1sec) the robot hasn't started moving forward (i.e. the event with id="First move" is still on and hasn't been executed). Since several conditions are checked in this event, the <conditions></conditions> tag is used with the logical connectors.

<event id="Waiting for going forward too long" settedUpInitially="true">
    <conditions glue="and">
        <timer timeout="1000" forceDropOnTimeout="true"/>
        <settedUp id="First move"/>
    </conditions>
    <trigger>
        <fail message="The robot never went in the first second"/>
    </trigger>
</event>

7. Set an event that checks that the robot has traveled to the wall. The condition checks that the value of the touch sensor located on port A1 is one (this means that the touch sensor has been triggered). If this condition is met, the trigger is triggered and the event id="Returned back" is triggered.

<event id="Touching wall">
    <condition>
        <equals>
            <objectState object="robot1.A1.value"/>
            <int value="1"/>
        </equals>
    </condition>
    <trigger>
        <setUp id="Returned back"/>
    </trigger>
</event>

8. Let's define an event that checks if the robot has returned to the start zone after touching the wall. To do this, we need to set an inside condition with attributes objectId="robot1" (our robot) and regionId="start_zone" (the zone to return to).

When this condition is met, two events are triggered and the iteration counter is incremented. The first event checks if the robot has touched the wall, the second event checks if the problem condition has been met.

<!-- An event that checks that the robot has gone back, increments the iteration counter and re-arms the first -->
<event id="Returned back">
    <condition>
        <inside objectId="robot1" regionId="start_zone"/>
    </condition>
    <triggers>
        <setUp id="Touching wall"/>
        <setUp id="Done?"/>
        <setter name="counter">
            <sum>
                <variableValue name="counter"/>
                <int value="1"/>
            </sum>
        </setter>
    </triggers>
</event>

9. Let's set an event that will display a message about the successful execution of the program if the value of counter is at least 5.

<event id="Done?">
    <condition>
        <notLess>
            <variableValue name="counter"/>
            <int value="5"/>
        </notLess>
    </condition>
    <trigger>
        <success/>
    </trigger>
</event>