Deutsch   English 

Documentation mbRobot, mbRobot Plus and micro:bit

 

Modul mbrobot / mbrobot_plus
(Mini: Maqueen Rover, real and simulation mode)
Module import: from mbrobot import * / from mbrobot_plus import *

forward() sets the Maqueen in forward motion
backward() sets the Maqueen in reverse motion
left() sets the Maqueen in a left turn (one motor in forward, the other in backward rotation)
right() sets the Maqueen in a right turn (one motor in forward, the other in backward rotation)
leftArc(radius) sets the Maqueen to a left curve with given radius (in cm, approx.)
rightArc(radius) sets the Maqueen to a right curve with given radius (in cm, approx.)
stop() stops the movement
setSpeed(speed)

sets the speed for the movements (10 < speed<100), default 50

setPID(1) [nur mbrobot_plus]

sets the speed for the movements (10 < speed<100), default 50

setPID(0) [nur mbrobot_plus]

PID is turned off, robot moves at normal speed

getDistance() returns the distance (in mm) measured with the ultrasonic sensor
setBeamAreaColor() [nur Simulation]

sets the color of the beam area boundaries

setProximityCircleColor() [nur Simulation]

sets the color of the proximity circle

setMeshTriangleColor() [nur Simulation] sets the color of the mesh triangles
eraseBeamArea() [nur Simulation

erases the beam area boundaries

irLeft.read_digital(), irRight.readDigital() infrared sensors return 0, if floor is dark; 1, if floor is bright
ledLeft.write_digital(n), ledRight.write_digital(n) turns LED on (n = 1) or off (n = 0)
playTone(freq, duration)

plays a tone with a given frequency (in Hertz) and duration (in ms)

 

Modul mbrobotmot / mbrobot_plus (Switch motors individually)
(Real- and Simulationsmodus)
Modul import: from mbrobotmot import * / from mbrorobot_plus import *

motL, motR Left and right motor
motX.rotate(speed) Sets the left or right motor in motion with the rotation speed speed. For speed > 0 forward, for speed < 0 backward, speed = 0 stops the rotation.


Module import: from micro:bit import *

Global function calls:

Function Action
panic(n) blocks the system and displays infinitely a "sad face" image followed by n (for developers only)
reset() restarts the board (and executes main.py)
sleep(dt) stops program for dt milliseconds
running_time() returns the time in milliseconds since the board was switched on or resetted
temperature() returns the temperature in degrees celsius (as float)


Class MicroBitButton
button_a object reference (instance) of button A
button_b object reference (instance) of button B

Methods:
is_pressed() returns True, if the button is down (pressed); otherwise False
was_pressed() returns True, if the button was pressed since the last call (or start of the program). Another call returns False, until the button is pressed again
get_presses() returns the number of button presses since the last call (or start of program). Another call returns False, until the button is pressed again

Example:

if button_a.was_pressed():
     do_something


Class MicroBitDisplay
display object reference (instance)

Methods:
set_pixel(x, y, value) sets the intensity of pixel at position x, y. value in range 0..9
clear() clears all pixels
show(str) shows given str on LED display. If str has more than 1 character, the text ist scrolled until the last character becomes visible
show(list_of_img, delay = 400, loop = False, wait = True, clear = False)

shows all images of the list in a timed sequence. If loop = True ist, the sequence is repeated infinitely. For wati = True the method is blocking, otherwise it returns while the sequence continues in the background. delay is the display time for each image in ms (default: 400). For clear = True, the display is clear after the last image is shown

show(img) show Image img on LED display. If img is bigger than 5x5 pixel, the pixels in range x, y = 0..4 are shown. If img is smaller than 5x5 pixel, the missing pixels are black
scroll(str) shows str as scrolling text. The last character disappears
off() turns off display (pin3, pin4, pin6, pin7, pin9, pin19 may be used for general digital in/out)
on() turns on the display and sets pin3, pin4, pin6, pin7, pin9, pin19 in display mode
scroll(str, delay = 150, loop = False, wait = True, monospace = False) show str as scrolling text . If loop = True, the sequence is repeated infinitely. For wait = True the method is blocking, otherwise it returns while the sequence continues in the background. delay is the display time for a single column (default: 150)

Examples:

display.show("A")
display.scroll("Hello")
display.show([Image.HAPPY, Image.SAD])



Class MicroBitImage
Image(str) creates object reference (instance). str has format "aaaaa:bbbbb:ccccc:ddddd:eeeee:" where a is a number in the range 0..9 and defines the intensity of the pixel, a are values of first line, b of second, etc.
Image() creates object reference (instance) with 5x5 pixels and all pixels are turned off
Image(width, height) creates object reference (instance) with given number of horizontal and vertical pixels with all pixels turned off (value = 0)

Methods:
set_pixel(x, y, value) sets the intensity of pixel at position x, y. value in range 0..9
shift_left(n) returns an Image object by shifting the picture left by n columns
shift_right(n) returns an Image object by shifting the picture right by n columns
shift_up(n) returns an Image object by shifting the picture up by n rows
shift_down(n) returns an Image object by shifting the picture down by n rows
copy() returns a clone of the image
invert() returns an Image object by inverting the intensity of all pixels (new_value = 9 - value)
fill(value) returns an Image with all pixel intensities set to to given value (0..9)
dest.blit(img, x, y, w, h, xdest, ydest) copies from given image img a rectangular section of size w, h at position x, y to dest image at position xdest, ydest

Operations:
image_new = image * n returns an object with all pixel intensities multiplied by n
image_new = image1 + image2 returns an object by adding the pixel intensities of image1 and image2


Predefined Images:

Remark:
A MicroBitImage object (short "image") is an abstraction of the real picture and gets visible when display.show(img) is called. An image may have any number of horizontal and vertical pixels (w, h), but only pixels in the range x = 0..4, y = 0..4 are shown. (If image is smaller, the non-defined pixels are black.) For bigger images, use blit()to extract a section.

Be aware that with the exception of set_pixel() and blit() the methods do not modify the image itself, but return a new image. To change img, it must be assigned to the return value.

Example:
img = Image(2, 2)
img = img.invert()
display.show(img)



Class MicroBitTouchPin
pin0, pin1, pin2, pin8, pin12, pin16 instances for general digital-in/digital-out
pin0, pin1, pin2 instances for analog-in/analog-out (PWM)
pin3, pin4, pin6, pin7, pin9, pin10 instances predefined for LED display (display mode)
pin5, pin11 instances predefine for button A, B (button mode)
pin13, pin14, pin15 instances predefined for SPI (spi mode)
pin19, pin20 instances predefined for I2C (i2c mode)

Methods:
read_digital() returns True, if the pin is logical 1 (HIGH); returns False, if logical 0 (LOW) (Pulldown 10 kOhm)
write_digital(v) if v = 1, sets the pin to logical 1 (HIGH); if v = 0, sets the pin to logical 0 (LOW) (max. current: 5 mA)
read_analog() returns value from ADC in range 0..1023 (input impedance: 10 MOhm)
write_analog(v) sets the PWM duty cycle (v = 0..1023 corresponds to 0..100%) (max. current: 5 mA)
set_analog_period(period) sets the PWM period in milliseconds
set_analog_period_microseconds(period) sets the PWM period in microseconds (> 300)


Class Accelerometer

accelerometer object reference (instance)

Methods:
get_x(), get_y(), get_z()

returns the current value of acceleration in x, y or z direction (int, range approx.. -2047 to +2048, corresponding approx. -20 m/s^2 to +20 m/s^2, gravitational acceleration of approx. 10 m/s^2 included). x direction: ButtonA-ButtonB; y direction: Pin2-USB; z direction: perpenticular to board

get_values() returns a tuple with the acceleration in x, y and z direction (ints, units as above)
current_gesture()

returns the current gesture. The following gestures are detected: " up", " down", " left", " right", " face up", " face down", " freefall", " 3g", " 6g", " 8g", " shake"

is_gesture(name) returns True, if name is the current gesture )
is_gesture()

