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. By creating 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 cyberpi library to implement the preceding described functions.


Import the cyberpi library


The cyberpi library described in this document refers to two separate libraries with the same name:

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.


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

Import the library as follows:


## Python coding-no omitting
import cyberpi
cyberpi.console.print("hello")


## MicroPython coding-omitting "cyberpi"
from cyberpi import *
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 cyberpi library


The cyberpi library provides multiple APIs for controlling hardware. This page describes the APIs for CyberPi. For the APIs provided for function extension and extension boards, see:

APIs for Function Extension

APIs for Extension boards

APIs for mBuild Modules


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

audio.play_until(music_name)

Plays a preset audio file

This API blocks the thread until the playing ends.

Parameter:


cyberpi.audio.play(music_name)

Plays a preset audio file

Parameter:


Setting range and sound effects
CategoryFile nameVariable nameSound effect
01-EmotionhelloSPEAKER.hellohello
hiSPEAKER.hihi
byeSPEAKER.byebye
yeahSPEAKER.yeahyeah
wowSPEAKER.wowwow
laughSPEAKER.laughlaugh
humSPEAKER.humhum
sadSPEAKER.sadsad
sighSPEAKER.sighsigh
annoyedSPEAKER.annoyedannoyed
angrySPEAKER.angryangry
surprisedSPEAKER.surprisedsurprised
yummySPEAKER.yummyyummy
curiousSPEAKER.curiouscurious
embarrassedSPEAKER.embarrassedembarrassed
readySPEAKER.readyready
sprintSPEAKER.sprintsprint
sleepySPEAKER.sleepysleepy
meowSPEAKER.meowmeow
02-Electronic soundsstartSPEAKER.startstart
switchSPEAKER.switchswitch
beepsSPEAKER.beepsbeeps
buzzingSPEAKER.buzzingbuzzing
explosionSPEAKER.explosionexplosion
jumpSPEAKER.jumpjump
laserSPEAKER.laserlaser
level-upSPEAKER.level-uplevel-up
low-energySPEAKER.low-energylow-energy
prompt-toneSPEAKER.prompt-toneprompt-tone
rightSPEAKER.rightright
wrongSPEAKER.wrongwrong
ringSPEAKER.ringring
scoreSPEAKER.scorescore
wakeSPEAKER.wakewake
warningSPEAKER.warningwarning
03-Physical soundsmetal-clashSPEAKER.metal-clashmetal-clash
shotSPEAKER.shot-1shot
glass-clinkSPEAKER.glass-clinkglass-clink
inflatorSPEAKER.inflatorinflator
running waterSPEAKER.running-waterrunning water
clockworkSPEAKER.clockworkclockwork
clickSPEAKER.clickclick
currentSPEAKER.currentcurrent
switchSPEAKER.switchswitch
wood-hitSPEAKER.wood-hit-3wood-hit
ironSPEAKER.iron-1iron
dropSPEAKER.dropdrop
bubbleSPEAKER.bubble-1bubble
waveSPEAKER.wavewave
magicSPEAKER.magicmagic
spitfireSPEAKER.spitfirespitfire
heartbeatSPEAKER.heartbeatheartbeat
loadSPEAKER.loadload


Instrument simulating

cyberpi.audio.play_music(note, beat, type = "piano")

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:


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

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


import time, cyberpi

cyberpi.console.println('Press B to play music')
cyberpi.console.println('Press B to play music.')
while True:
    while not cyberpi.controller.is_press('b'):
        pass
    # You can right-click a block to view help information.
    # The block uses MIDI codes to indicate notes. The following MIDI codes are used in this example:
    #
    # Numbered musical notation/Note/MIDI code
    # 1 C4 60
    # 2 D4 62
    # 3 E4 64
    # 4 F4 65
    # 5 G4 67
    # 6 A4 69
    # 7 B4 71
    cyberpi.audio.play_music(60, 0.25)
    cyberpi.audio.play_music(60, 0.25)
    cyberpi.audio.play_music(67, 0.25)
    cyberpi.audio.play_music(67, 0.25)
    cyberpi.audio.play_music(69, 0.25)
    cyberpi.audio.play_music(69, 0.25)
    cyberpi.audio.play_music(67, 0.25)
    time.sleep(1)
    cyberpi.audio.play_music(65, 0.25)
    cyberpi.audio.play_music(65, 0.25)
    cyberpi.audio.play_music(64, 0.25)
    cyberpi.audio.play_music(64, 0.25)
    cyberpi.audio.play_music(62, 0.25)
    cyberpi.audio.play_music(62, 0.25)
    cyberpi.audio.play_music(60, 0.25)


