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.
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 project is created. About adding and removing blocks to the scene, 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.
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 special window.
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:
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
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:
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 *.qrsformat 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) orAll files (*.*).
PuTTY
PuTTY — a client program for working with network protocols. You can connect to the TRIK controller 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.
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: .
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.
Array
An array is one of 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):
Or with explicit indices:
You can use arrays without creating them. For example, like this:
In this case, "empty spaces" in the array (indices that did not have an explicit assignment) will be filled with default values:
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
Programming TRIK with the visual programming language
For programming the TRIK controller with the visual language, TRIK Studio has , as well as .
Read more about visual programming in the article
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.
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
Adding and removing blocks in TRIK Studio Junior
Adding and removing blocks in TRIK Studio Junior is the same as in TRIK Studio:
VSCode
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,
autoformatter,
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.
Connecting to the TRIK controller via Wi-Fi
The TRIK controller has a Wi-Fi module that can work in two modes:
The access point mode, when the controller creates a new network, and we connect devices to it.
The Wi-Fi client mode, when we connect the controller to an existing network.
To select a mode in the controller menu, select the
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:
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:
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.
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.
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 , .
For detailed information about the TRIK controller, see the manufacturer's .
TRIK controller programming
To program the TRIK controller, select "TRIK" in the TRIK Studio settings in the "Robots" tab.
Use and blocks to write programs in a visual language. Read more about visual programming in the article
Read about text programming in the article
External tools
PuTTY, WinSCP, TRIK Gamepad
Three external programs are available in TRIK Studio:
To start the program, go to the menu Tools → External tools.
Class «accelerometer»
This article is automatically translated from Russian by Google Translator.
Represents the accelerometer of the TRIK controller.
Method
Description
read
Returns the current sensor reading as an array of three elements corresponding to the sensor readings along each axis.
Syntax
newData
The signal sent by the sensor when new data is ready.
TRIK Studio language types
Unlike , 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.
About TRIK Studio Junior
This article is automatically translated from Russian by Google Translator.
TRIK Studio Junior is a free programming environment with the for elementary grades.
The environment has a common interface with the programming environment for robots, which allows for a continuous learning process, starting from elementary grades.
Class «led»
This article is automatically translated from Russian by Google Translator.
Provides control of the LED on the body of the robot.
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 of TRIK Studio Junior, quick access to recent projects, and buttons for and .
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:
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.
You can add blocks to the scene in TRIK Studio in three ways:
Drag and drop the corresponding icons from the palette of elements onto the diagram.
.
between blocks using a linker.
Drag and drop from the palette
Left-click on the necessary block located in the 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 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
Start (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.
In the menu that appears, select "Create new element". A new menu with blocks will appear.
Select the block you need.
Delete block
Deleting a block from the scene is possible in two ways:
Select the block with the left mouse button and then click the "Delete" button on the keyboard.
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.
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
Download the send_files.cmd 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.
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 the TRIK controller to TRIK Studio
1. Connect the controller to the computer with TRIK Studio installed in either of two ways.
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:
Whether the IP address in TRIK Studio matches the IP address on the controller.
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.
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
Functions
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:
Using the TRIK controller as an access point (the controller creates a new network) and connects the devices to it.
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 .
TRIK Studio shortcuts
The table below shows the default shortcuts. You can change the keyboard shortcut for actions in the .
Built-in functions
In mathematical expressions, you can use the functions available for any platform.
Subprograms
Any program in TRIK Studio can be saved as a subprogram and used in another program.
Subprograms to a local collection or to a separate file for transfer to other computers.
To work with the collection of subprograms, use the menu item Tools → Subprograms:
.
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:
Using the .
With the .
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 .
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.
Class «encoder»
This article is automatically translated from Russian by Google Translator.
Represents power motor encoders connected to ports E1, E2, E3, E4.
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 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.
Class «keys»
This article is automatically translated from Russian by Google Translator.
Used to operate the buttons on the robot's remote control.
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 file for Windows and place it in the folder where TRIK Studio is installed.
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 and blocks with a link pointing from the "Timer" block to the program end block.
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.
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.
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”.
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.
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.
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.
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.
Download run_2d_model.cmd file for Windows orrun_2d_model.sh for Linux and place it in the folder where TRIK Studio is installed.
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:
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.
Returns the current encoder reading in degrees on the specified port.
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.
Download run_2d_model.cmd file for Windows orrun_2d_model.sh for Linux and place it in the folder where TRIK Studio is installed.
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.
Sent when the button with the specified code is pressed or released.
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:
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:
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.
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.
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.
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 ""), and in .qrs format.
Download for Windows or for Linux and place it in the folder where TRIK Studio is installed.
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 .
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:
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
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.
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:
Write a for the leading robot.
Write a for the second robot.
robots to a single network.
Message transmission algorithm
1. Switch TRIK Studio to the .
2. Enter a message variable for the message and initialize it by assigning it the number 5 in the "" block.
3. Add "" and "" 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 .
2. Add the "" 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 "", "" and "".
In the properties of the "Print text" block, check the Calculate box and specify true in the "Update image" field.
The complete algorithm
Class «lineSensor»
This article is automatically translated from Russian by Google Translator.
Camera in line sensor mode.
Method
Description
Detects the dominant color in the vertical bar in the center of the frame and remembers it as a line color.
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
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
detect
Detects the dominant color in the center of the frame and remembers it as the color of the object. After that, the "" method starts to return data for the object.
Syntax
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
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
stop
Turns off the camera and stops the sensor.
Syntax
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.
Method
Description
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.
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 .
2. In the 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 .
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 (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 . 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.
PyCharm
TRIK Studio can be integrated with the external programming environment PyCharm.
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:
TRIK Studio settings
Settings window
To open TRIK Studio preferences press the corresponding item in the :Settings → Preferences....
The left bar contains the next tabs:
TRIK controller firmware
Instructions for Windows, Linux and Ubuntu
Choose your operating system:
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 , if it is necessary for your task.
Object «Threading»
This article is automatically translated from Russian by Google Translator.
Provides management of parallel threads.
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.
{
"cmd": ["D:\\TRIKStudio\\send_filesl.cmd", “<path to scripts dir>”, "<file with ip addresses>"],
"selector": "source.js"
}
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.
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.
"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"
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.
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 firmware image.
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 firmware image.
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.
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:
To declare variables and set certain values for them, the “Variable Initialization” block is used.
"Variable Initialization" block
For mathematical expressions — "Expression" block.
"Expression" 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 "Common blocks".
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:
Sensor variables
Besides constants, 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
sensor<port name>
For example, sensorA1 for TRIK or sensor1 for Lego NXT.
A complete list of sensor variables is provided in sections for specific platforms:
.
.
.
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 main menu
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".
Visual programming
A program in the TRIK Studio is represented as a sequence of the blocks connected by the links.
Each program corresponds to the main diagram, which may contain other diagrams (subprograms). 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:
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.
Class «colorSensor»
This article is automatically translated from Russian by Google Translator.
The camera in color sensor mode.
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 from the diagram before downloading it to the robot or 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.
Function include
This article is automatically translated from Russian by Google Translator.
Function description
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:
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}:
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 "2D Model".
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. Connect 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.
Returns an array with the coordinates of the dominant color in the RGB color scale in the specified area of the frame.
Turns off the camera and stops the sensor.
init
Turns the camera on and initializes it in color sensor mode.
Syntax
brick.colorSensor("video1").init(true)
brick.colorSensor("video1").init(True);
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.
Turns the camera on and initializes it in color sensor 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.
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.
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 variablessum=function
include("other_file.js");print(sum(1
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.
This article is automatically translated from Russian by Google Translator.
Serves to work with the programmable control panel "TRIK Gamepad".
Method
Description
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
As a parameter, you must specify the number of the button - from 1 to 5.
Example
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
As a parameter, you must specify the number of the control area - 0 or 1.
Example
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
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
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
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
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
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
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.
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 .
accelerometer
An array of three elements containing accelerometer readings on the X, Y, and Z axis, respectively.
Example
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
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.
Пример
lineSensor
An array of three elements containing camera readings inline sensor mode. The values are updated when the sensor is on and initialized.
Class «gyroscope»
This article is automatically translated from Russian by Google Translator.
Represents the gyroscope 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.
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
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 function.
Rwsult:
Implementing the grayscale function
Converts the image to black and white and outputs it to the display:
Result:
Implementing the image binarization function
Translates the image to black and white and outputs it to the display:
Result:
.
Property editing
In TRIK Studio, there are two ways to edit property values of blocks and links between them:
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:
Hover over the value of the desired property.
Double-click the left mouse button to activate editing properties.
Enter the desired value.
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.
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.
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.
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).
// take a frame in rgb32 formatvarpic=getPhoto();brick.display().show(pic,total_height,total_width,"rgb32");script.wait(2000);
pic =getPhoto();
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
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
random
Returns a random number from the specified range.
Syntax
The range boundaries must be specified as parameters.
Example
readAll
Reads the entire contents of the specified file into a string array.
Syntax
As a parameter, you must specify the name of the file with the extension.
Example
removeFile
Deletes the specified file.
Syntax
As a parameter, you must specify the name of the file with the extension.
Example
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 "" method.
Syntax
system
Executes the command transmitted.
Syntax
As a parameter, you must specify the operating system console command.
Example
time
Returns the time stamp - the number of milliseconds elapsed since the beginning of January 1, 1970 GMT.
Syntax
timer
Creates and returns a timer (class QTimer) that sends a timeout signal every n milliseconds.
Syntax
n is passed as a parameter.
Example
wait
Suspends script execution for the number of milliseconds passed.
Syntax
The number of milliseconds is passed as a parameter.
Example
writeToFile
Writes a string to a file.
Syntax
The file name and the line to be written should be specified as parameters.
Example
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:
Connect the TRIK controller to the computer in any of the .
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:
Network
Ports
MEMS
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 .
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.
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.
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 "".
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.
About TRIK Studio
TRIK Studio — free robot programming environment.
It allows you to solve problems using both and programming languages.
A distinctive feature of TRIK Studio is an
x = accelerometer[0]; -- X-axis accelerometer readings
y = accelerometer[1]; -- Y-axis accelerometer readings
z = accelerometer[2]; -- Z-axis accelerometer readings
r = colorSensorR; -- red intensity
g = colorSensorG; -- green intensity
b = colorSensorB; -- blue intensity
x = gyroscope[0]; -- X-axis gyroscope readings
y = gyroscope[1]; -- Y-axis gyroscope readings
z = gyroscope[2]; -- Z-axis gyroscope readings
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);
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;
var pic = grayScale(pic);
brick.display().show(pic, total_height, total_width, "grayscale8");
script.wait(2000);
// 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;
var pic = binarization(80, pic);
brick.display().show(pic, total_height, total_width, "grayscale8");
script.wait(2000);
Gets a new message or blocks script execution until the message arrives.
Sends the specified message to the robot with the specified board number (or all robots).
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
mailbox.connect("ipAddress")mailbox.connect
mailbox.connect("ipAddress");mailbox.
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
mailbox.connect("192.168.0.20",8889)
mailbox.connect("192.168.0.20",8889);
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.
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.
. 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.
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.
The TRIK Studio interface depends on the selected mode. TRIK Studio has two modes:
Editing mode
It is intended for creating a robot control diagram and executing it in the generation 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:
Keyboard shortcuts Ctrl+1 / Ctrl+2.
.
Editing mode
TRIK Studio in edit mode has the following interface elements:
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:
For more information, see the article:
File panel
The "File" panel repeats the main operations available from the "" 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:
Hold down the Ctrl key and roll the mouse wheel.
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 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 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 tab.
Palette panel
The Palette panel contains a set of available blocks and the relationships between them, which can be added to the diagram.
The composition of the palette may vary depending on the platform selected in the .
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 . 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 ( or ) 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
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 .
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:
TRIK controller menu
The TRIK controller menu contains six sections:
File Manager — start and remove programs.
Testing — testing of devices connected to the TRIK controller.
Network Config— connecting the TRIK controller to other devices.
Comm settings — the interaction of several TRIK controllers.
Language — language selection.
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:
Analog sensors.
Servos.
Power motors.
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:
Wi-Fi access point.
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:
Programming.
System settings.
Version
Programming
Section "Programming" is intended for writing a program on the controller from ready-made commands.
Add commands to the algorithm using the "<new command>" item.
After the completion of the algorithm, select the "Run program" item.
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.
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.
Video module
USB webcam
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:
As a line sensor.
As objects sensor.
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).
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.
TRIK Studio main menu
The main menu of TRIK Studio contains a set of basic operations and environment settings:
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.
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 "TRIK Studio settings").
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.
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.
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).
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.
Installing drivers
Setting up the COM port
Modem installation
Modem setup
Creating a network connection
Setting up a network connection
Connecting to the controller
1. Installing drivers
1. the drivers from the converter manufacturer's official website: .
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 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.
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,
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,
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,
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,
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,
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
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
Common blocks
The list of available blocks depends on the chosen robotics kit and on the robot model (real robot or ). 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 .
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:
Draw a point at given coordinates.
Draw a rectangle with the upper left corner at the specified coordinates and having the specified width and height.
Close and clear the drawing window.
Redraw the window to draw. The changes to the display will only happen after this method is called.
Remove from the screen all text added to it by calls to the "addLabel" method.
Set the screen background to the color you specify.
Set the color of the brush used to draw the graphical primitives.
Set the thickness of the brush used to draw the graphical primitives, in pixels.
Display the image generated in the one-dimensional array on the controller.
Display the image previously loaded on the robot.
h — rectangle height,
from— initial angle bounding the arc,
to— finite angle bounding the arc.
h — rectangle height.
h — rectangle height.
blue, darkBlue,
cyan, darkCyan,
magenta, darkMagenta,
yellow, darkYellow,
gray, darkGray, lightGray,
black.
blue, darkBlue,
cyan, darkCyan,
magenta, darkMagenta,
yellow, darkYellow,
gray, darkGray, lightGray,
black.
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».
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.
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.
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 "2D model".
2D model elements:
Tools for editing world model
Editing the model of the world is carried out using the corresponding panel.
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:
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
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,
Context menu
Also, the functions of the two-dimensional model are available when you click the right mouse button 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.
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
Robot physics control
Model settings
robot mass.
Delete all colored lines drawn by the robot marker. Other elements remain on the scene.
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
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.
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.
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.
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).
— blocks that perform any action on the "Character movement": commands to drive forward, turn, play sound, and others.
— blocks waiting for an event to occur: certain sensor readings, pressing a button, etc.
— blocks displaying graphics and text on the screen.
Algorithms
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
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
A block for declaring a new variable and setting a value for it. The same operation can be performed using the block, but this block makes the program more clear.
Properties
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
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 "" or "" 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
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
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
A condition with several alternatives.
In the "Expression" parameter, you can specify an arbitrary expression (for more details, see the section ""), 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
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 "".
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.
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 "" block or in the "" 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
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
Finishes the task with the identifier specified in the "Task" property. Must be applied from another task.
Random Initialization
A block for assigning a specified variable to a random integer from a specified interval using the From and To properties.
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
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
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
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
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
Turns "Character movement" to the right.
Turn left
Turns "Character movement" to the right.
Say
Use the speaker to say the phrase passed as the block argument.
LED
Set the specified LED color on the controller.
Waiting
Timer
Block for setting the delay. The delay time is set in the Delay parameter in milliseconds.
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
Wait for the user to enter a value. The value will be assigned to the specified variable.
Properties
The block has three properties:
Example
Wait for Button
Wait until the specified button on the robot is pressed.
Drawing
Clear Screen
Erase everything that is drawn on the screen.
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
Finish drawing with a marker.
The block is available only in the two-dimensional model mode.
Print Text
Prints the specified string at the specified location on the robot's screen.
Properties
How to print a text?
To print a text:
Put your text into the Text property.
Uncheck the Evaluate checkbox.
How to print a variable value?
To print a variable value:
Put the variable name into the Text property.
Check the Evaluate checkbox.
Painter Color
Specify the color to draw simple graphical shapes on the robot's screen.
Painter Width
Specify the width of the line used to draw simple graphical figures on the robot's screen.
Draw Pixel
Draw a dot on the screen at the specified coordinates.
Draw Line
Draw a line segment on the screen. Segment ends are given as parameters to the block.
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 an ellipse inscribed in a given rectangle on the screen.
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
Draw a smiley face on the screen.
Sad Smile
Draw a sad smiley face on the screen.
Background Color
Sets the screen background color.
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.
Change subprogram icon background.
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.
Wait until the specified button on the robot is pressed.
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.
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.
A block for declaring a new variable and setting a value for it.
Property
Description
Value
An expression is specified that defines the initial value of the variable.
Variable
The variable name is specified.
Property
Description
Condition
A logical expression is indicated (for more details, see the article "Expression Syntax"), based on the value of which the further path of the diagram execution will be selected.
Property
Description
Condition
The logical expression is specified (for more details, see the article "Syntax of expressions"), based on the value of which the further path of the diagram interpretation will be selected.
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:
Switch to the mode.
Go to the .
Right-click on the scene and choose "Save world model..." in the context menu.
Editing an XML file
Open a saved XML file in a text editor. , 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:
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.
The simplest virtual world model without objects in .xml the format is as follows:
Robots
The following tags are available for describing robots:
<robots>...</robots>
Defines a robot on stage. Used as a container, has no attributes.
<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
Example:
<sensors>...</sensors>
Defines sensors on a robot. Used as a container, has no attributes.
<sensor/>
Sensors ports configuration.
Attributes
There are 5 types of sensors for TRIK and 9 types of sensors for EV3:
Example:
<startPosition/>
Defines the starting position of the robot.
Attributes
Example:
<wheels/>
Motor ports configuration.
Attributes
Example:
Objects
The following tags are available for describing objects:
<wall>
Adds a wall to the scene.
Attributes
Example:
<skittle>
Adds a skittle to the scene.
Attributes
Example:
<ball>
Adds a ball to the scene.
Attributes
Example:
<line>
Adds a line to the scene.
Attributes
Example:
<cubicBezier>
Adds a Bezier curve.
Attributes
Example:
<rectangle>
Adds a rectangle.
Attributes
Example:
<ellipse>
Adds an ellipse.
Attributes
Example:
<stylus>
Defines a stylus for drawing.
Attributes
Example:
<stylusLine>
Allows you to draw arbitrary shapes using the stylus. This block of code consists of many segments.
Attributes
Example:
<region>
Allows you to add regions to the scene. There are 2 types of regions:
rectangle
ellipse
Attributes
Example:
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
TRIK specific blocks
TRIK specific blocks consist of three categories:
Actions - blocks that perform any action on the controller: turning on the motors, playing sounds, etc.
Waiting - blocks waiting for an event to occur: certain sensor readings, pressing a button, etc.
- blocks displaying graphics and text on the screen.
For blocks common for all platforms see the article
Action blocks
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
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
Plays a sound with specified frequency and duration on the controller.
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 program.
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
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 the motors on the specified ports.
The ports are specified by lines M1, M2, M3, and M4, separated by commas.
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
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
Use the speaker to say the phrase passed as the block argument.
LED
Set the specified LED color on the controller.
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
Enable the video camera on the controller in one of three modes:
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).
Object sensor - detects a contrasting object in the center of the frame and later returns the coordinates of its center and diameter in pixels.
Color sensor - returns the dominant color in the center of the frame as its coordinates in the RGB color scale.
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
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
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
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
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 program for Windows or SCP for Linux.
Remove File
Deletes a file.
The path can be absolute or relative to the folder containing trik-studio.exe.
Stop Camera
Turn off the camera.
Disable Video Streaming
Stop the video feed from the robot's camera.
Calibrate Gyroscope
Sets the gyroscope angle to zero at the current position..
Waiting Blocks
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
Wait for the user to enter a value. The value will be assigned to the specified variable.
Properties
The block has three properties:
Example
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 the touch sensor to operate on the specified port.
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 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 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 until the revolutions count reading on the specified port is greater or less than the Tacho limit value.
Wait for Button
Wait until the specified button on the robot is pressed.
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 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 for one of the two active areas of the RC to be pressed. The coordinates of the click can be obtained with the "" sensory variables.
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 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 the RC to connect to the robot. If the RC is already connected, the program will continue running.
Drawing Blocks
Painter Color
Specify the color to draw simple graphical shapes on the robot's screen.
Painter Width
Specify the width of the line used to draw simple graphical figures on the robot's screen.
Draw Pixel
Draw a dot on the screen at the specified coordinates.
Draw Line
Draw a line segment on the screen. Segment ends are given as parameters to the block.
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 an ellipse inscribed in a given rectangle on the screen.
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
Draw a smiley face on the screen.
Sad Smile
Draw a sad smiley face on the screen.
Background Color
Sets the screen background color.
Print Text
Prints the specified string at the specified location on the robot's screen.
Properties
How to print a text?
To print a text:
Put your text into the Text property.
Uncheck the Evaluate checkbox.
How to print a variable value?
To print a variable value:
Put the variable name into the Text property.
Check the Evaluate checkbox.
Clear Screen
Erase everything that is drawn on the screen.
Specify the location and file name to save.
Motor ports configuration.
Sensor
Description
RangeSensor
Range sensor.
TouchSensor
Touch sensor.
Ev3Gyroscope
Gyroscope.
LightSensor
Light sensor.
ColorSensorGreen
Color sensor (green).
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.
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;
stroke="#ff000000″
Line color.
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.
Border color.
stroke-width="6"
Border width.
stroke="#ff000000″
Fill color.
Border width.
fill="#ff000000″
Border color.
stroke="#ff000000″
Fill color.
Fill color.
Fill color.
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).
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.
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.
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.
It is possible to add restrictions by to prepare for students.
There are three types of restrictions:
Time restrictions.
For example, a time limit to complete a task or a specific action in a specific time frame.
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.
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.
Binary arithmetic functions that have exactly two child elements, each of them must be an integer.
An unconditional event that runs before the program starts executing.
Attribute
Description
value="value"
Timeout in milliseconds after which the execution will be terminated and the "Time limit exceeded" error will be displayed.
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.
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.
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".
Attribute
Description
name="my_value"
Variable name
Attribute
Description
id="finish checker"
The ID of the event.
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)
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".
The TRIK Studio interface depends on the selected mode. TRIK Studio Junior, like TRIK Studio, has two modes:
Editing mode
It is intended for creating a robot control diagram and executing it in the generation mode.
Debug mode
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:
<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>
<timelimit value="35000"/>
<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>
<!-- 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>
<!-- Limits the location of the "robot1" robot to the "start" zone -->
<inside objectId="robot1" regionId="start"/>
<!-- The "event1" event is set up condition -->
<condition>
<settedUp id="event1"/>
</condition>
<!-- The "event2" event is dropped condition -->
<condition>
<dropped id="event2"/>
</condition>
<!-- 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>
<!-- 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>
<trigger>
<success/>
</trigger>
<fail message="Wrong answer!"/>
<success/>
<!-- 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>
<!-- Set up the "finish checker" event -->
<triggers>
<setUp id="finish checker"/>
</triggers>
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
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".
3. Copy the <constraints> block template below into the XML file of the world for which you want 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.
Below is the complete code to test this task.
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.
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 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 tag has an attribute failMessage, which allows you to specify the text of the error message.
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".
This constraint will be checked at all times of program execution. In the 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.
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 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 in the tag.
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.
Now let's take a closer look at how the check takes place.
1. Let's set a time limit for passing the task.
2. Let's set a constraint on the initial position of the robot. It will be checked once at the beginning of the program.
3. Set a restriction on the area that the robot cannot leave.
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 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 tag. With the 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 thetag 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.
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.
Now let's take a closer look at how the check takes place.
1. Let's set a time limit for the task.
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 .
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.
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.
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.
6. Finally, let's create an event that will notify you if the robot is in the finish area.
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.
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 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".
2. After that, in the block set the constraint check. First we will specify the limit on the execution time of the task.
3. Let's set a constraint on the initial position of the robot.
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 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.
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.
6. Set the event that will display a message about the successful execution of the program, if all the specified intersections are passed correctly.
Example 5. Kegelring
The robot must push all pins outside the circle.
Below is the complete code for checking this task.
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 tag.
2. Let's set a time limit for the task.
3. Let's set a constraint on the initial position of the robot.
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.
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.
Now let's take a closer look at how the check takes place.
1. Let's set a time limit for the task.
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 .
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.
4. Set a restriction on the area that the robot cannot leave.
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.
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 tag is used with the logical connectors.
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.
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.
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.
<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>
<?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>
<timelimit value="300000"/>
<constraint checkOnce="true" failMessage="The robot must be in the launch area before starting!">
<inside objectId="robot1" regionId="start_zone"/>
</constraint>
<?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>
<timelimit value="10000"/>
<constraint checkOnce="true" failMessage="The robot must be in the blue square before launching!">
<inside objectId="robot1" regionId="start_zone"/>
</constraint>
<constraint failMessage="Робот покинул допустимую зону!">
<inside objectId="robot1" regionId="warzone"/>
</constraint>
<?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>
<timelimit value="40000"/>
<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>
<constraint checkOnce="true" failMessage="The robot must be in the blue square before launching!">
<inside objectId="robot1" regionId="start_zone"/>
</constraint>
<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>
<!-- 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"/>
<timelimit value="50000"/>
<constraint failMessage="The robot must be in the launch area before starting!" checkOnce="true">
<inside regionId="start_zone" objectId="robot1"/>
</constraint>
<constraint failMessage="Робот должен находиться в круге перед запуском!" checkOnce="true">
<inside objectId="robot1" regionId="warzone"/>
</constraint>
<?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>
<timelimit value="40000"/>
<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>
<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 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>