returns a tuple of the gesture history. The most recent is listed last. Also clears the gesture history before returning

was_gesture(name)

returns True, if the given name is found in the gesture history



Class MicroBitCompass
compass object reference (instance)

Methods:
calibrate()

starts a blocking calibration routine needed to get accurate readings: tilt the micro:bit in different directions, so that the blinking pixel reaches the border, where the border pixel is turned on. When all border pixels are lit, the program continues

is_calibrated() returns True, if the compass was calibrated
clear_calibration() resets the compass to the non-calibrated state
heading() returns the angle of the current direction if the micro:bit with respect to the north
get_x(), get_y(), get_z() returns the current value of the x, y or z component of the magnetic field at the sensor position (int, in microtesla, no calibration needed)
get_values() returns a tuple with x , y and z components of the magnetic field at the sensor position (int, in microtesla, no calibration needed)


Class NeoPixel

(Module import: from neopixel import *)
np = NeoPixel(pin, n)

creates a Neopixel object (instance) with n neopixels controlled via given pin. Each pixel is addressed by its position (starting from 0) and its color is determined by assigning a RGB tuple, e.g. np[2] = (0, 100, 255) sets pixel # 2 to red = 0, green = 100, blue = 255. show() must be called to update the display

(Strips with WS2812 LEDs supported.)