cyberpi.audio.play_drum(type, beat)

Plays the specified sound for the specified beats

Setting range:

snare: snare drum

bass-drum: bass drum

side-stick: beating the edge of a drum

crash-cymbal: crash cymbal

open-hi-hat: open hi-hat

closed-hi-hat: closed hi-hat

tambourine: tambourine

hand-clap: handclap

claves: claves


Example program

# generated by mBlock5 for CyberPi
# codes make you happy

import event, time, cyberpi

@event.start
def on_start():
    global frequency
    while True:
        if cyberpi.is_tiltforward():
            cyberpi.audio.play_drum('snare', 0.25)

        if cyberpi.is_tiltforward():
            cyberpi.audio.play_drum('bass-drum', 0.25)

        if cyberpi.is_tiltforward():
            cyberpi.audio.play_drum('open-hi-hat', 0.25)

        if cyberpi.is_tiltforward():
            cyberpi.audio.play_drum('closed-hi-hat', 0.25)

Sounds recording and playing

cyberpi.audio.record()

Starts to record sounds

When this API is executed, CyberPi starts to record sounds until audio.stop_record() is executed or the recording exceeds 10 seconds. The recorded file is stored in RAM, and so the recorded file is lost if CyberPi


cyberpi.audio.stop_record()

Stops recording sounds

This API needs to be used in combination with audio.record().


cyberpi.audio.play_record_until()

Plays the recorded sounds

This API blocks the thread until the playing ends.


cyberpi.audio.play_record()

Plays the recorded sounds


Example program

# generated by mBlock5 for CyberPi
# codes make you happy

import time, event, cyberpi

@event.start
def on_start():
    """Press the middle of the joystick to start recording
    Press button A to stop recording
    Press button B to play the recorded sounds

    Move the joystick up or down to change the playing speed
    Move the joystick to the left or right to change the playing volume"""
    cyberpi.display.set_brush(255, 255, 255)
    cyberpi.led.set_bri(30)
    cyberpi.audio.set_vol(50)
    cyberpi.audio.set_tempo(100)
    cyberpi.console.println('1.Magical Recorder')
    cyberpi.console.println('Press the middle of the joystick to start recording')
    cyberpi.console.println('')
    cyberpi.led.show('orange orange orange orange orange')

@event.is_press('middle')
def is_press():
    cyberpi.console.clear()
    cyberpi.console.println('Press button A to stop recording')
    cyberpi.console.println('')
    cyberpi.led.show('green green green green green')
    cyberpi.audio.record()

@event.is_press('a')
def on_received():
    cyberpi.console.clear()
    cyberpi.console.println('Press button B to play the recorded sounds')
    cyberpi.console.println('Move the joystick up or down to change the playing speed and move it to the left or right to change the playing volume')
    cyberpi.console.println('')
    cyberpi.led.show('red red red red red')
    cyberpi.audio.stop_record()

@event.is_press('b')
def on_received1():
    cyberpi.console.clear()
    cyberpi.console.println('Playing...')
    cyberpi.console.println('Move the joystick up or down to change the playing speed and move it to the left or right to change the playing volume')
    cyberpi.console.println('')
    cyberpi.led.show('blue blue blue blue blue')
    cyberpi.audio.play_record_until()

@event.is_press('up')
def is_press1():
    """Move the joystick up or down to change the playing speed.
    The speed setting function is a feature of CyberPi's audio system, allowing you to have fun by slowing down or speeding up the playing.
    The speed setting function can also be used to slow down or speed up the playing of the preset audio files and simulated instrument sounds."""
    cyberpi.led.off(0)
    cyberpi.audio.add_tempo(10)
    cyberpi.console.println(str('Playing speed:') + str(cyberpi.audio.get_tempo()))
    cyberpi.console.println('')

@event.is_press('down')
def is_press2():
    cyberpi.led.off(0)
    cyberpi.audio.add_tempo(-10)
    if cyberpi.audio.get_tempo() < 40:
        cyberpi.audio.set_tempo(40)

    cyberpi.console.println(str('Playing speed:') + str(cyberpi.audio.get_tempo()))
    cyberpi.console.println('')

