
Welcome to the RoboMaster Developer Page¶
Introduction¶
Introduction to the EP kit¶
The RoboMaster EP educational extended kit provides rich expansibility based on the RoboMaster S1 education-series robot. It provides complete courses and new RoboMaster exclusive youth competitions. All its programming modules are carefully designed to meet teaching needs, delivering new teaching and learning experiences and expanding the boundaries of education.
EP robot appearance¶
By using the RoboMaster EP educational kit, you can assemble infantry robots or engineering robots. Infantry robots are similar in appearance to the common S1 version, but equipped with upgraded software and hardware and many new components. With greatly improved extension capabilities, the upgraded robot can connect to third-party sensors through the sensor adapter, enabling more programming possibilities.
On the basis of the S1, major changes have been made to the appearance of the engineering robot. Specifically, a parallel mechanical arm was added to replace the gimbal structure installed in the center of the chassis, the image transmission system was retained, and a mechanical gripper was installed at the end of the mechanical arm to perform more complex tasks. In terms of chassis mobility and the overall extension capabilities, the engineering robot is similar to the infantry robot.
Website content¶
As an education-series robot, the RoboMaster EP has strong extension and programming capabilities. To facilitate user programming, the official app integrates the functions of Scratch programming and Python programming and provides a Python SDK, plaintext SDK, and other programming methods.
This is the technical development website for RoboMaster series products. It is designed for students, teachers, and technology enthusiasts who use RoboMaster series products. It provides users with technical guidance to facilitate secondary development of RoboMaster EP, allowing them to implement more functions and fun applications.
This website has four parts, as described below:
- Quick Start
- This part summarizes the RoboMaster EP educational kit and the content of this website. It also describes how to install the programming environment and how RoboMaster EP communicates with third-party platforms to help users implement more functions.
- Python SDK
- The RoboMaster SDK is implemented based on the Python language and can be used with the Python SDK software library RoboMaster series products. Currently, the SDK can be used with RoboMaster EP and Tello Edu series products. It provides an extensive set of APIs, including: motion control, flight control, intelligent recognition, lighting effect configuration, data push, video streaming, and audio streaming. In addition, its concise design enables users to quickly master it for learning and teaching applications.
- Extended Module/Interface Description
- RoboMaster EP has more extended modules and interfaces than S1. This section briefly describes the configuration and usage of these extended modules and interfaces.
- Plaintext SDK Description
- After using a third-party platform to establish a connection with RoboMaster EP, users can perform more complex and interesting operations on the EP robot through the plaintext SDK. This section details the functions, usage, and related protocols of the plaintext SDK.
- Python Programming Description
- This section helps users develop the newly added functions and modules of EP in the built-in Python programming environment of the official RoboMaster EP app in order to implement more fun applications.
- Version Description
- This section describes how to match the appropriate documentation to different robot versions.
Contact us¶
If you have any suggestions or comments concerning this document, contact us at RoboMaster-SDK GitHub.
Programming Environment Installation¶
Introduction¶
After you establish a connection between your PC and the EP through Wi-Fi, USB, or UART, you can use the plaintext SDK to communicate with the EP for more complex secondary development. You can use C++, C#, Python, or other languages for programming on the PC based on your development capabilities.
This document describes the procedure for installing Python on your PC to help you understand the various modules and functions of the EP and to help you use the Python sample code on this website.
Install Python on Windows¶
Environment: Windows 10 64-bit
- Locate the Python installation package on the Python official website (Python 3.7.8 in this example) and download the installer in the package.
警告
Ensure that the downloaded python.exe file is for 64-bit installation and the Python version is between 3.6.6 and 3.8.9. Otherwise, you cannot use the Python SDK properly due to compatibility issues.

Step 1: Check that the installation package is for
64-bit
installation, otherwise you cannot use the Python SDK properly.Step 2: Select
Add Python 3.7 to Path
.Step (3): Select ``Install Now’’ to begin installation, as shown in the figure below:

- After the installation is complete, press the
Win+R
shortcut command, entercmd
in the window that appears to open the CLI, and then enter ``python’’ on the CLI to confirm that Python 3.7.8 has been installed successfully.

注解
The cmd window will display the corresponding version information. If you cannot see this information, reinstall Python by repeating the preceding steps.
Install Python on Ubuntu¶
Environment: Ubuntu 16.04 64-bit and Python 3.7.8
- Ubuntu 16.04 provides Python 2.7 or 3.5 by default. By entering the
python
command, you can view the default version of the installed Python program. Note that the Python program that comes with the system must not be uninstalled. - Run the following commands to install Python 3.7:
sudo add-apt-repository ppa:jonathonf/python-3.7
sudo apt-get update
sudo apt-get install python3.7
- Run the following commands to adjust the priority of Python 3 so that Python 3.7 has a higher priority:
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 2
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 100
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 150
- Run the
python
command again to verify that Python 3.7 has been installed successfully.
Third-party Platform Communication¶
Introduction¶
After using a third-party platform to establish a connection with RoboMaster EP, you can communicate with the EP robot through the plaintext SDK. In addition, you can control each built-in module and extended module and obtain the video stream and audio stream of the EP robot, which greatly improves the extension capabilities of EP and enables more fun applications.
Third-party platform types¶
Applicable third-party platforms are computing platforms with autonomous computing capabilities and Wi-Fi, USB, and UART interfaces, such as DJI Manifold, Arduino Development Board, Micro:bit, Raspberry Pi, Jetson Nano, or PCs.
Communication methods¶
There are three communication methods between the third-party platform and RoboMaster EP: Wi-Fi, USB, and UART. The working principles of the three communication methods are described below.
Wi-Fi connection¶
There are two Wi-Fi connection modes, direct connection mode and router mode, which are described as follows.
The direct connection mode¶
prerequisites: The third-party platform must have a Wi-Fi function.
purposes: After connecting to EP via Wi-Fi, the third-party platform communicates with EP through the plaintext SDK.
steps:
- Turn on the EP and set the connection method switch of the smart central control to the direct connection mode.
- Turn on the wireless network of the third-party platform and then scan for and connect to the EP hotspot.
- Communicate with EP through the plaintext SDK. (For detailed instructions, refer to Wi-Fi direct connection)
Application example: After connecting to EP via Wi-Fi, the DJI Manifold, Jetson Nano, or your PC communicates with EP through the plaintext SDK and obtains the video and audio streams from the EP.
schematic diagram: ![]()
DJI Manifold, Jetson Nano, or the PC connects to EP in Wi-Fi direct connection mode
The router mode¶
prerequisites: The third-party platform supports Wi-Fi or wireless connection.
purposes: The third-party platform and EP connect to the same LAN, and then the platform communicates with EP through the plaintext SDK.
steps:
- Turn on EP and set the connection method switch of the smart central control to the router mode.
- Connect EP to the router by scanning the QR code in the official app.
- The third-party platform connects to the same router via Wi-Fi or a wired network.
- Obtain the IP address of EP from the settings page in the official app or by scripting.
- Communicate with EP through the plaintext SDK. (For detailed instructions, refer to Wi-Fi router mode)
application example: After connecting to the same LAN, the DJI Manifold, Jetson Nano, or your PC communicates with EP through the plaintext SDK and obtains the video and audio streams of EP.
schematic diagram: ![]()
DJI Manifold, Jetson Nano, or the PC connects to EP in Wi-Fi router mode
USB connection¶
prerequisites: The third-party platform has a Type-A USB interface and supports the RNDIS function.
purposes: The third-party platform connects to the micro USB port of the smart central control of EP through a USB cable and uses the plaintext SDK to communicate with EP.
steps:
- Turn on EP without concerning yourself with the current connection method.
- The third-party platform connects to the smart central control of EP through a USB cable.
- Communicate with EP through the plaintext SDK. (For detailed instructions, refer to USB connection)
application example: Secure the Raspberry Pi or Jetson Nano, which is powered by the EP power adapter module, on the EP vehicle. Then, connect the powered device to EP via the USB port, communicate with EP through the plaintext SDK, and obtain the video and audio streams of EP.
schematic diagram: ![]()
Raspberry Pi connection diagram
![]()
Jetson Nano connection diagram
UART connection¶
prerequisites: The third-party platform has a UART interface or a serial-to-USB function.
purposes: The third-party platform connects to the UART port of the EP motion controller through UART and uses the plaintext SDK to communicate with EP.
steps:
- Turn on EP without concerning yourself with the current connection method.
- Connect the TX/RX and GND terminals of the UART module of the third-party platform to the RX/TX and GND terminals of the UART module of the EP motion controller. (Refer to Pin description)
- Communicate with EP through the plaintext SDK. (For detailed instructions, refer to UART connection)
application example: Secure the Arduino or Micro:bit, which is powered by the EP power adapter module, on the EP vehicle. Then, connect the powered device to the EP motion controller via UART and use the plaintext SDK to communicate with EP.
schematic diagram: ![]()
Arduino connection diagram
![]()
Micro:bit connection diagram
Install RoboMaster SDK¶
Install the SDK on the Windows platform¶
Prepare the development environment¶
小技巧
Before using the Python SDK, ensure that the corresponding Python environment has been installed on the programming platform. If the environment is not installed, install it by referring to Install the Python Programming Environment.
Install the required VC library¶
Download the (GitHub RoboMaster SDK repository) (Alternative download address: Gitee RoboMaster SDK repository) and run the executable file of the VC library:

警告
The following error occurs if you use the SDK without installing the VC library:

Install the RoboMaster Python SDK¶
Install the RoboMaster SDK, click the start menu on your PC, and enter cmd
in the search box. In the search results, right-click the CLI program and select ``Run as Administrator’’. Then, enter the following command::
pip install robomaster
小技巧
If the following error occurs, install the Python environment by referring to Install the Python Programming Environment.