Methods:
clear()

clears all pixels

show() shows the pixels. Must be called to make any change of color values visible


Module music

(Module import: from music import *)

Functions:
set_tempo(bpm = 120) sets the number of beats per minute (default: 120)
pitch(frequency, len, pin = microbit.pin0, wait = True) plays a tone with given frequency in Hertz during the given length (duration) (in milliseconds). pin defines the output pin at the GPIIO header (default: P0). If wait = True, the function is blocking; otherwise it returns while the sound continues (until finished or stop() is called)
play(melody, pin = microbit.pin0, wait = True, loop = False) plays a melody with current tempo. pin defines the output pin at the GPIIO header (default: P0). If wait = True, the function is blocking; otherwise it returns while the sound continues (until finished or stop() is called). If loop is True, the melody is played again infinitely
stop(pin = microbit.pin0) stops sound output at given header pin (default: P0)

Remark:
A melody is a list of strings in the format ["note:duration", "note:duration",...]
note in musical notation: c, d, e, f, g, a, h with optional octave number (default: 1): e.g. c2, d2, ... and optional sharp: c#, d#,... or c#2, d#2,...
duration in number of ticks (optional, defaut: 1)

Predifined song lists:


Module radio:

(Module import: from radio import *)

Computer communication over Bluetooth

Functions:
on() turns Bluetooth communication on. Connecting to a micro:bit node that has radio turned on
off() turns Bluetooth communicaion off
send(msg) sends the message string to the receiving node's message queue (First-In-First-Out, FIFO buffer)
msg = receive() returns the oldest message (string) in the message queue and removes it from the queue. None is returned, if the queue is empty. It is assumed that the messages is sent with send(smg), so it can be converted in a valuable string [otherwise a ValueError exception ("received packet is not a string") is raised]
send_bytes(msg_bytes) sends the message bytes (class bytes, e.g b'\x01\x48') to the receiving node's message queue (First-In-First-Out, FIFO buffer)
receive_bytes() returns the oldest message bytes from the message queue and deletes it from the queue. None is returned, if the queue is empty. To send the message, send_bytes(msg) must be used (and not send(msg))


Module mbglow:
Modul import: from mbglow import *

Functions:
makeGlow() creates a visible glowbug at position (0, 0) directed to the north with its trace enabled. Coordinate system: -2 <=x <=2 (+ to the right), -2 <= y <= 2 (+ upwards), (0, 0) at center pixel
setSpeed() sets the speed for movements (0..100)
show() enables the visibility for the following movements
hide() disables the visibility
clear() clears all visible pixels. The glowbug remains at the current position (but is invisible)
showTrace(enable) enables/disables the trace for the following movements (pixels are turned on at the glowbug position)
forward() moves the glowbug one step in the forward direction
back() moves the glowbug one step in the backward direction
left(angle) turns the glowbug in 45 degrees increments to the left (angle = 45, 90, 135, 180, 215, 270, 315)
right(angle) urns the glowbug in 45 degrees increments to the right (angle = 45, 90, 135, 180, 215, 270, 315)
setPos(x, y) sets the glowbug at position (x, y)
getPos() returns the current position of the glowbug (as tuple)
isLit() returns True, if the pixel at the current glowbug position is turned on

 