@event.is_press('left')
def is_press3():
    """Move the joystick to the left or right to change the playing volume"""
    cyberpi.led.off(0)
    cyberpi.audio.add_vol(-10)
    cyberpi.console.println(str('Playing volume:') + str(cyberpi.audio.get_vol()))
    cyberpi.console.println('')

@event.is_press('right')
def is_press4():
    cyberpi.led.off(0)
    cyberpi.audio.add_vol(10)
    cyberpi.console.println(str('Playing volume:') + str(cyberpi.audio.get_vol()))
    cyberpi.console.println('')


Buzzer simulating

cyberpi.audio.play_tone(freq, t)

Simulates the sound of a buzzer

Parameters:

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


Example program

import event, time, cyberpi

@event.is_press('a')
def on_received():
    global frequency
    for count in range(2):
        cyberpi.audio.play_tone(800, 1)
        cyberpi.audio.play_tone(200, 1)

Speed and volume of CyberPi's speaker

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


cyberpi.audio.add_tempo(pct)

Changes the playing speed of CyberPi's speaker

Parameter:


cyberpi.audio.set_tempo(pct)

Sets the playing speed of CyberPi's speaker

Parameter:


cyberpi.audio.get_tempo()

Obtains the playing speed of CyberPi's speaker

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


cyberpi.audio.add_vol(val)

Changes the playing volume of CyberPi's speaker

Parameter:


cyberpi.audio.set_vol(val)

Sets the playing volume of CyberPi's speaker

Parameter:


cyberpi.audio.get_vol()

Obtains the playing volume of CyberPi's speaker

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


cyberpi.audio.stop()

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.


cyberpi.led.on(r, g, b, id = "all")

Sets the color(s) of the LEDs

Parameters:

r: int , intensity of the red color; setting range: 0 - 255
r: str, full name or abbreviation of a color; the following describes colors and their abbreviations:


red r
orange o
yellow y
green g
cyan c
blue b
purple p
white w
black k


id: str, only the value all is valid.

id: int, setting range: 1-5, indicating the position of an LED. The following figure shows the

positions of the LEDs.

image.png

Example program

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


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


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


cyberpi.led.play(name = "rainbow")

Displays the specified LED animation

This API blocks the thread until the display ends.

Parameter:

rainbow

spoondrift

meteor_blue

meteor_green

flash_red

flash_orange

firefly


cyberpi.led.show(color)

Sets the color(s) of the five LEDs

Parameter:

red, r

green, g

blue, b

yellow, y

cyan, c

purple, p

white, w

orange, o

black, k


led.move(step = 1)

Makes the colors of the LEDs roll from left to right by the specified number of positions

Parameter:

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 the first LED is that of the original last LED, as shown in Figure B

            image.png  image.png


cyberpi.led.off(id = "all")

Turns off the specified LED(s)

Parameter:


cyberpi.led.add_bri(brightness)

Changes the brightness of CyberPi's LEDs

Parameter:



cyberpi.led.set_bri(brightness)

Sets the brightness of CyberPi's LEDs

Parameter:


cyberpi.led.get_bri()

Obtains the brightness of CyberPi's LEDs

The returned value is an integer ranging from 0 to 100.


Example program

# generated by mBlock5 for CyberPi
# codes make you happy

import cyberpi
while True:
    for count in range(10):
        cyberpi.led.add_bri(10)
        cyberpi.led.move(1)

    for count2 in range(10):
        cyberpi.led.add_bri(-10)
        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

cyberpi.console.print(message)

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:


Example program

import cyberpi
cyberpi.console.print('hello')
cyberpi.console.print('world')


cyberpi.console.println(message)

Displays texts on CyberPi's screen with forced line breaks


Example program

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


Positions of texts

cyberpi.display.show_label(message, size, x, y)

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

Parameter:

When x is str, the options are as follows:

top_mid: in the upper center

top_left: in the upper left

top_right: in the upper right

center: in the center

mid_left: in the middle left

mid_right: in the middle right

bottom_mid: in the lower center

bottom_left: in the lower left

bottom_right: in the lower right

When x is int, the value ranges from 0 to 128, indicating the x-coordinate of the upper left corner of the text.

The following figure shows the x- and y-coordinates defined for CyberPi's screen.

image.png

Example program

import cyberpi
cyberpi.display.show_label('cyberpi', 16, 'center')


import cyberpi
cyberpi.display.show_label('cyberpi', 16, x = 64, y = 64)

Charts