Upgrade the RoboMaster SDK¶
To upgrade the RoboMaster SDK, run the following command on the CLI::
pip install --upgrade robomaster
Install the SDK on the Linux platform¶
Ubuntu 16.04
Install the Python environment
The following example explains how to install the Python environment in Ubuntu 16.04.
Install the RoboMaster SDK
Install the RoboMaster SDK by running the following command::
pip install robomaster
Upgrade the RoboMaster SDK
To upgrade the RoboMaster SDK, run the following command on the CLI::
pip install --upgrade robomaster
小技巧
For the process of installing the Python environment on Raspberry Pi, refer to sdk install on Raspberry Pi.7z.
Install the SDK on the MacOS X platform¶
Install the RoboMaster SDK
Install RoboMaster SDK by running the following command::
pip install robomaster
Upgrade the RoboMaster SDK
To upgrade the RoboMaster SDK, run the following command on the CLI::
pip install --upgrade robomaster
Download RoboMaster SDK Source Code¶
You can download the SDK sample code on the official GitHub website.
Clone, fork, or report issues on the GitHub RoboMaster SDK repository.
You can also download the SDK sample code from Gitee (a domestic source for faster download).
Clone, fork, or report issues on the Gitee RoboMaster SDK repository.
Connect the RoboMaster SDK with Robots¶
EP connection method¶
The RoboMaster SDK can connect with EP through three methods: Wi-Fi direct connection, Wi-Fi networking, and USB (RNDIS) connection.
- Wi-Fi direct connection
Wi-Fi direct connection: Set the connection method of the robot to direct connection and connect to the robot’s Wi-Fi hotspot. In Wi-Fi direct connection mode, the default IP address of the robot is 192.168.2.1.
Turn on the robot and set the connection method switch of the smart central control to the direct connection mode, as shown in the figure below:
Prepare a device with a Wi-Fi connection function, such as DJI Manifold, Jetson Nano, or your PC.
Directly connect DJI Manifold, Jetson Nano, or your PC to EP via Wi-Fi connection.
Refer to the example in the
/examples/01_robot/04_ap_conn.py
directory of the SDK code (GitHub RoboMaster SDK repository).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import robomaster
from robomaster import robot
if __name__ == '__main__':
# 如果本地IP 自动获取不正确,手动指定本地IP地址
# robomaster.config.LOCAL_IP_STR = "192.168.2.20"
ep_robot = robot.Robot()
# 指定连接方式为AP 直连模式
ep_robot.initialize(conn_type='ap')
version = ep_robot.get_version()
print("Robot version: {0}".format(version))
ep_robot.close()
|
Execution result:
Robot Version: xx.xx.xx.xx
- USB connection
USB connection: Connect via the USB port on the robot’s smart central control. In this case, the default IP address of the robot is 192.168.42.2.
The USB connection method essentially uses the RNDIS protocol to virtualize the USB device on the robot as a network card. For information about establishing TCP/IP connections to access more RNDIS content through the USB port, refer to RNDIS Wikipedia.
Choose a third-party platform that has a Type-A USB port and supports RNDIS functions. In the following Raspberry Pi connection example, the blue line in the figure indicates the USB connection, and the red line indicates the power-supply line:
Raspberry Pi connection diagram
Refer to the example in the
/examples/01_robot/06_rndis_conn.py
directory of the SDK code (GitHub RoboMaster SDK repository).
1 2 3 4 5 6 7 8 9 10 11 12 13 | import robomaster
from robomaster import robot
if __name__ == '__main__':
ep_robot = robot.Robot()
# 指定连接方式为USB RNDIS模式
ep_robot.initialize(conn_type='rndis')
version = ep_robot.get_version()
print("Robot version: {0}".format(version))
ep_robot.close()
|
Execution result:
Robot Version: xx.xx.xx.xx
- Networking connection
Networking connection: Set the network connection method of the robot to networking and add the computing device and the robot to the same LAN in order to network them.
Turn on the robot and set the connection method switch of the smart central control to the networking mode.
Connect the DJI Manifold, Jetson Nano, or your PC and the EP to the same LAN for EP communication.
Route the DJI Manifold, Jetson Nano, or PC to EP.
Install the myqr library to generate a QR code, press the
Win+R
shortcut command, entercmd
in the window that appears to open the CLI, and then enter the following command on the CLI::pip install myqr
Refer to the example in the
/examples/01_robot/05_sta_conn_helper.py
directory of the SDK code (GitHub RoboMaster SDK repository).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import time
import robomaster
from robomaster import conn
from MyQR import myqr
from PIL import Image
QRCODE_NAME = "qrcode.png"
if __name__ == '__main__':
helper = conn.ConnectionHelper()
info = helper.build_qrcode_string(ssid="RoboMaster_SDK_WIFI", password="12341234")
myqr.run(words=info)
time.sleep(1)
img = Image.open(QRCODE_NAME)
img.show()
if helper.wait_for_connection():
print("Connected!")
else:
print("Connect failed!")
|
警告
In line 13 of the sample code, replace ssid (the router name) and password (the router password) with the actual name and password.
Run the sample code to display the QR code. Then, press the scan button on the smart central control of the robot, and scan the QR code to connect to the network.
Execution result:
Connected!
The light indicator of the robot changes from blinking white to solid turquoise.
小技巧
In networking mode, you can connect to a specified robot by using its SN. To specify the SN of a robot, assign a value to the sn parameter during initialization.
Refer to the example in /examples/01_robot/05_sta_conn_sn.py
(GitHub RoboMaster SDK repository). When sn is not specified, the SDK will establish a connection with the first robot detected by default.
1 2 3 4 5 6 7 8 9 10 11 12 13 from robomaster import robot from robomaster import config if __name__ == '__main__': ep_robot = robot.Robot() # 指定机器人的 SN 号 ep_robot.initialize(conn_type="sta", sn="3JKDH2T001ULTD") ep_version = ep_robot.get_version() print("Robot Version: {0}".format(ep_version)) ep_robot.close()
Connection methods of education-series devices¶
Currently, the main education-series drones are Tello EDU and Tello Talent. The RoboMaster SDK supports connection with these products via Wi-Fi direct connection.
- Wi-Fi direct connection
Wi-Fi direct connection: Set the connection method of the robot to direct connection and connect to the robot’s Wi-Fi hotspot. In Wi-Fi direct connection mode, the default IP address of the robot is 192.168.10.1.
First, set the robot to work in Wi-Fi direct connection mode.
Tello EDU: Short-press the power button indicated by the red arrow in the figure and wait for the yellow light to flash quickly to indicate successful device startup. The factory default connection method of the robot is Wi-Fi direct connection. If the robot is in networking mode after startup, press the power button to reset the Wi-Fi connection. To do this, long-press the power button for five seconds when the robot is on. During this operation, the status indicator will turn off and then flash yellow. When the status indicator flashes yellow quickly, the SSI and password of the Wi-Fi connection will be reset to their factory default settings. By default, there is no password.
Tello Talent:: Turn on the robot and set the mode switch of the extended module to the direct connection mode, as shown in the figure below:
Prepare a device with a Wi-Fi connection function to connect to the Wi-Fi hotspot of the education-series device. This can be a DJI Manifold, Jetson Nano, or your PC.
Refer to the example in the
/examples/12_drone/01_ap_conn.py
directory of the SDK code (GitHub RoboMaster SDK repository).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from robomaster import robot
if __name__ == '__main__':
# 如果本地IP 自动获取不正确,手动指定本地IP地址
# robomaster.config.LOCAL_IP_STR = "192.168.10.22"
tl_drone = robot.Drone()
# 初始化
tl_drone.initialize()
# 获取飞机SDK版本信息
version = tl_drone.get_sdk_version()
print("Drone SDK Version: {0}".format(version))
tl_drone.close()
|
Execution result:
Drone SDK Version: xx.xx.xx.xx
- Networking
Networking mode: Set the robot to work in networking mode and connect to the LAN of the device running the SDK.
- First, set the connection method of the robot to the direct connection mode and connect to the device running the SDK. For details, see the previous section.
- Run the provided
/examples/12_drone/23_set_sta.py
sample program (GitHub RoboMaster SDK repository) and replace the ssis and password parameters in the program with the account and password of the current router.
1 2 3 4 5 6 7 8 9 10 11 12 13 | import robomaster
from robomaster import robot
if __name__ == '__main__':
tl_drone = robot.Drone()
tl_drone.initialize()
# 切换飞行器WiFi模式为组网模式,指定路由器SSID和密码
tl_drone.config_sta(ssid="RoboMaster_SDK_WiFi", password="12341234")
tl_drone.close()
|
- Set the connection method switch of the extended module to the networking mode.Then, the device will automatically connect to the LAN of the specified router.
- Connect the device running the SDK to the same LAN so that the SDK and the device are on the same network.
Communication method¶
Communication method for EP¶
The three methods of connecting the RoboMaster SDK and EP support TCP and UDP communication.
小技巧
Use UDP if the robot needs to control movement in real time, and use TCP if the robot needs to perform event-based control.
Select an appropriate communication method based on your application scenario. For more information about TCP communication, refer to TCP Wikipedia. For more information about UDP communication, refer to UDP Wikipedia.
- TCP communication
- Refer to the example in the
/examples/01_robot/07_tcp_protocol.py
directory of the SDK code (GitHub RoboMaster SDK repository).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import robomaster
from robomaster import robot
if __name__ == '__main__':
ep_robot = robot.Robot()
# 指定连接方式为STA 组网模式, 网络通讯方式 tcp
ep_robot.initialize(conn_type='sta', proto_type='tcp')
version = ep_robot.get_version()
print("Robot Version: {0}".format(version))
ep_robot.close()
|
- Networking connection
Here, you can modify the connect_type parameter in line 8 of the code. sta
corresponds to networking connection, ap
corresponds to Wi-Fi direct connection, and rndis
corresponds to USB connection.
Run the program and obtain the execution result returned.:
Robot Version: xx.xx.xx.xx
- UDP communication
- Refer to the example in the
/examples/01_robot/08_udp_protocol.py
directory of the SDK code (GitHub RoboMaster SDK repository).
1 2 3 4 5 6 7 8 9 10 11 12 | import robomaster
from robomaster import robot
if __name__ == '__main__':
ep_robot = robot.Robot()
# 指定连接方式为AP 直连模式, 网络通讯方式 udp
ep_robot.initialize(conn_type='ap', proto_type='udp')
version = ep_robot.get_version()
print("Robot Version: {0}".format(version))
ep_robot.close()
|
- Perform networking connection
Here, you can modify the connect_type parameter in line 8 of the code. sta
corresponds to networking connection, ap
corresponds to Wi-Fi direct connection, and rndis
corresponds to USB connection.
小技巧
Different communication methods are implemented by modifying the proto_type parameter of the robot.initialize() function in line 8, where tcp
corresponds to TCP communication and udp
corresponds to UDP communication.
Run the program and obtain the execution result returned.:
Robot Version: xx.xx.xx.xx
Communication methods of education-series robots¶
Currently, Tello EDU and Tello Talent support only UDP communication. Therefore, no extra configuration is required.
Getting Started with RoboMaster SDK - Basics¶
What can the SDK do?¶
RoboMaster SDK (hereinafter referred to as the SDK) is a set of development kits for DJI RoboMaster series products. It currently supports products including RoboMaster EP, RoboMaster EP Core, Tello EDU, and Tello Talent. By using the SDK, users can control robot movement on the PC and obtain information from the robot sensors. (To be supplemented?)
Your first SDK program¶
This document explains how to obtain the version number of the SDK to write your first SDK program.
First, import the modules that you need from the installed robomaster package. Here, we will import the version module that contains SDK version information.:
from robomaster import version
Next, obtain the SDK version number from the __version__ attribute in the version module and print the version number.:
sdk_version = version.__version__ print("sdk version:", sdk_version)
Run the program. You will see the printed result:
sdk version: 0.1.1.29
The /examples/00_general/01_sdk_version.py
sample document describes the process of obtaining the SDK version number.
1 2 3 4 5 | from robomaster import version
if __name__ == "__main__":
sdk_version = version.__version__
print("sdk version:", sdk_version)
|
Getting Started with the RoboMaster SDK - EP¶
Initialize the robot¶
Before performing robot-related operations, you must initialize the robot object according to the specified configuration.
First, import the robot module from the installed robomaster package.:
from robomaster import robot
Specify the local IP address of the SDK (if you want to specify it manually). In this example, the retrieved local IP address is 192.168.2.20. (For example, in the Windows operating system, press the Win+R shortcut command and then enter cmd in the window that appears. Enter ipconfig in the window to view the IP address of the device.) To specify the IP address, run the following statement:
robomaster.config.LOCAL_IP_STR = "192.168.2.20"
小技巧
In most cases, the SDK can automatically obtain the correct local IP address, so you do not need to manually specify it. However, when the SDK runs on a device with multiple network cards, the automatically obtained IP address may not be the one used to connect to the robot. In this case, you need to manually specify the IP address.
Create an ep_robot instance object of the Robot class. Here, ep_robot is a robot object.:
ep_robot = robot.Robot()
Initialize the robot. If no input parameters are specified when you call the initialization method, the default connection mode configured in config.py (the Wi-Fi direct connection mode) and the default communication method (UDP communication) are used to initialize the robot. In this example, the connection mode of the robot is manually set to the networking mode. Do not specify the communication method to use the default one.:
ep_robot.initialize(conn_type="sta")
You can set the default connection mode and communication method by running the following statement. In this example, the default connection method is set to sta, and the default communication method is set to tcp.:
config.DEFAULT_CONN_TYPE = "sta" config.DEFAULT_PROTO_TYPE = "tcp"
Now, the initialization of the robot is completed. Then, you can use the robot for information query, motion control, and multimedia use through related interfaces. Later, this document will introduce the use of several types of interfaces.
Obtain module objects¶
Some SDK interfaces belong to the Robot object itself so they can be directly called through the Robot object. However, certain interfaces belong to other modules in the Robot object. For example, the interface for configuring the armored light is in the led module object, and the interface for controlling the chassis is in the chassis module object. To use these interfaces, you must first obtain the corresponding objects. The following uses the led module object as an example to explain how to obtain these objects.
First, initialize the robot object as described in the Initialize the robot section.
You can obtain the led object in two ways.
Method 1: Directly use the . operator to obtain the led object from the Robot() object.:
ep_led = ep_robot.led
Method 2: Use the get_module() method of the Robot object to obtain the specified object.:
ep_led = ep_robot.get_module("led")
After obtaining the object, you can call the SDK interfaces contained in it through the object.
Release robot resources¶
At the end of the program, you need to manually release the resources related to the robot object, including releasing the network address, ending the corresponding background thread, and releasing the corresponding address space. The Robot object provides the close() method for releasing these resources, which can be used as follows.:
ep_robot.close()
小技巧
To avoid unexpected errors, be sure to call the close() method at the end of the program.
Use the query interface¶
The query interface is the data acquisition interface, through which you can obtain the status of the robot and the status of sensors. The following two examples of querying the robot version and querying the robot SN can help you understand the usage of this interface.
Example 1: Query the version number of the robot¶
First, initialize the robot object as described in the Initialize the robot section.
Use the get_version() method of the Robot object. The return value of the method is the version number string of the robot. Print the obtained version number.:
ep_version = ep_robot.get_version() print("Robot Version: {0}".format(ep_version))
Release relevant resources as described in the Release robot resources section.
For the full process, refer to the /examples/01_robot/01_get_version.py
sample file.
1 2 3 4 5 6 7 8 9 10 11 | from robomaster import robot
if __name__ == '__main__':
ep_robot = robot.Robot()
ep_robot.initialize(conn_type="ap")
ep_version = ep_robot.get_version()
print("Robot Version: {0}".format(ep_version))
ep_robot.close()
|
Example 2: Obtain the SN of the robot¶
First, initialize the robot object as described in the Initialize the robot section.
Use the get_sn() method of the Robot object. The return value of the method is the SN string of the robot. Print the obtained SN.:
SN = ep_robot.get_sn() print("Robot SN:", SN)
Release relevant resources as described in the Release robot resources section.
For the full process, refer to the /examples/01_robot/02_get_sn.py
sample file.
1 2 3 4 5 6 7 8 9 10 11 | from robomaster import robot
if __name__ == '__main__':
ep_robot = robot.Robot()
ep_robot.initialize(conn_type="sta")
SN = ep_robot.get_sn()
print("Robot SN:", SN)
ep_robot.close()
|
Use the setup interface¶
The setup interface is used to configure the modules of the robot. This section uses configuring the overall robot movement mode and configuring the robot armored light to explain how to use the setup interface.
Example 1: Configure the overall movement mode of the robot¶
The robot has three movement modes: free mode (FREE), gimbal follows chassis (CHASSIS_LEAD), and chassis follows gimbal (GIMBAL_LEAD). This document sets the movement mode of the robot to chassis follows gimbal (CHASSIS_LEAD) in order to illustrate the use of the setup interface.
First, initialize the robot object as described in the Initialize the robot section.
Use the set_robot_mode() method in the Robot object to set the overall movement mode of the robot. This mode is defined in
/examples/01_robot/02_get_sn.py
. FREE, GIMBAL_LEAD, and CHASSIS_LEAD are the three options for this parameter. In this example, the overall movement mode of the robot is set to chassis follows gimbal (GIMBAL_LEAD).:ep_robot.set_robot_mode(mode=robot.GIMBAL_LEAD)
Release relevant resources as described in the Release robot resources section.
For the full process, refer to the /examples/01_robot/09_set_mode.py
sample file.
1 2 3 4 5 6 7 8 9 10 | from robomaster import robot
if __name__ == '__main__':
ep_robot = robot.Robot()
ep_robot.initialize(conn_type="ap")
ep_robot.set_robot_mode(mode=robot.GIMBAL_LEAD)
ep_robot.close()
|
Example 2: Configure the armored light of the robot¶
The process of configuring the armored light of the robot through the SDK is as follows.
First, initialize the robot object as described in the Initialize the robot section. You also need to import the led module because some definitions for the armored light in this module will be used to configure the light effect.:
from robomaster import led
You must obtain the led object first, because the armored light configuration interface of the robot belongs to the led module contained in the Robot object. Obtain the led object as described in the Obtain module objects section. In this example, method 1 is used to obtain module objects.:
ep_led = ep_robot.led
Use the set_led() method in the led object to configure the armored light effect of the robot. When using the led method, use the comp parameter to select the armored light that you want to control, the r, g, and b parameters to specify the light color, and the effect parameter to specify the lighting effect of the LED light. In this example, all armored lights are selected for control by comp, r, g, and b are set to specify the color red, and solid on is selected as the lighting effect by effect.:
ep_led.set_led(comp=led.COMP_ALL, r=255, g=0, b=0, effect=led.EFFECT_ON)
Release relevant resources as described in the Release robot resources section.
For the full process of configuring the armored light, refer to the /examples/01_robot/09_set_mode.py
sample program.
In this process, the for loop is used to implement 8 color changes of the LED light, each of which lasts for 1 second.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import time
from robomaster import robot
from robomaster import led
if __name__ == '__main__':
ep_robot = robot.Robot()
ep_robot.initialize(conn_type="sta")
ep_led = ep_robot.led
# 设置灯效为常亮,亮度递增
bright = 1
for i in range(0, 8):
ep_led.set_led(comp=led.COMP_ALL, r=bright << i, g=bright << i, b=bright << i, effect=led.EFFECT_ON)
time.sleep(1)
print("brightness: {0}".format(bright << i))
ep_robot.close()
|
Use the action interface¶
The action interface is used to control the robot to perform certain specified actions. Based on the characteristics of actions, the SDK provides two types of action interfaces: instant action control and task action control.
Instant action control¶
Instant control actions are actions that are performed immediately after being configured. Such actions refer to actions that are “instantaneously” performed from an overall perspective. Next, this document will explain how to control the firing of the blaster and control the speed of the chassis to help you understand this action interface.
Example 1: Control the firing of the blaster¶
First, initialize the robot object as described in the Initialize the robot section. You also need to import the blaster module because some definitions for the blaster in this module will be used to control the blaster.:
from robomaster import blaster
The interface for controlling the blaster belongs to the blaster module. Therefore, first obtain the blaster object as described in the Obtain module objects section. This example uses method 1 to obtain module objects.:
ep_blaster = ep_robot.blaster
Use the fire() method in the blaster object to control the firing of the blaster, the fire_type parameter of the method to specify the firing type (which can be water bomb or infrared bomb; water bomb is used in this example), and the times parameter to set the number of times to fire (1 in this example).:
ep_blaster.fire(fire_type=blaster.WATER_FIRE, times=1)
Release relevant resources as described in the Release robot resources section.
For the full process of controlling the firing of the blaster, refer to the examples/06_blaster/01_fire.py
sample program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import time
from robomaster import robot
from robomaster import blaster
if __name__ == '__main__':
ep_robot = robot.Robot()
ep_robot.initialize(conn_type="sta")
ep_blaster = ep_robot.blaster
# 发射1颗水弹
ep_blaster.fire(times=1)
time.sleep(2)
# 发射3颗水弹
ep_blaster.fire(fire_type=blaster.WATER_FIRE, times=3)
time.sleep(2)
# 发射1颗红外子弹
ep_blaster.fire(fire_type=blaster.INFRARED_FIRE)
time.sleep(2)
# 发射3颗红外子弹
ep_blaster.fire(fire_type=blaster.INFRARED_FIRE, times=3)
time.sleep(2)
ep_robot.close()
|
Example 2: Control the speed of the chassis¶
Controlling the speed of the chassis is a typical instant control practice. After a control command is issued, the robot immediately moves at the specified speed.
First, initialize the robot object as described in the Initialize the robot section.
The interface for controlling the chassis belongs to the chassis module. Therefore, first obtain the chassis object as described in the Obtain module objects section. This example uses method 1 to obtain module objects.:
ep_chassis = ep_robot.chassis
Use the drive_speed() method in the chassis object to control the speed of the chassis. The x, y, and z parameters of the method represent the forward, lateral, and rotational speeds respectively. In this example, the x forward speed is set to 0.5 m/s. The timeout parameter is used to specify a timeout period. If no speed control command is received after this period elapses, the SDK instructs the robot to stop. In this example, timeout is set to 5 seconds, and the speed is set to 0 after the robot moves at the specified speed for 3 seconds.:
ep_chassis.drive_speed(x=0.5, y=0, z=0, timeout=5) time.sleep(3) ep_chassis.drive_speed(x=0, y=0, z=0, timeout=5)
Release relevant resources as described in the Release robot resources section.
For the full process of controlling the speed of the chassis, refer to the examples/02_chassis/03_speed.py
sample program.
In this program, the speed of the robot changes every time the robot moves at the specified speed for three seconds.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import time
from robomaster import robot
if __name__ == '__main__':
ep_robot = robot.Robot()
ep_robot.initialize(conn_type="sta")
ep_chassis = ep_robot.chassis
x_val = 0.5
y_val = 0.3
z_val = 30
# 前进 3秒
ep_chassis.drive_speed(x=x_val, y=0, z=0, timeout=5)
time.sleep(3)
# 后退 3秒
ep_chassis.drive_speed(x=-x_val, y=0, z=0, timeout=5)
time.sleep(3)
# 左移 3秒
ep_chassis.drive_speed(x=0, y=-y_val, z=0, timeout=5)
time.sleep(3)
# 右移 3秒
ep_chassis.drive_speed(x=0, y=y_val, z=0, timeout=5)
time.sleep(3)
# 左转 3秒
ep_chassis.drive_speed(x=0, y=0, z=-z_val, timeout=5)
time.sleep(3)
# 右转 3秒
ep_chassis.drive_speed(x=0, y=0, z=z_val, timeout=5)
time.sleep(3)
# 停止麦轮运动
ep_chassis.drive_speed(x=0, y=0, z=0, timeout=5)
ep_robot.close()
|
Task action control¶
Task actions are actions that take a period of time to complete, such as controlling the chassis to move forward by 1 m. In this case, the chassis needs to perform this action for a period of time to reach the specified position. When you use the SDK to control task actions, the SDK sends the task to the robot. After the robot receives the task, it will choose to execute or reject the task (the robot may not be able to execute the task instantly) and notify the SDK. If the robot chooses to execute the task, the SDK will be notified again when the task is completed. When using the task action control interface, pay attention to the following two items:
- The return value of the task action interface is the action object, which provides the wait_for_completed(timeout) method. You can specify the timeout period of the action by using the timeout parameter. When calling the wait_for_completed(timeout) method, the program will be blocked at the statement until the action is completed or the execution times out.
- A single module can perform only one action at a time, so tasks of the same module are mutually exclusive. Different modules are independent of each other, so their actions can be performed simultaneously. For example, if you do not call the wait_for_completed() method immediately after using the task action control interface, you can control the chassis to move to the specified position while controlling the gimbal to rotate to the specified angle. However, you cannot send another task action to control the gimbal until the previous task action for the gimbal is completed.
小技巧
If you do not call the wait_for_completed() method immediately after using the task action control interface, be sure to control the logic in the program to avoid sending other task action commands that are mutually exclusive with the ongoing task.
Next, this document will explain how to control the chassis to move a specified distance to show you how to use this interface.
Example 1: Control the chassis to move a specified distance¶
Controlling the chassis to move a specified distance is a task action control scenario.
First, initialize the robot object as described in the Initialize the robot section.
The interface for controlling the chassis belongs to the chassis module. Therefore, first obtain the chassis object as described in the Obtain module objects section. In this example, you also need to obtain the led module because you will also control the armored light. This example uses method 1 to obtain module objects.:
ep_chassis = ep_robot.chassis ep_led = ep_robot.led
In this example, in order to demonstrate the characteristics of task actions, the armored light effect will be configured after you control the movement of the chassis. Use the move() method in the chassis object to control the relative movement of the chassis. The x and y parameters of the method represent the movement distance of the x-axis and that of the y-axis, respectively. The z parameter indicates the rotation speed of the z-axis. In this example, the movement distance of the x-axis is set to 0.5 m, and the y and z parameters are set to 0. You can use the xy_speed parameter to specify the movement speed along the x- and y-axes, and use the z_speed parameter to specify the rotation speed of the z-axis. In this example, the movement speeds of the x- and y-axes are both set to 0.7 m/s, and the rotation speed of the z-axis is set to 0. To set the armored light effect, refer to Example 2: Configure the armored light of the robot. Next, we will use three methods to control the task actions for chassis movement.:
Method 1: After performing the task action, call the wait_for_completed() method immediately.:
ep_chassis.move(x=x_val, y=0, z=0, xy_speed=0.7).wait_for_completed() ep_led.set_led(comp=led.COMP_ALL, r=255, g=0, b=0, effect=led.EFFECT_ON)
Method 2: Call the wait_for_completed() method after executing other commands.:
chassis_action = ep_chassis.move(x=x_val, y=0, z=0, xy_speed=0.7) ep_led.set_led(comp=led.COMP_ALL, r=255, g=0, b=0, effect=led.EFFECT_ON) chassis_action.wait_for_completed()
Method 3: Do not use the wait_for_completed() method, but use delay to ensure the completion of the action.:
ep_chassis.move(x=x_val, y=0, z=0, xy_speed=0.7) ep_led.set_led(comp=led.COMP_ALL, r=255, g=0, b=0, effect=led.EFFECT_ON) time.sleep(10)
The three calling mechanisms of the task action interface correspond to different behaviors of the robot. In method 1, the robot moves to the specified position and then sets the armored light to solid red. In method 2 and method 3, the armored light will be solid red during the movement.
小技巧
We recommend that you use method 1 and method 2, because it is less risky to call wait_for_completed() at an appropriate time.
- Release relevant resources as described in the Release robot resources section.
For the full process of controlling the chassis to move a specified distance, refer to the examples/02_chassis/01_move.py
sample program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | from robomaster import robot
if __name__ == '__main__':
ep_robot = robot.Robot()
ep_robot.initialize(conn_type="sta")
ep_chassis = ep_robot.chassis
x_val = 0.5
y_val = 0.6
z_val = 90
# 前进 0.5米
ep_chassis.move(x=x_val, y=0, z=0, xy_speed=0.7).wait_for_completed()
# 后退 0.5米
ep_chassis.move(x=-x_val, y=0, z=0, xy_speed=0.7).wait_for_completed()
# 左移 0.6米
ep_chassis.move(x=0, y=-y_val, z=0, xy_speed=0.7).wait_for_completed()
# 右移 0.6米
ep_chassis.move(x=0, y=y_val, z=0, xy_speed=0.7).wait_for_completed()
# 左转 90度
ep_chassis.move(x=0, y=0, z=z_val, z_speed=45).wait_for_completed()
# 右转 90度
ep_chassis.move(x=0, y=0, z=-z_val, z_speed=45).wait_for_completed()
ep_robot.close()
|
Use the multimedia interface¶
The multimedia interface is mainly used to obtain video streams and audio streams. The following two examples demonstrate how to use this interface.
Example 1: Obtain video streams¶
Obtaining video streams collected by the robot is very useful for implementing certain practical scenarios. The process of obtaining video streams through the SDK is as follows.
First, initialize the robot object as described in the Initialize the robot section. You also need to import the camera module because the definition of the camera module will be used in the example.:
from robomaster import camera
The interface for obtaining video streams belongs to the camera module. Therefore, first obtain the camera object as described in the Obtain module objects section. In this example, the method described in the Obtain module objects section is used to obtain module objects.:
ep_camera = ep_robot.camera
The start_video_stream method of the camera module has two parameters. The display parameter specifies whether to display the obtained video streams. The resolution parameter specifies the size of the video. This example describes two ways to obtain the video stream.
Method 1: Obtain the video stream and play it directly for 10 seconds.:
ep_camera.start_video_stream(display=True, resolution=camera.STREAM_360P) time.sleep(10) ep_camera.stop_video_stream()
Method 2: Obtain the video stream and display 200 image frames by using the method provided by cv2.:
ep_camera.start_video_stream(display=False) for i in range(0, 200): img = ep_camera.read_cv2_image() cv2.imshow("Robot", img) cv2.waitKey(1) cv2.destroyAllWindows() ep_camera.stop_video_stream()
Method 1 directly uses the start_video_stream() method of the camera object to obtain and play the video stream collected by the robot through the SDK. Method 2 obtains the video stream by using the start_video_stream method of the camera object and then plays the obtained video stream by using cv2.inshow().
Release relevant resources as described in the Release robot resources section.
For the full process of obtaining and then directly displaying the video scream, refer to the examples/04_camera/01_video_with_display.py
sample program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import time
from robomaster import robot
from robomaster import camera
if __name__ == '__main__':
ep_robot = robot.Robot()
ep_robot.initialize(conn_type="sta")
ep_camera = ep_robot.camera
# 显示十秒图传
ep_camera.start_video_stream(display=True, resolution=camera.STREAM_360P)
time.sleep(10)
ep_camera.stop_video_stream()
ep_robot.close()
|
For the full process of obtaining the video stream and then displaying images by using the method provided by cv2, refer to the examples/04_camera/03_video_without_display.py
sample program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import cv2
from robomaster import robot
if __name__ == '__main__':
ep_robot = robot.Robot()
ep_robot.initialize(conn_type="sta")
ep_camera = ep_robot.camera
# 显示200帧图传
ep_camera.start_video_stream(display=False)
for i in range(0, 200):
img = ep_camera.read_cv2_image()
cv2.imshow("Robot", img)
cv2.waitKey(1)
cv2.destroyAllWindows()
ep_camera.stop_video_stream()
ep_robot.close()
|
Example 2: Obtain the audio stream¶
This example shows how to obtain the audio stream collected by the robot through the SDK, and then locally save the obtained audio stream as a wav file.
First, initialize the robot object as described in the Initialize the robot section.
The interface for obtaining video streams belongs to the camera module. Therefore, first obtain the camera object as described in the Obtain module objects section. In this example, the method described in the Obtain module objects section is used to obtain module objects.:
ep_camera = ep_robot.camera
Save the obtained audio stream locally by calling the record_audio() method of the camera module. The save_file parameter of the method specifies the name of the saved file, the seconds parameter specifies the duration of the collected audio stream, and the sample_rate parameter specifies the collection frequency.:
ep_camera.record_audio(save_file="output.wav", seconds=5, sample_rate=16000)
Release relevant resources as described in the Release robot resources section.
For the full process of obtaining and then locally saving the audio stream, refer to the examples/04_camera/05_record_audio.py
sample program.
1 2 3 4 5 6 7 8 9 10 11 | from robomaster import robot
if __name__ == '__main__':
ep_robot = robot.Robot()
ep_robot.initialize(conn_type="rndis")
ep_camera = ep_robot.camera
ep_camera.record_audio(save_file="output.wav", seconds=5, sample_rate=16000)
ep_robot.close()
|
Getting Started with the RoboMaster SDK - Education-series Drones¶
Initialize the robot¶
Before performing robot-related operations, you must initialize the robot object according to the specified configuration.
First, import the robot module from the installed robomaster package.:
from robomaster import robot
Specify the local IP address of the SDK (if you want to specify it manually). In this example, the retrieved local IP address is 192.168.2.20. (For example, in the Windows operating system, press the Win+R shortcut command and then enter cmd in the window that appears. Enter ipconfig in the window to view the IP address of the device.) To specify the IP address, run the following statement:
robomaster.config.LOCAL_IP_STR = "192.168.2.20"
小技巧
In most cases, the SDK can automatically obtain the correct local IP address, and you do not need to manually specify it. However, when the SDK runs on a device with multiple network cards, the automatically obtained IP address may not be the one used to connect to the robot. In this case, you need to manually specify the IP address.
Create a tl_drone instance object of the Drone class. Here, tl_drone is a robot object.:
tl_drone = robot.Drone()
Initialize the robot object. Currently, no input parameters are required for the initialization of education-series drones.:
tl_drone.initialize()
Now, the initialization of the robot is completed. Then, you can use the robot for information query, motion control, and multimedia use through related interfaces. Later, this document will introduce the use of several types of interfaces.
Obtain module objects¶
Some SDK interfaces belong to the Drone object itself so they can be directly called through the Drone object. However, certain interfaces belong to other modules in the Drone object. For example, the interface for obtaining information about the drone battery is in the led module object, and the interface for controlling the drone is in the flight module object. To use these interfaces, you must first obtain the corresponding objects. The following uses the flight module object as an example to explain how to obtain these objects.
First, initialize the robot object as described in the Initialize the robot section.
You can obtain the flight object in two ways.
Method 1: Directly use the . operator to obtain the flight object from the Drone() object.:
tl_flight = tl_drone.flight
Method 2: Use the get_module() method of the Drone object to obtain the specified object.:
tl_flight = tl_drone.get_module("flight")
After obtaining the object, you can call the SDK interfaces contained in it through the object.
Release robot resources¶
At the end of the program, you need to manually release the resources related to the robot object, including releasing the network address, ending the corresponding background thread, and releasing the corresponding address space. The Drone object provides the close() method for releasing these resources, which can be used as follows.:
tl_drone.close()
小技巧
To avoid unexpected errors, be sure to call the close() method at the end of the program.
Use the query interface¶
The query interface is the data acquisition interface, through which you can obtain the status of the robot and the status of sensors. The following two examples of querying the SDK firmware version and querying the robot SN can help you understand the usage of this interface.
Example 1: Query the firmware SDK version number of the robot¶
First, initialize the robot object as described in the Initialize the robot section.
Use the get_sdk_version() method of the Drone object. The return value of the method is the version number string of the robot SDK firmware. Print the obtained version number.:
drone_version = tl_drone.get_sdk_version() print("Drone sdk version: {0}".format(drone_version))
Release relevant resources as described in the Release robot resources section.
For the full process, refer to the /examples/12_drone/02_get_version.py
sample file.
1 2 3 4 5 6 7 8 9 10 11 12 13 | import robomaster
from robomaster import robot
if __name__ == '__main__':
tl_drone = robot.Drone()
tl_drone.initialize()
# 获取飞机版本信息
drone_version = tl_drone.get_sdk_version()
print("Drone sdk version: {0}".format(drone_version))
tl_drone.close()
|
Example 2: Obtain the SN of the robot¶
First, initialize the robot object as described in the Initialize the robot section.
Use the get_sn() method of the Drone object. The return value of the method is the SN string of the robot. Print the obtained SN.:
SN = tl_drone.get_sn() print("drone sn: {0}".format(SN))
Release relevant resources as described in the Release robot resources section.
For the full process, refer to the /examples/12_drone/03_get_sn.py
sample file.
1 2 3 4 5 6 7 8 9 10 11 12 13 | import robomaster
from robomaster import robot
if __name__ == '__main__':
tl_drone = robot.Drone()
tl_drone.initialize()
# 获取飞机SN信息
SN = tl_drone.get_sn()
print("drone sn: {0}".format(SN))
tl_drone.close()
|
Use the setup interface¶
The setup interface is used to configure the modules of the robot. This section uses the extended LED module as an example to explain how to use the setup interface.
小技巧
Currently, configuring extended LED lights is only supported by Tello Talent devices.
Example 1: Configure the extended LED module of the robot¶
The process of configuring the extended LED module of the robot through the SDK is as follows.
First, initialize the robot object as described in the Initialize the robot section.
You must obtain the led object first, because the armored light configuration interface of the robot belongs to the led module contained in the Drone object. Obtain the led object as described in the Obtain module objects section. In this example, method 1 is used to obtain module objects.:
tl_led = tl_robot.led
Use the set_led() method in the led object to configure the extended LED lighting effect of the robot. When using the led method, you can use the r, g, and b parameters to specify the LED color. In this example, the color is specified as red.:
tl_led.set_led(r=255, g=0, b=0)
Release relevant resources as described in the Release robot resources section.
For the full process of configuring the armored light, refer to the /examples/12_drone/20_led.py
sample program.
In this process, the for loop is used to implement 8 color changes of the LED light, each of which lasts for 0.5 seconds.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import time
import robomaster
from robomaster import robot
if __name__ == '__main__':
tl_drone = robot.Drone()
tl_drone.initialize()
tl_led = tl_drone.led
tl_led.set_led(r=0, g=0, b=0)
rgb_list = [(100, 100, 100), (255, 255, 255), (255, 0, 0), (0, 0, 255),
(0, 255, 0), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
for rgb_info in rgb_list:
tl_led.set_led(r=rgb_info[0], g=rgb_info[1], b=rgb_info[2])
time.sleep(0.5)
tl_drone.close()
|
Use the action interface¶
The action interface is used to control the robot to perform certain specified actions. Based on the characteristics of actions, the SDK provides two types of action interfaces: instant action control and task action control. Due to their characteristic, drones must take off before they can be controlled. Therefore, this document will first introduce the task action control interface. After you are familiar with the flight actions, we will introduce the usage of the instant action control interface.
Task action control¶
Task actions are actions that take a period of time to complete, such as controlling the chassis to move forward by 1 m. In this case, the chassis needs to perform this action for a period of time to reach the specified position. When you use the SDK to control task actions, the SDK sends the task to the robot. After the robot receives the task, it will choose to execute or reject the task (the robot may not be able to execute the task instantly) and notify the SDK. If the robot chooses to execute the task, the SDK will be notified again when the task is completed. When using the task action control interface, pay attention to the following two items:
- The return value of the task action interface is the action object, which provides the wait_for_completed(timeout) method. You can specify the timeout period of the action by using the timeout parameter. When calling the wait_for_completed(timeout) method, the program will be blocked at the statement until the action is completed or the execution times out.
- A single module can perform only one action at a time, so tasks of the same module are mutually exclusive. Different modules are independent of each other, so their actions can be performed simultaneously. For example, if you do not call the wait_for_completed() method immediately after using the task action control interface, you can control the chassis to move to the specified position while controlling the gimbal to rotate to the specified angle. However, you cannot send another task action to control the gimbal until the previous task action for the gimbal is completed.
小技巧
If you do not call the wait_for_completed() method immediately after using the task action control interface, be sure to control the logic in the program to avoid sending other task action commands that are mutually exclusive with the ongoing task.
Next, this document will explain how to control the chassis to move a specified distance to show you how to use this interface.
Example 1: Control the drone to take off and fly back and forth¶
In this example, you first need to control the drone to take off and then move it forward 50 cm.
First, initialize the robot object as described in the Initialize the robot section.
The flight control interface belongs to the flight module. Therefore, first obtain the flight object as described in the Obtain module objects section. In this example, you also need to obtain the led module because you will control the extended LED module as well. This example uses method 1 to obtain module objects.:
tl_flight = tl_drone.flight tl_led = tl_drone.led
Next, have the drone take off. During this process, call the wait_for_completed() method in the action object returned by the task action interface to block the program until takeoff is completed.:
tl_flight.takeoff().wait_for_completed()
Then, control the drone to move forward 50 cm. In this example, the extended LED lighting effect will be configured after the vehicle takes off to demonstrate the characteristics of task actions. Use the forward() method in the flight object to control the forward movement of the chassis. This method uses only one parameter (distance) to specify the flight distance. To configure the extended LED module, see Example 1: Configure the extended LED module of the robot. Next, this document will explain how to use the task action interface in three ways.
Method 1: After performing the task action, call the wait_for_completed() method immediately.:
tl_flight.forward(distance=50).wait_for_completed() tl_led.set_led(r=255, g=0, b=0)
Method 2: Call the wait_for_completed() method after executing other commands.:
flight_action = tl_flight.forward(distance=50) tl_led.set_led(r=255, g=0, b=0) flight_action.wait_for_completed()
Method 3: Do not use the wait_for_completed() method, but use delay to ensure the completion of the action.:
flight_action = tl_flight.forward(distance=50) tl_led.set_led(r=255, g=0, b=0) time.sleep(8)
The calling mechanisms of the task action interface in the three methods correspond to different behaviors of the robot. In method 1, the robot moves forward to the specified position and then sets the LED color of the extended LED module to red. In method 2 and method 3, the LED color of the extended LED module is set to red while the vehicle is moving forward.
注解
In method 2 and method 3, be sure not to use other interfaces whose ack is ok/error during the flight. For information about the ack object of the robot, refer to “Tello SDK Instructions”.
小技巧
We recommend that you use method 1 and method 2, because it is less risky to call wait_for_completed() at an appropriate time.
Land the drone:
tl_flight.land().wait_for_completed()
Release relevant resources as described in the Release robot resources section.
For the full process of controlling the chassis to move forward and backward 50 cm, refer to the examples/12_drone/07_forward_backward.py
sample program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import robomaster
from robomaster import robot
if __name__ == '__main__':
tl_drone = robot.Drone()
tl_drone.initialize()
tl_flight = tl_drone.flight
# 起飞
tl_flight.takeoff().wait_for_completed()
# 向前飞50厘米,向后飞50厘米
tl_flight.forward(distance=50).wait_for_completed()
tl_flight.backward(distance=50).wait_for_completed()
# 降落
tl_flight.land().wait_for_completed()
tl_drone.close()
|
Instant action control¶
Instant control actions are actions that are performed immediately after being configured. Such actions refer to actions that are “instantaneously” performed from an overall perspective. Next, this document will explain how to control the remote control stick to help you understand this action interface.
Example 1: Control the remote control stick movement¶
Controlling the remote control stick movement is a typical instant control practice. After a control command is issued, the robot immediately flies at the specified speed and direction.
First, initialize the robot object as described in the Initialize the robot section.
The flight control interface belongs to the flight module. Therefore, first obtain the flight object as described in the Obtain module objects section. This example uses method 1 to obtain module objects.:
tl_flight = tl_drone.flight
Next, have the drone take off. During this process, call the wait_for_completed() method in the action object returned by the task action interface to block the program until takeoff is completed.:
tl_flight.takeoff().wait_for_completed()
Then, control the drone to move leftward at the specified speed for three seconds and then stop. Use the rc() method in the flight object to control the forward movement of the chassis. This is done by controlling the four speed parameters: roll, pitch, accelerate, and yaw. For details about these parameters, refer to the API documentation. In this example, set the value of the a roll parameter to 20 in order to move the drone leftward. Then, set all speed parameters to 0 after 3 seconds to stop the flight.:
tl_flight.rc(a=20, b=0, c=0, d=0) time.sleep(4)
Land the drone:
tl_flight.land().wait_for_completed()
Release relevant resources as described in the Release robot resources section.
For the full process of controlling the flight of the vehicle by controlling remote control stick movements, refer to the examples/12_drone/13_rc.py
sample program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import time
import robomaster
from robomaster import robot
if __name__ == '__main__':
tl_drone = robot.Drone()
tl_drone.initialize()
tl_flight = tl_drone.flight
# 起飞
tl_flight.takeoff().wait_for_completed()
# 左移
tl_flight.rc(a=20, b=0, c=0, d=0)
time.sleep(4)
# 右移
tl_flight.rc(a=-20, b=0, c=0, d=0)
time.sleep(3)
# 停止
tl_flight.rc(a=0, b=0, c=0, d=0)
# 降落
tl_flight.land().wait_for_completed()
tl_drone.close()
|
Use the multimedia interface¶
The primary multimedia application of education-series drones is obtaining video streams.
Example 1: Obtain video streams¶
Obtaining video streams collected by the robot is very useful for implementing certain practical scenarios. The process of obtaining video streams through the SDK is as follows.
First, initialize the robot object as described in the Initialize the robot section. You also need to import the camera module because the definition of the camera module will be used in the example.:
from robomaster import camera
The interface for obtaining video streams belongs to the camera module. Therefore, first obtain the camera object as described in the Obtain module objects section. In this example, the method described in the Obtain module objects section is used to obtain module objects.:
tl_camera= tl_robot.camera
The start_video_stream method of the camera module has two parameters. The display parameter specifies whether to display the obtained video streams. The following example describes two video stream acquisition methods.
Method 1: Obtain the video stream and play it directly for 10 seconds.:
tl_camera.start_video_stream(display=True) time.sleep(10) tl_camera.stop_video_stream()
Method 2: Obtain the video stream and display 200 image frames by using the method provided by cv2.:
tl_camera.start_video_stream(display=False) for i in range(0, 200): img = tl_camera.read_cv2_image() cv2.imshow("Drone", img) cv2.waitKey(1) cv2.destroyAllWindows() tl_camera.stop_video_stream()
Method 1 directly uses the start_video_tream() method of the camera object to obtain and play the video stream collected by the robot through the SDK. Method 2 obtains the video stream by using the start_video_stream method of the camera object and then plays the obtained video stream by using cv2.inshow().
Release relevant resources as described in the Release robot resources section.
For the full process of obtaining the video stream and then displaying images by using the method provided by cv2, refer to the examples/04_camera/01_video_with_display.py
sample program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | from robomaster import robot
if __name__ == '__main__':
tl_drone = robot.Drone()
tl_drone.initialize()
tl_camera = tl_drone.camera
# 显示302帧图传
tl_camera.start_video_stream(display=False)
tl_camera.set_fps("high")
tl_camera.set_resolution("high")
tl_camera.set_bitrate(6)
for i in range(0, 302):
img = tl_camera.read_cv2_image()
cv2.imshow("Drone", img)
cv2.waitKey(1)
cv2.destroyAllWindows()
tl_camera.stop_video_stream()
tl_drone.close()
|
Getting Started with the RoboMaster SDK - Multi-device Control¶
Introduction to multi-device control¶
The RoboMaster SDK supports multi-device control. By calling corresponding multi-device interfaces, you can easily control multiple devices in order to perform complex multi-device formations and other tasks.
Multi-device control process¶
Multi-device control mainly consists of the following processes:
- Multi-device initialization: Establish a connection with multiple devices in the LAN and initialize relevant robots.
- Multi-device numbering: Number drones by their SNs to facilitate the selection and control of multiple devices.
- Multi-device grouping and Group control: Group multiple devices to facilitate multi-device selection.
- Task control: Control different groups to perform different actions simultaneously through task control.
The following sections describe each of those processes.
Multi-device initialization¶
Install the netifaces package for environment preparation.:
pip install netifaces
小技巧
If the following error occurs, download and install visualcppbuildtools_full.exe (from the GitHub RoboMaster SDK repository) instead.

1. First, set the robot to work in router networking mode. Then, connect all robots and the device running the RoboMaster SDK to the same LAN. For details, refer to EP connection method for RoboMaster EP and Connection methods of education-series devices for education-series drones.
Import the packages related to multi-device control.:
from multi_robomaster import multi_robot
Generate multi-device objects
Example 1: Generate a multi-device object for EP robots:
multi_robot = multi_robot.MultiEP()Example 2: Generate a multi-device object for education-series robots:
multi_drones = multi_robot.MultiDrone()
4. Call the multi-device initialization function to complete the multi-device scanning and initialization steps. The initialization function for EP multi-device control does not require any input parameters. The multi-device initialization function for education-series drones requires you to specify the number of vehicles to be scanned for.
Example 1: Initialize the multi-device object for EP robots:
multi_robots.initialize()Example 2: Initialize the multi-device object for 2 education-series drones:
multi_drones.initialize(2)
注解
Take note of the difference in multi-device initialization between EP robots and education-series robots.
Multi-device numbering¶
Number the robots to facilitate multi-device control. The currently supported numbering method is to bind a robot with a number based on the entered SN. The numbering methods for multi-device objects are described below.:
number_id_by_sn([id1, SN1], [id2, SN2], [id2, SN3] ...)
The method parameter is an array of robot number information, with each element in the array consisting of two items: [id, SN]. The first item is the desired ID, and the other item is the robot SN string. The number of elements is the number of devices that the user needs to number. The return value of this method is the number of successfully numbered devices.
The following example of EP multi-device numbering will help you understand how to use this function. The multi-device numbering process for education-series devices is similar to that for EP devices.
Example 1: Assume that two EP robots need to be numbered and the multi_robots multi-device object has been created and initialized. Now, you want to number the robot with the SN 3JKDH2T001ULTD as robot 0 and the robot with the SN 3JKDH3B001NN0E as robot 1. To do this, execute the following statement::
multi_robots.number_id_by_sn([0, '3JKDH2T001ULTD'], [1, '3JKDH3B001NN0E'])
Multi-device grouping and group control¶
By grouping robots, you can easily implement multi-device control. During control, the call method of the control interface for a group object is similar to that for a standalone device. In most control situations, you can think of a group object as a standalone object.
Generate a group object¶
You can use the array of robot number information pairs (see the previous section for multiple-device numbering) to generate a group object containing multiple robots. In this way, operations on this group object act on each robot in the group. Multi-device objects support the following interface for creating group objects::
build_group(robot_id_list)
The input parameter of the method is a list of ID information of the robots that need to be grouped, and the return value of the method is the created group object. The following example explains how to group EP devices. The grouping method for education-series robots is similar to this method.
Example 1: Assume that there are three EP robots and the previous steps have been completed. The numbers of these robots are 0, 1, and 2. Now, you want to place robots 0 and 1 into a group, robot 2 into another group, and all three robots in a third group. To do this, execute the following statements::
robot_group1 = multi_robots.build_group([0, 1]) robot_group2 = multi_robots.build_group([2]) robot_group_all = multi_robots.build_group([0, 1, 2])After running the code above, the created robot_group1 object is the group object containing robots 0 and 1. The created robot_group2 object is the group object containing robot 2. The created robot_group_all object is the group object containing all three robots. Then, you can use these group objects to control the robots they contain to have them execute the same commands.
Task control¶
The previous section explained how to perform simple group control with group objects. However, you may also want to make different groups perform different actions at the same time and ensure synchronization when different groups perform tasks simultaneously. This section explains how to use the task control method for multi-device objects. In this case, the required interface is as follows::
run([robot_group1, action_task1], [robot_group2, action_task2], [robot_group3, action_task3]...)
Through this interface, you can make different groups perform different actions at the same time. The run method ensures that all action tasks input by the method are performed when the statement is fully executed. The input parameter of the run interface is an array of task information. Each element in the array consists of two items: the group object that will perform the task and the task function written by the user. User-defined task functions must meet certain interface development conditions. That is, each task function has only one parameter, which is the group object that executes the action in the function. The following example explains how to use the control interface for EP robots. The process for education-series robots is similar to the process in this example.
Example 1: Assume that three robot group objects have been obtained by completing the previous steps. Specifically, these group objects are robot_group1 containing robots 0 and 1, robot_group2 containing robot 2, and robot_group_all containing robots 1, 2, and 3. Now, you want to instruct the chasses of the two robots in robot_group1 to move forward 1 meter, instruct the only robot in robot_group2 to move backward 1 meter, and instruct the three robots to move leftward 1 meter after completing the prior two task actions. To do this, you can use the following method.
First, define task functions for the three actions.:
def move_forward_task(robot_group): robot_group.chassis.move(x=1, y=0, z=0, xy_speed=0.7).wait_for_completed() def move_backward_task(robot_group): robot_group.chassis.move(x=-1, y=0, z=0, xy_speed=0.7).wait_for_completed() def move_left_task(robot_group): robot_group.chassis.move(x=0, y=-1, z=0, xy_speed=0.7).wait_for_completed()Then, use the run() method of the multi_robots multi-device object to specify group objects to perform these tasks.:
# Move the chasses of robots `0` and `1` forward 1 meter and move robot `2` backward 1 meter. multi_robots.run([robot_group1, move_forward_task], [robot_group2, move_backward_task]) # Move the chasses of all three robots leftward 1 meter. multi_robots.run([robot_group_all, move_left_task])
注解
User-defined action task functions must meet the interface development conditions.
Logging for the RoboMaster SDK¶
Configure the log level¶
The default log level of the RoboMaster SDK is ERROR. Users can change it as needed.
The statement for setting the log level in
/examples/01_robot/00_logger.py
is as follows::logger.setLevel(logging.ERROR)
You can change it to this statement based on their needs::
logger.setLevel(logging.WARNING)
You can also change the statement to the following::
logger.setLevel(logging.INFO)
Use log files¶
If users encounter a problem during use, they need to write the log to a file and provide the log file to technical support personnel.
Generation method of log files
Add this statement at the beginning of the program::
robomaster.enable_logging_to_file()
Run the program.
The SDK will automatically generate a system log file and store it in a directory at the same level as the program. The name format of log files is as follows::
RoboMasterSDK_YYYYMMDDHHMMSS_log.txt
Send the generated system log file to developer@dji.com by using this email template::
xxxxxxxx xxxxxxxx xxxxxxxx
Sample code
- Refer to the example in the
/examples/01_robot/00_logger.py
directory of SDK code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import robomaster
from robomaster import robot
if __name__ == '__main__':
robomaster.enable_logging_to_file()
# 如果本地IP 自动获取不正确,手动指定本地IP地址
# robomaster.config.LOCAL_IP_STR = "192.168.2.20"
ep_robot = robot.Robot()
# 指定连接方式为AP 直连模式
ep_robot.initialize(conn_type='rndis')
version = ep_robot.get_version()
print("Robot version: {0}".format(version))
ep_robot.close()
|
After running the program, the SDK will automatically generate a system log file in a directory at the same level as the program, as shown in the figure below:
RoboMaster SDK APIs¶
List of APIs
Detailed Description of RoboMaster SDK APIs¶
robomaster package¶
robomaster.action¶
-
class
robomaster.action.
Action
(**kw)¶ 基类:
object
-
wait_for_completed
(timeout=None)¶ 等待任务动作直到完成
参数: timeout – 超时,在timeout前未完成任务动作,直接返回 返回: bool: 动作在指定时间内完成,返回True; 动作超时返回False
-
robomaster.armor¶
-
class
robomaster.armor.
Armor
(robot)¶ 基类:
robomaster.module.Module
-
static
comp2id
(comp)¶ 装甲部位转换为装甲ID
参数: comp – enum (“bottom_back”, “bottom_front”, “bottom_left”, “bottom_right”, “top_left”, “top_right”) 装甲部位 返回: int: [1, 6] 装甲ID
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
static
id2comp
(armor_id)¶ 装甲ID转换为装甲部位
参数: armor_id – int [1, 6],装甲ID Return comp: enum: (“bottom_back”, “bottom_front”, “bottom_left”, “bottom_right”, “top_left”, “top_right”), 装甲部位
-
set_hit_sensitivity
(comp='all', sensitivity=5)¶ 设置装甲灵敏度
参数: - comp – enum:(“all”, “top_all”, “bottom_all”, “top_left”, “top_right”, “bottom_left”, “bottom_right”, “bottom_front”, “bottom_back”):要设置的装甲部位
- sensitivity – int:[0, 10] 灵敏度系数,系数越大灵敏度越低
返回: bool:返回调用结果
-
sub_hit_event
(callback=None, *args, **kw)¶ 打击事件订阅
参数: - callback –
回调函数, 返回数据 (armor_id, hit_type):
param armor_id: int:[1, 6]打击装甲的编号,1 底盘后;2 底盘前;3 底盘左;4 底盘右;5 云台左;6 云台右 param hit_type: enum:(“water”, “ir”),被打击类型,water:水弹,ir:红外 - args – 可变参数
- kw – 关键字参数
返回: bool: 事件订阅结果
- callback –
-
sub_ir_event
(callback=None, *args, **kw)¶ 红外打击事件订阅
参数: - callback – 回调函数, 返回数据 (hit_cnt)
- hit_cnt – 受到红外击打的次数
- args – 可变参数
- kw – 关键字参数
返回: bool: 事件订阅结果
-
unsub_hit_event
()¶ 取消打击事件订阅
返回: bool: 取消事件订阅结果
-
unsub_ir_event
()¶ 取消红外打击事件订阅
返回: bool: 取消事件订阅结果
-
static
robomaster.battery¶
-
class
robomaster.battery.
Battery
(robot)¶ 基类:
robomaster.module.Module
EP 电池模块
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
sub_battery_info
(freq=5, callback=None, *args, **kw)¶ 订阅电池信息
参数: - freq – enum:(1,5,10,20,50) 设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 percent:
percent: 电池电量百分比 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
unsub_battery_info
()¶ 取消电池订阅
返回: bool: 取消订阅结果
-
-
class
robomaster.battery.
TelloBattery
(robot)¶ 基类:
object
教育无人机 电池模块
-
get_battery
()¶ 获取电池电量信息
返回: int: 电池的剩余电量百分比
-
sub_battery_info
(freq=5, callback=None, *args, **kw)¶ 订阅电池信息
参数: - freq – enum:(1,5,10) 设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 percent:
percent: 电池电量百分比 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
unsub_battery_info
()¶ 取消订阅飞机电池信息
返回: 返回取消订阅结果
-
robomaster.blaster¶
-
class
robomaster.blaster.
Blaster
(robot)¶ 基类:
robomaster.module.Module
EP 发射器模块
-
fire
(fire_type='water', times=1)¶ 发射器发射
参数: - fire_type – enum: (“water”, “ir”), 发射器发射类型,水弹、红外弹
- times – 发射次数
返回: bool: 调用结果
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
set_led
(brightness=255, effect='on')¶ 设置发射器灯效
参数: - brightness – int:[0,255],亮度
- effect – enum:(“on”, “off”),on 表示常亮,off 表示常灭
返回: bool:调用结果
-
robomaster.camera¶
-
class
robomaster.camera.
EPCamera
(robot)¶ 基类:
robomaster.module.Module
,robomaster.camera.Camera
EP 摄像机模块
-
audio_stream_addr
¶ 机器人音频流地址
返回: tuple:(ip, port),机器人音频流地址
-
conf
¶ 相机参数配置
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
read_audio_frame
(timeout=1)¶ 读取一段音频流信息
参数: timeout – float: (0, inf),超时时间,超过指定timeout时间后函数返回 返回: data, 已解码的音频流帧字节流
-
read_cv2_image
(timeout=3, strategy='pipeline')¶ 读取一帧视频流帧
参数: - timeout – float: (0, inf),超时参数,在timeout时间内未获取到视频流帧,函数返回
- strategy – enum: (“pipeline”, “newest”),读取帧策略:pipeline 依次读取缓存的帧信息,newest 获取最新的一帧 数据,会清空旧的数据帧
返回: image
-
read_video_frame
(timeout=3, strategy='pipeline')¶ 读取一帧视频流帧
参数: - timeout – float: (0, inf),超时时间,超过指定timeout时间后函数返回
- strategy – enum: (“pipeline”, “newest”) 读取帧策略:pipeline 流水线依次读取,newest 获取最新的一帧数据, 注意会清空老的数据帧队列
返回: frame, 已解码的视频流帧字节流
-
record_audio
(save_file='output.wav', seconds=5, sample_rate=48000)¶ 录制音频,保存到本地,支持wav格式,单通道
参数: - save_file – 本地文件路径,目前仅支持wav格式
- seconds – 录制时间
- sample_rate – 采样率
返回: bool: 调用结果
-
start_audio_stream
()¶ 开启音频流
-
start_video_stream
(display=True, resolution='720p')¶ 开启视频流
参数: - display – bool,是否显示视频流
- resolution – enum: (“360p”, “540p”, “720p”),设置图传分辨率尺寸
返回: bool:调用结果
-
stop
()¶ 停止
-
stop_audio_stream
()¶ 停止音频流
Return:bool: 调用结果
-
stop_video_stream
()¶ 停止视频流
返回: bool: 调用结果
-
take_photo
()¶ 拍照
返回: bool: 调用结果
-
video_stream_addr
¶ 机器人视频流地址
返回: tuple:(ip, port):机器人视频流地址
-
-
class
robomaster.camera.
TelloCamera
(robot)¶ 基类:
robomaster.camera.Camera
教育无人机 摄像机模块
-
read_cv2_image
(timeout=3, strategy='pipeline')¶ 读取一帧视频流帧
参数: - timeout – float: (0, inf),超时参数,在timeout时间内未获取到视频流帧,函数返回
- strategy – enum: (“pipeline”, “newest”),读取帧策略:pipeline 依次读取缓存的帧信息,newest 获取最新的一帧 数据,会清空旧的数据帧
返回: image
-
read_video_frame
(timeout=3, strategy='pipeline')¶ 读取一帧视频流帧
参数: - timeout – float: (0, inf),超时时间,超过指定timeout时间后函数返回
- strategy – enum: (“pipeline”, “newest”) 读取帧策略:pipeline 流水线依次读取,newest 获取最新的一帧数据, 注意会清空老的数据帧队列
返回: frame, 已解码的视频流帧字节流
-
set_bitrate
(bitrate)¶ 设置飞机传输码率
参数: bitrate – 需要设置的传输码率,[0, 6] 返回: bool: 设置结果
-
set_fps
(fps)¶ 设置飞机视频帧率
参数: fps – 需要设置的帧率,[high, middle, low] 返回: bool: 设置结果
-
set_resolution
(resolution)¶ 设置飞机视频分辨率
参数: resolution – 需要设置的视频分辨率,[high, low] 返回: bool: 设置结果
-
start_video_stream
(display=True)¶ 开启视频流
参数: display – bool, 是否显示视频流 返回: bool: 调用结果
-
robomaster.chassis¶
-
class
robomaster.chassis.
Chassis
(robot)¶ 基类:
robomaster.module.Module
EP 底盘模块,可以控制底盘的速度、位置、订阅底盘的数据,控制麦克纳姆轮等操作
-
drive_speed
(x=0.0, y=0.0, z=0.0, timeout=None)¶ 设置底盘速度,立即生效
参数: - x – float:[-3.5,3.5],x 轴向运动速度即前进速度,单位 m/s
- y – float:[-3.5,3.5],y 轴向运动速度即横移速度,单位 m/s
- z – float:[-600,600],z 轴向运动速度即旋转速度,单位 °/s
- timeout – float:(0,inf),超过指定时间内未收到麦轮转速指令,主动控制机器人停止,单位 s
-
drive_wheels
(w1=0, w2=0, w3=0, w4=0, timeout=None)¶ 设置麦轮转速
参数: - w1 – int:[-1000,1000],右前麦轮速度,以车头方向前进旋转为正方向,单位 rpm
- w2 – int:[-1000,1000],左前麦轮速度,以车头方向前进旋转为正方向,单位 rpm
- w3 – int:[-1000,1000],左后麦轮速度,以车头方向前进旋转为正方向,单位 rpm
- w4 – int:[-1000,1000],右后麦轮速度,以车头方向前进旋转为正方向,单位 rpm
- timeout – float:(0,inf),超过指定时间内未收到麦轮转速指令,主动控制机器人停止,单位 s
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
move
(x=0, y=0, z=0, xy_speed=0.5, z_speed=30)¶ 控制底盘运动当指定位置,坐标轴原点为当前位置
参数: - x – float: [-5,5],x轴向运动距离,单位 m
- y – float: [-5,5],y轴向运动距离,单位 m
- z – float: [-1800,1800],z轴向旋转角度,单位 °
- xy_speed – float: [0.5,2],xy轴向运动速度,单位 m/s
- z_speed – float: [10,540],z轴向旋转速度,单位 °/s
返回: 返回action对象
-
set_pwm_freq
(pwm1=None, pwm2=None, pwm3=None, pwm4=None, pwm5=None, pwm6=None)¶ 设置PWM输出频率
参数: pwm1~6 – int:[0,50000],pwm输出频率,单位Hz
-
set_pwm_value
(pwm1=None, pwm2=None, pwm3=None, pwm4=None, pwm5=None, pwm6=None)¶ 设置PWM输出占空比
参数: - pwm1 – int:[0,100],pwm输出占空比,单位%
- pwm2 – int:[0,100],pwm输出占空比,单位%
- pwm3 – int:[0,100],pwm输出占空比,单位%
- pwm4 – int:[0,100],pwm输出占空比,单位%
- pwm5 – int:[0,100],pwm输出占空比,单位%
- pwm6 – int:[0,100],pwm输出占空比,单位%
-
sub_attitude
(freq=5, callback=None, *args, **kw)¶ 订阅底盘姿态信息
参数: - freq – enum: (1, 5, 10, 20, 50) 设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 (yaw, pitch, roll):
yaw: yaw轴姿态角 pitch: pitch轴姿态角 roll: roll轴姿态角 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
sub_esc
(freq=5, callback=None, *args, **kw)¶ 订阅底盘电调信息
参数: - freq – enum: (1, 5, 10, 20, 50),设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 (speed[4], angle[4], timestamp, state):
speed[4]: 4个电机的速度值,单位rpm,范围:-8192~8191 angle[4]: 4个电机的角度值,数值范围:0~32767映射0~360 timestamp: 4个电机的包序号 state: 4个电调的状态 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
sub_imu
(freq=5, callback=None, *args, **kw)¶ 订阅底盘IMU陀螺仪信息
参数: - freq – enum: (1, 5, 10, 20, 50),设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 (acc_x, acc_y, acc_z, gyro_x, gyro_y, gyro_z):
acc_x: x轴加速度 acc_y: y轴加速度 acc_z: z轴加速度 gyro_x: x轴角速度 gyro_y: y轴角速度 gyro_z: z轴角速度 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
sub_mode
(freq=5, callback=None, *args, **kw)¶ 订阅底盘模式信息
参数: - freq – enum: (1, 5, 10, 20, 50),设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 mode:
mode: 底盘模式 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
sub_position
(cs=0, freq=5, callback=None, *args, **kw)¶ 订阅底盘位置信息
参数: - cs – int: [0,1] 设置底盘位置的坐标系,0 机器人当前位置,1 机器人上电位置
- freq – enum: (1, 5, 10, 20, 50) 设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 (x, y, z):
x: x轴方向距离,单位 m y: y轴方向距离,单位 m z: z轴方向旋转角度,单位 ° - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
sub_status
(freq=5, callback=None, *args, **kw)¶ 订阅底盘状态信息
参数: - freq – enum: (1, 5, 10, 20, 50),设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 (static_flag, up_hill, down_hill, on_slope, is_pickup, slip_flag, impact_x, impact_y, impact_z, roll_over, hill_static):
static_flag: 状态标准位 up_hill: 处于上坡状态 down_hill: 处于下坡状态 on_slope: 处于倾斜状态 is_pickup: 处于抱起状态 slip_flag: 车身打滑 impact_x: x轴发生撞击 impact_y: y轴发生撞击 impact_z: z轴发生撞击 roll_over: 车身翻转 hill_static: 处于斜坡状态 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
sub_velocity
(freq=5, callback=None, *args, **kw)¶ 订阅底盘加速度信息
参数: - freq – enum:(1, 5, 10, 20, 50) 设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据(vgx, vgy, vgz, vbx, vby, vbz):
vgx: 上电时刻下的世界坐标系下x方向速度 vgy: 上电时刻下的世界坐标系下y方向速度 vgz: 上电时刻下的世界坐标系下z方向速度 vbx: 当前时刻的车身坐标系下x方向速度 vby: 当前时刻的车身坐标系下y方向速度 vbz: 当前时刻的车身坐标系下z方向速度 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
unsub_attitude
()¶ 取消订阅底盘姿态信息
返回: bool: 取消数据订阅的结果
-
unsub_esc
()¶ 取消订阅电调信息
返回: bool: 取消数据订阅的结果
-
unsub_imu
()¶ 取消订阅底盘IMU陀螺仪信息
返回: bool: 取消数据订阅的结果
-
unsub_mode
()¶ 取消订阅底盘模式信息
返回: bool: 取消数据订阅的结果
-
unsub_position
()¶ 取消订阅底盘位置信息
返回: bool: 取消数据订阅的结果
-
unsub_status
()¶ 取消订阅底盘状态信息
返回: bool: 取消数据订阅的结果
-
unsub_velocity
()¶ 取消订阅底盘加速度信息
返回: bool: 取消数据订阅的结果
-
robomaster.exceptions¶
robomaster.flight¶
-
class
robomaster.flight.
Flight
(robot)¶ 基类:
object
教育无人机 飞行器模块
-
backward
(distance=0, retry=True)¶ 向后飞行distance厘米, 指相对距离
Param: distance: float:[20, 500]向后飞行的相对距离,单位 cm Param: retry: bool:是否重发命令 返回: action对象
-
curve
(x1=0, y1=0, z1=0, x2=0, y2=0, z2=0, speed=20, mid=None, retry=True)¶ 以设置速度飞弧线,经过对应坐标系中的(x1, y1, z1)点到(x2, y2, z2)点
如果选用mid参数,则对应坐标系为指定挑战卡的坐标系。不使用挑战卡时,飞机的前方为x轴正方向,飞机的左方为y轴的正方向 如果mid参数为默认值None,则为飞机自身坐标系
Param: x1: float:[-500, 500] x轴坐标 Param: y1: float:[-500, 500] y轴坐标 Param: z1: float:如果使用挑战卡(mid不为None),取值范围为 [0, 500]; 如果不使用挑战卡(mid为None),取值范围为[-500, 500] Param: x2: float:[-500, 500] x轴坐标 Param: y2: float:[-500, 500] y轴坐标 Param: z2: float:如果使用挑战卡(mid不为None),取值范围为 [0, 500]; 如果不使用挑战卡(mid为None),取值范围为[-500, 500] Param: speed: float:[10, 60] 飞行的速度 Param: mid: string: 不使用挑战卡时mid为None,运动坐标系为飞机自身坐标系;当使用挑战卡时mid为对应挑战卡编号,运动坐标系为对应挑战卡 坐标系。挑战卡编号参考挑战卡使用说明 Param: retry: bool:是否重发命令 返回: action对象
-
down
(distance=0, retry=True)¶ 向下飞distance厘米,指相对距离
Param: distance: float:[20, 500]向下飞行的相对距离,单位 cm Param: retry: bool:是否重发命令 返回: action对象
-
flip
(direction='f', retry=True)¶ 控制飞机向指定方向翻滚
当电量低于50%时无法完成翻滚 :param direction: string: 飞机翻转的方向, ’l‘ 向左翻滚,’r‘ 向右翻滚,’f‘ 向前翻滚, ’b‘ 向后翻滚 :param: retry: bool:是否重发命令 :return: action对象
-
flip_backward
(retry=True)¶ 控制飞机向后翻滚
当电量低于50%时无法完成翻滚 :param: retry: bool:是否重发命令 :return: action对象
-
flip_forward
(retry=True)¶ 控制飞机向前翻滚
当电量低于50%时无法完成翻滚 :param: retry: bool:是否重发命令 :return: action对象
-
flip_left
(retry=True)¶ 控制飞机向左翻滚
当电量低于50%时无法完成翻滚 :param: retry: bool:是否重发命令 :return: action对象
-
flip_right
(retry=True)¶ 控制飞机向右翻滚
当电量低于50%时无法完成翻滚 :param: retry: bool:是否重发命令 :return: action对象
-
fly
(direction='forward', distance=0, retry=True)¶ 控制飞机向指定方向飞行指定距离。
Param: direction: string: 飞行的方向,”forward” 向上飞行, “back” 向下飞行, “up” 向上飞行, “down” 向下飞行, “left” 向左飞行, “right” 向右飞行 Param: distance: float:[20, 500],飞行的距离,单位 cm Param: retry: bool:是否重发命令 返回: action对象
-
forward
(distance=0, retry=True)¶ 向前飞行distance厘米,指相对距离
Param: distance: float:[20, 500]向前飞行的相对距离,单位 cm Param: retry: bool:是否重发命令 返回: action对象
-
get_speed
()¶ 获取当前设置速度
返回: float: 当前速度值,单位 cm/s
-
go
(x, y, z, speed=10, mid=None, retry=True)¶ 控制飞机以设置速度飞向指定坐标位置
注意, x,y,z 同时在-20~20时,飞机不会运动。当不使用挑战卡时,飞机所在位置为坐标系原点,飞机的前方为x轴正方向,飞机的左方为y轴的正方向
Param: x: float: [-500, 500] x轴的坐标,单位 cm Param: y: float: [-500, 500] y轴的坐标,单位 cm Param: z: float: [-500, 500] z轴的坐标,单位 cm Param: speed: float: [10, 100] 运动速度, 单位 cm/s Param: mid: string: 不使用挑战卡时mid为None,运动坐标系为飞机自身坐标系;当使用挑战卡时mid为对应挑战卡编号, 运动坐标系为指定挑战卡的坐标系。支持编号可参考挑战卡使用说明。 Param: retry: bool:是否重发命令 返回: action对象
-
jump
(x=0, y=0, z=0, speed=20, yaw=0, mid1='m-1', mid2='m-1', retry=True)¶ 飞行器飞往mid1坐标系的(x, y, z)点后悬停,识别mid2的挑战卡,飞到mid2坐标系下(0, 0, z)的位置并且旋转到设定的yaw值
Param: x: float: [-500, 500],x轴的坐标,单位 cm Param: y: float: [-500, 500],y轴的坐标,单位 cm Param: z: float: [0, 500],z轴的坐标,单位 cm Param: speed: float:[10, 60],飞行的速度, 单位 cm/s Param: yaw: [-360, 360] 最终悬停的yaw轴角度, 单位 ° Param: mid1: string: 第一个挑战卡的id, 挑战卡id的介绍参考挑战卡使用说明 Param: mid2: string: 第一个挑战卡的id, 挑战卡id的介绍参考挑战卡使用说明 Param: retry: bool:是否重发命令 返回: action对象
-
land
(retry=True)¶ 自动降落
Param: retry: bool:是否重发命令 返回: action对象
-
left
(distance=0, retry=True)¶ 向左飞行distance厘米, 指相对距离
Param: distance: float:[20, 500]向左飞行的相对距离,单位 cm Param: retry: bool:是否重发命令 返回: action对象
-
mission_pad_off
()¶ 关闭挑战卡探测
返回: bool:控制结果
-
mission_pad_on
()¶ 打开挑战卡探测
默认同时打开前视和下视探测 :return: bool: 控制结果
-
motor_off
()¶ 控制飞机停桨
返回: action对象
-
motor_on
()¶ 控制飞机转桨
返回: action对象
-
move
(x=0, y=0, z=0, speed=10, mid=None, retry=True)¶ 飞机相对位置的控制
x/y/z值不能同时在-20~20之间,适用该接口时应当先打开挑战卡检测功能
Param: x: float:[-500, 500],目标位置在挑战卡坐标系中的x坐标,实际取值范围要根据挑战卡大小调整,单位 cm Param: y: float:[-500, 500],目标位置在挑战卡坐标系中的y坐标,实际取值范围要根据挑战卡大小调整,单位 cm Param: z: float:[-500, 500],目标位置在挑战卡坐标系中的z坐标,实际取值范围要根据挑战卡大小调整,单位 cm Param: speed: int:[10, 100],运动速度,单位 cm/s Param: mid: string: 挑战卡的编号,支持编号可参考挑战卡使用说明 Param: retry: bool:是否重发命令 返回: action对象
-
moveto
(yaw=0, retry=True)¶ 控制飞机旋转到挑战卡坐标系中指定的绝对角度
Param: yaw: float:[-180, 180],飞机在挑战卡上的的角度,俯视时,顺时针为正角度,逆时针为负角度 Param: retry: bool:是否重发命令 返回: action 对象
-
rc
(a=0, b=0, c=0, d=0)¶ 控制飞机遥控器的四个杆量
参数: - a – float:[-100, 100] 横滚
- b – float:[-100, 100] 俯仰
- c – float:[-100, 100] 油门
- d – float:[-100, 100] 偏航
-
right
(distance=0, retry=True)¶ 向右飞行distance厘米, 指相对距离
Param: distance: float:[20, 500]向右飞行的相对距离,单位 cm Param: retry: bool:是否重发命令 返回: action对象
-
rotate
(angle=0, retry=True)¶ 控制飞机旋转指定角度
Param: angle: float:[-360, 360] 旋转的角度,俯视飞机时,顺时针为正角度,逆时针为负角度 Param: retry: bool:是否重发命令 返回: action对象
-
set_speed
(speed=0)¶ 设置当前飞行速度
参数: speed – float:[10, 100],飞行速度,单位 cm/s 返回: bool: 设置结果
-
stop
(retry=True)¶ 停止rc运动并悬停,任何时候都可以
Param: retry: bool:是否重发命令 返回: bool: 控制结果
-
sub_attitude
(freq=5, callback=None, *args, **kw)¶ 订阅飞机姿态信息
参数: - freq – enum:(1, 5, 10),订阅数据的频率
- callback – 传入数据处理的回掉函数
- args – 回调函数参数
- kw – 回调函数参数
返回: bool: 数据订阅结果
-
sub_imu
(freq=5, callback=None, *args, **kw)¶ 订阅飞机陀螺仪信息
参数: - freq – enum:(1, 5, 10),订阅数据的频率
- callback – 传入数据处理的回掉函数
- args – 回调函数参数
- kw – 回调函数参数
返回: bool: 数据订阅结果
-
takeoff
(retry=True)¶ 自动起飞
Param: retry: bool:是否重发命令 返回: action对象
-
throw_fly
()¶ 控制飞机抛飞
返回: action对象
-
unsub_attitude
()¶ 取消订阅飞机姿态信息
返回: bool: 取消数据订阅结果
-
unsub_imu
()¶ 取消订阅飞机陀螺仪信息
返回: bool: 取消数据订阅结果
-
up
(distance=0, retry=True)¶ 向上飞distance厘米,指相对距离
Param: distance: float:[20, 500]向上飞行的相对距离,单位 cm Param: retry: bool:是否重发命令 返回: action对象
-
robomaster.gimbal¶
-
class
robomaster.gimbal.
Gimbal
(robot)¶ 基类:
robomaster.module.Module
EP 云台模块
-
drive_speed
(pitch_speed=30.0, yaw_speed=30.0)¶ 控制以一定速度转动
参数: - pitch_speed – float: [-360, 360],pitch轴速度,单位 °/s
- yaw_speed – float: [-360, 360],yaw 轴速度,单位 °/s
返回: bool:调用结果
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
move
(pitch=0, yaw=0, pitch_speed=30, yaw_speed=30)¶ 控制云台运动到指定位置,坐标轴原点为当前位置
参数: - pitch – float: [-55, 55],pitch 轴角度,单位 °
- yaw – float: [-55, 55],yaw 轴角度,单位 °
- pitch_speed – float: [0, 540],pitch 轴运动速速,单位 °/s
- yaw_speed – float: [0, 540],yaw 轴运动速度,单位 °/s
返回: 返回action对象
-
moveto
(pitch=0, yaw=0, pitch_speed=30, yaw_speed=30)¶ 控制云台运动到指定位置,坐标轴原点为上电位置
参数: - pitch – int: [-25, 30],pitch 轴角度,单位 °
- yaw – int: [-250, 250],yaw 轴角度,单位 °
- pitch_speed – int: [0, 540],pitch 轴运动速度,单位 °
- yaw_speed – int: [0, 540],yaw 轴运动速度,单位 °
返回: 返回action对象
-
recenter
(pitch_speed=60, yaw_speed=60)¶ 控制云台回中
参数: - pitch_speed – float: [-360, 360],pitch轴速度,单位 °/s
- yaw_speed – float: [-360, 360],yaw 轴速度,单位 °/s
返回: 返回action对象
-
resume
()¶ 控制云台从休眠状态中恢复
返回: bool:调用结果
-
sub_angle
(freq=5, callback=None, *args, **kw)¶ 订阅云台姿态角信息
参数: - freq – enum: (1, 5, 10, 20, 50) 设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 (pitch_angle, yaw_angle, pitch_ground_angle, yaw_ground_angle):
pitch_angle: 相对底盘的pitch轴角度 yaw_angle: 相对底盘的yaw轴角度 pitch_ground_angle: 上电时刻pitch轴角度 yaw_ground_angle: 上电时刻yaw轴角度 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
suspend
()¶ 控制云台进入休眠状态
返回: bool:调用结果
-
unsub_angle
()¶ 取消云台姿态角订阅
返回: bool: 取消数据订阅的结果
-
robomaster.gripper¶
-
class
robomaster.gripper.
Gripper
(robot)¶ 基类:
robomaster.module.Module
EP 机械爪模块
-
close
(power=50)¶ 控制机械爪关闭
参数: power – int: [1, 100],控制出力 返回: bool: 调用结果
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
open
(power=50)¶ 控制机械爪张开
参数: power – int: [1, 100],控制出力 返回: bool: 调用结果
-
pause
()¶ 控制机械爪停止
返回: bool: 调用结果
-
sub_status
(freq=5, callback=None, *args, **kw)¶ 订阅夹爪的状态信息
参数: - freq – enum: (1, 5, 10, 20, 50),设置数据订阅数据的推送频率,单位 Hz
- callback –
传入数据处理的回调函数,回调函数参数为:
gripper_status: opened:夹爪打开 closed:夹爪闭合。 - callback –
回调函数,返回数据 (status):
status: opened 夹爪完全打开,closed 夹爪完全闭合,normal 处在中间正常状态 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
unsub_status
()¶ 取消夹爪状态信息订阅
返回: 取消订阅结果
-
robomaster.led¶
-
class
robomaster.led.
Led
(robot)¶ 基类:
robomaster.module.Module
EP 装甲灯模块
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
set_gimbal_led
(comp='top_all', r=255, g=255, b=255, led_list=[0, 1, 2, 3], effect='on')¶ 设置云台灯效
参数: - comp – enum: (“top_all”, “top_left”, “top_right”),云台部位
- r – int: [0, 255],RGB红色分量值
- g – int: [0, 255],RGB绿色分量值
- b – int: [0, 255],RGB蓝色分量值
- led_list – list [idx0, idx1, …],idx:int[0,7] 云台灯序号列表.
- effect – enum: (“on”, “off”),灯效类型
返回: bool: 调用结果
-
set_led
(comp='all', r=0, g=0, b=0, effect='on', freq=1)¶ 设置整机装甲灯效
参数: - comp – enum: (“all”, “top_all”, “top_right”, “top_left”, “bottom_all”, “bottom_front”, “bottom_back”, “bottom_left”, “bottom_right”) 灯效部位,all: 所有装甲灯;top_all:云台所有装甲灯; top_right: 云台右侧装甲灯;top_left: 云台左侧装甲灯; bottom_all: 底盘所有装甲灯;bottom_front: 前装甲灯; bottom_back: 后装甲灯;bottom_left: 左装甲灯;bottom_right: 右装甲灯
- r – int: [0~255],RGB红色分量值
- g – int: [0~255],RGB绿色分量值
- b – int: [0~255],RGB蓝色分量值
- effect – enum: (“on”, “off”, “flash”, “breath”, “scrolling”) 灯效类型,on:常亮;off:常灭;flash:闪烁; breath:呼吸;scrolling:跑马灯(仅对云台灯有效)
- freq – int: [1, 10],闪烁频率,仅对闪烁灯效有效
返回: bool:调用结果
-
-
class
robomaster.led.
TelloLed
(robot)¶ 基类:
object
教育无人机 扩展LED模块
-
set_led
(r=0, g=255, b=0)¶ 设置扩展模块led颜色
参数: - r – int:[0, 255], 扩展led红色通道的强度
- g – int:[0, 255], 扩展led绿色通道的强度
- b – int:[0, 255], 扩展led蓝色通道的强度
返回: bool: 扩展led模块控制结果
-
set_led_blink
(freq=5, r1=0, g1=255, b1=0, r2=0, g2=255, b2=255)¶ 设置扩展模块led以制定的两种颜色与频率实现闪烁效果
参数: - freq – int:[0.1, 10], 扩展ked闪烁模式下的频率, 共十档,随着数字增大速度变快
- r1 – int:[0, 255], 第一种颜色的红色通道的强度
- g1 – int:[0, 255], 第一种颜色的绿色通道的强度
- b1 – int:[0, 255], 第一种颜色的蓝色通道的强度
- r2 – int:[0, 255], 第二种颜色的红色通道的强度
- g2 – int:[0, 255], 第二种颜色的绿色通道的强度
- b2 – int:[0, 255], 第二种颜色的蓝色通道的强度
返回: bool: 扩展led模块控制结果
-
set_led_breath
(freq=1, r=0, g=255, b=0)¶ 设置扩展模块led以指定的颜色与频率实现呼吸效果
参数: - freq – int:[0.1, 2.5], 扩展led呼吸模式下的频率,共十档,随着数字增大速度变快
- r – int:[0, 255], 扩展led红色通道的强度
- g – int:[0, 255], 扩展led绿色通道的强度
- b – int:[0, 255], 扩展led蓝色通道的强度
返回: bool: 扩展led模块控制结果
-
set_mled_boot
(display_graph)¶ 设置点阵屏的开机画面
参数: display_graph – string: 长度最大为64,点阵屏显示图案的编码字符串,每个字符解读为二进制后对应位置的led点的状态, ‘0’为关闭该位置led,’r’为点亮红色,’b’为点亮蓝色,’p’ 为点亮紫色,输入的长度不足64,后面对应的led点默认都是’0’熄灭状态 :return: bool: 设置开机动画的结果
-
set_mled_bright
(bright=255)¶ 设置点阵屏的亮度
参数: bright – int:[0, 255] 点阵屏的亮度 返回: bool: 点阵屏亮度的设置结果
-
set_mled_char
(color='r', display_char='0')¶ 控制扩展点阵屏模块,显示输入的字符
Param: color: char: ‘r’为红色,’b’为蓝色,’p’ 为紫色 Param: display_char: char: [0~9, A~F, heart], 显示的字符 返回: bool: 控制结果
-
set_mled_char_scroll
(direction='l', color='r', freq=1.5, display_str='DJI')¶ 控制扩展点阵屏滚动显示字符串
Param: direction: char: 点阵屏滚动方向,’l’: 字符串向左移动,’r’: 字符串向右移动,’u’ 字符串向上移动,’d’ 字符串向下移动 Param: color: char: 点阵屏显示的颜色, ‘r’红色,’b’蓝色,’p’紫色 Param: freq: float:[0.1, 2.5], 点阵屏滚动的频率, 0.1-2.5HZ之间, 随着数字增大速度变快 Param: display_str: string:需要显示的字符串 返回: 设置结果
-
set_mled_graph
(display_graph)¶ 用户自定义扩展点阵屏显示图案
参数: display_graph – string: 长度最大为64,点阵屏显示图案的编码字符串,每个字符解读为二进制后对应位置的led点的状态, ‘0’为关闭该位置led,’r’为点亮红色,’b’为点亮蓝色,’p’ 为点亮紫色,输入的长度不足64,后面对应的led点默认都是’0’熄灭状态 :return:bool: 控制结果
-
set_mled_graph_scroll
(direction='l', freq=1.5, display_graph='00rrrr000r0000r0r0r00r0rr000000rr0r00r0rr00rr00r0r0000r000rrrr00')¶ 控制扩展点阵屏滚动显示图像
Param: direction: char: 点阵屏滚动方向,’l’: 字符串向左移动,’r’: 字符串向右移动,’u’ 字符串向上移动,’d’ 字符串向下移动 Param: freq: float:[0.1, 2.5], 点阵屏滚动的频率, 0.1-2.5HZ之间, 随着数字增大速度变快 Param: display_str: string:需要显示的图像 返回: 设置结果
-
set_mled_sc
()¶ 清除点阵屏开机显示画面
返回: bool: 清除点阵屏机显示画面的结果
-
robomaster.robot¶
-
class
robomaster.robot.
Robot
(cli=None)¶ 基类:
robomaster.robot.RobotBase
RoboMaster EP 机甲大师 机器人
-
battery
¶ 获取电池模块对象
-
blaster
¶ 获取水弹枪模块对象
-
camera
¶ 获取相机模块对象
-
chassis
¶ 获取底盘模块对象
-
get_module
(name)¶ 获取模块对象
参数: name – 模块名称,字符串,如:chassis, gimbal, led, blaster, camera, battery, vision, etc. 返回: 模块对象
-
get_robot_mode
()¶ 获取机器人工作模式
返回: 自由模式返回free; 底盘跟随云台模式返回gimbal_lead;云台跟随底盘模式返回chassis_lead
-
get_sn
()¶ 获取机器人硬件SN信息
返回: 硬件SN字符串,如:”3JKDH2T0011000”
-
get_version
()¶ 获取机器人固件版本号信息
返回: 版本字符串,如:”01.01.0305”
-
gimbal
¶ 获取云台模块对象
-
initialize
(conn_type='ap', proto_type='udp', sn=None)¶ 初始化机器人
参数: - conn_type – 连接建立类型: ap表示使用热点直连;sta表示使用组网连接,rndis表示使用USB连接
- proto_type – 通讯方式: tcp, udp
注意:如需修改默认连接方式,可在conf.py中指定DEFAULT_CONN_TYPE
-
led
¶ 获取灯效控制模块对象
-
play_audio
(filename)¶ 播放本地音频文件
参数: filename – 播放音效的文件名,目前仅支持单通道,48KHz采样的wav格式文件 返回: action对象
-
play_sound
(sound_id, times=1)¶ 播放系统音效
参数: - sound_id – 系统音效ID值
- times – 播放次数
返回: action对象
-
reset
()¶ 重置机器人到初始默认状态
-
robotic_arm
¶ 获取机械臂模块对象
-
set_robot_mode
(mode='gimbal_lead')¶ 设置机器人工作模式
参数: mode – 机器人工作模式: free表示自由模式;chassis_lead表示云台跟随底盘模式;gimbal_lead表示底盘跟随云台模式 返回: bool: 调用结果
-
vision
¶ 获取智能识别模块对象
-
-
class
robomaster.robot.
Drone
(cli=None)¶ 基类:
robomaster.robot.RobotBase
教育系列无人机
-
close
()¶ 停止drone对象
-
config_sta
(ssid, password)¶ 设置飞机的连接模式为组网模式
参数: - ssid – 路由器的账号
- password – 路由器的密码
返回: bool: 设置结果
-
get_acceleration
()¶ 获取飞机三轴加速度值
返回: dict: 飞机三轴加速度值
-
get_attitude
()¶ 获取飞机三轴姿态信息
返回: dict: 飞机三轴姿态信息
-
get_baro
()¶ 获取电机气压计高度
返回: float: 电机气压计高度
-
get_drone_version
()¶ 获取飞机固件版本号
返回: string: 版本号
-
get_esp32_version
()¶ 获取esp32版本号
返回: string: 版本号
-
get_hardware
()¶ 获取飞机硬件信息 本命令仅支持SDK版本号>=30 可通过hardware?指令查询是否有接WIFI拓展模块,没接拓展模块返回TELLO,接了拓展模块返回RMTT。
返回: string: 硬件信息
-
get_height
()¶ 获取飞机相对高度
返回: string: 飞机相对高度
-
get_motor_time
()¶ 获取电机运行时间
返回: string: 电机的运行时间
-
get_sdk_version
()¶ 获取SDK版本号
返回: string: 版本号
-
get_sn
()¶ 获取飞机sn号
返回: string: 飞机的SN号
-
get_ssid
()¶ 获取SSID名称
返回: string: ssid名称
-
get_status
(name)¶ 获取飞机指定的状态
参数: name – string:需要获取的状态名,可列表[“MID”, “x”, “y”, “z”, “mpry”, “pitch”, “roll”, “yaw”, “vgx”, “vgy”, “vgz”, “templ”, “temph”, “tof”, “h”, “bat”, “baro”, “time”, “agx”, “agy”, “agz”],详细介绍 参考SDK使用文档 返回: name对应状态的数据值,DDS_PAD_MPRY_FLAG 对应状态的返回值为长度为3的list,分别代表的在飞机相对挑战卡的pitch、yaw、row值, 其他状态返回的都是float数据
-
get_subnets
()¶ Look through the machine’s internet connection and returns subnet addresses and server ip :return: list[str]: subnets
list[str]: addr_list
-
get_temp
()¶ 获取飞机机身温度
返回: dict: 飞机机身温度
-
get_wifi
()¶ 获取wifi信噪比
返回: float: wifi的信噪比数值
-
get_wifi_version
()¶ 获取WIFI版本号
返回: string: 版本号
-
scan_drone_robot
()¶ Automatic scanning of robots in the network
参数: num – 返回:
-
set_wifichannel
(channel)¶ 设置飞机WIFI信道
参数: channel – 需要设置的信道 返回: bool: 设置结果
-
sub_drone_info
(freq=5, callback=None, *args, **kw)¶ 订阅飞机高度、气压计、电机运行时间信息
参数: - freq – 订阅数据的频率, 1HZ, 5HZ, 10HZ
- callback – 传入数据处理的回掉函数
- args – 回调函数参数
- kw – 回调函数参数
返回: 返回订阅结果
-
sub_temp
(freq=5, callback=None, *args, **kw)¶ 订阅飞机温度信息
参数: - freq – 订阅数据的频率, 1HZ, 5HZ, 10HZ
- callback – 传入数据处理的回掉函数
- args – 回调函数参数
- kw – 回调函数参数
返回: 返回订阅结果
-
sub_tof
(freq=5, callback=None, *args, **kw)¶ 订阅飞机tof信息
参数: - freq – 订阅数据的频率, 1HZ, 5HZ, 10HZ
- callback – 传入数据处理的回掉函数
- args – 回调函数参数
- kw – 回调函数参数
返回: 返回订阅结果
-
unsub_drone_info
()¶ 取消订阅飞机高度、气压计、电机运行时间信息
返回: 返回取消订阅结果
-
unsub_temp
()¶ 取消订阅温度信息。
返回: 返回取消订阅结果。
-
unsub_tof
()¶ 取消订阅tof信息
返回: 返回取消订阅结果
-
robomaster.robotic_arm¶
-
class
robomaster.robotic_arm.
RoboticArm
(robot)¶ 基类:
robomaster.module.Module
EP 机械臂 模块
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
move
(x=0, y=0)¶ 机械臂相对位置移动
参数: - x – float, x轴运动距离,向前移动为正方向,单位 mm
- y – float, y轴运动距离,向上移动为正方向,单位 mm
返回: action对象
-
moveto
(x=0, y=0)¶ 机械臂绝对位置移动
参数: - x – float, x轴运动距离,向前移动为正方向,单位 mm
- y – float, y轴运动距离,向上移动为正方向,单位 mm
返回: action对象
-
recenter
()¶ 控制机械臂回中
返回: action对象
-
sub_position
(freq=5, callback=None, *args, **kw)¶ 订阅机械臂的位置信息
参数: - freq – enum:(1,5,10,20,50) 设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 (pos_x, pos_y):
pos_x: 机械臂x轴位置信息 pos_y: 机械臂y轴位置信息 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
unsub_position
()¶ 取消机械臂位置信息订阅
返回: bool: 取消订阅结果
-
robomaster.sensor¶
-
class
robomaster.sensor.
DistanceSensor
(robot)¶ 基类:
robomaster.module.Module
EP 距离传感器模块
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
sub_distance
(freq=5, callback=None, *args, **kw)¶ 订阅距离传感器测量的距离信息
参数: - freq – 订阅数据的频率,支持的订阅频率为1、5、10、20、50hz
- callback –
传入数据处理的回调函数,回调函数的参数为:
distance[4]: 4个tof的距离信息 - args – 传入参数。
返回: 返回订阅结果。
-
unsub_distance
()¶ 取消距离传感器的信息订阅。
-
-
class
robomaster.sensor.
SensorAdaptor
(robot)¶ 基类:
robomaster.module.Module
EP 传感器板模块
-
get_adc
(id=1, port=1)¶ 传感器板adc值获取
参数: - id – int[1,8],传感器板编号
- port – int:[1,2],传感器板端口号
返回: adc值
-
get_io
(id=1, port=1)¶ 传感器板io电平值获取
参数: - id – int[1,8], 传感器板编号
- port – int:[1,2], 传感器板端口号
返回: io电平值
-
get_pulse_period
(id=1, port=1)¶ 传感器板电平持续时间获取
参数: - id – int[1,8], 传感器板编号
- port – int:[1,2], 传感器板端口号
返回: 电平持续时间,单位ms
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
robomaster.servo¶
-
class
robomaster.servo.
Servo
(robot)¶ 基类:
robomaster.module.Module
EP 舵机模块
-
get_angle
(index=1)¶ 获取舵机角度值
参数: index – int: [1,3],舵机编号 返回: int 舵机角度
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
moveto
(index=0, angle=0)¶ 舵机绝对位置移动
参数: - index – int [1, 3],舵机编号
- angle – int: [-180, 180],舵机旋转角度,单位(°)
返回: action对象
-
pause
(index=0)¶ 停止
参数: index – int: [1, 3],舵机编号 Return bool: 调用结果
-
sub_servo_info
(freq=5, callback=None, *args, **kw)¶ 订阅舵机角度信息
参数: - freq – enum: (1, 5, 10, 20, 50) 设置数据订阅数据的推送频率,单位 Hz
- callback –
回调函数,返回数据 (valid[4], speed[4], angle[4]):
valid[4]: 4个舵机在线状态 speed[4]: 4个舵机的速度值 angle[4]: 4个舵机的角度值 - args – 可变参数
- kw – 关键字参数
返回: bool: 数据订阅结果
-
unsub_servo_info
()¶ 取消订阅舵机的角度信息 :return: bool: 调用结果
-
robomaster.uart¶
-
class
robomaster.uart.
Uart
(robot)¶ 基类:
robomaster.module.Module
EP 串口模块
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
serial_param_set
(baud_rate=0, data_bit=1, odd_even=0, stop_bit=0, rx_en=1, tx_en=1, rx_size=50, tx_size=50)¶ 底盘串口参数设置
默认设置:’9600’, ‘bit8’, ‘none’, ‘1’
参数: - baud_rate – 串口波特率,设置范围:0~4映射‘9600’,‘19200’,‘38400’,‘57600’,‘115200’
- data_bit – 数据位设置,设置范围:0~3映射‘bit7’, ‘bit8’, ‘bit9’, ‘bit10’
- odd_even – 数据校验位,设置范围:0~3映射‘none’, ‘odd’, ‘even’
- stop_bit – 停止位,设置范围:1~2
- rx_en – 接收使能
- tx_en – 发送使能
- rx_size – 接收buff大小
- tx_size – 发送buff大小
返回: 返回串口设置结果
-
serial_send_msg
(msg_buf)¶ 底盘串口数据数据发送
参数: - msg_buf – 发送的数据
- msg_len – 发送的数据长度
返回: 返回串口数据发送结果
-
robomaster.version¶
robomaster.vision¶
-
class
robomaster.vision.
Vision
(robot)¶ 基类:
robomaster.module.Module
EP 视觉识别模块
-
get_version
()¶ 获取模块版本号
:return:字符串,格式为:AA.BB.CC.DD
-
sub_detect_info
(name, color=None, callback=None, *args, **kw)¶ 订阅智能识别消息
参数: - name – enum: (“person”, “gesture”, “line”, “marker”, “robot”),person 行人,gesture 手势,line 线识别, marker 标签识别,robot 机器人识别
- color – enum:(“red”, “green”, “blue”): 指定识别颜色,仅线识别和标签识别时生效
- callback –
回调函数,返回数据 (list(rect_info)):
rect_info: 包含的信息如下: person 行人识别:(x, y, w, h), x 中心点x轴坐标,y 中心点y轴坐标,w 宽度,h 高度 gesture 手势识别:(x, y, w, h), x 中心点x轴坐标,y 中心点y轴坐标,w 宽度,h 高度 line 线识别:(x, y, theta, C),x点x轴坐标,y点y轴坐标,theta切线角,C 曲率 marker 识别:(x, y, w, h, marker), x 中心点x轴坐标,y 中心点y轴坐标,w 宽度,h 高度,marker 识别到的标签 robot 机器人识别:(x, y, w, h),x 中心点x轴坐标,y 中心点y轴坐标,w 宽度,h 高度
-
unsub_detect_info
(name)¶ 取消智能订阅消息
参数: name – enum: (“person”, “gesture”, “line”, “marker”, “robot”),取消的智能识别功能 返回: bool: 调用结果
-
Module contents¶
Summary of RoboMaster SDK Multi-device APIs¶
Currently, most of the APIs supported by multiple devices are used in the same way as for standalone devices. Therefore, this document mainly summarizes the APIs currently supported by multiple devices. This document also describes the different interfaces used in multi-device and standalone scenarios. For a detailed description of the parameter types, value ranges, and return values of other APIs, refer to the descriptions of APIs for standalone devices.
Summary of multi-device APIs¶
For EP robots¶
For education-series robots¶
module | api |
flight | takeoff() |
land() | |
up(distance) | |
down(distance) | |
forward(distance) | |
backword(distance) | |
left(distance) | |
right(distance) | |
rotate(angle) | |
flip_forward() | |
flip_backward() | |
flip_left() | |
flip_right() | |
go(distance) | |
mission_pad_on() | |
mission_pad_off() | |
motor_on() | |
mortor_off() | |
led | set_led(r, g, b) |
set_led_blink(freq, r1, g1, b1, r2, g2, b2) | |
set_led_breath(freq, r, g, b) | |
set_mled_bright(bright) | |
set_mled_boot(display_graph) | |
set_mled_sc() | |
set_mled_graph(display_graph) | |
set_mled_char(color, display_char) | |
set_mled_char_scroll(direction, color, freq, display_str) | |
set_mled_char_scroll(direction, color, freq, display_graph) | |
battery | get_battery() |
The use of the following two interfaces with multiple devices is different from their use with a standalone device:
The go() command of the flight module:
go(go_dict) Parameter: go_dict {robot_id1: [x1, y1, z1, speed1, mid1], robot_id2: [x2, y2, z2, speed2, mid2], ... } Where, "robot_id" indicates the number of the drone, "x", "y", and "z" respectively indicate the x, y, and z coordinates of the go command for a standalone device, "speed" indicates the movement speed of the go command, and "mid" indicates the challenge card number of the go command. Return value: the multi_action object
Commands for the led module:
The command_dict parameter has been recently added. This parameter controls the led module of a standalone drone by using command_dict. Its function is similar to that of the go command. Parameter: command_dict {robot_id1: [*args], robot_id2: [*args], ... } Where, robot_id indicates the number of the drone, and *args are the parameters for each led module Return value: the multi_action object
get_battery() command of the battery module:
get_battery() Parameter: none Print the ID of the drone and its battery level to the console.
Implement Multi-device Formation for TT by Using the RoboMaster SDK¶
Initialize the drone¶
Before performing drone-related operations, you must initialize the drone object according to the specified configuration.
First, import the multi_robot module from the installed multi_robomaster package.:
from multi_robomaster import multi_robot
Create a multi_drone instance object of the MultiDrone class. Here, multi_drone` is a multi-device controller object.:
multi_drone = multi_robot.MultiDrone()
Initialize the drone object. Currently, you must specify the number of drones that you want to control to initialize education-series drones.:
multi_drone.initialize(drone_num)
Now, you have finished initializing the drones.
Number and group drones¶
To simplify the process of controlling multiple devices, we group them by SN, which is the only unique identifier of a device. Therefore, multi-drone formation is implemented based on SNs. To simplify the formation, the SDK must map custom IDs to drone SNs.
After initialization, use the instantiated multi_drone object to number SNs.:
multi_drone.number_id_by_sn([1, "0TQZH79ED00H56"], [2, "0TQZH79ED00H89"])
You can map multiple IDs to the same SN, but only one SN can be mapped to an ID.
Use the instantiated multi_drone object to group drones.:
multi_drone_group1 = multi_drone.build_group([1, 2])
The grouping result is multi_drone_group1 for the multi_group object. You can group the same drone multiple times. For example::
multi_drone_group1 = multi_drone.build_group([1])
multi_drone_group2 = multi_drone.build_group([1, 2])
If you do not want to number drones, you can use the number_id_to_all_drone API to implicitly number the drones with random numbers ranging from 0 to drone_num.:
multi_drone.number_id_to_all_drone()
This completes the grouping of drones. Now, you can perform information query, motion control, and other operations on the drone through relevant interfaces.
Instruct drones to execute commands¶
After action grouping, use the instantiated multi_drone object to perform actions.:
multi_drone.run([multi_drone_group1, base_action_1])
Where, multi_drone_group1 is the grouped multi_group object, and base_action_1 is the user-defined command function, whose format is as follows::
def base_action_1(robot_group):
robot_group.get_sn()
robot_group.get_battery()
If you want multiple groups to perform multiple actions simultaneously, use the following method. Here, we use two groups::
multi_drone.run([multi_drone_group1, base_action_1],
[multi_drone_group2, base_action_2])
You have now had the drones execute commands.
Release drone resources¶
At the end of the program, you need to manually release the resources related to the drone object, including releasing the network address, ending the corresponding background thread, and releasing the corresponding address space. The multi_drone.close object provides the close() method for releasing these resources, which can be used as follows.:
multi_drone.close()
小技巧
To avoid unexpected errors, be sure to call the close() method at the end of the program.
Use the query interface¶
The query interface is the data acquisition interface, through which you can obtain the status of the drone and the status of sensors. The following two examples of querying the SN of the drone and querying the battery level of the drone can help you understand the usage of this interface.
Example 1: Query the SN and battery level of the drone¶
- First, complete the operations on the drone object as described in the `Control a drone to execute commands`_ section.
- Execute the following code for base_action_1 (base_task in this example):
1 2 3 | def basic_task(robot_group):
robot_group.get_sn()
robot_group.get_battery()
|
The SN and battery level of the drone are printed in the console in the format: “DRONE id: {}, reply: {}”.
- Release relevant resources as described in the Release drone resources section.
For the full process, refer to the /examples/15_multi_robot/multi_drone/02_basic.py
sample file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | from multi_robomaster import multi_robot
def basic_task(robot_group):
robot_group.get_sn()
robot_group.get_battery()
if __name__ == '__main__':
# get drone sn by run the expamles of /15_multi_robot/multi_drone/01_scan_ip.py
robot_sn_list = ["0TQZH79ED00H56", "0TQZH79ED00H89"]
sn_list = []
battery_list = []
drone_num = 2
multi_drone = multi_robot.MultiDrone()
multi_drone.initialize(robot_num=2)
multi_drone.number_id_by_sn([0, robot_sn_list[0]], [1, robot_sn_list[1]])
tello_group = multi_drone.build_group([0, 1])
multi_drone.run([tello_group, basic_task])
multi_drone.close()
|
Use the setup interface¶
The setup interface is used to configure the modules of the drone. This section uses the extended LED module as an example to explain how to use the setup interface.
小技巧
Currently, configuring extended LED lights is only supported by Tello Talent devices.
Example 1: Configure the extended LED module of the drone¶
The process of configuring the extended LED module of the drone through the SDK is as follows.
- First, complete the operations on the drone object as described in the `Control a drone to execute commands`_ section.
- Execute the following code for base_action_1:
1 2 3 4 | def base_action_1(robot_group):
robot_group.set_led(255, 255, 255)
time.sleep(2)
robot_group.set_led(command_dict={1: [255, 0, 0], 2: [255, 255, 0]})
|
Using the set_led(255, 255, 255) interface allows you to light up all drones in the current group white. To set different colors for different drones, use the command_dict keyword. If you use command_dict with the parameter type set to dict, you can set different colors for different drones in the current group. As shown in the previous example, drone 1 lights up red, and drone 2 lights up green.
Note that when you use the command_dict keyword with its parameter type set to dict, other parameters will be ignored. The number of drones in the dictionary must equal the number of drones in the current group rather than the default setting.
- Release relevant resources as described in the Release drone resources section.
For the full process, refer to the /examples/15_multi_robot/multi_drone/06_led.py
sample file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import time
from multi_robomaster import multi_robot
def base_action_1(robot_group):
robot_group.set_led(255, 255, 255)
time.sleep(2)
robot_group.set_led(command_dict={1: [255, 0, 0], 2: [255, 255, 0]})
if __name__ == '__main__':
# get drone sn by run the expamles of /15_multi_robot/multi_drone/01_scan_ip.py
robot_sn_list = ["0TQZH79ED00H56", "0TQZH79ED00H89"]
multi_drone = multi_robot.MultiDrone()
multi_drone.initialize(robot_num=2)
multi_drone.number_id_by_sn([1, robot_sn_list[0]], [2, robot_sn_list[1]])
multi_drone_group1 = multi_drone.build_group([1, 2])
multi_drone.run([multi_drone_group1, base_action_1])
multi_drone.close()
|
Use the action interface¶
The action interface is used to instruct a drone to perform flight actions. This section explains how to use this interface.
警告
If you use drone firmware v2.5.1.4 and Wi-Fi module v1.0.0.33, you must upgrade the drone before using the action interface, otherwise unexpected flight actions can occur. To locate this information, refer to the interface documentation for standalone devices.
Example 1: Control the drone to take off and fly back and forth¶
In this example, you first need to control two drones to take off and then move them forward and backward 100 cm respectively.
- First, complete the operations on the drone object as described in the `Control a drone to execute commands`_ section. Then, write this program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
from multi_robomaster import multi_robot
def takeoff_land_task1(robot_group):
robot_group.takeoff().wait_for_completed()
robot_group.forward(100).wait_for_completed()
robot_group.land().wait_for_completed()
def takeoff_land_task2(robot_group):
robot_group.takeoff().wait_for_completed()
robot_group.backward(100).wait_for_completed()
robot_group.land().wait_for_completed()
if __name__ == '__main__':
# get drone sn by run the expamles of /15_multi_robot/multi_drone/01_scan_ip.py
robot_sn_list = ["0TQZH79ED00H56", "0TQZH79ED00H89"]
multi_drone = multi_robot.MultiDrone()
multi_drone.initialize(robot_num=2)
multi_drone.number_id_by_sn([0, robot_sn_list[0]], [1, robot_sn_list[1]])
multi_drone_group1 = multi_drone.build_group([0])
multi_drone_group2 = multi_drone.build_group([1])
multi_drone.run([multi_drone_group1, takeoff_land_task1],
[multi_drone_group2, takeoff_land_task2])
multi_drone.close()
|
- Release relevant resources as described in the Release drone resources section.
警告
Different from a standalone drone operation, the wait_for_completed() interface is required when multiple drones perform flight actions. If you forget to include this interface, the next action after the current action may not be performed. With this interface, after waiting for a period of time, the drone performs the next action.
Example 2: Control drones to move to the target coordinate point¶
In this example, you first need to control two drones to take off and then move along a square track at a height of 100 cm and a speed of 100 cm/s. The center of the large carpet is used as the center point and the side length is set to 50 cm.
- First, complete the operations on the drone object as described in the `Control a drone to execute commands`_ section.
- Execute the following code for base_action_1:
1 2 3 4 5 6 7 8 9 10 11 | def base_action_1(robot_group):
robot_group.mission_pad_on()
robot_group.takeoff().wait_for_completed()
robot_group.go({1: [-50, -50, 100, 100, "m12"], 2: [50, 50, 100, 100, "m12"]}).wait_for_completed()
robot_group.set_mled_char("r", "heart")
robot_group.go({1: [-50, 50, 100, 100, "m12"], 2: [50, -50, 100, 100, "m12"]}).wait_for_completed()
robot_group.set_mled_char("p", "heart")
robot_group.go({1: [50, 50, 100, 100, "m12"], 2: [-50, -50, 100, 100, "m12"]}).wait_for_completed()
robot_group.go({1: [50, -50, 100, 100, "m12"], 2: [-50, 50, 100, 100, "m12"]}).wait_for_completed()
robot_group.land().wait_for_completed()
robot_group.mission_pad_off()
|
Note that the go command for multi-device formation forces users to use the mat coordinates for movement. To ensure programming security, the drone’s own coordinate system cannot be used for drone movement. The number of drones in the dictionary must equal the number of drones in the current group rather than the default setting.
- Release relevant resources as described in the Release drone resources section.
For the full process, refer to the /examples/15_multi_robot/multi_drone/05_go.py
sample file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from multi_robomaster import multi_robot
def base_action_1(robot_group):
robot_group.mission_pad_on()
robot_group.takeoff().wait_for_completed()
robot_group.go({1: [-50, -50, 100, 100, "m12"], 2: [50, 50, 100, 100, "m12"]}).wait_for_completed()
robot_group.set_mled_char("r", "heart")
robot_group.go({1: [-50, 50, 100, 100, "m12"], 2: [50, -50, 100, 100, "m12"]}).wait_for_completed()
robot_group.set_mled_char("p", "heart")
robot_group.go({1: [50, 50, 100, 100, "m12"], 2: [-50, -50, 100, 100, "m12"]}).wait_for_completed()
robot_group.go({1: [50, -50, 100, 100, "m12"], 2: [-50, 50, 100, 100, "m12"]}).wait_for_completed()
robot_group.land().wait_for_completed()
robot_group.mission_pad_off()
if __name__ == '__main__':
# get drone sn by run the expamles of /15_multi_robot/multi_drone/01_scan_ip.py
robot_sn_list = ["0TQZH79ED00H56", "0TQZH79ED00H89"]
multi_drone = multi_robot.MultiDrone()
multi_drone.initialize(robot_num=2)
multi_drone.number_id_by_sn([1, robot_sn_list[0]], [2, robot_sn_list[1]])
multi_drone_group1 = multi_drone.build_group([1, 2])
multi_drone.run([multi_drone_group1, base_action_1])
multi_drone.close()
|
Implement Multi-device Formation for EP by Using the RoboMaster SDK¶
This document uses the Windows 64-bit operating system as an example to illustrate how to implement EP formation by using the RoboMaster SDK.
Demo environment requirements and materials checklist¶
- Programming environment
- Download the RoboMaster-SDK compressed package from GitHub at RoboMaster-SDK compressed package (alternative Gitee download address: RoboMaster-SDK compressed package) by completing the following steps:
- Click
Code
and thenDownload ZIP
to download the compressed package.

- Decompress the downloaded RoboMaster-SDK-master.zip compressed package:

The compressed archive contains the following files:
- The VS-related runtime library: VisualCppRedist_AIO_20200707.exe
- The VS build tool: visualcppbuildtools_full.exe
- RoboMaster SDK sample code: examples
- The third-party library installation script: lib_install.bat
- Install the required VC library:
Run VisualCppRedist_AIO_20200707.exe in the decompressed RoboMaster-SDK archive and complete the installation:

警告
The following error occurs if you use the SDK without installing the VC library:

- Install the VS build tool:
Run visualcppbuildtools_full.exe in the decompressed RoboMaster-SDK archive and complete the installation:

- Installation process in Python:
- Locate the Python installation package on the Python official website (Python 3.7.8 in this example) and download the installer in the package.
警告
Ensure that the downloaded python.exe file is for 64-bit installation and the Python version is 3.6.6 or later. Otherwise, you cannot use the Python SDK properly due to compatibility issues. If you have already installed Python on your PC, we recommend that you uninstall it and install the required version.

Step 1: Check that the installation package is for
64-bit
installation, otherwise you cannot use the Python SDK properly.Step 2: Select
Add Python 3.7 to Path
.Step (3): Select ``Install Now’’ to begin installation, as shown in the figure below:

- After the installation is complete, press the
Win+R
shortcut command, entercmd
in the window that appears to open the CLI, and then enter ``python’’ on the CLI to confirm that Python 3.7.8 has been installed successfully.

Install the dependent Python third-party library:
Method 1: Locate the lib_install.bat file in the downloaded RoboMaster-SDK archive (
RoboMaster-SDK-master/lib_install.bat
), right-click the file, and select “Run as Administrator”.Method 2: Install RoboMaster SDK, click the start menu on your PC, and enter
cmd
in the search box. In the search results, right-click the CLI program and selectRun as Administrator
in the menu that appears. Then, enter the following commands in sequence:pip install robomaster pip install netaddr pip install netifaces pip install myqr
- EP vehicles
- Quantity: 6 EP infantry vehicles
小技巧
If you do not have 6 EP vehicles, use 2 EP vehicles. In this case, replace the rest of the code by referring to /examples/15_muti_robot/multi_ep/02_two_ep_demo.py
.
- Firmware version: 01.01.0500
小技巧
You can upgrade the firmware version in the RoboMaster app to ensure that the firmware version is 01.01.0500 or later.
EP networking connection¶
Step 1: Set the network connection method of each EP robot to networking and add the PC and the robots to the same LAN for networking,
as shown in the figure below:

Step 2: Generate a QR code
- Refer to the example in the sample code directory of
/examples/01_robot/05_sta_conn_helper.py
in the downloaded and decompressed RoboMaster-SDK archive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import time
import robomaster
from robomaster import conn
from MyQR import myqr
from PIL import Image
QRCODE_NAME = "qrcode.png"
if __name__ == '__main__':
helper = conn.ConnectionHelper()
info = helper.build_qrcode_string(ssid="RoboMaster_SDK_WIFI", password="12341234")
myqr.run(words=info)
time.sleep(1)
img = Image.open(QRCODE_NAME)
img.show()
if helper.wait_for_connection():
print("Connected!")
else:
print("Connect failed!")
|
警告
In line 13 of the sample code:
info = helper.build_qrcode_string(ssid=”RoboMaster_SDK_WIFI”, password=”12341234”)
Replace ssid (the router name) and password (the router password) with the actual name and password.
Run the sample code to display the QR code. Then, press the scan button on the smart central control of the robot, and scan the QR code to connect to the network.
Execution result:
Connected!
The light indicator of the robot changes from blinking white to solid turquoise.
注解
A total of 6 EP vehicles need to be connected to the Wi-Fi hotspot. When connecting the 6 EP vehicles one by one for the first time, repeatedly run the sample code to connect to each vehicle. After successful connection, the vehicles will be automatically connected upon the next startup.
Run the sample code for multi-device formation¶
- Refer to the example in the sample code directory of
/examples/15_muti_robot/multi_ep/03_six_ep_demo.py
in the downloaded and decompressed RoboMaster-SDK archive.
- After each robot is successfully connected to the same router, you need to manually change the robot SNs in the sample code. The SN of each robot can be found on the label of the smart central control, as shown in the figure below:

Edit the sample code and locate line 203:
1 2
'3JKDH3B001M8MW', '3JKDH3B001PQ53', '3JKDH3B001470C']
Change the SNs in the sample code based on the actual SNs of the robots.
According to the order of the six SNs, place the six robots in sequence as shown in the figure below. The direction of the arrow is the direction of the robots.

Run the modified sample program¶
Go to the: file:/examples/15_muti_robot/multi_ep/ directory, press and hold the Shift key, right-click any blank area in the directory, and then select “Open Powershell Window Here” or “Open Command Window Here”.
Run the code and enter the following in the command window::
python 03_six_ep_demo.py
Mechanical Arm and Mechanical Gripper¶
Introduction¶
The mechanical arm supports FPV precise remote control, and the mechanical gripper is used in conjunction with the mechanical arm to support clamping force control. In the app, you can control the mechanical arm and the mechanical gripper to complete tasks from the first-person perspective.

Instructions for use¶
Users can control the movement range of the mechanical arm and the opening and closing distance of the mechanical gripper. Specifically, the horizontal movement range of the mechanical arm is 0 to 0.22 m, and the vertical movement range is 0 to 0.15 m. The opening and closing distance of the mechanical claw is about 10 cm.
警告
- When the mechanical arm or mechanical gripper is working, avoid applying external force to it as far as possible.
- Do not collide or damage the mechanical arm or mechanical gripper to avoid performance degradation or abnormal operation of the servo.
- Do not touch the rotating or sharp parts of the mechanical arm or mechanical gripper to avoid injury.
- Promptly clean water droplets, crystal bomb residue, and other foreign objects to avoid corrosion of the structure surface.
Description of the mechanical gripper’s PWM interface:¶
The mechanical gripper supports the torque control mode

The frequency of the PWM signal is 50Hz, and the duty cycle is between 2.5% and 12.5%.
- A duty cycle between 2.5% and 7.5% corresponds to the [Maximum, 0] closing force.
- A duty cycle between 7.5% and 12.5% corresponds to the [0, Maximum] opening force.
Python API¶
Refer to Mechanical Arm and Mechanical Gripper.
Servo¶
Introduction¶
In addition to supporting 485 control, the throttle control mode of the servo can also be controlled by PWM. The control modes are the speed mode and the angle mode.
注解
Control modes of the servo
The control mode of the servo is switched through the official programming interface (Scratch/Python). This mode is recorded in the servo and will not be reset when the servo is powered off. Before using PWM control, confirm the current control mode of the servo.
Pin description¶
The 485 and PWM pins on the servo are multiplexed, as shown in the figure below:

No. | Pin |
---|---|
1 | 485A/PWM |
2 | 485B |
3 | VCC-12V |
4 | GND |
Control description¶
In PWM control mode, the input and output of the servo are described as follows.
Control mode | Pulse period | Throttle range | Servo output |
---|---|---|---|
Angle mode | 50Hz | 2.5%-12.5% | 0°-360° |
Speed mode | 50Hz | 2.5%-7.5% | 49-0 rpm (clockwise) |
7.5%-12.5% | 0-49 rpm (counterclockwise) |
Infrared Distance Sensor¶
Introduction¶
The infrared distance sensor is designed based on the time of flight (TOF) principle. That is, the sensor emits modulated near-infrared light, which is reflected when it strikes an object. The sensor then calculates the distance to the object by calculating the time difference or phase difference between light emission and reflection.
Product features¶
The detection area of the infrared distance sensor is shown in the figure below:

The sensor emits a conical light with an angle of 20°. The relationship between the spot (D) and the distance (Dist) is calculated as follows:
D=2×Dist×tan(10)
To achieve optimal test results, the size of the target must at least equal the size of the TOF spot.
小技巧
If the size of the target is smaller than the spot size, ensure that the target is in the center of the spot as far as possible because the light intensity distribution in the spot is not uniform, but a Gauss-like distribution. Specifically, the light intensity is strong in the center and weaker around the edges. For this reason, to ensure sufficient reflected light energy, the target must be in the center of the light spot as far as possible.
Communication protocol and data format¶
Control command input:
-
ir_distance_sensor_measure_on
¶ Description: Enables data output by the infrared distance sensor, at the output frequency of 20 Hz.
-
ir_distance_sensor_measure_off
¶ Description: Disables data output by the infrared distance sensor.
Data output:
-
ir distance:xxx
Description: Data format of the infrared distance sensor
小技巧
Commands are input and output in the form of strings.
Python API¶
Refer to Infrared Distance Sensor.
Sensor Adapter¶
Introduction¶
The sensor adapter module is designed to help you to connect the temperature, pressure, ranging, and other sensors to RoboMaster EP. Sensor data information can be obtained in the Scratch programming environment. Each sensor adapter module has two sensor interfaces with identical functions.

Pin description¶
Port | Pin | Function |
---|---|---|
port1 | VCC | Positive terminal with an output voltage of 3.3V |
GND | The power ground | |
I/O | The level input, with an input range of 0-3.3V | |
AD | The analog voltage input, with an input range of 0-3.3V | |
port2 | Same as port1 | Same as port1 |
Python API¶
Refer to Sensor Adapter.
UART Interface¶
Introduction¶
UART is used to connect third-party platforms with EP. You can easily establish a connection between the MCU mounted on EP and EP through UART and implement the interactive logic on the MCU. Then, you can use the cleartext SDK to communicate with the EP robot to implement automatic EP control.
Pin description¶
The UART interface of EP is on the motion controller, and the pins are described as follows:
Serial port configuration¶
Third-party platform connection method¶
Refer to UART connection.
Python programming example¶
The PC is connected to the UART interface of the EP motion controller through a serial-to-USB adapter.
Turn on the serial-port debugging assistant on the PC. Then, select and enable the COM port corresponding to the serial port.
Open the official app that has established a connection with EP and enter the Python programming mode.
On the Python programming page, write a simple program, using read_string() to read data from the serial port. Next, output the data and forward it with write_string(). Then, click the “Start” button to run the program.
Send a string by using the serial-port debugging assistant to see if you can receive the string correctly. Meanwhile, check whether the string is correctly output on the app.
The serial debugging assistant sends and echoes the string
The app outputs the received string and then forwards it
Cleartext SDK example¶
The PC is connected to the UART interface of the EP motion controller through a serial-to-USB adapter.
Turn on the serial-port debugging assistant on the PC. Then, select and enable the COM port corresponding to the serial port.
Send the
command;
string through the serial-port debugging assistant. If you receive ``ok’’ from EP, the cleartext SDK successfully parsed the sent string.The serial debugging assistant sends the SDK string and receives the response
警告
When sending a cleartext SDK command through UART, you must append a semicolon (;
) after the command, otherwise parsing will fail.
Introduction to the Plaintext SDK¶
A major function of RoboMaster EP is its support for the plaintext SDK, which includes the control interfaces of each built-in module and extended module, as well as the output interfaces of video streams and audio streams. EP supports multiple access methods such as USB, Wi-Fi, and UART. Users can choose any access methods based on their platform interfaces.
The plaintext SDK greatly enriches the extensibility of EP, enabling easy communication with third-party platforms for secondary development. This document explains how to use plaintext protocols in the SDK through the Wi-Fi direct connection method (for other available connection methods, refer to Establish a Connection) to control blaster firing as an example.
Development preparations¶
- Prepare a PC with a Wi-Fi connection function.
- Install the Python 3.x environment on the PC. For the installation process, refer to Python Getting Started.
Establish a connection¶
Turn on the robot.
Turn on the robot and set the connection method switch of the smart central control to the direct connection mode, as shown in the figure below:
Establish a Wi-Fi connection.
Open the wireless network access list on the PC, select the Wi-Fi hotspot name displayed on the sticker on the robot body, enter the 8-digit password, and then select “Connect”.
Prepare the connection script.
After establishing the Wi-Fi connection, write code to establish a TPC/IP connection with the robot and transmit a specific plaintext protocol on the corresponding port for control. For more information about plaintext protocols, refer to Protocol Content.
The following example uses the Python programming language to write a script to Establish control connection, receive user instructions, and transmit plaintext protocols. This allows you to control the robot.
The sample code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | # -*- encoding: utf-8 -*-
# Test environment: Python 3.6
import socket
import sys
# In direct connection mode, the default IP address of the robot is 192.168.2.1 and the control command port is port 40923.
host = "192.168.2.1"
port = 40923
def main():
address = (host, int(port))
# Establish a TCP connection with the control command port of the robot.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Connecting...")
s.connect(address)
print("Connected!")
while True:
# Wait for the user to enter control commands.
msg = input(">>> please input SDK cmd: ")
# When the user enters Q or q, exit the current program.
if msg.upper() == 'Q':
break
# Add the ending character.
msg += ';'
# Send control commands to the robot.
s.send(msg.encode('utf-8'))
try:
# Wait for the robot to return the execution result.
buf = s.recv(1024)
print(buf.decode('utf-8'))
except socket.error as e:
print("Error receiving :", e)
sys.exit(1)
if not len(buf):
break
# Disconnect the port connection.
s.shutdown(socket.SHUT_WR)
s.close()
if __name__ == '__main__':
main()
|
Save the preceding code as rm_sdk.py.
Run the script.
Run the rm_sdk.py file. (In Windows, after installing the Python environment, double-click the *.py file to run it. If you fail to run the file, press the
Win+R
shortcut command and entercmd
. Then, press Enter to open the CLI and enterpython rm_sdk.py
to run the file. In Linux, pressCtrl+Alt+T
to open the CLI and enterpython rm_sdk.py
.)Establish a TCP/IP control connection.
When
Connecting...'' appears in the running window, the system is attempting to establish a connection with the robot. When ``Connected!;
appears in the running window, the control connection has been established.
Enable the SDK mode¶
To perform SDK control, you need to have the robot enter SDK mode. To do this, enter command in the aforementioned Python running window and press Enter. The program will then send the command to the robot. If the robot returns ok, it has entered SDK mode.:
>>> please input SDK cmd: command
ok
After entering SDK mode, you can enter control commands to control the robot.
Send control commands¶
When you enter blaster fire, ok is returned and the blaster fires once.:
>>> please input SDK cmd: blaster fire
ok
Now, you can enter other control commands to further control the robot. For more control commands, refer to Plaintext Protocols.
Exit SDK mode.¶
After completing all control commands, you need to exit SDK mode to allow the use of other robot functions.
Enter quit to exit SDK mode. After exiting SDK mode, you can no longer use SDK functions. To use them, enter command again to re-enter SDK mode.:
>>> please input SDK cmd: quit
ok
Summary¶
In the preceding steps, we established a physical connection with the robot, established a TCP/IP control connection with the robot, instructed the robot to enter SDK mode, sent control commands, and quit SDK mode. This illustrated the use of relevant control functions through the SDK. You can implement more complex logic and more interesting functions by building on the content in the Send control commands section.
When writing the control code, if you are more familiar with other languages, you can use them for the entire control process.
If your device does not support Wi-Fi connection and cannot use Wi-Fi direct connection, refer to 连接 for other available connection methods.
For more information about the SDK, refer to the SDK documentation. For more sample code, refer to RoboMaster Sample Code.
Access Methods¶
Connection methods¶
The robot supports multiple connection methods. You can use any of them to access SDK functions.
Direct connection
- Wi-Fi direct connection: Set the connection method of the robot to direct connection and connect to the robot’s Wi-Fi hotspot.
- USB connection: Connect through the USB port on the robot’s smart central control. In this mode, support for RNDIS functions is required.
- UART connection: Connect through the UART port on the robot’s motion controller.
Networking connection
Networking connection: Set the network connection method of the robot to networking and add the computing device and the robot to the same LAN in order to network them.
Connection parameters¶
The parameters for Wi-Fi direct connection, Wi-Fi networking, and USB connection are described as follows.
IP address description:
- In Wi-Fi direct connection mode, the default IP address of the robot is 192.168.2.1.
- In Wi-Fi networking mode, the IP address of the robot is dynamically assigned by the router. The IP address of the robot in the existing LAN can be obtained by monitoring the IP broadcast data port and using it to connect to the robot.
- In USB connection mode, the computing device needs to support RNDIS functions, and the default IP address of the robot is 192.168.42.2.
Port and connection method description:
- For the UART connection method, see the description of UART parameters below.
警告
Description of data in the UART connection method:
In UART connection mode, only control command/message push/event reporting data is available. If you need video stream/audio stream data, use the Wi-Fi/USB connection method instead.
Connection examples¶
The following examples illustrate how to use the connection methods based on the Python programming language. In all these examples, the Python 3.x environment must be installed as the default environment on your PC (for the installation of the Python environment, refer to Python Getting Started .
Wi-Fi direct connection¶
- Prepare the environment
- Prepare a PC with a Wi-Fi connection function.
- Establish a connection
Turn on the robot.
Turn on the robot and set the connection method switch of the smart central control to the direct connection mode, as shown in the figure below:
Establish a Wi-Fi connection.
Open the wireless network access list on the PC, select the Wi-Fi hotspot name displayed on the sticker on the robot body, enter the 8-digit password, and then select “Connect”.
Prepare the connection script.
After establishing the Wi-Fi connection, we also need to program to establish a TCP/IP connection with the robot. The robot opens multiple ports for connection. To establish a TCP/IP connection, first connect to the control command port (in direct connection mode, the IP address of the robot is
192.168.2.1'', and the control command port is port ``40923
) to enable the SDK mode of the robot.The following example uses the Python programming language to write a script in order to Establish control connection and enable SDK mode.
The sample code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
# -*- encoding: utf-8 -*- # Test environment: Python 3.6 import socket import sys # In direct connection mode, the default IP address of the robot is 192.168.2.1 and the control command port is port 40923. host = "192.168.2.1" port = 40923 def main(): address = (host, int(port)) # Establish a TCP connection with the control command port of the robot. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Connecting...") s.connect(address) print("Connected!") while True: # Wait for the user to enter control commands. msg = input(">>> please input SDK cmd: ") # When the user enters Q or q, exit the current program. if msg.upper() == 'Q': break # Add the ending character. msg += ';' # Send control commands to the robot. s.send(msg.encode('utf-8')) try: # Wait for the robot to return the execution result. buf = s.recv(1024) print(buf.decode('utf-8')) except socket.error as e: print("Error receiving :", e) sys.exit(1) if not len(buf): break # Disconnect the port connection. s.shutdown(socket.SHUT_WR) s.close() if __name__ == '__main__': main()
Save the preceding code as rm_direct_connection_sdk.py.
Run the script.
Windows: After installing the Python environment, double-click the *.py file to run it. If you fail to run the file, press the
Win+R
shortcut command and enter ``cmd’’. Then, press Enter to open the CLI and enter ``python rm_direct_connection_sdk.py’’ to run the file.Linux: Press
Ctrl+Alt+T
to open the CLI and enterpython rm_direct_connection_sdk.py
to run the file.Establish a TCP/IP control connection.
When
Connecting...'' appears in the running window, the system is attempting to establish a connection with the robot. When ``Connected!;
appears in the running window, the control connection has been established.
- Verify the connection
After successfully establishing the control connection, enter command
on the CLI. If the robot returns ok;
, the connection has been established and the robot has entered SDK mode. Then, you can enter control commands to control the robot.
- Other
For information about how to establish a UART physical connection, refer to UART.
Wi-Fi router mode¶
- Prepare the environment
- Prepare a PC with a network connection function (Wi-Fi or wired connection).
- Prepare a router.
- Establish a connection
Turn on the robot.
Turn on the robot and set the connection method switch of the smart central control to the networking mode.
Establish a networking connection.
For Wi-Fi:
If you are using a Wi-Fi connection, connect your PC to the router via Wi-Fi.
For wired connection:
If you are using a wired connection, connect your PC to the LAN port on the router via a network cable.
Ensure that the PC is connected to the router and open the RoboMaster app. In the app, go to the networking connection page, press the scan button on the smart central control of the robot, and scan the provided QR code to connect to the network.
Obtain the IP address of the robot in the LAN.
After the networking connection is established, your PC resides in the same LAN as the robot. Next, write code to establish a TPC/IP connection with the robot and connect to the control command port to enable the SDK mode of the robot.
If the router enabled the DHCP service, the IP address of the robot is dynamically assigned by the router, and you need to obtain the IP address of the robot in the LAN. There are two methods to do this:
- If you established the networking connection in the RoboMaster app, navigate to the Settings -> Connection page in the app, where you can see the IP address of the robot in the LAN.
- If you established the networking connection using another method, use Monitor robot address broadcasting to obtain the IP address of the robot in the LAN. For more details, see the Broadcasting section.
The sample code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13
# -*- encoding: utf-8 -*- import socket ip_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind with the IP broadcasting port. ip_sock.bind(('0.0.0.0', 40926)) # Wait to receive data. ip_str = ip_sock.recvfrom(1024) # Output the data. print(ip_str)
Save the preceding code as rm_get_robot_ip.py and run the code to display the following output::
robot ip 192.168.0.115
By using Monitor robot address broadcasting you can see that the IP address of the robot in the LAN is
192.168.0.115
.
Prepare the connection script.
After obtaining the IP address of the robot, use the Python programming language to write a script in order to Establish control connection and enable SDK mode.
The sample code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
# -*- encoding: utf-8 -*- # Test environment: Python 3.6 import socket import sys # In networking connection mode, the current IP address of the robot is 192.168.0.115 and the control command port is port 40923. # Replace the IP address of the robot with the actual one. host = "192.168.0.115" port = 40923 def main(): address = (host, int(port)) # Establish a TCP connection with the control command port of the robot. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Connecting...") s.connect(address) print("Connected!") while True: # Wait for the user to enter control commands. msg = input(">>> please input SDK cmd: ") # When the user enters Q or q, exit the current program. if msg.upper() == 'Q': break # Add the ending character. msg += ';' # Send control commands to the robot. s.send(msg.encode('utf-8')) try: # Wait for the robot to return the execution result. buf = s.recv(1024) print(buf.decode('utf-8')) except socket.error as e: print("Error receiving :", e) sys.exit(1) if not len(buf): break # Disconnect the port connection. s.shutdown(socket.SHUT_WR) s.close() if __name__ == '__main__': main()
Save the preceding code as rm_networking_connection_sdk.py.
Run the script.
Windows: After installing the Python environment, double-click the *.py file to run it. If you fail to run the file, press the
Win+R
shortcut command and enter ``cmd’’. Then, press Enter to open the CLI and enter ``python rm_networking_connection_sdk.py’’ to run the file.Linux: Press
Ctrl+Alt+T
to open the CLI and enterpython rm_networking_connection_sdk.py
to run the file.Establish a TCP/IP control connection.
When
Connecting...'' appears in the running window, the system is attempting to establish a connection with the robot. When ``Connected!;
appears in the running window, the control connection has been established.
- Verify the connection
After successfully establishing the control connection, enter command
on the CLI. If the robot returns ok;
, the connection has been established and the robot has entered SDK mode. Then, you can enter control commands to control the robot.
USB connection¶
The USB connection method essentially uses the RNDIS protocol to virtualize the USB device on the robot as a network card and then initiate a TCP/IP connection via USB. For more information about RNDIS, refer to the RNDIS Wikipedia entry.
- Prepare the environment
- Prepare a PC with RNDIS enabled (check that RNDIS is ready on the PC.)
- Prepare a Micro-USB data cable.
- Establish a connection
Turn on the robot.
Turn on the robot without concerning yourself with the connection method switch.
Establish a USB connection
Connect one end of the USB data cable to the USB port on the smart central control of the robot and connect the other end to the PC.
Test the connection.
Open the CLI window and run the following command::
ping 192.168.42.2
If the CLI returns communication successful (as shown below), the connection is working properly, and you can proceed to the next step.:
PING 192.168.42.2 (192.168.42.2) 56(84) bytes of data. 64 bytes from 192.168.42.2: icmp_seq=1 ttl=64 time=0.618 ms 64 bytes from 192.168.42.2: icmp_seq=2 ttl=64 time=1.21 ms 64 bytes from 192.168.42.2: icmp_seq=3 ttl=64 time=1.09 ms 64 bytes from 192.168.42.2: icmp_seq=4 ttl=64 time=0.348 ms 64 bytes from 192.168.42.2: icmp_seq=5 ttl=64 time=0.342 ms --- 192.168.42.2 ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4037ms rtt min/avg/max/mdev = 0.342/0.723/1.216/0.368 ms
If the CLI returns Cannot access… or the response times out (as shown below), check whether the RNDIS service is correctly configured on the PC. Then, restart the vehicle to try again.:
PING 192.168.42.2 (192.168.42.2) 56(84) bytes of data. --- 192.168.42.2 ping statistics ---
4 packets transmitted, 0 received, 100% packet loss, time 3071ms
Prepare the connection.
The connection process is similar to Wi-Fi direct connection -> Prepare the connection script, except that you must replace the IP address of the robot with the IP address in USB mode.
The modified sample code is as follows:
1 2 3 4 5 6 7 8 9 10 11
# -*- encoding: utf-8 -*- # Test environment: Python 3.6 import socket import sys # In USB connection mode, the default IP address of the robot is 192.168.42.2 and the control command port is port 40923. host = "192.168.42.2" port = 40923 # other code
- Verify the connection
After successfully establishing the control connection, enter command
on the CLI. If the robot returns ok;
, the connection has been established and the robot has entered SDK mode. Then, you can enter control commands to control the robot.
UART connection¶
- Prepare the environment
- Prepare a PC and check that the USB-to-serial module driver has been installed.
- Prepare a USB-to-serial module.
- Prepare three Dupont lines.
- Establish a connection
Turn on the robot.
Turn on the robot without concerning yourself with the connection method switch.
Connect to the UART port.
Attach one end of the Dupont lines to the GND, RX, and TX pins on the UART port of the main control of the robot chassis and the other end to the GND, TX, and RX pins of the USB-to-serial module.
Configure UART to establish a communication connection.
The following example uses the Python programming language to configure UART in the Windows operating system.
Check that the PC has recognized the USB-to-serial module and confirm the serial port in Device Manager > Ports, such as COM3.
Install the serial module.:
pip install pyserial
Program to implement UART control by referring to the following sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
# -*- encoding: utf-8 -*- # Test environment: Python 3.6 import serial ser = serial.Serial() # Set the baud rate to 115200, 8 data bits, 1 stop bit, no parity bit, and set the timeout period to 0.2 seconds for the serial port. ser.port = 'COM3' ser.baudrate = 115200 ser.bytesize = serial.EIGHTBITS ser.stopbits = serial.STOPBITS_ONE ser.parity = serial.PARITY_NONE ser.timeout = 0.2 # Open the serial port. ser.open() while True: # Wait for the user to enter control commands. msg = input(">>> please input SDK cmd: ") # When the user enters Q or q, exit the current program. if msg.upper() == 'Q': break # Add the ending character. msg += ';' ser.write(msg.encode('utf-8')) recv = ser.readall() print(recv.decode('utf-8')) # Close the serial port. ser.close()
- Save the preceding code as rm_uart.py and run it.
- Verify the connection
After successfully establishing the control connection, enter command;
on the CLI. If the robot returns ok;
, the connection has been established and the robot has entered SDK mode. Then, you can enter control commands to control the robot.
Plaintext Protocol¶
Protocol Format¶
Control commands¶
IN:<obj> <command> <params> [<seq>];
- Description
- The format of the control command protocol, which is generally used to interact with the robot for control purposes.
- The ending character is
;
.
- Parameters
- obj (str): The control object string
- command (str): The control command string
- params (str): The command parameter string, which is generally in the format of <key> <value>
- seq (str): The command sequence number string, which is generally in the format of seq <seq_value>. This parameter is optional.
OUT:<result> [<seq>];
- Description
- The format of the control command response protocol, which is generally used to confirm the execution results of control commands.
- Unless otherwise stated, all control commands have responses.
- The ending character is
;
.
- Parameters
- result (exec_result_enum): The execution result string
- seq (str): The execution result sequence number string, which is generally in the format of seq <seq_value>
注解
<seq>
The <seq> parameter is used to identify the uniqueness of the current message. When the control command contains the <seq> parameter, the response result of the command contains the corresponding sequence number.
Message push¶
OUT: <obj> push <attr> <value>;
- Description
- The format of the message push protocol. You can receive messages after enabling message push through a control command.
- Message push runs at a fixed frequency, which is set when the message push is enabled.
- The ending character is
;
.
- Parameters
- obj (str): The push object
- attr (str): The push data attribute
- value (str): The push data value
Event reporting¶
OUT: <obj> event <attr> <value>;
- Description
- The format of the event reporting protocol. You can receive reporting after enabling an event reporting switch through a control command.
- The ending character is
;
.
- Parameters
- obj (str): The object of the event
- attr (str): The event data attribute
- value (str): The event data value
注解
The trigger mechanism
After the corresponding event reporting function is enabled, event reporting will be triggered when an event occurs.
IP broadcasting¶
OUT: robot ip <addr>;
- Parameters
- addr (str): The IPv4 address of the robot in the current connection method
注解
The broadcasting lifecycle
In Wi-Fi networking mode, the robot continuously broadcasts its own IPv4 address through the corresponding port, and you can connect to the robot through this IP address. When a connection is established, the broadcast stops.
The video stream¶
OUT: H.264-encoded real-time video stream data with a resolution of 1280×720 and a refresh rate of 30 fps. The video stream data must be correctly decoded to display the video picture in real time.
The audio stream¶
OUT: Opus-encoded real-time audio stream data with a sampling rate of 48,000 bps, a frame size of 960 bit, and a single channel. The audio stream data must be correctly decoded to play audio in real time.
小技巧
Decoder
For the sample code for decoding video and audio streams on the receiving end, refer to Stream Decoder.
注解
IN/OUT
In this document, the IN or OUT prefix in the control commands has no practical meaning. Instead, it only identifies the data flow direction of the current command from the perspective of the robot.
IN: indicates that the current data is sent from an external device to the robot.
OUT: indicates that the current data is sent from the robot to an external device.
During actual use, ignore this identifier and simply send and receive actual control commands.
Protocol Content¶
SDK mode control¶
Enter SDK mode¶
IN:command;
- Description
- Instructs the robot to enter the SDK mode.
- The robot will respond to other control commands only after it enters SDK mode.
Exit SDK mode.¶
IN: quit;
- Description
- Instructs the robot to exit SDK mode and reset all settings.
- In Wi-Fi/USB connection mode, the robot automatically exits SDK mode when the connection is disconnected.
Robot control¶
Robot movement mode control¶
IN:robot mode <mode>
- Description
- Sets the robot movement mode.
- Parameters
- mode (
mode_enum
): The robot movement mode
- Example
- robot mode chassis_lead;: Set the robot movement mode to “gimbal follows chassis”.
注解
Robot movement modes
The robot movement mode describes the relationship and mutual movement between the gimbal and the chassis. Each robot mode corresponds to a specific interaction relationship.
There are three robot movement modes:
- Gimbal follows chassis: In this mode, the yaw axis of the gimbal always follows the movement of the yaw axis of the chassis. In addition, the gimbal does not respond to the yaw axis control part of all control commands. The affected commands are gimbal movement speed control, gimbal relative position control, and gimbal absolute position control.
- Chassis follows gimbal: In this mode, the yaw axis of the chassis always follows the movement of the yaw axis of the gimbal. In addition, the chassis does not respond to the yaw axis control part of all control commands. The affected commands are chassis movement speed control, chassis wheel speed control, and chassis relative position control.
- Free: In this mode, the movement of the yaw axis of the gimbal does not affect the movement of the yaw axis of the chassis, and vice versa.
Obtain the robot movement mode¶
IN: robot mode ?
- Description
- Queries the current robot movement mode.
- Return values
- mode (
mode_enum
): The robot movement mode
- Example
- IN: robot mode ?;: Query the current robot movement mode.
- OUT: chassis_lead;: The robot returns the current movement mode, gimbal follows chassis.
警告
? in the query command
Note: There is a space between ? in the query command and the prior part of the command.
Obtain the remaining battery capacity of the robot¶
IN: robot battery ?
- Description
- Queries the remaining battery level of the robot.
- Return values
- battery_percentage (int:[1-100]): The remaining battery level of the robot. This value is 100 when the robot is fully charged.
- Example
- IN: robot battery ?;: Query the remaining battery level of the robot.
- OUT: 20; : The robot returns the current battery level, 20.
Chassis control¶
Chassis movement speed control¶
IN: chassis speed x <speed_x> y <speed_y> z <speed_z>
- Description
- Controls the chassis movement speed.
- Parameters
- speed_x (float:[-3.5,3.5]): The x-axis movement speed in m/s
- speed_y (float:[-3.5,3.5]): The y-axis movement speed in m/s
- speed_z (float:[-600,600]): The z-axis rotation speed in °/s
- Example
- chassis speed x 0.1 y 0.1 z 1;: The x-axis speed of the chassis is 0.1 m/s, the y-axis speed is 0.1 m/s, and the z-axis rotation speed is 1°/s.
Chassis wheel speed control¶
IN: chassis wheel w1 <speed_w1> w2 <speed_w2> w3 <speed_w3> w4 <speed_w4>
- Description
- Control the speed of the four wheels.
- Parameters
- speed_w1 (int:[-1000, 1000]): The speed of the front-right mecanum wheel in rpm
- speed_w2 (int:[-1000, 1000]): The speed of the front-left mecanum wheel in rpm
- speed_w3 (int:[-1000, 1000]): The speed of the rear-right mecanum wheel in rpm
- speed_w4 (int:[-1000, 1000]): The speed of the rea-left mecanum wheel in rpm
- Example
- chassis wheel w2 100 w1 12 w3 20 w4 11;: The speed of the front-left mecanum wheel of the chassis is 100 rpm, that of the front-right mecanum wheel is 12 rpm, that of the rear-right mecanum wheel is 20 rpm, and that of the rear-left mecanum wheel is 11 rpm.
Chassis relative position control¶
IN: chassis move { [x <distance_x>] | [y <distance_y>] | [z <degree_z>] } [vxy <speed_xy>] [vz <speed_z>]
- Description
- Controls the chassis to move to a specified position. The origin of the coordinate plane is the current position.
- Parameters
- distance_x (float:[-5, 5]): The x-axis movement distance in meters
- distance_y (float:[-5, 5]): The y-axis movement distance in meters
- degree_z (int:[-1800, 1800]): The z-axis rotation angle in degrees
- speed_xy (float:(0, 3.5]): The xy-axes movement speed in m/s
- speed_z (float:(0, 600]): The z-axis rotation speed in °/s
- Example
- chassis move x 0.1 y 0.2;: Taking the current position as the origin of the coordinate plane, move 0.1 m along the x-axis and 0.2 m along the y-axis.
Obtain the chassis speed¶
IN: chassis speed ?
- Description
- Obtain chassis speed information.
- Return values
- <x> <y> <z> <w1> <w2> <w3> <w4>: The x-axis movement speed (m/s), the y-axis movement speed (m/s), the z-axis rotation speed (°/s), the speed of the w1 front-right mecanum wheel (rpm), the speed of the w2 front-left mecanum wheel (rpm), the speed of the w3 rear-right mecanum wheel (rpm), and the speed of the w4 rear-left mecanum wheel (rpm)
- Example
- IN: chassis speed ?;: - Obtain speed information of the chassis.
- OUT: 1 2 30 100 150 200 250; : The current x-axis movement speed of the chassis is 1 m/s, the y-axis movement speed is 2 m/s, the z-axis rotation speed is 20°/s, the speed of wheel 1 is 100 rpm, the speed of wheel 2 is 100 rpm, the speed of wheel 3 is 100 rpm, and the speed of wheel 4 is 100 rpm.
Obtain the chassis position¶
IN: chassis position ?
- Description
- Obtains chassis position information.
- Return values
- <x> <y> <z>: x-axis position (m), y-axis position (m), and yaw angle (°)
- Example
- IN: chassis position ?;: Obtain position information of the chassis.
- OUT: 1 1.5 20;: Compared with the position of the chassis when the vehicle was turned on, the current position of the chassis is 1 m along the x-axis and 1.5 m along the y-axis, with a rotation angle of 20°.
Obtain the chassis posture¶
IN: chassis attitude ?
- Description
- Obtains chassis posture information.
- Return values
- <pitch> <roll> <yaw>: pitch-axis angle (°), roll-axis angle (°), and yaw-axis angle (°)
- Example
- chassis attitude ?;: Query the posture information of the chassis.
Obtain the chassis status¶
IN: chassis status ?
- Description
- Obtains chassis status information.
- Return values
- <static> <uphill> <downhill> <on_slope> <pick_up> <slip> <impact_x> <impact_y> <impact_z> <roll_over> <hill_static>
- static: Whether the chassis is still
- uphill: Whether the chassis is going uphill
- downhill: Whether the chassis is going downhill
- on_slope: Whether the chassis is on a slope
- pick_up: Whether the chassis is picked up
- slip: Whether the chassis is slipping
- impact_x: Whether the x-axis senses an impact
- impact_y: Whether the y-axis senses an impact
- impact_z: Whether the z-axis senses an impact
- roll_over: Whether the chassis is rolled over
- hill_static: Whether the chassis is still on a slope
- Example
- IN: chassis status ?;: Query the status of the chassis.
- OUT: 0 1 0 0 0 0 0 0 0 0 0; : The chassis is going uphill.
Chassis information push control¶
IN:chassis push {[position <switch> pfreq <freq>][attitude <switch> afreq <freq>] | [status <switch> sfreq <switch>] [freq <freq_all>]}
- Description
- Enables or disables information push for chassis attributes
- Frequency configuration
- Each function supports a separate frequency setting, for example:
- chassis push position on pfreq 1 attitude on;: Enable position and posture push, the frequency of position push is 1Hz, and the posture push frequency is the default value of 5Hz.
- Supports the unified configuration of the frequencies of all functions in the current module, for example:
- chassis push freq 10; #Set all chassis push frequencies to 10Hz.
- chassis push position pfreq 1 freq 5; #In this case, the freq parameter is specified, and the pfreq parameter is ignored.
- The supported frequencies are 1, 5, 10, 20, 30, and 50.
- For the push data format, see Chassis push information data.
- Parameters
- switch (
switch_enum
): When this parameter is set to on, pushing of the corresponding attribute is enabled. When this parameter is set to off, pushing of the corresponding attribute is disabled.- freq (int:(1,5,10,20,30,50)): The push frequency of the corresponding attribute
- freq_all (int:(1,5,10,20,30,50)): The push frequencies of all relevant chassis information
- Example
- chassis push attitude on;: Enable chassis posture information push.
- chassis push attitude on status on;: Enable chassis posture push and status information push.
- chassis push attitude on afreq 1 status on sfreq 5;: Enable chassis posture information push, with a push frequency of once per second. At the same time, enable chassis status information push, with a push frequency of five times per second.
- chassis push freq 10;: Set the push frequencies for all chassis information to 10 times per second.
Chassis push information data¶
OUT: chassis push <attr> <data>
- Description
- After the user enables chassis information push, the robot will push corresponding information to the user at the set frequency.
- Parameters
- attr (
chassis_push_attr_enum
): The name of the subscribed attribute
- data: The data of the subscribed attribute
- When attr is set to position, the content of data is <x> <y>.
- When attr is set to attitude, the content of data is <pitch> <roll> <yaw>.
- When attr is set to status, the content of data is <static> <uphill> <downhill> <on_slope> <pick_up> <slip> <impact_x> <impact_y> <impact_z> <roll_over> <hill_static>.
- Example
- chassis push attitude 0.1 1 3;: The pitch, roll, and yaw posture information of the current chassis are 0.1, 1, and 3 respectively.
Gimbal control¶
Gimbal movement speed control¶
IN: gimbal speed p <speed> y <speed>
- Description
- Controls the gimbal movement speed.
- Parameters
- p (float:[-450, 450]): The pitch-axis speed in °/s
- y (float:[-450, 450]): The yaw-axis speed in °/s
- Example
- gimbal speed p 1 y 1;: The pitch-axis speed of the gimbal is 1°/s, and the yaw-axis speed is 1°/s.
Gimbal relative position control¶
IN: gimbal move { [p <degree>] [y <degree>] } [vp <speed>] [vy <speed>]
- Description
- Controls the gimbal to move to a specified position. The origin of the coordinate plane is the current position.
- Parameters
- p (float:[-55, 55]): The pitch-axis angle in degrees
- y (float:[-55, 55]): The yaw-axis angle in degrees
- vp (float:[0, 540]): The pitch-axis movement speed in °/s
- vy (float:[0, 540]): The yaw-axis movement speed in °/s
- Example
- gimbal move p 10;: Taking the current position as the origin, move the gimbal to the position where the pitch-axis angle is 10°.
Gimbal absolute position control¶
IN: gimbal moveto { [p <degree>] [y <degree>] } [vp <speed>] [vy <speed>]
- Description
- Controls the gimbal to move to a specified position. The origin of the coordinate plane is the startup position.
- Parameters
- p (int:[-25, 30]): The pitch-axis angle (°)
- y (int:[-250, 250]): The yaw-axis angle (°)
- vp (int:[0, 540]): The pitch-axis movement speed (°)
- vy (int:[0, 540]): The yaw-axis movement speed (°)
- Example
- gimbal moveto p 10 y -20 vp 0.1;: Taking the robot startup position as the origin, move the gimbal to the position where the pitch-axis angle is 10° and the yaw-axis angle is -20°. At the same time, set the speed of the pitch axis to 0.1 °/s during the movement.
Gimbal sleep control¶
IN: gimbal suspend
- Description
- Puts the gimbal to sleep.
- Example
- gimbal suspend;: Puts the gimbal in the sleeping state.
Gimbal wakeup control¶
IN: gimbal resume
- Description
- Wakes up the gimbal from the sleeping state.
- Parameters
- None
- Example
- gimbal resume;: Wake up the gimbal from the sleeping state.
警告
The sleeping state When the gimbal is in the sleeping state, the motors of the gimbal axes will no longer exercise control, and the gimbal will not respond to any control commands.
To wake up the gimbal from the sleeping state, see Gimbal wakeup control.
Gimbal recenter control¶
IN: gimbal recenter
- Description
- Recenters the gimbal.
- Example
- gimbal recenter;: Recenter the gimbal.
Obtain the gimbal posture¶
IN: gimbal attitude ?
- Description
- Obtains gimbal posture information.
- Return values
- <pitch> <yaw>: pitch-axis angle (°) and yaw-axis angle (°)
- Example
- IN: gimbal attitude ?;: Query the angle information of the gimbal.
- OUT: -10 20;: Set the pitch-axis angle of the gimbal to -10° and the yaw-axis angle to 20°.
Gimbal information push control¶
IN: gimbal push <attr> <switch> [afreq <freq_all>]
- Description
- Enables or disables information push for gimbal attributes.
- For the push data format, see Gimbal push information data.
- Parameters
- attr (
gimbal_push_attr_enum
): The name of the subscribed attribute- switch (
switch_enum
): When this parameter is set to on, pushing of the corresponding attribute is enabled. When this parameter is set to off, pushing of the corresponding attribute is disabled.- freq_all: The push frequencies of all relevant gimbal information
- Example
- gimbal push attitude on;: Enable gimbal information push.
Gimbal push information data¶
OUT: gimabal push <attr> <data>
- Description
- After the user enables gimbal information push, the robot will push corresponding information to the user at the set frequency.
- Parameters
- attr (
gimbal_push_attr_enum
): The name of the subscribed attribute
- data: The data of the subscribed attribute
- When attr is set to attitude, the content of data is <pitch> <yaw>.
- Example
- gimbal push attitude 20 10;: Set the pitch-axis angle of the gimbal to 20° and the yaw-axis angle to 10°.
Blaster control¶
Single blaster shot amount¶
IN:blaster bead <num>
- Description
- Sets the single blaster shot amount.
- Parameters
- num (int:[1,5]): The shot amount
- Example
- blaster bead 2;: Instruct the blaster to fire two shots at a time.
Blaster firing control¶
IN: blaster fire
- Description
- Instructs the water gun to fire once.
- Example
- blaster fire;: Instruct the water gun to fire once.
Obtain the amount of a single blaster shot¶
IN: blaster bead ?
- Description
- Obtains the number of water bombs fired by the water gun at a time.
- Return values
- <num>: The number of water bombs fired by the water gun at a time
- Example
- IN: blaster bead ?;: Query the number of water bombs fired by the water gun at a time.
- OUT: 3;: The current number of water bombs fired by the water gun at a time is 3.
Armored plate control¶
Armored plate sensitivity control¶
IN: armor sensitivity <value>
- Description
- Sets the strike detection sensitivity of the armored plate.
- Parameters
- value (int:[1,10]): The greater the sensitivity of the armored plate, the easier it is to detect a strike. The default sensitivity value is 5.
- Example
- armor sensitivity 1;: Set the strike detection sensitivity of the armored plate to 1.
Obtain the armored plate sensitivity¶
IN: armor sensitivity ?
- Description
- Obtains the strike detection sensitivity of the armored plate.
- Parameters
- <value>: Sensitivity of the armored plate
- Example
- IN: armor sensitivity ?;: Query the strike detection sensitivity of the armored plate.
- OUT: 5;: Query the strike detection sensitivity of the armored plate.
Armored-plate event reporting control¶
IN: armor event <attr> <switch>
- Description
- Controls armored-plate detected event reporting.
- For the format of event reporting data, see Armored-plate event reporting data.
- Parameters
- attr (
armor_event_attr_enum
): The name of the event attribute- switch (
switch_enum
): The event attribute control switch
- Example
- armor event hit on;: Enable armored-plate detected event push.
Armored-plate event reporting data¶
OUT: armor event hit <index> <type>
- Description
- When an armored-plate hit event occurs, this message can be received from the event push port.
- Parameters
- index (int:[1, 6]): The ID of the armored plate where a hit event occurs
1
: At the rear end the chassis2
: At the front end of the chassis3
: On the left side of the chassis4
: On the right side of the chassis5
: On the left side of the gimbal6
: On the right side of the gimbal
- type (int:[0, 2]): The type of the current tap event
0
: A water-bomb attack1
: A strike2
: A hand hit
- Example
- armor event hit 1 0;: Armored plate 1 detects a water-gun attack.
Voice recognition control¶
Voice recognition event reporting control¶
IN: sound event <attr> <switch>
- Description
- Controls voice recognition event reporting. Once enabled, relevant events will be reported.
- For the format of reporting data, see Voice recognition event reporting data.
- Parameters
- attr (
sound_event_attr_enum
): The name of the event attribute- switch (
switch_enum
): The event attribute control switch
- Example
- sound event applause on;: Enables voice (applause) recognition.
Voice recognition event reporting data¶
OUT: sound event <attr> <data>
- Description
- When a certain voice event occurs, this message can be received from the event push port.
- For information about enabling this event, refer to Voice recognition event reporting control.
- Parameters
- attr (
sound_event_attr_enum
): The name of the event attribute
- data: The data of the event attribute
- When attr is set to
applause
, data is <count>, indicating the number of hand claps within a short time.
- Example
- sound event applause 2;: Two hand claps were recognized in a short time.
PWM control¶
Control the PWM output duty cycle¶
IN: pwm value <port_mask> <value>
- Description
- Sets the PWM output duty cycle.
- Parameters
- port_mask (hex:0-0xffff): The PWM extended port mask combination. The mask for output port X is 1 << (X-1).
- value (float:0-100): The PWM output duty cycle, which defaults to 12.5.
- Example
- pwm value 1 50;: Set the duty cycle of PWM port 1 to 50%.
PWM output frequency control¶
IN: pwm freq <port_mask> <value>
- Description
- Sets the PWM output frequency.
- Parameters
- port_mask (hex:0-0xffff): The PWM extended port mask combination. The mask for output port X is 1 << (X-1).
- value (int:XXX): The PWM output frequency
- Example
- pwm freq 1 1000;: Set the frequency of PWM port 1 to 1,000Hz.
LED control¶
LED lighting effect control¶
IN:led control comp <comp_str> r <r_value> g <g_value> b <value> effect <effect_str>
- Description
- This interface controls the robot’s LED lighting effect. Multiple effects can be configured.
- The marquee effect is available only to the LED lights on both sides of the gimbal.
- Parameters
- comp_str (
led_comp_enum
): The LED light number- r_value (int:[0, 255]): The red component value of RGB
- g_value (int:[0, 255]): The green component value of RGB
- b_value (int:[0, 255]): The blue component value of RGB
- effect_str (
led_effect_enum
): The type of the LED lighting effect
- Example
- led control comp all r 255 g 0 b 0 effect solid; : Set all LED lights of the robot to solid red.
Sensor adapter control¶
Obtain the ADC value of the sensor adapter¶
IN: sensor_adapter adc id <adapter_id> port <port_num> ?
- Description
- Obtains the ADC value of the sensor adapter.
- Parameters
- adapter_id (int:[1, 6]): The adapter ID
- port_num (int:[1, 2]): The port number
- Return values
- adc_value: Measure the voltage of the specified port on the corresponding adapter, whose range is [0V, 3,3V].
- Example
- IN: sensor_adapter adc id 1 port 1 ?;: Query the ADC value of port 1 on adapter 1
- OUT: 1.1;: The retrieved ADC value of the port is 1.1.
Obtain the I/O value of the sensor adapter¶
IN: sensor_adapter io_level id <adapter_id> port <port_num> ?
- Description
- Obtain the logic level of the I/O port on the sensor adapter.
- Parameters
- adapter_id (int:[1, 6]): The adapter ID
- port_num (int:[1, 2]): The port number
- Return values
- io_level_value: Measure the logical level of the specified port on the corresponding adapter, which is 0 or 1.
- Example
- IN: sensor_adapter io_level id 1 port 1 ?;: Query the I/O logic level of port 1 on adapter 1.
- OUT: 1;: The retrieved I/O value of the port is 1.
Obtain the I/O pin level transition time of the sensor adapter¶
IN: sensor_adapter pulse_period id <adapter_id> port <port_num>
- Description
- Obtains the level transition duration of the I/O port on the sensor adapter.
- Parameters
- adapter_id (int:[1, 6]): The adapter ID
- port_num (int:[1, 2]): The port number
- Return values
- pulse_period_value: Measure the level transition duration of the specified port on the corresponding adapter, in milliseconds.
- Example
- sensor_adapter pulse_period id 1 port 1;: Query the level transition duration of port 1 on adapter 1.
Sensor adapter event reporting control¶
IN: sensor_adapter event io_level <switch>
- Description
- Enables or disables the push of level transition events of the sensor adapter. When enabled, messages are pushed when the I/O level transits. For details, see the next section [Push sensor adapter level transition events](#Push sensor adapter level transition).
- Parameters
- switch (
switch_enum
): The control switch for level transition event reporting
- Example
- sensor_adapter event io_level on;: Enable the pushing of sensor adapter level transition events.
Sensor adapter event reporting data¶
OUT: sensor_adapter event io_level (<id>, <port_num>, <io_level>)
- Description
- Pushes a message when the sensor adapter encounters a level transition. This message can be received from the event push port.
- You need to enable push for sensor adapter level transition. For details, see Sensor adapter event reporting data.
- Parameters
- id: The sensor adapter ID
- port_num: The I/O port ID
- io_level: The current logic level
- Example
- sensor_adapter event io_level (1, 1, 0);: The logic level of I/O port 1 on adapter 1 transits to 0.
Infrared distance sensor control¶
Switch control for the infrared distance sensor¶
IN: ir_distance_sensor measure <switch>
- Description
- Enables or disables all infrared sensor switches.
- Parameters
- switch (
switch_enum
): The switch of the infrared sensor
- Example
- ir_distance_sensor measure on;: Enables all infrared distance sensors.
Obtain the distance measured by the infrared distance sensor¶
IN: ir_distance_sensor distance <id> ?
- Description
- Obtains the distance measured by the infrared distance sensor of the specified ID.
- Parameters
- id (int:[1, 4]): Infrared sensor ID
- Return values
- distance_value: The distance measured by the infrared sensor of the specified ID, in millimeters.
- Example
- IN: ir_distance_sensor distance 1 ?;: Query the distance measured by infrared distance sensor 1.
- OUT: 1000;: The current distance measured by the infrared distance sensor is 1,000 mm.
Servo control¶
Servo angle control¶
IN: servo angle id <servo_id> angle <angle_value>
- Description
- Set the servo angle.
- Parameters
- servo_id (int:[1, 3]): The servo ID
- angle_value (float:[-180, 180]): The specified angle in degrees
- Example
- servo angle id 1 angle 20;: Set the angle of servo 1 to 20°.
Servo speed control¶
IN: servo speed id <servo_id> speed <speed_value>
- Description
- Sets the speed of the specified servo.
- Parameters
- servo_id (int:[1, 3]): The servo ID
- speed_value (float:[-1800, 1800]): The set speed in °/s
- Example
- servo speed id 1 speed 20;: Set the speed of servo 1 to 10°/s.
Servo stop control¶
IN: servo stop
- Description
- Stops the servo.
- Example
- servo stop;: Stop the servo.
Servo angle query¶
IN: servo angle id <servo_id> ?
- Description
- Obtains the angle of the specified servo.
- Parameters
- servo_id (int:[1, 3]): The servo ID
- Return values
- angle_value: The angle of the specified servo
- Example
- IN: servo angle id 1 ?;: Obtain the angle of servo 1.
- OUT: 30;: The current angle of the servo is 30°.
Mechanical arm control¶
Control the relative position of the mechanical arm¶
IN: robotic_arm move x <x_dist> y <y_dist>
- Description
- Controls the mechanical arm to move a certain distance. The current position is the origin of the coordinates plane.
- Parameters
- x_dist (float:[]): The x-axis movement distance in centimeters
- y_dist (float:[]): The y-axis movement distance in centimeters
- Example
- robotic_arm move x 5 y 5;: Move the mechanical arm 5 cm along the x-axis and 5 cm along the y-axis.
Control the absolute position of the mechanical arm¶
IN: robotic_arm moveto x <x_pos> y <y_pos>
- Description
- Controls the mechanical arm to move to a certain position. The startup position of the robot is the origin of the coordinate plane.
- Parameters
- x_pos (float:[]): The target x-axis coordinate in centimeters
- y_pos (float:[]): The target y-axis coordinate in centimeters
- Example
- robotic_arm moveto x 5 y 5;: Move the mechanical arm to the 5 cm coordinate position on the x-axis and the 5 cm coordinate position on the y-axis.
Mechanical arm recenter control¶
IN: robotic_arm recenter
- Description
- Recenters the mechanical arm.
- Parameters
- None
- Example
- robotic_arm recenter;: Recenter the mechanical arm.
Mechanical arm stop control¶
IN: robotic_arm stop
- Description
- Stops the mechanical arm.
- Parameters
- None
- Example
- robotic_arm stop;: Stop the mechanical arm.
Query the absolute position of the mechanical arm¶
IN: robotic_arm position ?
- Description
- Obtains the position of the mechanical arm.
- Parameters
- None
- Return values
- <x_pos> <y_pos>: The coordinates of the mechanical arm
- x_pos: The x-axis coordinate in centimeters
- y_pos: The y-axis coordinate in centimeters
- Example
- IN: robotic_arm position ?;: Query the position of the mechanical arm.
- OUT: 50 60;: The mechanical arm is 50 cm from the calibration point on the x-axis and 60 cm on the y-axis.
Mechanical gripper control¶
Mechanical gripper opening control¶
IN: robotic_gripper open [leve <level_num>]
- Description
- Opens the mechanical gripper.
- Parameters
- level_num (int:[1,4]): The opening force level of the mechanical gripper, whose range is [1,4]
- Example
- robotic_gripper open 1;: Opens the mechanical arm with a force of 1.
Mechanical gripper closing control¶
IN: robotic_gripper close [leve <level_num>]
- Description
- Closes the mechanical gripper.
- Parameters
- level_num (int:[1,4]): The closing force level of the mechanical gripper, whose range is [1,4]
- Example
- robotic_gripper close 1;: Closes the mechanical arm with a force of 1.
注解
The mechanical gripper control force
The mechanical gripper control force describes the speed of the mechanical gripper during the movement and the maximum clamping force in the locked-rotor state.
The greater the force, the faster the movement speed and the greater the clamping force.
Query the open/close status of the mechanical gripper¶
IN: robotic_gripper status ?
- Description
- Obtains the open/close status of the mechanical gripper
- Parameters
- None
- Return values
- status: The current open/close status of the mechanical gripper
0
: The mechanical gripper is fully closed.1
: The mechanical gripper is neither fully closed nor fully opened.2
: The mechanical gripper is fully opened.
- Example
- IN: robotic_gripper status ?;: Obtain the open/close status of the mechanical gripper.
- OUT: 2;: The mechanical gripper is opened.
Intelligent recognition function control¶
Control intelligent recognition function attributes¶
IN: AI attribute { [line_color <line_color>] [marker_color <marker_color>] [marker_dist <dist>] }
- Description
- Controls intelligent recognition function attributes.
- Parameters
- line_color (
line_color_enum
): The line identification color- marker_color (
marker_color_enum
): The visual label color- marker_dist (float:[0.5, 3]): The minimum effective distance of visual labels in meters
- Example
- IN: AI attribute line_color red;: Set the line identification color to red.
Control intelligent recognition function push¶
IN: AI push <attr> <switch>
- Description
- Controls intelligent recognition function push.
- Different intelligent recognition functions are mutually exclusive and cannot be enabled at the same time. If mutually exclusive functions exist in the set of functions to enable, all functions will fail to be enabled. For the mutual exclusion relationships, refer to Mutual exclusion relationships between intelligent recognition functions.
- You cannot currently set the frequency.
- For the data submission format, see Intelligent recognition function push data.
- Parameters
- attr (
AI_push_attr_enum
): Enumerated intelligent recognition functions, which cannot be enabled at the same time for certain parameters.- switch (
switch_enum
): When this parameter is set to on, pushing of the corresponding attribute is enabled. When this parameter is set to off, pushing of the corresponding attribute is disabled.
- Example
- IN: AI push marker on line on;: Enable the push for line and visual label recognition data.
注解
Mutual exclusion relationships between intelligent recognition functions
Due to the limited computing resources of the robot, mutual exclusion relationships exist between intelligent recognition functions. Mutually exclusive intelligent functions cannot be turned on at the same time. Intelligent recognition functions are divided into groups A and B:
A people pose marker robot B line
For the preceding two groups, only one function can be turned on for each group at a time, and any function combinations between the two groups are allowed.
Intelligent recognition function push data¶
OUT: AI push <attr> <data>
- Description
- After you enable intelligent recognition function push, the robot will push corresponding information to you at the set frequency.
- Parameters
- attr (
AIi_push_attr_enum
): The subscribed function name
- data: The subscribed attribute data
- When attr is set to person, the content is <n> <x1> <y1> <w1> <h1> <x2> <y2>… <wn> <hn>
- When attr is set to gesture, the content is <n> <info1> <x1> <y1> <w1> <h1> <x2> <y2>… <wn> <hn>. For the meaning of info, refer to
AI_pose_id_enum
.- When attr is set to marker, the content is <n> <info1> <x1> <y1> <w1> <h1> <x2> <y2>… <wn> <hn>. For the meaning of info, refer to
AI_marker_id_enum
.- When attr is set to line, the content is <n> <x1> <y1> <θ1> <c1> <x2> <y2>… <θ10n> <c10n>
- When attr is set to robot, the content is <n> <x1> <y1> <w1> <h1> <x2> <y2>… <wn> <hn>
- Example
- OUT: AI push person 1 0.5 0.5 0.3 0.7;: A pedestrian is currently recognized, the coordinates are (0.5, 0.5), the target width is 0.3, and the height is 0.7.
注解
Intelligent function push data
In intelligent recognition function push data, n, x, y, w, and h are all general data, which are described as follows:
n: The number of recognized targets
x: The center of the recognized target on the x-axis of the field of view
y: The center of the recognized target on the y-axis of the field of view
w: The width of the recognized target
h: The height of the recognized target
n, x, y, θ, and c in line recognition push data are described as follows:
n: The number of recognized lines. Each line has 10 points. For detailed point data, see below.
x: The line point is on the x-axis of the field of view.
y: The line point is on the y-axis of the field of view.
θ: The tangent angle of the line point
c: The curvature of the curve corresponding to the line point, whose range is [0, 10]. The value 0 indicates a straight line.
The preceding x, y, w, and h values are all normalized values, whose ranges are all [0, 1]. The origin of the coordinate plane is at the upper-left of the field of view.
Camera control¶
Camera exposure configuration¶
IN: camera exposure <ev_level>
- Description
- Sets the camera exposure value.
- Parameters
- ev_level (
camera_ev_enum
): Enumerated camera exposure values
- Example
- camera exposure small;: Set the camera exposure value to low.
Video stream control¶
Video stream on control¶
IN: stream on
- Description
- Turns on the video stream.
- When turned on, you can receive H.264-encoded stream data from the video stream port.
- Example
- stream on;: Turn on the video stream.
Video stream off control¶
IN: stream off
- Description
- Turns off the video stream.
- When turned off, H.264-encoded stream data output stops.
- Example
- stream off;: Turn off the video stream.
Audio stream control¶
Audio stream on control¶
IN: audio on
- Description
- Turns on the audio stream.
- When turned on, you can receive Opus-encoded audio stream data from the audio stream port.
- Example
- audio on;: Turn on the audio stream.
Audio stream off control¶
IN: audio off
- Description
- Turns off the audio stream.
- When turned off, Opus-encoded audio stream data output stops.
- Example
- audio off;: Turn off the audio stream.
IP broadcasting¶
OUT: robot ip <ip_addr>
- Description
- When no connection is established with the robot, this message can be received from the IP broadcasting port. After a connection is established, this message stops being broadcast.
- Displays the IP address of the current robot, which is applicable to situations where the robot is in the same LAN but the IP information of the robot is unknown.
- Parameters
- ip_addr: The current IP address of the robot
- Example
- robot ip 192.168.1.102;: The current IP address of the robot is 192.168.1.102.
Event data acquisition¶
Turn on keyboard data push¶
IN: game_msg on
- Description
- Turns on keyboard and mouse data push for youth competition systems.
- Parameters
- None
- Example
- game_msg on;: Turn on keyboard and mouse data push.
Turn off keyboard data push¶
IN: game_msg off
- Description
- Turns off keyboard and mouse data push for youth competition systems.
- Parameters
- None
- Example
- game_msg off;: Turn off keyboard and mouse data push.
Keyboard data push data¶
OUT: game msg push <data>
- Description
- After you enable event data push, the robot will push the corresponding information as a string to you at a fixed frequency.
- Parameters
- data: The subscribed attribute data
- The content is [cmd_id, len, mouse_press, mouse_x, mouse_y, seq, key_num, key_1, key2,…].
- mouse_press: 1 for the right mouse button, 2 for the left mouse button, and 4 for the central mouse button
- mouse_x: The mouse movement distance, whose range is -100 to 100
- mouse_y: The mouse movement distance, whose range is -100 to 100
- seq: The serial number, whose range is 0 to 255
- key_num: The number of recognized buttons, which cannot exceed three
- key1: The key value
- Example
- OUT: game msg push [0, 6, 1, 0, 0, 255, 1, 199]; : cmd_id is 0, the data length is 6, the right mouse button is recognized, the w button is pressed, and the packet serial number is 255.
Data Description¶
-
switch_enum
¶ on
: Onoff
: Off
-
mode_enum
¶ chassis_lead
: Gimbal follows chassis modegimbal_lead
: Chassis follows gimbal modefree
: Free mode
-
chassis_push_attr_enum
¶ position
: The chassis positionattitude
: The chassis posturestatus
: The chassis status
-
gimbal_push_attr_enum
¶ attitude
: The gimbal posture
-
armor_event_attr_enum
¶ hit
: The armor hit detected
-
sound_event_attr_enum
¶ applause
: Applause
-
led_comp_enum
¶ all
: All LED lightstop_all
: All LED lights on the gimbaltop_right
: Right LED light on the gimbaltop_left
: Left LED light on the gimbalbottom_all
: All LED lights on the chassisbottom_front
: Front LED light on the chassisbottom_back
: All rear LED lightsbottom_left
: All left LED lightsbottom_right
: All right LED lights
-
led_effect_enum
¶ solid
: Solid onoff
: Offpulse
: Breathingblink
: Flashingscrolling
: Marquee
-
line_color_enum
¶ red
: Redblue
: Bluegreen
: Green
-
marker_color_enum
¶ red
: Redblue
: Blue
-
ai_push_attr_enum
¶ person
: Pedestriangesture
: Gestureline
: Linemarker
: Visual labelrobot
: Robot
-
ai_pose_id_enum
¶ 4
: The forward V gesture5
: The reverse V gesture6
: The shooting gesture
-
ai_marker_id_enum
¶ 1
: Stop4
: Turn left5
: Turn right6
: Move forward8
: Red heart10 - 19
: A number between 0 and 920 - 45
: A letter between A and Z
-
camera_ev_enum
¶ default
: Defaultsmall
: Smallmedium
: Mediumlarge
: Large
Formation Control¶
Introduction¶
The formation control function arranges the actions of multiple robots connected to the same LAN, using the plaintext SDK for overall control. Users can use this function to implement more complex actions and implement attractive formation movement.
This function works by connecting multiple robots to the same LAN in Wi-Fi router mode, allowing you to communicate with these robots by using Python scripts on your PC while sending plaintext SDK commands in order to implement formation control. The following simple example explains how to implement formation control by using a Python script through the plaintext SDK.
Environment¶
- Hardware devices: a router, two EP robots, and a PC
- Python version: Python 3.6
Establish a multi-device connection¶
Set the EP robots to operate in Wi-Fi router mode and, in the app, connect the robots for formation control to the router one by one. After successfully establishing the connection, go to the connection page in the app settings and record the IP addresses of the robots. For detailed instructions, refer to Wi-Fi router mode.
Run the sample program¶
Enter the IP addresses in the IP_LIST list in the sample code and save the script code as ep.py.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
#!/usr/bin/env python3 # coding=utf-8 import sys import time import threading import socket IP_LIST = ['192.168.1.103', '192.168.1.117'] EP_DICT = {} class EP: def __init__(self, ip): self._IP = ip self.__socket_ctrl = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__socket_isRelease = True self.__socket_isConnect = False self.__thread_ctrl_recv = threading.Thread(target=self.__ctrl_recv) self.__seq = 0 self.__ack_list = [] self.__ack_buf = 'ok' def __ctrl_recv(self): while self.__socket_isConnect and not self.__socket_isRelease: try: buf = self.__socket_ctrl.recv(1024).decode('utf-8') print('%s:%s' % (self._IP, buf)) buf_list = buf.split(' ') if 'seq' in buf_list: self.__ack_list.append(int(buf_list[buf_list.index('seq') + 1])) self.__ack_buf = buf except socket.error as msg: print('ctrl %s: %s' % (self._IP, msg)) def start(self): try: self.__socket_ctrl.connect((self._IP, 40923)) self.__socket_isConnect = True self.__socket_isRelease = False self.__thread_ctrl_recv.start() self.command('command') self.command('robot mode free') except socket.error as msg: print('%s: %s' % (self._IP, msg)) def exit(self): if self.__socket_isConnect and not self.__socket_isRelease: self.command('quit') self.__socket_isRelease = True try: self.__socket_ctrl.shutdown(socket.SHUT_RDWR) self.__socket_ctrl.close() self.__thread_ctrl_recv.join() except socket.error as msg: print('%s: %s' % (self._IP, msg)) def command(self, cmd): self.__seq += 1 cmd = cmd + ' seq %d;' % self.__seq print('%s:%s' % (self._IP, cmd)) self.__socket_ctrl.send(cmd.encode('utf-8')) timeout = 2 while self.__seq not in self.__ack_list and timeout > 0: time.sleep(0.01) timeout -= 0.01 if self.__seq in self.__ack_list: self.__ack_list.remove(self.__seq) return self.__ack_buf if __name__ == "__main__": # Instantiate the robots for ip in IP_LIST: print('%s connecting...' % ip) EP_DICT[ip] = EP(ip) EP_DICT[ip].start() for ip in IP_LIST: EP_DICT[ip].command('gimbal moveto p 0 y 0 vp 90 vy 90 wait_for_complete false') time.sleep(3) while True: for ip in IP_LIST: EP_DICT[ip].command('gimbal moveto p 0 y 45 vp 90 vy 90 wait_for_complete false') time.sleep(3) for ip in IP_LIST: EP_DICT[ip].command('gimbal moveto p 0 y -45 vp 90 vy 90 wait_for_complete false') time.sleep(3) for ip in IP_LIST: EP_DICT[ip].exit()
Run the script.
- For Windows: After installing the Python environment, click ep.py to start the script.
- For Linux: Enter “python ep.py” on the CLI to start the script.
- View the running performance.
The gimbals of the robots for formation control move together in the yaw-axis direction.
- View the running result.
The command-line port outputs cleartext communication data between the robots and the host.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 192.168.1.103 connecting... 192.168.1.103:command seq 1 192.168.1.103:ok seq 1 192.168.1.103:robot mode free seq 2 192.168.1.103:ok seq 2 192.168.1.117 connecting... 192.168.1.117:command seq 1 192.168.1.117:ok seq 1 192.168.1.117:robot mode free seq 2 192.168.1.117:ok seq 2 192.168.1.103:gimbal moveto p 0 y 0 vp 90 vy 90 wait_for_complete false seq 3 192.168.1.103:ok seq 3 192.168.1.117:gimbal moveto p 0 y 0 vp 90 vy 90 wait_for_complete false seq 3 192.168.1.117:ok seq 3
Introduction to Python Programming¶
Introduction¶
The Python programming described in this chapter refers to connecting to the EP robot with your device and then going to the app lab to perform Python programming.
On the Python programming page, players are allowed to complete Python programming based on the basic syntax of Python 3.6.6. They can also write their own Python programs by referring to the RoboMaster EP Programming Module Manual <https://dl.djicdn.com/downloads/ROBOMASTER_EP/RoboMaster_EP_Programming_Manual_CHS.pdf> on the official website and Python API on this website to call the programming interfaces provided by RoboMaster EP. They can also assemble the generated Python programs into autonomous programs or custom skills.
The multi-device communication interface of RoboMaster EP allows multiple robots to communicate with each other through Python programming for real-time interaction between multiple devices. EP allows you to program custom UI systems and develop virtual controls in Python, enabling the flexible design of interactive interfaces and expanded EP applications.
Interface¶
To facilitate code editing, the PC app is generally used for Python programming.
![]()
Python programming interface on the PC
Reference documents¶
Introduction to Python Functions¶
Multi-device Communication System¶
The multi-device communication system implements communication between robots through a local area network (LAN). With this system, you can have multiple robots collaborate to realize functions such as performances in formation.
When using this system, you must add all target robots to the same LAN and use the official Python API for programming in order to implement the communication mechanism between robots and realize other functions.
For the Python API, refer to :doc:`Custom UI System<./multi_comm>`_.
User-defined UI System¶
A custom UI system allows users to generate custom UI controls by using their own programs to expand the input and output of the programs.
Processing input and output is an important part of our programming work. For our robot, the program output can be actions of the chassis, gimbal, blaster, or other modules, or lighting effects, sound effects, and other effects. The input can be initial variables, visual recognition by the robot, applause recognition, detection of armor plate strikes, and mobile phone gyroscope signals. Now, we can interact with the generated UI controls through a custom UI system to implement input. We can also use the processing results of the program to output information through the UI controls.
We can write Python programs in the RoboMaster app, call related interfaces of the custom UI system to generate UI controls, and bind event callbacks of the controls. After programming and debugging the program in the lab, we can assemble the program into custom skills and release them for single-device driving or multiplayer competition.
For information on the Python API, refer to Custom UI System.
Python API¶
Multi-device Communication¶
-
multi_comm_ctrl.
set_group
(send_group, recv_group_list)¶ Description: Sets the group number of the device to
send_group
, and the device can receive messages from the group numbers registered inrecv_group_list
. If the ``recv_group_list’’ parameter is not used, messages from group 0 will be received by default.参数: - send_group (int) – The sending group number of the current device. The default group number is 0.
- recv_group_list (list/tuple) – The current list of groups that receive messages, whose type can be list or tuple
返回: None
Example: multi_comm_ctrl.set_group(1, (1,2,3))
Example description: Set the current sending group number to 1 and receive messages from groups 1, 2, and 3. If the receiving group includes the sending group, you will receive the messages you send.
-
multi_comm_ctrl.
send_msg
(msg, group)¶ Description: Send a message via multi-device communication. Sending groups for this message can be set separately.
参数: - msg (int) – The message that needs to be sent
- group (int) – An optional parameter, which specifies the current message sending group number. If you do not specify this parameter, the previously set group number will be used by default.
返回: None
Example: multi_comm_ctrl.send_msg('RoboMaster EP', 3)
Example description: Send the
'RoboMaster EP'
message to group 3
-
multi_comm_ctrl.
recv_msg
(timeout)¶ Description: Receive messages (valid when recv_callback is not registered). You can set a timeout period. 参数: timeout (int) – The waiting time, which indicates the waiting time of the receiving function, whose accuracy is 1 second. The default value of this parameter is 72 seconds. 返回: <msg_group>, <msg>
, which is the group number of the message sender and the content of the messageExample: group, recv_msg = multi_comm_ctrl.recv_msg(30)
Example description: Receive the message with a waiting time of 30 seconds, where “group” is the group number of the message sender, and “msg” is the content of the received message
-
multi_comm_ctrl.
register_recv_callback
(callback)¶ Description: Registers the callback function for receiving messages. When a message is received, the callback function is run automatically. 参数: callback (function) – The callback function to be registered. The prototype of the callback function is def callback(msg)
, where the type of themsg
parameter is the(msg_group, msg)
tuple.返回: None Example:
1 2 3 4 5 6 | #Define a function and register it as a callback function for receiving messages
def recv_callback(msg):
pass
multi_comm_ctrl.register_recv_callback(recv_callback)
|
提示
For a description of the module, refer to Multi-device Communication.
Custom UI System¶
Common¶
The methods described in this section are applicable to all custom UI controls except Stage.
-
common_object.
set_active
(status)¶ Description: Sets whether to display the current control 参数: status (bool) – The activity of the control, where True indicates to display the current control, and False indicates to hide the current control 返回: None Example: my_Slider.set_active(Flase)
Example description: Set the my_Slider control to hidden
-
common_object.
get_active
()¶ Description: Obtains the display state of the current control 参数: void – None 返回: A boolean value, which indicates the display state of the control Example: status = my_Slider.get_active()
Example description: Obtain the display state of the my_Slider control and assign it to the status variable
-
common_object.
set_name
(name)¶ Description: Set the name of the current control 参数: name (string) – Name of the control 返回: None Example: my_Dropdown.set_name('my_dropdown')
Example description: Set the name of the my_Dropdown control to “my_dropdown”
-
common_object.
get_name
()¶ Description: Obtains the name of the current control 参数: void – None 返回: A string, which indicates the name of the control Example: name = my_Dropdown.get_name()
Example description: Obtain the name of the my_Dropdown control and assign it to the name variable
-
common_object.
set_position
(x, y)¶ Description: Sets the coordinates of the control, where the origin is at the center of the screen
参数: - x (int) – The abscissa of the control, whose value is the actual pixel position on the screen. The 0 point is at the horizontal center of the screen, and rightward is the positive direction.
- y (int) – The ordinate of the control, whose value is the actual pixel position on the screen. The 0 point is at the vertical center of the screen, and upward is the positive direction.
返回: None
Example: my_Text.set_position(-200, 500)
Example description: Set the coordinates of the my_Text control to (-200, 500)
-
common_object.
get_position
()¶ Description: Obtains the coordinates of the control 参数: void – None 返回: [x,y], which represents the position of the control Example: pos = my_Text.get_position()
Example description: Obtain the position of the my_Text control and assign it to the pos variable, which is a list
-
common_object.
set_size
(w, h)¶ Description: Sets the size of the control
参数: - w (int) – Width of the control
- h (int) – Height of the control
返回: None
Example: my_Button.set_size(300, 200)
Example description: Set the width of the my_Button control to 300 and the height to 200
-
common_object.
get_size
()¶ Description: Obtains the size of the control 参数: void – None 返回: [w,h], which represents the size of the control Example: size = my_Button.get_size()
Example description: Obtain the size of the my_Button control and assign it to the size variable, which is a list
-
common_object.
set_rotation
(degree)¶ Description: Sets the rotation angle of the control 参数: degree (int) – The rotation angle of the control, whose range is [0, 360]. A positive value indicates clockwise rotation, and a negative value indicates counterclockwise rotation. 返回: None Example: my_Button.set_rotation(90)
Example description: Set the my_Button control to rotate 90 degrees clockwise
-
common_object.
get_rotation
()¶ Description: Obtains the rotation angle of the control 参数: void – None 返回: An int value, which indicates the rotation angle of the control, whose range is [0, 360]. A positive value indicates clockwise rotation, and a negative value indicates counterclockwise rotation. Example: degree = my_Button.get_rotation()
Example description: Obtain the rotation angle of the my_Button control and assign it to the degree variable
-
common_object.
set_privot
(x, y)¶ Description: Sets the anchor coordinates of the control, where the input parameter is a normalized parameter. The origin is at the lower-left corner of the control. The anchor point of the control defaults to the center of the control, that is (0.5, 0.5). The position and rotation of the control are controlled by the anchor point.
参数: - x (int) – The x-coordinate of the anchor point, whose range is [0, 1]. Rightward is the positive direction.
- y (int) – The y-coordinate of the anchor point, whose range is [0, 1]. Upward is the positive direction.
返回: None
Example: my_Button.set_privot(0, 1)
Example description: Set the anchor point of the control to the upper-left corner of the control
-
common_object.
get_privot
()¶ Description: Obtains the anchor coordinates of the control 参数: void – None 返回: [x,y], which represents the anchor coordinates of the control Example: privot = my_Button.get_privot()
Example description: Obtain the anchor coordinates of the control and assign them to the privot variable, which is a list
-
common_object.
set_order
(order)¶ Description: Sets the display priority of the control. If multiple controls overlap with each other, the control with higher priority is in the upper layer. The greater the display priority value, the higher the priority. 参数: order (int) – The specified priority of the control. If multiple controls overlap with each other, the control with higher priority is displayed first. 返回: None Example: my_Button.set_order(8)
Example description: Set the display priority of the control to 8. When multiple controls overlap, the controls with priority values lower than this priority value are covered.
-
common_object.
get_order
()¶ Description: Obtains the display priority value of the control 参数: void – None 返回: An int value, which indicates the display priority value of the control Example: order = my_Button.get_order()
Example description: Obtain the display priority value of the my_Button control and assign it to the order variable
-
common_object.
callback_register
(event, callback)¶ Description: The callback function triggered by the registered control event. When the control detects this event, the registered callback function is executed.
参数: - event (string) –
Specify the trigger event of the callback function
The events that can be registered for each control are described as follows:
- The Button control:
on_click
: Trigger this event when the button is released in the process of pressing and releasing the button onceon_press_down
: Trigger this event when the button is pressedon_press_up
: Trigger this event when the button is released
- The Toggle control:
- Trigger this event when the value of
on_value_changed
changes. The args parameter in the callback function is a boolean value, which is the updated value of the Toggle control.
- Trigger this event when the value of
- The Dropdown control:
- Trigger this event when the value of
on_value_changed
changes. The args parameter in the callback function is an int value, which is the selected index entry after the value of the Toggle control changes.
- Trigger this event when the value of
- The Text control:
- No trigger events are available.
- The InputField control:
- Trigger this event when the value of
on_value_changed
changes. The args parameter in the callback function is a string, which is the updated value of the InputField control.
- Trigger this event when the value of
- callback (function) – The callback function that needs to be registered. The unified signature of callback functions is
def callback(widget,*args,**kw):
, where widget is the reference to the control that triggered the event, and args and kw are parameters.
返回: None
Example 1: - event (string) –
1 2 3 4 5 6 | # When the my_Button control is clicked, the information will be output to the console, and the robot will shoot once.
def button_callback(widget,*args,**kw):
print('the button is clicked and the button's name is '+ widget.get_name())
gun_ctrl.fire_once()
my_Button.callback_register('on_click',button_callback)
|
example 2:
1 2 3 4 5 6 7 | # When the my_Toggle control is clicked, the value of the control changes, the information is output to the console, and the robot will play a sound.
def toggle_callback(widget,*args,**kw):
print("the toggle's value is changed and the toggle's name is "+ widget.get_name())
print("the toggle's value now is "+ str(args))
media_ctrl.play_sound(rm_define.media_sound_recognize_success)
my_Toggle.callback_register('on_value_changed',toggle_callback)
|
example 3:
1 2 3 4 5 6 7 | # When you click the my_Dropdown control to change its selected value, the value changes, the information is output to the console, and the robot will play a sound.
def dropdown_callback(widget,*args,**kw):
print("the dropdown's value is changed and the dropdown's name is "+ widget.get_name())
print("the dropdown's value now is "+ str(args))
media_ctrl.play_sound(rm_define.media_sound_solmization_1A)
my_Dropdown.callback_register('on_value_changed',dropdown_callback)
|
example 4:
1 2 3 4 5 6 | # When you click the my_InputField control to change its selected value, the value changes, and the information is output to the console.
def input_field_callback(widget,*args,**kw):
print("the input_field's value is changed and the input_field's name is "+ widget.get_name())
print("the input_field's value now is "+ str(args))
my_InputField.callback_register('on_value_changed',input_field_callback)
|
Stage¶
When the system is initialized, a stage object of the Stage class is automatically created, which can be used directly without the need for users to create it themselves.
-
stage.
add_widget
(widget_obj)¶ Description: Adds the controls in the parameter to the UI 参数: widget_obj (object) – Control objects to be added to the UI 返回: None Example:
1 2 3 4 | #Create a Button object and add it to the UI
my_button = Button()
stage.add_widget(my_button)
|
-
stage.
remove_widget
(widget_obj)¶ Description: Removes the controls of the parameter from the UI 参数: widget_obj (object) – The controls that need to be removed from the UI 返回: None Example: stage.remove_widget(my_button)
Example description: Remove the my_button control from the UI
Button¶
The Button control is used to start or confirm an operation in response to a click from users.
Description: Set the text attribute of the button object
参数: - content (string) – The content of the string displayed on the button
- [color_r, color_g, color_b, color_a] (list) – Optional parameters, which indicate the color of the string to be displayed. These parameters respectively indicate the r value, b value, g value, and transparency of the displayed color, and their value ranges are all [0, 255].
- align (enum) – An optional enumeration-type parameter, which indicates the alignment mode of the text to be displayed. For details, see the
align
table. - size (int) – The font size of the displayed text
返回: None
Example: my_Button.set_text(120, 120, 120, 255, text_anchor.upper_left, 12)
Example description: Set the rgb value of text color to (120, 120, 120), the transparency to 255, the text alignment mode to top-left, and the font size to 12
Description: Set the color of the text
参数: - r (int) – The r value of text color, whose range is [0, 255]
- g (int) – The g value of text color, whose range is [0, 255]
- b (int) – The b value of text color, whose range is [0, 255]
- a (int) – The transparency of text color, whose range is [0, 255]
返回: None
Example: my_button.set_text_color(120, 120, 120, 200)
Example description: Set the rgb value of text color to (120, 120, 120) and the transparency to 200
Description: Set the text alignment mode 参数: align (enum) – An optional enumeration-type parameter, which indicates the alignment mode of the text to be displayed. For details, see the align
table.返回: None Example: my_button.set_text_align(text_anchor.upper_left)
Example description: Set the text alignment mode to top-left
Description: Set the text font size 参数: size (int) – Text font size 返回: None Example: my_button.set_text_size(12)
Example description: Set the text font size to 12
Description: Set the background color of the button
参数: - r (int) – The r value of font color, whose range is [0, 255]
- g (int) – The g value of font color, whose range is [0, 255]
- b (int) – The b value of font color, whose range is [0, 255]
- a (int) – The transparency of font color, whose range is [0, 255]
返回: None
Example: my_button.set_background_color(200, 200, 200, 230)
Example description: Set the rgb value of background color to (200, 200, 200) and the transparency to 230
Toggle¶
The Toggle control is used to draw a switch on the screen and perform certain operations by turning the switch on and off.
-
toggle_object.
set_text
(string, [color_r, color_g, color_b, color_a, ]align, size)¶ Description: Set the display text of the control
参数: - string (string) – The content of the string displayed on the control
- [color_r, color_g, color_b, color_a] (list) – Optional parameters, which indicate the color of the string to be displayed. These parameters respectively indicate the r value, b value, g value, and transparency of the displayed color, and their value ranges are all [0, 255].
- align (enum) – An optional enumeration-type parameter, which indicates the alignment mode of the text to be displayed. For details, see the
align
table. - size (int) – The font size of the displayed text
返回: None
Example: my_Toggle.set_text(120, 120, 120, 200, text_anchor.upper_left, 12)
Example description: Set the rgb value of text to (120, 120, 120), the transparency to 200, the text alignment mode to top-left, and the font size to 12
-
toggle_object.
set_text_color
(r, g, b, a)¶ Description: Sets the color of text
参数: - r (int) – The r value of text color, whose range is [0, 255]
- g (int) – The g value of text color, whose range is [0, 255]
- b (int) – The b value of text color, whose range is [0, 255]
- a (int) – The transparency of text color, whose range is [0, 255]
返回: None
Example: my_Toggle.set_text_color(120, 120, 120, 200)
Example description: Set the rgb value of the font to (120, 120, 120) and the transparency to 200
-
toggle_object.
set_text_align
(align)¶ Description: Set the text alignment mode 参数: align (enum) – An optional enumeration-type parameter, which indicates the alignment mode of the text to be displayed. For details, see the align
table.返回: None Example: my_Toggle.set_text_align(text_anchor.upper_left)
Example description: Set the font alignment mode to top-left
-
toggle_object.
set_text_size
(size)¶ Description: Set the text font size 参数: size (int) – Font size of text 返回: None Example: my_Toggle.set_text_size(12)
Example description: Set the font size of text to 12
-
toggle_object.
set_background_color
(r, g, b, a)¶ Description: Sets the background color of the control
参数: - r (int) – The r value of background color, whose range is [0, 255]
- g (int) – The g value of background color, whose range is [0, 255]
- b (int) – The b value of background color, whose range is [0, 255]
- a (int) – The transparency of background color, whose range is [0, 255]
返回: None
Example: my_Toggle.set_background_color(200, 200, 200, 230)
Example description: Set the rgb value of background color to (200, 200, 200) and the transparency to 230
-
toggle_object.
set_checkmark_color
(r, g, b, a)¶ Description: Set the color of the selection icon in the control
参数: - r (int) – The r value of icon color, whose range is [0, 255]
- g (int) – The g value of icon color, whose range is [0, 255]
- b (int) – The b value of icon color, whose range is [0, 255]
- a (int) – The transparency of icon color, whose range is [0, 255]
返回: None
Example: my_Toggle.set_checkmark_color(200, 200, 200, 230)
Example description: Set the rgb value of the selection icon to (200, 200, 200) and the transparency to 230
-
toggle_object.
set_is_on
(status)¶ Description: Set the state of the control 参数: status (bool) – Set whether the control is enabled, where True indicates yes, and False indicates no 返回: None Example: my_Toggle.set_is_on(True)
Example description: Set the Toggle control to enabled
Text¶
The Text control is used to display text.
-
text_object.
set_text
(string, [color_r, color_g, color_b, color_a, ]align, size)¶ Description: Sets text attributes of the control
参数: - string (string) – The content of the string to be displayed
- [color_r, color_g, color_b, color_a] (list) – Optional parameters, which indicate the color of the string to be displayed. These parameters respectively indicate the r value, b value, g value, and transparency of the displayed color, and their value ranges are all [0, 255].
- align (enum) – An optional enumeration-type parameter, which indicates the alignment mode of the text to be displayed. For details, see the
align
table. - size (int) – The font size of the displayed text
返回: None
Example: my_Text.set_text(120, 120, 120, 200, text_anchor.upper_left, 12)
Example description: Set the rgb value of text color to (120, 120, 120), the transparency to 200, the text alignment mode to top-left, and the font size to 12
-
text_object.
set_text_color
(r, g, b, a)¶ Description: Sets the text color of the control
参数: - r (int) – The r value of text color, whose range is [0, 255]
- g (int) – The g value of text color, whose range is [0, 255]
- b (int) – The b value of text color, whose range is [0, 255]
- a (int) – The transparency of text color, whose range is [0, 255]
返回: None
Example: my_Text.set_text_color(120, 120, 120, 200)
Example description: Set the rgb value of text to (120, 120, 120) and the transparency to 200
-
text_object.
set_text_align
(align)¶ Description: Set the text alignment mode 参数: align (enum) – An optional enumeration-type parameter, which indicates the alignment mode of the text to be displayed. For details, see the align
table.返回: None Example: my_Text.set_text_align(text_anchor.upper_left)
Example description: Set the text alignment mode to top-left
-
text_object.
set_text_size
(size)¶ Description: Set the text font size 参数: size (int) – Font size of text 返回: None Example: my_Text.set_text_size(12)
Example description: Set the font size of text to 12
-
text_object.
set_border_active
(active)¶ Description: Whether to display text borders 参数: active (bool) – Whether to display text borders, where True indicates to display borders, and False indicates not to display borders 返回: None Example: my_Text.set_border_active(True)
Example description: Display text borders
-
text_object.
set_background_color
(r, g, b, a)¶ Description: Sets the background color of the control
参数: - r (int) – The r value of background color, whose range is [0, 255]
- g (int) – The g value of background color, whose range is [0, 255]
- b (int) – The b value of background color, whose range is [0, 255]
- a (int) – The transparency of background color, whose range is [0, 255]
返回: None
Example: my_Text.set_background_color(200, 200, 200, 230)
Example description: Set the rgb value of background color to (200, 200, 200) and the transparency to 230
-
text_object.
set_background_active
(active)¶ Description: Whether to display the text background 参数: active (bool) – Whether to display the text background, where True indicates to display the background, and False indicates not to display the background 返回: None Example: my_Text.set_background_active(True)
Example description: Display the text background
-
text_object.
append_text
(content)¶ Description: Adds text to the Text control 参数: content (string) – The text that needs to be added to the Text control 返回: None Example: my_Text.append_text('RoboMaster EP')
Example description: Add the RoboMaster EP
text to the Text control
-
align
¶
InputField¶
The InputField control is used to receive text information input by users.
-
inputfield_object.
set_text
(string, [color_r, color_g, color_b, color_a, ]align, size)¶ Description: Sets the text attributes in the input box object
参数: - string (string) – The content of the string to be displayed
- [color_r, color_g, color_b, color_a] (list) – Optional parameters, which indicate the color of the string to be displayed. These parameters respectively indicate the r value, b value, g value, and transparency of the displayed color, and their value ranges are all [0, 255].
- align (enum) – An optional enumeration-type parameter, which indicates the alignment mode of the text to be displayed. For details, see the
align
table. - size (int) – The font size of the displayed text
返回: None
Example: my_InputField.set_text('Hello RoboMaster',120, 120, 120, 200, text_anchor.upper_left, 12)
Example description: Set the RGB value of the font to (120, 120, 120), the transparency to 200, the font alignment mode to top-left, and the font size to 12
-
input_field_object.
set_text_color
(r, g, b, a)¶ Description: Sets the color of text
参数: - r (int) – The r value of text color, whose range is [0, 255]
- g (int) – The g value of text color, whose range is [0, 255]
- b (int) – The b value of text color, whose range is [0, 255]
- a (int) – The transparency of text color, whose range is [0, 255]
返回: None
Example: my_button.set_text_color(120, 120, 120, 200)
Example description: Set the RGB value of the font to (120, 120, 120) and the transparency to 200
-
input_field_object.
set_text_align
(align)¶ Description: Sets the alignment mode of text in the control 参数: align (enum) – An optional enumeration-type parameter, which indicates the alignment mode of the text to be displayed. For details, see the align
table.返回: None Example: my_Input_field.set_text_align(text_anchor.upper_left)
Example description: Set the text alignment mode to top-left
-
input_field_object.
set_text_size
(size)¶ Description: Sets the font size of text in the control 参数: size (int) – Font size of text 返回: None Example: my_Input_field.set_text_size(12)
Example description: Set the font size of text to 12
-
input_field_object.
set_background_color
(r, g, b, a)¶ Description: Sets the background color of the control
参数: - r (int) – The r value of background color, whose range is [0, 255]
- g (int) – The g value of background color, whose range is [0, 255]
- b (int) – The b value of background color, whose range is [0, 255]
- a (int) – The transparency of background color, whose range is [0, 255]
返回: None
Example: my_Input_field.set_background_color(200, 200, 200, 230)
Example description: Set the RGB value of the background color to (200, 200, 200) and the transparency to 230
-
input_field_object.
set_hint_text
(string, [color_r, color_g, color_b, color_a, ]align, size)¶ Description: Sets the attributes of prompt text in the control
参数: - string (string) – The content of the string to be displayed
- [color_r, color_g, color_b, color_a] (list) – Optional parameters, which indicate the color of the string to be displayed. These parameters respectively indicate the r value, b value, g value, and transparency of the displayed color, and their value ranges are all [0, 255].
- align (enum) – An optional enumeration-type parameter, which indicates the alignment mode of the text to be displayed. For details, see the
align
table. - size (int) – The font size of the displayed text
返回: None
Example: my_Input_field.set_hint_text(120, 120, 120, 200, text_anchor.upper_left, 12)
Example description: Set the RGB value of the prompt text to (120, 120, 120), the transparency to 200, the font alignment mode to top-left, and the font size to 12
-
input_field_object.
set_hint_text_color
(r, g, b, a)¶ Description: Sets the color of control prompt text
参数: - r (int) – The r value of text color, whose range is [0, 255]
- g (int) – The g value of text color, whose range is [0, 255]
- b (int) – The b value of text color, whose range is [0, 255]
- a (int) – The transparency of text color, whose range is [0, 255]
返回: None
Example: my_Input_field.set_text_color(120, 120, 120, 200)
Example description: Set the RGB value of the prompt text to (120, 120, 120) and the transparency to 200
-
input_field_object.
set_hint_text_align
(align)¶ Description: Sets the alignment mode of prompt text 参数: align (enum) – An optional enumeration-type parameter, which indicates the alignment mode of the text to be displayed. For details, see the align
table.返回: None Example: my_Input_field.set_text_align(text_anchor.upper_left)
Example description: Set the alignment mode of prompt text to top left
-
input_field_object.
set_hint_text_size
(size)¶ Description: Sets the font size of prompt text 参数: size (int) – Font size of text 返回: None Example: my_Input_field.set_text_size(12)
Example description: Set the font size of the text in the hint object to 12
Dropdown¶
The Dropdown control is often used to select a specific value among the multiple attribute options of an object.
-
dropdown_object.
set_options
(*options)¶ Description: Sets the content of the dropdown box, which is a list of strings. The number of items in the list is the number of dropdown box options. 参数: *args (string) – Options in the dropdown box 返回: None Example: my_Dropdown.set_options('RoboMaser EP', 'People')
Example description: There are two options in the dropdown box, RoboMaster EP
andPeople
-
dropdown_object.
set_background_color
(r, g, b, a)¶ Description: Sets the background color of the selected item in the dropdown box
参数: - r (int) – The r value of background color, whose range is [0, 255]
- g (int) – The g value of the background color, whose range is [0, 255]
- b (int) – The b value of the background color, whose range is [0, 255]
- a (int) – The transparency of the background color, whose range is [0, 255]
返回: None
Example: my_DropDown.set_background_color(200, 200, 200, 230)
Example description: Set the rgb value of the background color of selected items in the dropdown box to (200, 200, 200) and the transparency to 230
-
dropdown_object.
set_arrow_color
(r, g, b, a)¶ Description: Sets the color of the selection arrow in the dropdown box
参数: - r (int) – The r value of arrow color, whose range is [0, 255]
- g (int) – The g value of arrow color, whose range is [0, 255]
- b (int) – The b value of arrow color, whose range is [0, 255]
- a (int) – The transparency of arrow color, whose range is [0, 255]
返回: None
Example: my_Dropdown.set_arrow_color(120, 120, 120, 200)
Example description: Set the rgb value of the color of the selection arrow in the dropdown box to (120, 120, 120) and the transparency to 200
-
dropdown_object.
set_item_background_color
(r, g, b, a)¶ Description: Sets the background color of unselected items in the dropdown box
参数: - r (int) – The r value of background color, whose range is [0, 255]
- g (int) – The g value of the background color, whose range is [0, 255]
- b (int) – The b value of the background color, whose range is [0, 255]
- a (int) – The transparency of the background color, whose range is [0, 255]
返回: None
Example: my_DropDown.set_item_background_color(200, 200, 200, 230)
Example description: Set the rgb value of the background color of unselected items in the dropdown box to (200, 200, 200) and the transparency to 230
-
dropdown_object.
set_item_checkmark_color
(r, g, b, a)¶ Description: Sets the color of the selection icon in the dropdown box
参数: - r (int) – The r value of checkmark color, whose range is [0, 255]
- g (int) – The g value of checkmark color, whose range is [0, 255]
- b (int) – The b value of checkmark color, whose range is [0, 255]
- a (int) – The transparency of checkmark color, whose range is [0, 255]
返回: None
Example: my_DropDown.set_item_checkmark_color(200, 200, 200, 230)
Example description: Set the rgb value of the checkmark color in the dropdown box to (200, 200, 200) and the transparency to 230
提示
For a description of functions, refer to User-defined UI System.
Blaster¶
-
ir_blaster_ctrl.
set_fire_count
(count)¶ Description: Sets the emission frequency of infrared beams, i.e., the number of infrared beams emitted per second 参数: color_enum (int) – The emission frequency, i.e. the number of infrared beams emitted per second, whose range is [1:8] 返回: None Example: ir_blaster_ctrl.set_fire_count(4)
Example description: Set the emission frequency of infrared beams to 4
-
ir_blaster_ctrl.
fire_once
()¶ Description: Instructs the blaster to emit a single infrared beam 参数: void – None 返回: None Example: ir_blaster_ctrl.fire_once()
Example description: Instruct the blaster to emit a single infrared beam
-
ir_blaster_ctrl.
fire_continuous
()¶ Description: Instructs the blaster to continuously emit infrared beams 参数: void – None 返回: None Example: ir_blaster_ctrl.fire_continuous()
Example description: Instruct the blaster to continuously emit infrared beams
-
ir_blaster_ctrl.
stop
()¶ Description: Stops infrared beam emission 参数: void – None 返回: None Example: ir_blaster_ctrl.stop()
Example description: Stop infrared beam emission
Mechanical Gripper¶
-
gripper_ctrl.
open
()¶ Description: Controls the opening of the mechanical gripper 参数: void – None 返回: None Example: gripper_ctrl.open()
Example description: Control the opening of the mechanical gripper
-
gripper_ctrl.
close
()¶ Description: Controls the closing of the mechanical gripper 参数: void – None 返回: None Example: gripper_ctrl.close()
Example description: Control the closing of the mechanical gripper
-
gripper_ctrl.
stop
()¶ Description: Controls the stopping of the mechanical gripper 参数: void – None 返回: None Example: gripper_ctrl.stop()
Example description: Control the stopping of the mechanical gripper
-
gripper_ctrl.
update_power_level
(level)¶ Description: Sets the force level of the gripper 参数: level (int) – The force level of the mechanical gripper, whose range is [1:4]. The default is 1. 返回: None Example: gripper_ctrl.update_power_level(1)
Example description: Set the force level of the gripper to 1
-
gripper_ctrl.
is_closed
()¶ Description: Obtains the clamping state of the mechanical gripper 参数: void – None 返回: The clamping state of the mechanical gripper. If the mechanical gripper is clamped, true is returned, otherwise false is returned. 返回类型: bool Example: ret = gripper_ctrl.is_closed()
Example description: Obtain the clamping state of the mechanical gripper
-
gripper_ctrl.
is_open
()¶ Description: Obtains the open state of the mechanical gripper 参数: void – None 返回: The open state of the mechanical gripper. If the mechanical gripper is fully opened, true is returned, otherwise false is returned. 返回类型: bool Example: ret = gripper_ctrl.is_open()
Example description: Obtain the open state of the mechanical gripper
提示
For the description of the module, refer to Mechanical Arm and Mechanical Gripper.
Mechanical Arm¶
-
robotic_arm_ctrl.
move
(x, y, wait_for_complete=True)¶ Description: Sets the relative movement position of the mechanical arm
参数: - x (int32) – Set the horizontal movement distance of the mechanical arm. A positive number indicates forward movement, and a negative number indicates backward movement. The accuracy is 1 mm.
- y (int32) – Set the vertical movement distance of the mechanical arm. A positive number indicates upward movement, and a negative number indicates downward movement. The accuracy is 1 mm.
- wait_for_complete (bool) – Whether to wait for execution to be completed. The default value is True.
返回: None
Example: robotic_arm_ctrl.move(40, 50, True)
Example description: Set the mechanical arm to move 20 mm forward and 30 mm upward, and wait for execution to be completed
-
robotic_arm_ctrl.
moveto
(x, y, wait_for_complete=True)¶ Description: Sets the absolute coordinates of mechanical arm movement
参数: - x (int32) – Set the coordinates of horizontal arm movement, with an accuracy of 1 mm
- y (int32) – Set the coordinates of vertical arm movement, with an accuracy of 1 mm
- wait_for_complete (bool) – Whether to wait for execution to be completed. The default value is True.
返回: None
Example: robotic_arm_ctrl.moveto(40, 50, True)
Example description: Set the absolute coordinates of the mechanical arm to (x=40mm, y=50mm) and wait for the execution to be completed
-
robotic_arm_ctrl.
get_position
()¶ Description: Obtains the position of the mechanical arm 参数: void – None 返回: The absolute coordinates of the mechanical arm, with an accuracy of 1 mm 返回类型: An [x, y] list, where x and y are of int32 type Example: [x, y] = robotic_arm_ctrl.get_position()
Example description: Obtain the absolute coordinates of the mechanical arm
-
robotic_arm_ctrl.
recenter
()¶ Description: Recenters the mechanical arm 参数: void – None 返回: None Example: robotic_arm_ctrl.recenter()
Example description: Recenter the mechanical arm
提示
For a description of the module, refer to Mechanical Arm and Mechanical Gripper.
Servo¶
-
servo_ctrl.
get_angle
(servo_id)¶ Description: Obtains the rotation angle of the servo 参数: servo_id (uint8) – The number of the servo, whose range is [1:3] 返回: The angle of the servo, with an accuracy of 0.1° 返回类型: int32 Example: angle = servo_ctrl.get_angle(1)
Example description: Obtain the rotation angle of servo 1
-
servo_ctrl.
set_angle
(servo_id, angle, wait_for_complete=True)¶ Description: Set the rotation angle of the servo
参数: - servo_id (uint8) – The number of the servo, whose range is [1:3]
- angle (int32) – The rotation angle, with an accuracy of 0.1°. A positive number indicates clockwise rotation, and a negative number indicates counterclockwise rotation.
- wait_for_complete (bool) – Whether to wait for execution to be completed. The default value is True.
返回: None
Example: servo_ctrl.set_angle(1, 900, True)
Example description: Set servo 1 to rotate 90° clockwise and wait for execution to be completed
-
servo_ctrl.
recenter
(servo_id, wait_for_complete=True)¶ Description: Sets the servo back to normal
参数: - servo_id (uint8) – The number of the servo, whose range is [1:3]
- wait_for_complete (bool) – Whether to wait for execution to be completed. The default value is True.
返回: None
Example: servo_ctrl.recenter(1, True)
Example description: Set servo 1 back to normal and wait for execution to be completed
-
servo_ctrl.
set_speed
(servo_id, speed)¶ Description: Sets the rotation speed of the servo
参数: - servo_id (uint8) – The number of the servo, whose range is [1:3]
- speed (int32) – The rotation speed, with an accuracy of 1 °/second. A positive number indicates clockwise rotation, and a negative number indicates counterclockwise rotation.
返回: None
Example: servo_ctrl.set_speed(1, 5)
Example description: Set servo 1 to rotate clockwise at a rotation speed of 5 °/second
提示
For the description of the module, refer to Servo.
Vision¶
-
vision_ctrl.
marker_detection_color_set
(color_enum)¶ Description: Sets the color for identifying visual labels 参数: color_enum – For available label colors, refer to the color_enum
table.返回: None Example: vision_ctrl.marker_detection_color_set(rm_define.marker_detection_color_red)
Example description: Set the color for identifying visual labels to red
-
color_enum
¶
Armor Plate¶
-
def ir_hit_detection_event(msg):
Description: After detecting the robot is under attack by infrared beams, run the program in the function 参数: msg – Message parameter in the function 返回: None Example:
1 2 3 4 | #After detecting that the robot is under attack by infrared beams, run the program in the function.
def ir_hit_detection_event(msg):
pass
|
-
armor_ctrl.
cond_wait
(condition_enum)¶ Description: When the waiting robot is under attack by infrared beams, execute the next instruction 参数: condition_enum – Event type, ``rm_define.cond_ir_hit_detection’’ indicates that the robot is under attack by infrared beams 返回: None Example: armor_ctrl.cond_wait(rm_define.cond_ir_hit_detection)
Example description: When the waiting robot is under attack by infrared beams, execute the next instruction
-
armor_ctrl.
check_condition
(condition_enum)¶ Description: Determine whether the robot is under attack by infrared beams 参数: condition_enum – Event type, ``rm_define.cond_ir_hit_detection’’ indicates that the robot is under attack by infrared beams 返回: Whether the robot is under attack by infrared beams. If yes, true is returned. If no, false is returned. 返回类型: bool Example: if armor_ctrl.check_condition(rm_define.cond_ir_hit_detection):
Example description: If the robot is under attack by infrared beams, execute the next instruction
Infrared Distance Sensor¶
-
ir_distance_sensor_ctrl.
enable_measure
(port_id)¶ Description: Enables the ranging function of the infrared distance sensor 参数: port_id (int) – The module number of the infrared distance sensor, whose range is [1:4] 返回: None Example: ir_distance_sensor_ctrl.enable_measure(1)
Example description: Enable the ranging function of infrared distance sensor 1
-
ir_distance_sensor_ctrl.
disable_measure
(port_id)¶ Description: Disables the ranging function of the infrared distance sensor 参数: port_id (int) – The module number of the infrared distance sensor, whose range is [1:4] 返回: None Example: ir_distance_sensor_ctrl.disable_measure(1)
Example description: Disable the ranging function of infrared distance sensor 1
-
ir_distance_sensor_ctrl.
get_distance_info
(port_id)¶ Description: Obtains the ranging information of the infrared distance sensor 参数: port_id (int) – The module number of the infrared distance sensor, whose range is [1:4] 返回: The distance to the obstacle in front of the infrared distance sensor, with an accuracy of 1 cm 返回类型: uint16 Example: ir_distance_sensor_ctrl.get_distance_info(1)
Example description: Obtain the ranging information of infrared distance sensor 1
-
def ir_distance_[port_id]_[compare_type]_[dist]_event(msg):
Description: When the distance to the obstacle in front of the infrared distance sensor is judged to satisfy the relevant conditions, run the program in the function
参数: - port_id (int) – The module number of the infrared distance sensor, whose range is [1:4]
- compare_type – The comparison type, which can be eq (equal), ge (greater than or equal to), gt (greater than), le (less than or equal to), or lt (less than).
- dist – The distance used for comparison, with an accuracy of 1 cm, range of 5-500 cm, and error rate of 5%
返回: None
Example:
1 2 3 4 | #When the distance to the obstacle in front of the infrared distance sensor is judged to satisfy the relevant conditions, run the program in the function
def ir_distance_1_lt_10_event(msg):
pass
|
-
ir_distance_sensor_ctrl.
cond_wait
('ir_distance_[port_id]_[compare_type]_[dist]')¶ Description: When the distance to the obstacle in front of the waiting infrared distance sensor is judged to satisfy the relevant conditions, execute the next instruction
参数: - 'ir_distance_[port_id]_[compare_type]_[dist]' – The string used for distance comparison, which includes the module number, comparison type, and distance
- port_id (int) – The module number of the infrared distance sensor, whose range is [1:4]
- compare_type – The comparison type, which can be eq (equal), ge (greater than or equal to), gt (greater than), le (less than or equal to), or lt (less than).
- dist – The distance used for comparison, with an accuracy of 1 cm, range of 5-500 cm, and error rate of 5%
返回: None
Example: ir_distance_sensor_ctrl.cond_wait('ir_distance_1_gt_50')
Example description: If the distance to the obstacle in front of infrared distance sensor 1 is greater than 50 cm, execute the next instruction
-
ir_distance_sensor_ctrl.
check_condition
('ir_distance_[port_id]_[compare_type]_[dist]')¶ Description: Determines whether the distance to the obstacle in front of the infrared distance sensor meets the relevant conditions
参数: - 'ir_distance_[port_id]_[compare_type]_[dist]' – The string used for distance comparison, which includes the module number, comparison type, and distance
- port_id (int) – The module number of the infrared distance sensor, whose range is [1:4]
- compare_type – The comparison type, which can be eq (equal), ge (greater than or equal to), gt (greater than), le (less than or equal to), or lt (less than).
- dist – The distance used for comparison, with an accuracy of 1 cm, range of 5-500 cm, and error rate of 5%
返回: Whether the relevant conditions are satisfied. If yes, true is returned. If no, false is returned.
返回类型: bool
Example:
1 2 3 4 | #When the distance to the obstacle in front of the infrared distance sensor is judged to satisfy the relevant conditions, run the program in the function
if ir_distance_sensor_ctrl.check_condition('ir_distance_1_gt_50'):
pass
|
提示
For the description of the module, refer to Infrared Distance Sensor.
Sensor Adapter¶
-
sensor_adapter_ctrl.
get_sensor_adapter_adc
(board_id, port_num)¶ Description: Obtains the ADC value of the analog pin for the corresponding port on the sensor adapter
参数: - board_id (int) – The module number of the sensor adapter, whose range is [1:6]
- port_num (uint8) – The number of the port on the sensor adapter, whose range is [1:2]
- wait_for_complete (bool) – Whether to wait for execution to be completed. The default value is True.
返回: The ADC value of the analog pin for the corresponding port on the sensor adapter, whose range is [0:1023]
返回类型: uint16
Example: ret = sensor_adapter_ctrl.get_sensor_adapter_adc(1, 2)
Example description: Obtain the ADC value of the analog pin for port 2 on sensor adapter 1
-
sensor_adapter_ctrl.
get_sensor_adapter_pulse_period
(board_id, port_num)¶ Description: Obtains the pulse duration of the pin for the corresponding port on the sensor adapter
参数: - board_id (int) – The module number of the sensor adapter, whose range is [1:6]
- port_num (uint8) – The number of the port on the sensor adapter, whose range is [1:2]
返回: The pulse duration of the pin for the corresponding port on the sensor adapter, with an accuracy of 1 ms
返回类型: uint32
Example: ret = sensor_adapter_ctrl.get_sensor_pulse_period(1, 2)
Example description: Obtain the pulse duration of the analog pin for port 2 on sensor adapter 1
-
def sensor_adapter[board_id]_port[port_id]_[judge_type]_event(msg):
Description: When the pulse on the pin of the corresponding port on the sensor adapter changes to high, low, or bidirectional, run the program in the function
参数: - board_id (int) – The module number of the sensor adapter, whose range is [1:6]
- port_num (uint8) – The number of the port on the sensor adapter, whose range is [1:2]
- judge_type – The trigger condition, which can be high, low, or trigger. These values indicate high level, low level, and bidirectional skipping respectively.
返回: None
Example:
1 2 3 4 | #When the pulse on the pin of port 2 on sensor adapter 1 changes to high, run the program in the function
def sensor_adapter1_port2_high_event(msg):
pass
|
-
sensor_adapter_ctrl.
cond_wait
(rm_define.cond_sensor_adapter[board_id]_port[port_id]_[judge_type]_event)¶ Description: When the pulse on the pin of the corresponding port on the waiting sensor adapter is high, low, or trigger, execute the next instruction
参数: - board_id (int) – The module number of the sensor adapter, whose range is [1:6]
- port_num (uint8) – The number of the port on the sensor adapter, whose range is [1:2]
- judge_type – The trigger condition, which can be high, low, or trigger. These values indicate high level, low level, and bidirectional skipping respectively.
返回: None
Example: sensor_adapter_ctrl.cond_wait(rm_define.cond_sensor_adapter1_port2_high_event)
Example description: When the pulse on the pin of port 2 on sensor adapter 1 is high, execute the next instruction
-
sensor_adapter_ctrl.
check_condition
(rm_define.cond_sensor_adapter[board_id]_port[port_id]_[judge_type]_event)¶ Description: Determines whether the pulse on the pin of the corresponding port on the sensor adapter is high, low, or trigger
参数: - board_id (int) – The module number of the sensor adapter, whose range is [1:6]
- port_num (uint8) – The number of the port on the sensor adapter, whose range is [1:2]
- judge_type – The trigger condition, which can be high, low, or trigger. These values indicate high level, low level, and bidirectional skipping respectively.
返回: Whether the relevant conditions are satisfied. If yes, true is returned. If no, false is returned.
返回类型: bool
Example:
1 2 3 4 | #If the pulse on the pin of port 2 on sensor adapter 1 is trigger, execute the next instruction
if sensor_adapter_ctrl.check_condition(rm_define.cond_sensor_adapter1_port2_trigger_event):
pass
|
提示
For the description of the module, refer to Sensor Adapter.
UART¶
-
serial_ctrl.
serial_config
(baud_rate, data_bit, odd_even, stop_bit)¶ Description: Sets the baud rate, data bit, parity bit, and stop bit attributes of the serial port
参数: - baud_rate – Set the baud rate, which can be 9600, 19200, 38400, 57600, or 115200
- data_bit – Set the data bit, which can be cs7 or cs8
- odd_even_crc – Set parity check. For details, refer to the
odd_even_crc
table. - stop_bit – Set the stop bit, which can be 1 or 2
返回: None
Example: serial_ctrl.serial_config(9600, 'cs8', 'none', 1)
Example description: Set the baud rate to 9600, 8 data bits, no parity check, and 1 stop bit for the serial port
-
serial_ctrl.
write_line
(msg_string)¶ Description: Send string information and automatically add line breaks ( '\\n'
)参数: msg_string (string) – The string information that needs to be sent. Automatically append line breaks ( '\\n'
) after the string when sending it.返回: None Example: serial_ctrl.write_line('RoboMaster EP')
Example description: Write 'RoboMaster EP\\n'
to the serial port and add line breaks automatically. You only need to send'RoboMaster EP'
in this case.
-
serial_ctrl.
write_string
(msg_string)¶ Description: Send string information 参数: msg_string (string) – String information that needs to be sent 返回: None Example: serial_ctrl.write_string('RoboMaster EP')
Example description: Write 'RoboMaster EP'
to the serial port
-
serial_ctrl.
write_number
(value)¶ Description: Convert the numeric parameter to a string and send the string through the serial port 参数: value (int) – The value that needs to be sent 返回: None Example: serial_ctrl.write_number(12)
Example description: Write the '12'
string to the serial port
-
serial_ctrl.
write_numbers
(value1, value2, value3...)¶ Description: Convert the list of numbers to a string and send the string through the serial port
参数: - value1 (int) – Value 1 in the list that needs to be sent
- value2 (int) – Value 2 in the list that needs to be sent
- value3 (int) – Value 3 in the list that needs to be sent
返回: None
Example: serial_ctrl.write_numbers(12,13,14)
Example description: Write the
'12,13,14'
string to the serial port
-
serial_ctrl.
write_value
(key, value)¶ Description: Converts the parameter to a string of key-value pairs and sends the string through the serial port
参数: - key (string) – The key to be sent
- value (int) – The value to be sent
返回: None
Example: serial_ctrl.write_value('x', 12)
Example description: Write the
'x:12'
string to the serial port
-
serial_ctrl.
read_line
([timeout])¶ Description: Read the string ending with '\\n'
from the serial port参数: timeout (float) – An optional parameter, which indicates the timeout period in seconds. The default value of this parameter is permanent blocking. 返回: The string read from the serial port 返回类型: string Example: recv = serial_ctrl.read_line()
Example description: Read a string ending with '\\n'
from the serial port
-
serial_ctrl.
read_string
([timeout])¶ Description: Read the string from the serial port (the string may or may not end with '\\n'
)参数: timeout (float) – An optional parameter, which indicates the timeout period in seconds. The default value of this parameter is permanent blocking. 返回: The string read from the serial port 返回类型: string Example: recv = serial_ctrl.read_string()
Example description: Read a string from the serial port
-
serial_ctrl.
read_until
(stop_sig[, timeout])¶ Description: Reads a string from the serial port until the string matches the specified
'stop_sig'
ending character参数: - stop_sig – The specified ending character, whose type is char and range is [
'\n'
|'$'
|'#'
|'.'
|':'
|';'
] - timeout (float) – An optional parameter, which indicates the timeout period in seconds. The default value of this parameter is permanent blocking.
返回: The matched string read from the serial port
返回类型: string
Example: serial_ctrl.read_until('#')
Example description: Read a string from the serial port until the ending character of the string matches
'#'
- stop_sig – The specified ending character, whose type is char and range is [
-
odd_even_crc
¶
提示
For the description of the module, refer to UART.
Version Description¶
To provide a better user experience and more powerful functions, the developer documentation will be updated regularly. Before using this documentation, please check that your robot version, SDK version, and document version match. If they do not match, we recommend that you update the robot to the required version or use the corresponding version of the documentation.
The following table describes version information:
Updated on September 30, 2020:
- Added the SOP for multi-device formation.
- Optimized the stability of TT formation.
- Added the subscription feature for infrared strike events.
- Optimized multi-device interfaces.