Module linkup
(ESP32 Coprocessor Board connected to I2C)
(Module import: from linkup import *)

connectAP(ssid, password)

connects the LinkUp with an existing access point (hotspot, router) with ssid and password
httpGet(url) executes an HTTP GET request and returns the response. url in the form "http://<server>?key=value&key=value&...". https can also be used instead of http
httpPost(url, content) executes an HTTP POST request and returns the response. url in the form "http://<server>". content in the format "key=value&key=value&...". https can also be used instead of http
httpDelete(url) executes an HTTP DELETE request with the given resource (file name)
startHTTPServer(ssid, password, startAP)

starts an HTTP server (web server on port 80) and listens for HTTP GET requests. When a GET request is received, the file linkup.html is sent as response to the browser, where any %s format fields are replaced with the strings that were passed with sendReply().
If startAP = True, a local access point with given ssid and password is started. If startAP = False, an existing access point with ssid and password is used and the dotted IP address attributed by the access point is returned (empty, if login fails).
The server is blocking. To return to command mode, the Micro:LinkUp must be rebooted

pollRequest() checks if a GET request has been received and returns a tuple with the filename as string ('/' if none has been specified) and with the request parameter as dictionary {key : value} (empty, if none were specified). Returns None, if no request was received
sendReply(param1, param2,...)

transfers values to the Micro:LinkUp after a pollRequest, which are transferred to the HTML as format parameters before the HTML supplemented in this way is sent to the web browser. The number and sequence of the parameters must match the format specifications in the HTML

saveHTML(text)

sends the text string to the Micro:LinkUp and saves it there as linkup.hrml in the file system. It may contain %s format fields, which are replaced with strings passed with sendReply()



Modul mqtt
(Micro:LinkUp ESP32 coprocessor breakout am I2C-Port)
Modul import: import mqtt

Funkcion Action

mqtt.connectAP(ssid, password)

connects to the existing access point (hotspot, router) with ssid and password. Returns the received dotted IP address; empty if login fails

mqtt.broker(host, port = 1883,
user = "", password = "", keepalive = 0)

broker (IP address, IP port and if necessary authentication details). keepalive determines how long the connection remains open without data exchange (in sec) (default depends on the broker). No connection to the broker is established yet

mqtt.connect(cleanSession = True)

connects to the broker. For cleanSession = True, all previous data will be deleted. Returns True if the connection has been established; otherwise False

mqtt.ping()

sends a ping request to the server to keep the connection open. Returns True if successful; otherwise False

mqtt.publish(topic, payload, retain = False, qos = 0)

sends a message for the given topic (payload). If retain = True, this message is regarded as the last good/retain message. qos is the Quality of Service level (only 0, 1 supported). Returns True if successful; otherwise False