cyberpi.linechart.add(data)

Adds a piece of data and displays a line chart

You can use the API display.set_brush(color) to set the color of a line, and thus can draw a line chart with different colors of lines to present different data sets.

Parameter:

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.


cyberpi.linechart.set_step(step)

Sets the spacing between data points in a line chart

For example, the following figures show the line charts with the same data but different data point spacings.

image.png


cyberpi.barchart.add(data)

Adds a piece of data and displays a bar chart

You can use the API display.set_brush(r, g, b) 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:

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.


cyberpi.piechart.add(data)

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:


cyberpi.table.add(row, column, data)

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.


You can use the API display.set_brush(r, g, b) to set the color of the content. The content can be texts and predefined icons.

Parameter:


Example program

# generated by mBlock5 for CyberPi
# codes make you happy

import random, cyberpi, event, time

@event.start
def on_start():
    cyberpi.console.println('2.Volumn-reactive Lights and Columns')
    cyberpi.console.println('2.光影音量柱')
    cyberpi.console.println('Press B to start')
    cyberpi.console.println('按 B 以开始...')
    while not cyberpi.controller.is_press('b'):
        cyberpi.display.set_brush(random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))

        # The color of the texts changes randomly before you press button B.
        cyberpi.console.print('')
        time.sleep(0.1)

    cyberpi.broadcast('Message 1')

@event.receive('Message 1')
def on_receive():
    """The bar chart changes with the volume of the sounds in the ambient environment. Try playing a song!
    The brightness of the LEDs also changes with the volume."""
    cyberpi.led.on(114, 0, 255, 1)
    cyberpi.led.on(191, 0, 255, 2)
    cyberpi.led.on(255, 0, 195, 3)
    cyberpi.led.on(255, 0, 72, 4)
    cyberpi.led.on(255, 0, 0, 5)
    while True:
        cyberpi.led.set_bri(cyberpi.get_loudness("maximum"))
        cyberpi.display.set_brush(114, 0, 255)
        cyberpi.barchart.add(cyberpi.get_loudness("maximum"))
        time.sleep(0.02)
        cyberpi.display.set_brush(191, 0, 255)
        cyberpi.barchart.add(cyberpi.get_loudness("maximum"))
        time.sleep(0.02)
        cyberpi.display.set_brush(255, 0, 195)
        cyberpi.barchart.add(cyberpi.get_loudness("maximum"))
        time.sleep(0.02)
        cyberpi.display.set_brush(255, 0, 72)
        cyberpi.barchart.add(cyberpi.get_loudness("maximum"))
        time.sleep(0.02)
        cyberpi.display.set_brush(255, 24, 24)
        cyberpi.barchart.add(cyberpi.get_loudness("maximum"))
        time.sleep(0.05)


cyberpi.display.set_brush(r, g, b)

r: int , intensity of the red color; setting range: 0 - 255

r: str, full name or abbreviation of a color; the following describes colors and their abbreviations:


red r
orange o
yellow y
green g
cyan c
blue b
purple p
white w
black k



Display directions

cyberpi.display.rotate_to(angle)

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

Parameter

The corresponding displaying directions are shown in the following figure.

image.png

cyberpi.display.clear()

Clears CyberPi's screen


cyberpi.display.off()

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.

image.png

The following APIs are available for programming CyberPi:


cyberpi.controller.is_press(name)

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

Parameter:

Setting range:

a: button A (in the square shape)

b: button B (in the rectangle shape)

up: joystick moved up

down: joystick moved down

left: joystick moved to the left

right: joystick moved to the right

middle: joystick pressed in the center

any_direction: joystick moved in any one direction

any_button: button A or B

any: any button or joystick moving direction

A bool value is returned.


cyberpi.controller.get_count(name)

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

Parameter:

Setting range:

a: button A (in the square shape)

b: button B (in the rectangle shape)

up: joystick moved up

down: joystick moved down

left: joystick moved to the left

right: joystick moved to the right

middle: joystick pressed in the center

An int value is returned.


cyberpi.controller.reset_count(name)

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

Parameter:

Setting range:

a: button A (in the square shape)

b: button B (in the rectangle shape)

up: joystick moved up

down: joystick moved down

left: joystick moved to the left

right: joystick moved to the right

middle: joystick pressed in the center

any_direction: joystick moved in any one direction

any_button: button A or B

any: any button or joystick moving direction


Sensor outputs

