0% found this document useful (0 votes)
93 views

mBot2_API_cyberpi

Uploaded by

Alex Zambrano
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

mBot2_API_cyberpi

Uploaded by

Alex Zambrano
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Python API Documentation for CyberPi https://www.yuque.

com/makeblock-help-center-en/mcode/cyberpi-api

Python API Documentation for CyberPi

Welcome to use CyberPi for Python learning!

CyberPi provides abundant input and output functions, allowing you to interact with
your code and view the output of your code.

CyberPi is equipped with built-in Bluetooth and Wi-Fi, which can be used to set up a
local area network (LAN) or connect to the Internet. You can create your own projects

with CyberPi. It can help you understand and master the knowledge and skills related to

various fields, such as Internet of things (IoT), artificial intelligence (AI), computing,

and network.

In addition, CyberPi supports more than 30 electronic modules and multiple extension
shields, allowing you to create various projects such as smart farm, smart home, self-

driving car, intelligent robot, and competition robot.

You can use the library to implement the functions described in the

preceding.

Import the library

The library described in this document refers to two separate libraries with

the same name:


● MicroPython library that can run on CyberPi
● Python library that can run on computers
These two libraries include the same APIs and almost the same output.

The CyberPi team develop these two libraries in this way on purpose, so that the
MicroPython code you compile in Upload mode (to run on CyberPi) can be executed as
Python code in Live mode (to run on a computer). We think this would be a good way to
help learners make the transition from MicroPython learning to Python learning.

To help you use the APIs more efficiently, the application scenarios of the APIs are
labelled as follows:

1 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

: indicates that an API supports Python 3 programming and can be used in Live

mode on the mBlock Python editor.

: indicates that an API supports MicroPython programming and can be used in

Upload mode on the mBlock Python editor.

: indicates that an API supports both Python 3 and MicroPython programming

and can be used in both Live and Upload modes on the mBlock Python editor.

You can use the library on mBlock-Python Editor or mBlock 5.


Import the library as follows:

1 ## Python coding-no omitting


2 import cyberpi
3 cyberpi.console.print("hello")
4
5
6 ## MicroPython coding-omitting "cyberpi"
7 from cyberpi import *
8 console.print("hello")

The non-omitting coding way is preferable for Python coding (Live mode), which

prevents errors of the code compiled for CyberPi when other Python libraries are
imported.

The omitting coding way is preferable for MicroPython coding (Upload mode), which
allows you to write fewer words.

mBlock 5 uses the non-omitting way for transcoding in most of the cases to prevent

errors.

APIs in the library

The library provides multiple APIs for controlling hardware. This page
describes the APIs for CyberPi. For the APIs provided for function extension and

2 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

extension boards, see:


APIs for Function Extension <https://www.yuque.com/makeblock-help-center-en/mcode

/cyberpi-api-function-extension>

APIs for Extension boards <https://www.yuque.com/makeblock-help-center-en/mcode


/cyberpi-api-shields>
APIs for mBuild Modules <https://www.yuque.com/makeblock-help-center-en/mcode

/cyberpi-api-mbuild>

APIs for CyberPi

These APIs can be used to control CyberPi, allowing CyberPi to perform its functions.

APIs for CyberPi include the following:

Audio
CyberPi is equipped with a speaker and microphone. You can use the following APIs to

record and play audio files and set the volume and playing speed.

Preset audio files

Plays a preset audio file


This API blocks the thread until the playing ends.

Parameter:
● music : name of the audio file to be played. The table "Setting range and
sound effects" describes the setting range and sound effects of this parameter.

Plays a preset audio file

Parameter:
● music : name of the audio file to be played. The table "Setting range and
sound effects" describes the setting range and sound effects of this parameter.

Setting range and sound effects

3 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Category File name Variable name Sound effect

hello SPEAKER.hello hello

hi SPEAKER.hi hi

bye SPEAKER.bye bye

yeah SPEAKER.yeah yeah

wow SPEAKER.wow wow

laugh SPEAKER.laugh laugh

hum SPEAKER.hum hum

sad SPEAKER.sad sad

sigh SPEAKER.sigh sigh

annoyed SPEAKER.annoyed annoyed


01-Emotion
angry SPEAKER.angry angry

surprised SPEAKER.surprised surprised

yummy SPEAKER.yummy yummy

curious SPEAKER.curious curious

embarrassed SPEAKER.embarrassed embarrassed

ready SPEAKER.ready ready

sprint SPEAKER.sprint sprint

sleepy SPEAKER.sleepy sleepy

meow SPEAKER.meow meow

start SPEAKER.start start

switch SPEAKER.switch switch

beeps SPEAKER.beeps beeps

buzzing SPEAKER.buzzing buzzing


02-Electronic sounds
explosion SPEAKER.explosion explosion

jump SPEAKER.jump jump

laser SPEAKER.laser laser

level-up SPEAKER.level-up level-up

4 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

low-energy SPEAKER.low-energy low-energy

prompt-tone SPEAKER.prompt-tone prompt-tone

right SPEAKER.right right

wrong SPEAKER.wrong wrong

ring SPEAKER.ring ring

score SPEAKER.score score

wake SPEAKER.wake wake

warning SPEAKER.warning warning

metal-clash SPEAKER.metal-clash metal-clash

shot SPEAKER.shot-1 shot

glass-clink SPEAKER.glass-clink glass-clink

inflator SPEAKER.inflator inflator

running water SPEAKER.running-water running water

clockwork SPEAKER.clockwork clockwork

click SPEAKER.click click

current SPEAKER.current current

switch SPEAKER.switch switch


03-Physical sounds
wood-hit SPEAKER.wood-hit-3 wood-hit

iron SPEAKER.iron-1 iron

drop SPEAKER.drop drop

bubble SPEAKER.bubble-1 bubble

wave SPEAKER.wave wave