mqtt.subscribe(topic, qos = 0

subscribes the given topic with the given qos level (only 0, 1 supported). A maximum of 50 receiving message tuples (topic, payload) are stored one after the other in a message buffer (maximum lengths topic: 50, payload: 200 bytes). Returns True if successful; otherwise False

topic, payload = mqtt.receive() retrieves the first element of the message buffer (the "oldest") as a tuple (topic, payload) and removes the element from the buffer. If there is no data in the buffer, (None, None) is returned. The poll period should be at least 1 sec. Returns None, if the connection to the broker is lost

mqtt.set_last_will(topic, message, retain = False, qos = 0)

defines the message that is sent to all subscribers when the connection is closed. Returns True if successful; otherwise False

mqtt.disconnect() closes the connection


Modul ntptime

(using Micro:LinkUp ESP32 coprocessor as I2C slave)
(Modul import: import ntptime)

ntptime.getTimeRaw(server = "pool.ntp.org"

gibt die aktuelle Datumzeit zurück, die vom gegebenen Server abgegeben wurde. Format: Tupel (yyyy, mm, dd, h, m, s, week_day, day_of_year) alles Ints. Zeit ist GMT
ntptime.getTime(server = "pool.ntp.org") dasselbe, aber es wird ein formatierter String zurückgegeben (Beispiel: "Tu 2019-06-11 13:04:44 GMT")

Module sht
(Sensirion temperature and air humidity sensor connected to I2C)
Module import: import sht

sht.getTempHumi() returns a tuple with temperature (in degrees Celsius) and humidity (in percent)


Modul sgp
SGP30 Air Quality Sensor (Co2-Sensor am I2C-Port)
Modul import: import sgp

sht.getValues() returns a tuple with CO2 concentration (in ppm) and TVOC (Total Volantile Organic Compunds) . The sensor is calibrated to CO2 = 400. With values higher than 1000, the air quality is poor and ventilation is urgently required. I2C address (SGP30: 0x58)


Modul mcp9808

(Microchip Temperatursensor am I2C-Port)
Modul import: from mcp9808 import MCP9808

mcp = MCP9808()

creates a sensor instance

mcp.temperature()

returns the temperature (in degrees Celsius)



Realtime Clock (RTC)

(RTC Clock Modul DS3231 am I2C-Port (Adresse 0x68))
Modul import: import rtc

Function Action
rtc.set(yy, mm, dd, h, m, s, w)

sets year, month, day, hour, minute, second, weekday (usually 1..7, 1: sunday)
returns the temperature (in degrees Celsius)

rtc.set([yy, mm, dd, h, m, s, w])

same with list (or tuple)

rtc.get()

return a tuple (yy, mm, dd, h, m , s, w) (all ints)


7-segment display (4 digits withTM1637 driver)
Modul import:
from mb7seg import FourDigit
from mb7segmin import FourDigit, reduziertes Modul, falls Memory overflow, nur (*)

Function Action
(*) disp = FourDigit(clkPin = pin1, dioPin = pin2, lum = 4)

creates a display instance for a display connected to the given pins. Display luminosity 0..9

disp.erase()

clears the display
(*) disp.show(text, pos = 0)

shows the text starting at position 0 (far left digit). The text can contain more than 4 characters. text can also be an integer

disp.scroll(text) shows a scrolling text
disp.toRight() moves the text one position to the right
disp.toLeft()

moves the text one position to the left

disp.start()

sets the text to the starting position

disp.setLuminosity(lum) sets the luminosity (0..9)
(*) disp.setColon(enable) activates/deactivates the colon


Modul bme280

(Temperature-, air humidity and air pressure sensor from Bosch at I2C po)
Modul import: from bme280 import BME280

bme = BME280()

creates a sensor instance
bme.temperature() returns the temperature (in degrees Celsius)
bme.humidity()

returns the humidity (in percent)

bme.pressure()

returns the air pressure (in hPa)

bme.altitude()

returns the altitude above sea level (using air pressure 1013.25 hPa at sea level)

bme.all()

returns temperature, air pressure, humidity and height above sea level simultaneously in a tuple

bme.set_qnh()

sets the air pressure at sea level (in hPa)



Modul tcs34725
(RGB Color Sensor am I2C-Port)
Modul import: from tcs34725 import ColorSensor

cs = ColorSensor()

creates a sensor instance

cs.getRGB()

returns a tuple with the 3 RGB values (each in the range 0...255)

cs.getLum()

returns the brightness in the range 0..65565

 

pModul touchbitp
(Remote Control Module "TouchBit")
Modul import: from touchbit import *

registerCallbacks(buttonPress = None, buttenRelease = None, buttonRepeat = None)

registers callback functions that are called at the corresponding event, if the pollButtons() function is run through

pollButtons()

must be called periodically so that the callbacks are active

onButtonEvent(btn, down) signature of callback
Beispiel:
def onButtonPressed(btn):
    print("Button", btn, "pressed")

def onButtonReleased(btn):
    print("Button", btn, "released")

def onButtonRepeated(btn):
    print("Button", btn, "repeated")

registerCallbacks(onButtonPressed, onButtonReleased, onButtonRepeated)     
while True:
    pollButtons()
    sleep(50)