cyberpi.get_bri()

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

An int value ranging from 0 to 100 is returned. When the value returned is 100, the upper measuring limit is reached.


cyberpi.get_loudness(mode = "maximum")

Obtains the ambient sound loudness detected by the microphone on CyberPi

Parameter:

Setting range

average: average loudness in a period

maximum: maximum loudness in a period; obviously, this mode is preferable for sound-sensitive projects.


An int value ranging from 0 to 100 is returned. When the value returned is 100, the upper measuring limit of the microphone is reached.


Timer

cyberpi.timer.get()

Obtains the count value of the timer

The timer starts to count when CyberPi starts up.

A float value is returned, in seconds.


cyberpi.timer.reset()

Resets the count value of CyberPi's timer to 0


Other outputs

cyberpi.get_mac_address()

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 str value, for example, FFEE33445566.


cyberpi.get_battery()

Obtains the battery level (in %) of the pocket shield connected to CyberPi

An int value ranging from 0 to 100 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.


cyberpi.get_firmware_version()

Obtains the version number of the firmware

The value returned is a str value, for example, 44.01.001.


cyberpi.get_ble()

Obtains the Bluetooth device name used by CyberPi

The value returned is a str value, for example, Makeblock_LE_XXXXX.


cyberpi.get_name()

Obtains the name of your CyberPi

The default name is cyberpi, and you can set the name of your CyberPi by using the API set_name(name).


cyberpi.set_name(name)

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:


cyberpi.get_language()

Obtains the system language currently used on CyberPi

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

"chinese": Chinese

"cantonese": Cantonese

"japanese": Japanese

"english": English

"french": French

"german": German

"spanish": Spanish

"portuguese": Portuguese

"russian": Russian

"korean": Korean

"italian": Italian

"dutch": Dutch


Motion Sensing

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

cyberpi.is_tiltforward()

Determines whether CyberPi is tilted forward

The following figure shows the posture of tilting forward.

image.png

A bool value is returned.


cyberpi.is_tiltback()

Determines whether CyberPi is tilted backward

The following figure shows the posture of tilting backward.

image.png

A bool value is returned.


cyberpi.is_tiltleft()

Determines whether CyberPi is tilted to the left

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

image.png

A bool value is returned.


cyberpi.is_tiltright()

Determines whether CyberPi is tilted to the right

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

image.png

A bool value is returned.


cyberpi.is_faceup()

Determines whether CyberPi faces up

The following figure shows the posture of facing up.

image.png

A bool value is returned.


cyberpi.is_facedown()

Determines whether CyberPi faces down

The following figure shows the posture of facing down.

image.png

A bool value is returned.


cyberpi.is_stand()

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

垂直地面.png

A bool value is returned.


cyberpi.is_handstand()

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

倒置.png

返回 bool


Continuous motions


cyberpi.is_shake()

Determines whether CyberPi is shaken

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

A bool value is returned.


cyberpi.is_waveup()

Determine whether CyberPi is waved up

A bool value is returned.

image.png

cyberpi.is_wavedown()

Determine whether CyberPi is waved down

A bool value is returned.

image.png

cyberpi.is_waveleft()

Determine whether CyberPi is waved to the left

A bool value is returned.

image.png

cyberpi.is_waveright()

Determine whether CyberPi is waved to the right

A bool value is returned.

image.png

cyberpi.is_freefall()

Determines whether CyberPi is falling down

A bool value is returned.

image.png

cyberpi.is_clockwise()

Determines whether CyberPi rotates clockwise around the z-axis

A bool value is returned.

image.png

cyberpi.is_anticlockwise()

Determines whether CyberPi rotates counterclockwise around the z-axis

A bool value is returned.

image.png

Posture and acceleration data

cyberpi.get_shakeval()

Obtains the shaking strength

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

An int value ranging from 0 to 100 is returned. When the value returned is 100, the upper shaking strength limit is reached.


cyberpi.get_wave_angle()

Obtains the direction in which CyberPi is shaken

An int value ranging from –179 to 180 is returned, in degrees.

image.png

cyberpi.get_wave_speed()

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 int value ranging from 0 to 100 is returned.


cyberpi.get_pitch()

Obtains the pitch angle of CyberPi

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

An int value ranging from –90 to 90 is returned, in degrees.

image.png

cyberpi.get_roll()

Obtains the roll angle of CyberPi

The roll angle refers to the angle between the x-axis and horizontal plane.