magic SPEAKER.magic magic

spitfire SPEAKER.spitfire spitfire

heartbeat SPEAKER.heartbeat heartbeat

load SPEAKER.load load

Instrument simulating

5 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Plays the specified note of the specified instrument for the specified beats
This API blocks the thread until the playing ends. You can use it to compile and play

music.

Parameters:
● type : type of the instrument to be simulated. The value is set to .
● note : frequency of the sound to be played. Setting range: . The table
"Values and corresponding notes" describes the values and their corresponding
notes.
● beat : duration a note is to be played. Setting range: beat > 0. At general
playing speed, one beat equals one second.

Values and corresponding notes

Value Note Value Note Value Note

0 C-1 43 G2 86 D6

1 C#-1 44 G#2 87 D#6

2 D-1 45 A2 88 E6

3 D#-1 46 A#2 89 F6

4 E-1 47 B2 90 F#6

5 F-1 48 C3 91 G6

6 F#-1 49 C#3 92 G#6

7 G-1 50 D3 93 A6

8 G#-1 51 D#3 94 A#6

9 A-1 52 E3 95 B6

10 A#-1 53 F3 96 C7

11 B-1 54 F#3 97 C#7

12 C0 55 G3 98 D7

13 C#0 56 G#3 99 D#7

14 D0 57 A3 100 E7

15 D#0 58 A#3 101 F7

16 E0 59 B3 102 F#7

17 F0 60 C4 103 G7

6 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

18 F#0 61 C#4 104 G#7

19 G0 62 D4 105 A7

20 G#0 63 D#4 106 A#7

21 A0 64 E4 107 B7

22 A#0 65 F4 108 C8

23 B0 66 F#4 109 C#8

24 C1 67 G4 110 D8

25 C#1 68 G#4 111 D#8

26 D1 69 A4 112 E8

27 D#1 70 A#4 113 F8

28 E1 71 B4 114 F#8

29 F1 72 C5 115 G8

30 F#1 73 C#5 116 G#8

31 G1 74 D5 117 A8

32 G#1 75 D#5 118 A#8

33 A1 76 E5 119 B8

34 A#1 77 F5 120 C9

35 B1 78 F#5 121 C#9

36 C2 79 G5 122 D9

37 C#2 80 G#5 123 D#9

38 D2 81 A5 124 E9

39 D#2 82 A#5 125 F9

40 E2 83 B5 126 F#9

41 F2 84 C6 127 G9

42 F#2 85 C#6

Example program

7 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

1 import time, cyberpi


2
3 cyberpi.console.println('Press B to play music')
4 cyberpi.console.println('Press B to play music.')
5 while True:
6 while not cyberpi.controller.is_press('b'):
7 pass
8 # You can right-click a block to view help information.
9 # The block uses MIDI codes to indicate notes. The following MIDI codes are used in t
10 #
11 # Numbered musical notation/Note/MIDI code
12 # 1 C4 60
13 # 2 D4 62
14 # 3 E4 64
15 # 4 F4 65
16 # 5 G4 67
17 # 6 A4 69
18 # 7 B4 71
19 cyberpi.audio.play_music(60, 0.25)
20 cyberpi.audio.play_music(60, 0.25)
21 cyberpi.audio.play_music(67, 0.25)
22 cyberpi.audio.play_music(67, 0.25)
23 cyberpi.audio.play_music(69, 0.25)
24 cyberpi.audio.play_music(69, 0.25)
25 cyberpi.audio.play_music(67, 0.25)
26 time.sleep(1)
27 cyberpi.audio.play_music(65, 0.25)
28 cyberpi.audio.play_music(65, 0.25)
29 cyberpi.audio.play_music(64, 0.25)
30 cyberpi.audio.play_music(64, 0.25)
31 cyberpi.audio.play_music(62, 0.25)
32 cyberpi.audio.play_music(62, 0.25)
33 cyberpi.audio.play_music(60, 0.25)
34
35

Plays the specified sound for the specified beats


● type : type of the instrument to be simulated.
Setting range:
: snare drum
: bass drum
: beating the edge of a drum
: crash cymbal
: open hi-hat

8 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

: closed hi-hat
: tambourine
: handclap
: claves
● beat : duration a note to be played. The value must be greater than 0. At
general playing speed, one beat equals one second.

Example program

1 # generated by mBlock5 for CyberPi


2 # codes make you happy
3
4 import event, time, cyberpi
5
6 @event.start
7 def on_start():
8 global frequency
9 while True:
10 if cyberpi.is_tiltforward():
11 cyberpi.audio.play_drum('snare', 0.25)
12
13 if cyberpi.is_tiltforward():
14 cyberpi.audio.play_drum('bass-drum', 0.25)
15
16 if cyberpi.is_tiltforward():
17 cyberpi.audio.play_drum('open-hi-hat', 0.25)
18
19 if cyberpi.is_tiltforward():
20 cyberpi.audio.play_drum('closed-hi-hat', 0.25)
21
22

Sounds recording and playing

Starts to record sounds

When this API is executed, CyberPi starts to record sounds until


is executed or the recording exceeds 10 seconds. The recorded file is stored in RAM,

and so the recorded file is lost if CyberPi is turned off or restarted.

9 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Stops recording sounds


This API needs to be used in combination with .

Plays the recorded sounds


This API blocks the thread until the playing ends.

Plays the recorded sounds

Example program

10 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

11 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

1 # generated by mBlock5 for CyberPi