An int value ranging from –179 to 180 is returned, in degrees.

image.png

cyberpi.get_yaw()

Obtains the yaw angle of CyberPi

The yaw angle refers to the angle CyberPi rotates around the z-axis.

An int value ranging from –180 to 180 is returned, in degrees.

image.png

Note: Accumulated errors may be caused in the obtained yaw angle due to the lack of compass. You can use the API reset_yaw() to calibrate the yaw angle. No compass is configured in CyberPi, and therefore, reset_yaw() is used to reset the yaw angle to 0.


cyberpi.reset_yaw()

Resets the yaw angle

No compass is configured in CyberPi, and therefore, reset_yaw() is used to reset the yaw angle to 0.


cyberpi.get_acc(axis)

image.png

Obtains the output (in m/s²) of the accelerometer on the specified axis

Parameter:


cyberpi.get_gyro(axis)

Obtains the angular speed around the specified axis

Parameter:

An int value ranging from –500 to 500 is returned, in degree/seconds (°/s).


cyberpi.get_rotation(axis)

Obtains the angle CyberPi rotates around the specified axis, with the counterclockwise direction as the positive direction

Parameter:

A value is returned, in degrees.


cyberpi.reset_rotation(axis= "all")

Resets the angle (s) CyberPi rotates around the specified axis(axes) to zero

After this API is executed, the value obtained by get_rotation(axis) is counted from zero.

Parameter:


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.

cyberpi.wifi.connect(ssid, password)

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 wifi.is_connect() to determine whether the Wi-Fi connection is complete.

Parameter:


cyberpi.wifi.is_connect()

Detects the Wi-Fi connection status

A bool value is returned.


cyberpi.wifi_broadcast.set(message, val)

cyberpi.wifi_broadcast.get(message)

Sends and 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 Makeblock to implement the AI and IoT functions of CyberPi.

Use the API cyberpi.cloud.setkey(key) 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:

Sign in to mBlock 5 on the web or your PC client, and then obtain your cloud service authorization code as follows.

image.png

IoT


cyberpi.cloud.weather(option, woe_id)

Obtains the real-time weather data of the specified location

Parameters:

Setting range:

max_temp: highest temperature

min_temp: lowest temperature

weather: temperature

humidity: humidity

You can visit Yahoo Weather to obtain the codes of cities.

image.png

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.

city code.gif


A str value is returned, providing the weather information.

The returned value may be one of the following:


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


cyberpi.cloud.air(option, woe_id)

Setting range

aqi: air quality index

pm2.5: density of PM2.5

pm10: density of PM10

co: density of CO

so2: density of SO2

no2: density of NO2

A str value is returned, providing the corresponding air quality information.


cyberpi.cloud.time(option, location)

Setting range:

sunrise_time: at sunrise

sunrise_hour: hour of the sunrise time

sunrise_minute: minute of the sunrise time

sunset_hour: hour of the sunset time

sunset_minute: minute of the sunset time

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


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.

cyberpi.cloud.listen(language, t=3)

Starts to recognize a speech in the specified language

This API blocks the thread until the speech is recognized.

Parameters:

Setting range:

"chinese": Chinese

"chinese_taiwan": Taiwan Mandarin

"cantonese": Cantonese

"japanese": Japanese

"english": English

"french": French

"german": German

"spanish": Spanish

"portuguese": Portuguese

"russian": Russian

"korean": Korean

"italian": Italian

"dutch": Dutch


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


cyberpi.cloud.listen_result()

Obtains the last recognized speech

A str value is returned.


cyberpi.cloud.tts(language, message)

Reads the specified text out loud

Parameters:

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": Chinese

"chinese_taiwan": Taiwan Mandarin

"cantonese": Cantonese

"japanese": Japanese

"english": English

"french": French

"german": German

"spanish": Spanish

"portuguese": Portuguese

"russian": Russian

"korean": Korean

"italian": Italian

"dutch": Dutch


cyberpi.cloud.translate(language, message)

Translates a text to the specified language

Parameters:

Setting range:

"chinese": Chinese

"chinese_taiwan": Taiwan Mandarin

"cantonese": Cantonese

"japanese": Japanese

"english": English

"french": French

"german": German

"spanish": Spanish

"portuguese": Portuguese

"russian": Russian

"korean": Korean

"italian": Italian

"dutch": Dutch


Broadcast

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


Basic broadcast

cyberpi.broadcast(message)

Sends a broadcast message

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

Parameter:


LAN broadcast

Note:

All CyberPis on the same LAN must use the same channel for communication.

Without router connection, CyberPis use the same default channel and thus can communicate with each other on the LAN; when CyberPi is connected to a router, its channel depends on the setting of the router, which may be different from the default channel, and thus it may fail to communicate with another CyberPi that is not connected to the router.

Therefore, to ensure proper communication, if you use a router, connect all CyberPis on the same LAN to the router.


cyberpi.wifi_broadcast.set(message, val)

Sends a LAN broadcast message

Parameters:


cyberpi.wifi_broadcast.get(message)

Obtains the value transmitted by a LAN broadcast message

Parameter:

A str value is returned.


Upload mode broadcast

cyberpi.upload_broadcast.set(message, val)

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:


cyberpi.upload_broadcast.get(message)

Obtains the value transmitted by the specified upload mode broadcast message

Parameter

A str value is returned.


User cloud broadcast

cyberpi.cloud_broadcast.set(message, val)

Sends a user cloud broadcast message

To use this API, you need to use wifi.is_connect() and cloud.setkey(key) 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:

cyberpi.cloud_broadcast.get(message)

Obtains the value transmitted by the specified user cloud broadcast message

Parameter:

A str value is returned.


Script control

cyberpi.stop_all()

Stops all the scripts


cyberpi.stop_this()

Stops the current script


cyberpi.stop_other()

Stops all the scripts except the current one


cyberpi.restart()

Restarts CyberPi

Events

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.


Note: The Events APIs can't be used in Python3 programming. You need to use the threading mechanism provided by Python3 to compile multi-thread code.


Event compiling

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

import cyberpi

@cyberpi.event.start # Event to be listened to
def callback():
    cyberpi.led.on("green") # Code to be executed after the event happens
 
@cyberpi.event.received('hello') # Event (with a parameter) to be listened to
def callback():
    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 callback() 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 callback() is executed when you start CyberPi and the other function callback() 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.


Event header APIs for CyberPi

cyberpi.event.start

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


cyberpi.event.is_press(name)

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:

a: button A (in the square shape)

b: button B (in the rectangle shape)

up: joystick moved up

down: joystick moved down

left: joystick moved to the left

right: joystick moved to the right

middle: joystick pressed in the center

any_direction: joystick moved in any one direction

any_button: button A or B

any: any button or joystick moving direction


cyberpi.event.is_tiltforward

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


cyberpi.event.is_tiltback

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


cyberpi.event.is_tiltleft

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


cyberpi.event.is_tiltright

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


cyberpi.event.is_faceup

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


cyberpi.event.is_facedown

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


cyberpi.event.is_shake

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


cyberpi.event.is_waveup

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


cyberpi.event.is_wavedown

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


cyberpi.event.is_waveleft

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


cyberpi.event.is_waveright

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


cyberpi.event.is_freefall

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


cyberpi.event.is_clockwise

Listens to the motion of CyberPi and executes the subsequent code when CyberPi rotates clockwise around the z-axis


cyberpi.event.is_anticlockwise

Listens to the motion of CyberPi and executes the subsequent code when CyberPi rotates counterclockwise around the z-axis


cyberpi.event.greater_than(threshold, type)

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

Parameters:

Setting range:

microphone: microphone

light_sensor: light sensor

shake_val: shaking strength

timer: timer


cyberpi.event.smaller_than(threshold, type)

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

Parameters:

Setting range:

microphone: microphone

light_sensor: light sensor

shake_val: shaking strength

timer: timer


cyberpi.event.receive(message)

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

Parameter


cyberpi.event.upload_broadcast(message)

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

Parameter:


cyberpi.event.cloud_broadcast(message)

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

Parameter:


cyberpi.event.wifi_broadcast(message)

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

Parameter:

Change history


Date

Description

2020/07/08

Initial draft

2020/08/25

Added the description of the Sprites and Doodle APIs 

2020/09/29

Added the API cyberpi.piechart.add(data)cyberpi.get_language(), cyberpi.is_stand()cyberpi.is_handstand()cyberpi.event.is_stand, and cyberpi.event.is_handstand


Modified the APIs cyberpi.cloud.listen(language,t=3)

cyberpi.cloud.tts(language, message), and cyberpi.cloud.translate(language, message)


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

2020/11/12

Separated the APIs for function extension, extension boards, and mBuild 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."