2 # codes make you happy
3
4 import time, event, cyberpi
5
6 @event.start
7 def on_start():
8 """Press the middle of the joystick to start recording
9 Press button A to stop recording
10 Press button B to play the recorded sounds
11
12 Move the joystick up or down to change the playing speed
13 Move the joystick to the left or right to change the playing volume"""
14 cyberpi.display.set_brush(255, 255, 255)
15 cyberpi.led.set_bri(30)
16 cyberpi.audio.set_vol(50)
17 cyberpi.audio.set_tempo(100)
18 cyberpi.console.println('1.Magical Recorder')
19 cyberpi.console.println('Press the middle of the joystick to start recording'
20 cyberpi.console.println('')
21 cyberpi.led.show('orange orange orange orange orange')
22
23 @event.is_press('middle')
24 def is_press():
25 cyberpi.console.clear()
26 cyberpi.console.println('Press button A to stop recording')
27 cyberpi.console.println('')
28 cyberpi.led.show('green green green green green')
29 cyberpi.audio.record()
30
31 @event.is_press('a')
32 def on_received():
33 cyberpi.console.clear()
34 cyberpi.console.println('Press button B to play the recorded sounds'
35 cyberpi.console.println('Move the joystick up or down to change the playing speed and
36 cyberpi.console.println('')
37 cyberpi.led.show('red red red red red')
Buzzer simulating
38 cyberpi.audio.stop_record()
39
40 @event
41 def on_received1():
Simulates
42 thecyberpi.console.clear()
sound of a buzzer
43 cyberpi.console.println('Playing...')
Parameters:
44 cyberpi.console.println('Move the joystick up or down to change the playing speed and
● freq : frequency of the sound to be played. Setting range: Hz. To
45 cyberpi.console.println('')
46protect your ears, no sound is made
cyberpi.led.show('blue if the
blue frequency
blue is out of the range. Your ears
blue blue')
47 cyberpi.audio.play_record_until()
may get hurt if you listen to high-frequency sounds for a long period.
48
49In addition, if you want to change music by setting the frequency, refer to the
@event.is_press('up')
50following notes and their corresponding frequencies:
def is_press1():
51 """Move the joystick up or down to change the playing speed.
52 The speed setting function is a feature of CyberPi's audio system, allowing you to ha
53 The speed setting function can also be used to slow down or speed up the playing of t

12 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api
53 The speed setting function can also be used to slow down or speed up the playing of t
54 cyberpi.led.off(0)
55 cyberpi.audio.add_tempo(10)
56 cyberpi.console.println(str('Playing speed:') + str(cyberpi.audio.get_tempo
57 cyberpi.console.println('')
58
59 @event.is_press('down')
60 def is_press2():
61 cyberpi.led.off(0)
62 cyberpi.audio.add_tempo(-10)
63 if cyberpi.audio.get_tempo() < 40:
64 cyberpi.audio.set_tempo(40)
65
66 cyberpi.console.println(str('Playing speed:') + str(cyberpi.audio.get_tempo
67 cyberpi.console.println('')
68
69 @event.is_press('left')
70 def is_press3():
71 """Move the joystick to the left or right to change the playing volume"""
72 cyberpi.led.off(0)
73 cyberpi.audio.add_vol(-10)
74 cyberpi.console.println(str('Playing volume:') + str(cyberpi.audio.
75 cyberpi.console.println('')
76
77 @event.is_press('right')
78 def is_press4():
79 cyberpi.led.off(0)
80 cyberpi.audio.add_vol(10)
81 cyberpi.console.println(str('Playing volume:') + str(cyberpi.audio.
82 cyberpi.console.println('')
83
84

1 ['C2','65'], ['D2','73'], ['E2','82'], ['F2','87'],


2 ['G2','98'], ['A2','110'], ['B2','123'], ['C3','131'],
3 ['D3','147'], ['E3','165'], ['F3','175'], ['G3','196'],
4 ['A3','220'], ['B3','247'], ['C4','262'], ['D4','294'],
5 ['E4','330'], ['F4','349'], ['G4','392'], ['A4','440'],
6 ['B4','494'], ['C5','523'], ['D5','587'], ['E5','659'],
7 ['F5','698'], ['G5','784'], ['A5','880'], ['B5','988'],
8 ['C6','1047'], ['D6','1175'], ['E6','1319'], ['F6','1397'],
9 ['G6','1568'], ['A6','1760'], ['B6','1976'], ['C7','2093'],
10 ['D7','2349'], ['E7','2637'], ['F7','2794'], ['G7','3136'],
11 ['A7','3520'], ['B7','3951'], ['C8','4186'], ['D8','4699'],

● : duration the sound is to be played. Setting range: t ≥ 0

Example program

13 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

1 import event, time, cyberpi


2
3 @event.is_press('a')
4 def on_received():
5 global frequency
6 for count in range(2):
7 cyberpi.audio.play_tone(800, 1)
8 cyberpi.audio.play_tone(200, 1)
9

Speed and volume of CyberPi's speaker


You can use the following APIs to set the playing speed and volume of CyberPi's speaker.

Changes the playing speed of CyberPi's speaker


Parameter:
● pct: , percentage (of the normal playing speed) by which the playing speed is
to be changed; a negative value indicates decreasing the speed, and a positive one
indicates increasing the speed

Sets the playing speed of CyberPi's speaker


Parameter:
● pct: , percentage of the normal playing speed; setting range: %

Obtains the playing speed of CyberPi's speaker

The value returned is an integer, ranging from 25 to 400 (%).

Changes the playing volume of CyberPi's speaker

Parameter:
● pct: , percentage by which the playing volume is changed; setting range:

14 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

%; a negative value indicates decreasing the volume, and a positive one


indicates increasing the volume

Sets the playing volume of CyberPi's speaker

Parameter:
● pct: , percentage of the playing volume; setting range: %

Obtains the playing volume of CyberPi's speaker

The value returned is an integer, ranging from 0 to 100 (%).

Stops the playing of all sounds

LED
CyberPi is equipped with five programmable LEDs. You can use the following APIs to
compile programs for controlling the LEDs.

Sets the color(s) of the LEDs

Parameters:
● r: or
r: , intensity of the red color; setting range:
r: , full name or abbreviation of a color; the following describes colors
and their abbreviations:

15 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

1 red r
2 orange o
3 yellow y
4 green g
5 cyan c
6 blue b
7 purple p
8 white w
9 black k

● g: , intensity of the green color; setting range:


● b: , intensity of the blue color; setting range:
● id: or ; the default value is
id: , only the value is valid.
id: , setting range: , indicating the position of an LED. The following
figure shows the
positions of the LEDs.

Example program

1 import cyberpi
2 cyberpi.led.on(255,0,0) #Lights up all the LEDs

1 import cyberpi
2 cyberpi.led.on('red', id = 1) #Lights up LED 1 in red

1 import cyberpi
2 cyberpi.led.on('r', id = 1) #Lights up LED 1 in red

Displays the specified LED animation

16 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

This API blocks the thread until the display ends.


Parameter:
● name: , name of an LED animation; the default value is , and the
options include the following:

Sets the color(s) of the five LEDs

Parameter:
● color: , color(s) of the five LEDs, set in the
mode, with one space between any two colors. If you set more than five
colors, only the first five colors are used. You can set this parameter to the full name
or abbreviation of the colors. The options include the following:
,
,
,
,
,
,
,
,
,

Makes the colors of the LEDs roll from left to right by the specified number of positions
Parameter:
● step: , number of positions by which the colors of the LEDs roll; setting range:
; default value:
For example, you set the colors of the five LEDs to r,o,y,g,c and then use this
API. When you set step to 0, the colors of the LEDs are shown in Figure A; and when
you set step to 1, the colors roll from left to right by one position, and the color of

17 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

the first LED is that of the original last LED, as shown in Figure B

Turns off the specified LED(s)


Parameter:
● id: or , position of the LED to be turned off; the default value is ,
indicating all the LEDs; when you set it to an integer, the setting range is 1 to 5.

Changes the brightness of CyberPi's LEDs


Parameter:
● brightness: , percentage by which the brightness is to be changed; setting
range: %; a negative value indicates decreasing, and a positive one
indicates increasing.

Sets the brightness of CyberPi's LEDs


Parameter:
● brightness: , brightness of the LEDs, in percentage; setting range: (%)

Obtains the brightness of CyberPi's LEDs

The returned value is an integer ranging from to .

Example program

18 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

1 # generated by mBlock5 for CyberPi


2 # codes make you happy
3
4 import cyberpi
5 while True:
6 for count in range(10):
7 cyberpi.led.add_bri(10)
8 cyberpi.led.move(1)
9
10 for count2 in range(10):
11 cyberpi.led.add_bri(-10)
12 cyberpi.led.move(1)

Display
CyberPi is equipped with a 1.89-inch full-color display. With the following APIs, you can

use CyberPi to display texts and images, draw charts, design games, and create apps.

Texts and images

Displays texts on CyberPi's screen with automatic line breaks


When this block is executed, texts are displayed on the same line, and when a line is full,
the texts are continued on new lines.
Parameter:
● message: , text to be displayed, such as

Example program

1 import cyberpi
2 cyberpi.console.print('hello')
3 cyberpi.console.print('world')

Displays texts on CyberPi's screen with forced line breaks

19 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

● message: , text to be displayed, such as

Example program

1 import cyberpi
2 cyberpi.console.println('hello world')
3 cyberpi.console.print('hello'+' '+'world')

Positions of texts

Displays a text in the specified position of CyberPi's screen

Parameter:
● message: , text to be displayed, such as
● size: , font size of the text to be displayed; setting range: , , and
● x: or , position where the text is to be displayed
When x is , the options are as follows:
: in the upper center

: in the upper left


: in the upper right

: in the center
: in the middle left

: in the middle right

: in the lower center


: in the lower left

: in the lower right


When x is , the value ranges from to , indicating the x-coordinate of
the upper left corner of the text.
● y: , y-coordinate of the upper left corner of the text; setting range:
The following figure shows the x- and y-coordinates defined for CyberPi's screen.

20 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Example program

Charts

Adds a piece of data and displays a line chart

You can use the API to set the color of a line,

and thus can draw line charts in different colors to present different data sets.
Parameter:
● data: , ranging from to
If a value to be input exceeds the setting range, rescale all the original data to be
within the setting range.
For example, you can rescale the values 200, 300, and 400 to 20, 30, and 40,
respectively.

Sets the spacing between data points in a line chart


● step: , spacing between data points; setting range: (pixels)
For example, the following figures show the line charts with the same data but

different data point spacings.

21 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Adds a piece of data and displays a bar chart

You can use the API to set the color of a bar, and thus can draw
a bar chart with different colors of bars to present different data sets. The width of a bar

changes with the number of bars.


Parameter:
● data: , ranging from to
If a value to be input exceeds the setting range, rescale all the original data to be
within the setting range.
For example, you can rescale the values 200, 300, and 400 to 20, 30, and 40,
respectively.

Adds a piece of data and displays a pie chart


You can use the API display.set_brush(r, g, b) to set the color of a section, and thus can
draw a pie chart with different colors of sections to present different pieces of data. The
degree of a section changes with the number of pieces of data.

Parameter:
● data: , ranging from to

Adds a piece of data and displays a table


The number of rows and columns depends on the content you input. A maximum table
of 4 (rows) × 3 (columns) is supported. When a piece of content is too long, it scrolls in

the cell.

22 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

You can use the API to set the color of the content.
The content can be texts and predefined icons.

Parameter:
● row: , number of rows to be created
● column: , number of columns to be created
● data: , content to be input into a cell of the table

Example program

23 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

1 # generated by mBlock5 for CyberPi


2 # codes make you happy
3
4 import random, cyberpi, event, time
5
6 @event.start
7 def on_start():
8 cyberpi.console.println('2.Volumn-reactive Lights and Columns')
9 cyberpi.console.println('2.光影音量柱')
10 cyberpi.console.println('Press B to start')
11 cyberpi.console.println('按 B 以开始...')
12 while not cyberpi.controller.is_press('b'):
13 cyberpi.display.set_brush(random.randint(1, 255), random.randint
14
15 # The color of the texts changes randomly before you press button B.
16 cyberpi.console.print('')
17 time.sleep(0.1)
18
19 cyberpi.broadcast('Message 1')
20
21 @event.receive('Message 1')
22 def on_receive():
23 """The bar chart changes with the volume of the sounds in the ambient environment. Tr
24 The brightness of the LEDs also changes with the volume."""
25 cyberpi.led.on(114, 0, 255, 1)
26 cyberpi.led.on(191, 0, 255, 2)
27 cyberpi.led.on(255, 0, 195, 3)
28 cyberpi.led.on(255, 0, 72, 4)
29 cyberpi.led.on(255, 0, 0, 5)
30 while True:
31 cyberpi.led.set_bri(cyberpi.get_loudness("maximum"))
32 cyberpi.display.set_brush(114, 0, 255)
33 cyberpi.barchart.add(cyberpi.get_loudness("maximum"))
34 time.sleep(0.02)
35 cyberpi.display.set_brush(191, 0, 255)
36 cyberpi.barchart.add(cyberpi.get_loudness("maximum"))
37 time.sleep(0.02)
38 cyberpi.display.set_brush(255, 0, 195)
39 cyberpi.barchart.add(cyberpi.get_loudness("maximum"))
40 time.sleep(0.02)
41 cyberpi.display.set_brush(255, 0, 72)
42 cyberpi.barchart.add(cyberpi.get_loudness("maximum"))
43 time.sleep(0.02)
44 cyberpi.display.set_brush(255, 24, 24)
45 cyberpi.barchart.add(cyberpi.get_loudness("maximum"))
46 time.sleep(0.05)

24 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

● r: or
r: , intensity of the red color; setting range:
r: , full name or abbreviation of a color; the following describes colors
and their abbreviations:

1 red r
2 orange o
3 yellow y
4 green g
5 cyan c
6 blue b
7 purple p
8 white w
9 black k

● g: , intensity of the green color, ranging from to


● b: , intensity of the blue color, ranging from to

Display directions

Sets CyberPi's screen to the specified displaying direction (angles)


Parameter
● angle: , displaying direction; setting range: , , , ,

The corresponding displaying directions are shown in the following figure.

25 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Clears CyberPi's screen

Turns off the background light of CyberPi's screen

Sensing
With the following APIs, you can obtain output values of the sensors on your CyberPi or

information about your CyberPi.

Button or joystick status


CyberPi is equipped a joystick (that can be moved in five directions to implement
control) and two buttons (buttons A and B), as shown in the following figure.

26 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

The following APIs are available for programming CyberPi:

Determines whether the specified button is pressed or the joystick is moved to the

specified direction
Parameter:
● name: , name of the button or joystick direction
Setting range:
: button A (in the square shape)
: button B (in the rectangle shape)

: joystick moved up

: joystick moved down

: joystick moved to the left

: joystick moved to the right

: joystick pressed in the center

: joystick moved in any one direction

: button A or B

: any button or joystick moving direction

A value is returned.

Obtains the number of times the specified button is pressed or the joystick is moved to

the specified direction


Parameter:
● name: , name of the button or joystick direction
Setting range:
: button A (in the square shape)
: button B (in the rectangle shape)

: joystick moved up

: joystick moved down

: joystick moved to the left

: joystick moved to the right

: joystick pressed in the center

An value is returned.

27 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Resets the number of times the specified button is pressed or the joystick is moved to

the specified direction

Parameter:
● name: , name of the button or joystick direction
Setting range:
: button A (in the square shape)

: button B (in the rectangle shape)

: joystick moved up

: joystick moved down

: joystick moved to the left

: joystick moved to the right

: joystick pressed in the center

: joystick moved in any one direction

: button A or B

: any button or joystick moving direction

Sensor outputs

Obtains the ambient light brightness detected by the light sensor on CyberPi

An value ranging from to is returned. When the value returned is 100,


the upper measuring limit is reached.

Obtains the ambient sound loudness detected by the microphone on CyberPi

Parameter:
● mode: , type of loudness you want to obtain
Setting range
: average loudness in a period
: maximum loudness in a period; obviously, this mode is preferable for
sound-sensitive projects.

28 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

An value ranging from to is returned. When the value returned is 100,


the upper measuring limit of the microphone is reached.

Timer

Obtains the count value of the timer

The timer starts to count when CyberPi starts up.


A value is returned, in seconds.

Resets the count value of CyberPi's timer to 0

Other outputs

Obtains the media access control address (MAC address) of the Wi-Fi
Note that the address obtained may be wrong if Wi-Fi is not connected.

The value returned is a 12-byte value, for example, .

Obtains the battery level (in %) of the pocket shield connected to CyberPi
An value ranging from to is returned. When the value 100 is returned,

the battery is at its highest level; and when 0 is returned, no pocket shield is connected

to CyberPi or the battery of the connected pocket shield runs out of battery.

Obtains the version number of the firmware


The value returned is a value, for example, .

29 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Obtains the Bluetooth device name used by CyberPi


The value returned is a value, for example, .

Obtains the name of your CyberPi


The default name is , and you can set the name of your CyberPi by using the

API .

Sets the name of your CyberPi


The name you set is displayed on the UI of the CyberOS system that runs on your

CyberPi. By setting device names, users can find their CyberPis or identify one another
on a LAN or IoT.

Parameter:
● name: , name you set for your CyberPi, for example, ,

Obtains the system language currently used on CyberPi

The value returned is a value and may be one of the following:


: Chinese
: Cantonese
: Japanese
: English
: French
: German
: Spanish
: Portuguese
: Russian
: Korean
: Italian
: Dutch

Motion Sensing

30 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

With the gyroscope, accelerometer, and built-in motion detection algorithm on CyberPi,
you can implement motion-based control. You can use the following APIs to obtain the

postures of CyberPi.

CyberPi's postures

Determines whether CyberPi is tilted forward

The following figure shows the posture of tilting forward.

A value is returned.

Determines whether CyberPi is tilted backward


The following figure shows the posture of tilting backward.

A value is returned.

31 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Determines whether CyberPi is tilted to the left


The following figure shows the posture of tilting to the left.

A value is returned.

Determines whether CyberPi is tilted to the right

The following figure shows the posture of tilting to the right.

A value is returned.

Determines whether CyberPi faces up

The following figure shows the posture of facing up.

A value is returned.

32 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Determines whether CyberPi faces down


The following figure shows the posture of facing down.

A value is returned.

Determines whether CyberPi is placed perpendicular to the ground, with the LED strip
on the bottom, as shown in the following figure:

A value is returned.

Determines whether CyberPi is placed perpendicular to the ground, with the LED strip

on the top, as shown in the following figure:

33 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

返回 。

Continuous motions

Determines whether CyberPi is shaken


It is determined that CyberPi is shaken when the shaking strength is higher than 20.

A value is returned.

Determine whether CyberPi is waved up

A value is returned.

34 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Determine whether CyberPi is waved down


A value is returned.

Determine whether CyberPi is waved to the left


A value is returned.

Determine whether CyberPi is waved to the right


A value is returned.

35 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Determines whether CyberPi is falling down

A value is returned.

Determines whether CyberPi rotates clockwise around the z-axis


A value is returned.

Determines whether CyberPi rotates counterclockwise around the z-axis

36 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

A value is returned.

Posture and acceleration data

Obtains the shaking strength


The shaking strength is positively related to the shaking frequency and amplitude.

An value ranging from to is returned. When the value returned is 100,


the upper shaking strength limit is reached.

Obtains the direction in which CyberPi is shaken


An value ranging from to is returned, in degrees.

Obtains the speed at which CyberPi is waved


The speed is positively related to but not equal to the actual moving speed of CyberPi.

A large error may be caused in the value obtained due to the integral error.
An value ranging from to is returned.

37 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Obtains the pitch angle of CyberPi

The pitch angle refers to the angle between the y-axis and horizontal plane.

An value ranging from to is returned, in degrees.

Obtains the roll angle of CyberPi


The roll angle refers to the angle between the x-axis and horizontal plane.
An value ranging from to is returned, in degrees.

Obtains the yaw angle of CyberPi

38 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

The yaw angle refers to the angle CyberPi rotates around the z-axis.
An value ranging from to is returned, in degrees.

Resets the yaw angle

No compass is configured in CyberPi, and therefore, is used to reset the


yaw angle to 0.

39 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Obtains the output (in m/s²) of the accelerometer on the specified axis
Parameter:
● axis: , axis defined for CyberPi; setting range: , , and
A value is returned. Note that the accelerometer measures Earth's gravity.
When CyberPi is placed on a desk, the output of the accelerometer on the z-axis is
–9.8m/s² (1g = 9.8m/s²).

Obtains the angular speed around the specified axis


Parameter:
● axis: , axis defined for CyberPi; setting range: , , and
An value ranging from to is returned, in degree/seconds (°/s).

Obtains the angle CyberPi rotates around the specified axis, with the counterclockwise
direction as the positive direction
Parameter:
● axis: , axis defined for CyberPi; setting range: , , and
A value is returned, in degrees.

Resets the angle (s) CyberPi rotates around the specified axis(axes) to zero
After this API is executed, the value obtained by is counted

40 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

from zero.
Parameter:
● axis: , axis or all the axes defined for CyberPi; setting range: , , , and

Wi-Fi
CyberPi is equipped with a Wi-Fi module. You can use the following APIs to connect
CyberPi to the Internet or perform LAN broadcast.

Starts Wi-Fi connection

This API doesn't block the thread, and therefore CyberPi is not necessarily connected to
the Internet when this API stops. You need to use to determine

whether the Wi-Fi connection is complete.


Parameter:
● ssid: , Wi-Fi account; set it to an account that can be used
● password: , Wi-Fi password; set it to the password of the account you use

Detects the Wi-Fi connection status

A value is returned.

Sends a LAN broadcast

For more information, see LAN broadcast.

Receives a LAN broadcast

For more information, see LAN broadcast.

Cloud Services

After connecting CyberPi to the Internet, you can use various cloud services provided by

41 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Makeblock to implement the AI and IoT functions of CyberPi.

Use the API to verify your mBlock account, so that you

can use the cloud services provided by Makeblock. Note that you can use this API only

after you have connected CyberPi to the Internet.


Parameter:
● key: , authorization code for cloud services
Sign in to mBlock 5 on the web or your PC client, and then obtain your cloud
service authorization code as follows.

IoT

Obtains the real-time weather data of the specified location

Parameters:
● option: , weather data option
Setting range:
: highest temperature
: lowest temperature
: temperature
: humidity
● woe_id: , code of the city for which weather data is to be obtained
You can visit Yahoo Weather <https://www.yahoo.com/news/weather> to obtain
the codes of cities.

42 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Change the location to the one of which the weather information is to be searched
for, and then view the code on the address bar.

Alternatively, you can view the code of a city in the corresponding block on mBlock

5, as shown in the following figure.

A value is returned, providing the weather information.

43 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

The returned value may be one of the following:

44 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

1 0 tornado
2 1 tropical storm
3 2 hurricane
4 3 severe thunderstorms
5 4 thunderstorms
6 5 mixed rain and snow
7 6 mixed rain and sleet
8 7 mixed snow and sleet
9 8 freezing drizzle
10 9 drizzle
11 10 freezing rain
12 11 showers
13 12 rain
14 13 snow flurries
15 14 light snow showers
16 15 blowing snow
17 16 snow
18 17 hail
19 18 sleet
20 19 dust
21 20 foggy
22 21 haze
23 22 smoky
24 23 blustery
25 24 windy
26 25 cold
27 26 cloudy
28 27 mostly cloudy (night)
29 28 mostly cloudy (day)
30 29 partly cloudy (night)
31 30 partly cloudy (day)
32 31 clear (night)
33 32 sunny
34 33 fair (night)
35 34 fair (day)
36 35 mixed rain and hail
37 36 hot
38 37 isolated thunderstorms
39 38 scattered thunderstorms
40 39 scattered showers (day)
41 40 heavy rain
42 41 scattered snow showers (day)
43 42 heavy snow
44 43 blizzard
45 44 not available
46 45 scattered showers (night)
47 46 scattered snow showers (night)
48 47 scattered thundershowers

45 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

● option: , air quality option


Setting range
: air quality index
: density of PM2.5
: density of PM10
: density of CO
: density of SO2
: density of NO2
● woe_id: , code of the city for which weather data is to be obtained
A value is returned, providing the corresponding air quality information.

● option: , time option


Setting range:
: sunrise time
: hour of the sunrise time
: minute of the sunrise time
: sunset time
: hour of the sunset time
: minute of the sunset time
[To be implemented]
: hour of the specified time zone
: minute of the specified time zone
: second of the specified time zone
: year of the specified time zone
: month of the specified time zone
: week day of the specified time zone
: date of the specified time zone
● location: or
: code of the city for which weather data is to be obtained
You can visit Yahoo Weather <https://www.yahoo.com
/news/weather> to obtain the codes of cities.

46 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Change the location to the one of which the weather information is to


be searched for, and then view the code on the address bar.

Alternatively, you can view the code of a city in the corresponding

block on mBlock 5, as shown in the following figure.

[To be implemented] : time zone of which the time information is to


be obtained.
Setting range: –12 to +12

A or value is returned, providing the corresponding time information.

47 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

AI
CyberPi provides some AI capabilities. After being connected to the Internet, CyberPi
can recognize speeches, read texts out loud, and translate some texts through the

corresponding AI interfaces.

Starts to recognize a speech in the specified language

This API blocks the thread until the speech is recognized.


Parameters:
● language: , language of the speech to be recognized
Setting range:
: Chinese
: Taiwan Mandarin
: Cantonese
: Japanese
: English
: French
: German
: Spanish
: Portuguese
: Russian
: Korean
: Italian
: Dutch

● t: or ; the default value is 3


When you set t to , it indicates the period for recognizing a speech, in
seconds; when you set it to , you can set it only to , indicating
that the last recorded audio file is used for speech recognization.

Obtains the last recognized speech

A value is returned.

48 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Reads the specified text out loud


Parameters:
● language: , language in which the text is to read out loud
Currently, the language parameter can't be set due to the limitation of cloud
services. This API automatically recognizes the content of message and reads it out
loud in Chinese or English. The following languages will be gradually supported:

: Chinese
: Taiwan Mandarin
: Cantonese
: Japanese
: English
: French
: German
: Spanish
: Portuguese
: Russian
: Korean
: Italian
: Dutch
● message: , text to be read out loud

Translates a text to the specified language


Parameters:
● language: , target language of the translation
Setting range:
: Chinese
: Taiwan Mandarin
: Cantonese
: Japanese
: English
: French
: German
: Spanish
: Portuguese
: Russian
: Korean
: Italian

49 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

: Dutch
● message: , text to be translated

Broadcast
CyberPi supports multiple types of broadcasts. With these broadcasts, CyberPi can
implement communication between threads and on LANs and the Internet.

Basic broadcast

Sends a broadcast message

The message can be received by all threads on CyberPi or by mBlock sprites in Live
mode.

Parameter:
● message: , name of the broadcast message

LAN broadcast

Sends a LAN broadcast message

Parameters:
● message: , name of the LAN broadcast message
● val: , value transmitted by the LAN broadcast message

50 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Obtains the value transmitted by a LAN broadcast message


Parameter:
● message: , name of the LAN broadcast message.
A value is returned.

1 import cyberpi
2 import time
3
4 while True:
5 cyberpi.led.on(0,0,255,1)
6 time.sleep(1)
7 cyberpi.wifi_broadcast.get(message)

Upload mode broadcast

Sends an upload mode broadcast message


When CyberPi is connected to mBlock 5 through Bluetooth or a USB cable, upload

mode broadcast messages are received by mBlock 5 sprites. This API is preferable for
projects in which real-time interaction between mBlock 5 sprites and hardware devices

is required.

Parameters:
● message: , name of the upload mode broadcast message
● val: , value transmitted by the upload mode broadcast message

Obtains the value transmitted by the specified upload mode broadcast message

51 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Parameter
● message: , name of the upload mode broadcast message
A value is returned.

1 import cyberpi
2 import time
3
4 while True:
5 cyberpi.led.on(0,0,255,1)
6 time.sleep(1)
7 cyberpi.upload_broadcast.get(message)

User cloud broadcast

Sends a user cloud broadcast message

To use this API, you need to use and to


obtain the permission to use the cloud services provided by Makeblock for your
CyberPi.

User cloud messages can be used to share data across devices and projects. For
example, after signing in to mBlock 5 on multiple PCs, you can send a user cloud

broadcast message on one PC to all the other online hardware devices and mBlock 5

sprites on the other PCs.


With this API, you can easily access and control your hardware devices through the

Internet. In addition, you can use mBlock 5 or mBlock-Python Editor to design visual
interaction UIs.
Parameters:
● message: , name of the user cloud broadcast message
● val: , value transmitted by the user cloud broadcast message

52 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Obtains the value transmitted by the specified user cloud broadcast message
Parameter:
● message: , name of the user cloud broadcast message
A value is returned.

1 import cyberpi
2 import time
3
4 while True:
5 cyberpi.led.on(0,0,255,1)
6 time.sleep(1)
7 cyberpi.cloud_broadcast.get(message)

Script control

Stops all the scripts

Stops the current script

Stops all the scripts except the current one

Restarts CyberPi

Events

53 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

CyberPi supports the execution of multiple threads. You can add a thread for CyberPi by
adding the corresponding event header, and the thread listens to the specified event.

When the event happens, the subsequent code in the thread is executed.

Event compiling
Event headers are compiled by using decorators, as shown in the following example:

1 import cyberpi
2
3 @cyberpi.event.start # Event to be listened to
4 def callback():
5 cyberpi.led.on("green") # Code to be executed after the event happens
6
7 @cyberpi.event.received('hello') # Event (with a parameter) to be listened to
8 def callback():
9 cyberpi.led.on("blue") # Code to be executed after the event happens

In this coding way, when the event defined in the event header happens, the
subsequent code is executed. In the preceding example, the function name
is used. As a matter of fact, however, any function name that meets the naming
convention can be used. In addition, it's OK to use function names repeatedly because
functions are defined after events.

As you can see in the preceding example, the function is executed when
you start CyberPi and the other function is executed when CyberPi
receives the broadcast message "hello." No conflict occurs because they are defined
after different events.

Event determination mechanism


An event header is triggered only when the event listened to happens. For example, if
the event "button x pressed" is listened to, the event header is triggered and the
subsequent code is executed only when the state of button x is changing from
"unpressed" to "pressed". If button x keeps in the pressed state, the subsequent code is
not executed.

54 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Event header APIs for CyberPi

Listens to the start of CyberPi and executes the subsequent code when CyberPi starts

Listens to the state of the specified button or joystick moving direction and executes the
subsequent code when the specified button is pressed or the joystick is moved to the
specified direction
Parameter:
● name: , name of the button or joystick direction

Setting range:

: button A (in the square shape)


: button B (in the rectangle shape)

: joystick moved up

: joystick moved down

: joystick moved to the left

: joystick moved to the right

: joystick pressed in the center

: joystick moved in any one direction

: button A or B

: any button or joystick moving direction

Listens to the posture of CyberPi and executes the subsequent code when CyberPi tilts

forward

Listens to the posture of CyberPi and executes the subsequent code when CyberPi tilts
backward

55 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Listens to the posture of CyberPi and executes the subsequent code when CyberPi tilts

to the left

Listens to the posture of CyberPi and executes the subsequent code when CyberPi tilts
to the right

Listens to the posture of CyberPi and executes the subsequent code when CyberPi's
screen faces up

Listens to the posture of CyberPi and executes the subsequent code when CyberPi's

screen faces down

Listens to the motion of CyberPi and executes the subsequent code when CyberPi is

shaken

Listens to the motion of CyberPi and executes the subsequent code when CyberPi is

waved up

Listens to the motion of CyberPi and executes the subsequent code when CyberPi is

waved down

56 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Listens to the motion of CyberPi and executes the subsequent code when CyberPi is

waved to the left

Listens to the motion of CyberPi and executes the subsequent code when CyberPi is
waved to the right

Listens to the motion of CyberPi and executes the subsequent code when CyberPi falls
down

Listens to the motion of CyberPi and executes the subsequent code when CyberPi

rotates clockwise around the z-axis

Listens to the motion of CyberPi and executes the subsequent code when CyberPi

rotates counterclockwise around the z-axis

Listens to the comparison result and executes the subsequent code when the value is

greater than the threshold


Parameters:
● threshold: , threshold; setting range:
● type: , type of the data source
Setting range:
: microphone
: light sensor
: shaking strength

57 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

: timer

Listens to the comparison result and executes the subsequent code when the value is
smaller than the threshold
Parameters:
● threshold: , threshold; setting range:
● type: , type of the data source
Setting range:
: microphone
: light sensor
: shaking strength
: timer

Listens to the specified broadcast message and executes the subsequent code when the
broadcast message is received

Parameter
● message: , name of the broadcast message listened to

Listens to the specified upload mode broadcast message and executes the subsequent

code when the upload mode broadcast message is received


Parameter:
● message: , name of the upload mode broadcast message listened to

Listens to the specified user cloud broadcast message and executes the subsequent

code when the user cloud broadcast message is received


Parameter:
● message: , name of the user cloud broadcast message listened to

58 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

Listens to the specified LAN broadcast message and executes the subsequent code

when the LANbroadcast message is received


Parameter:
● message: , name of the LAN broadcast message listened to

Change history

Date Description

2020/07/08 Initial draft

2020/08/25 Added the description of the Sprites and Doodle APIs

Added the API ,


, ,
, and

2020/09/29 Modified the APIs ,


, and

Added the "APIs for mBot2 Shield" and "APIs for mBuild modules" sections

Separated the APIs for function extension, extension boards, and mBuild
2020/11/12 modules from this page and created new pages for them. Currently, this page
describes only the APIs for CyberPi.

2021/02/25 Added a note for "LAN broadcast."

2021/6/25 Added the labels for indicating whether the APIs support Python 3
programming, MicroPython programming, or both

<https://service.weibo.com/share/share.php?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fwww.yuque.com%2Fmakeblock-
pic=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F757912%2F1
e27c18c11826.png&title=Python%20API%20
%20Welcome%20to%20use%20CyberPi%20for%20Python%20learning!CyberPi%20provides%20abundan
%2C%20allowing%20you%20to%20interact%20with

59 von 60 29.01.2023, 18:23


Python API Documentation for CyberPi https://www.yuque.com/makeblock-help-center-en/mcode/cyberpi-api

60 von 60 29.01.2023, 18:23

You might also like