Skip to content

Commit 8484691

Browse files
microbit-matt-hillsdonmicrobit-robertmicrobit-carlos
authored
v2.1 beta docs (#56)
Update corresponds to https://github.com/microbit-foundation/micropython-microbit-v2/releases/tag/v2.1.0-beta.3 so further minor changes are possible. Co-authored-by: Robert Knight <robert@microbit.org> Co-authored-by: Carlos Pereira Atencio <carlos@microbit.org>
1 parent b3ec22f commit 8484691

File tree

12 files changed

+374
-56
lines changed

12 files changed

+374
-56
lines changed

examples/en-only/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Temporary home for files that cannot be processed by the translated versions
2+
yet. After the translation sync they should be found better homes.

examples/en-only/power_one.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from microbit import *
2+
import power
3+
4+
5+
@run_every(s=20)
6+
def silly_face():
7+
display.show(Image.SILLY)
8+
sleep(500)
9+
10+
11+
while True:
12+
if button_a.is_pressed():
13+
display.scroll("Off")
14+
# In this mode the micro:bit can only wake up via the reset button
15+
power.off()
16+
# This line of code will never be executed, as waking up from this
17+
# mode starts the programme from the beginning
18+
display.show(Image.SURPRISED)
19+
elif button_b.is_pressed():
20+
display.scroll("Sleep")
21+
# Go into Deep Sleep with multiple wake up sources
22+
power.deep_sleep(
23+
wake_on=(pin0, pin1, button_a),
24+
ms=5 * 60 * 1000, # In 5 minutes it wakes up anyway
25+
run_every=False, # Blocks run_every from waking up the board
26+
)
27+
# When the micro:bit wakes up will it continue running from here
28+
display.show(Image.ASLEEP)
29+
sleep(1000)
30+
display.show(Image.HAPPY)
31+
sleep(200)

examples/en-only/power_two.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from microbit import *
2+
import power
3+
import log
4+
5+
# Log the temperature every 5 minutes
6+
@run_every(min=5)
7+
def log_temperature():
8+
log.add(temp=temperature())
9+
10+
11+
while True:
12+
# Display the temperature when button A is pressed
13+
if button_a.is_pressed():
14+
display.scroll(temperature())
15+
# To go sleep, wake up when button A is pressed, and ensure the
16+
# function scheduled with run_every still executes in the background
17+
power.deep_sleep(wake_on=button_a, run_every=True)

examples/en-only/sound_effects.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
from microbit import *
2+
3+
# Play the default Sound Effect
4+
audio.play(audio.SoundEffect())
5+
6+
# Create a new Sound Effect and immediately play it
7+
audio.play(
8+
audio.SoundEffect(
9+
freq_start=400,
10+
freq_end=2000,
11+
duration=500,
12+
vol_start=100,
13+
vol_end=255,
14+
waveform=audio.SoundEffect.WAVEFORM_TRIANGLE,
15+
fx=audio.SoundEffect.FX_VIBRATO,
16+
shape=audio.SoundEffect.SHAPE_LOG,
17+
)
18+
)
19+
20+
# Play a Sound Effect instance, modify an attribute, and play it again
21+
my_effect = audio.SoundEffect(
22+
freq_start=400,
23+
freq_end=2000,
24+
)
25+
audio.play(my_effect)
26+
my_effect.duration = 1000
27+
audio.play(my_effect)
28+
29+
# You can also create a new effect based on an existing one, and modify
30+
# any of its characteristics via arguments
31+
my_modified_effect = my_effect.copy()
32+
my_modified_effect.waveform = audio.SoundEffect.WAVEFORM_NOISE
33+
audio.play(my_modified_effect)
34+
35+
# Use sensor data to modify and play an existing Sound Effect instance
36+
my_effect.duration = 600
37+
while True:
38+
# int() might be temporarily needed: https://github.com/microbit-foundation/micropython-microbit-v2/issues/121
39+
my_effect.freq_start = int(
40+
scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 9999))
41+
)
42+
my_effect.freq_end = int(
43+
scale(accelerometer.get_y(), from_=(-2000, 2000), to=(0, 9999))
44+
)
45+
audio.play(my_effect)
46+
47+
if button_a.is_pressed():
48+
# Button A silences the micro:bit
49+
speaker.off()
50+
display.show(Image("09090:00000:00900:09990:00900"))
51+
sleep(500)
52+
elif button_b.is_pressed():
53+
# Button B re-enables the speaker & plays an effect while showing an image
54+
speaker.on()
55+
audio.play(audio.SoundEffect(), wait=False)
56+
display.show(Image.MUSIC_QUAVER)
57+
sleep(500)
58+
59+
sleep(150)

lang/en/typeshed/stdlib/audio.pyi

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,5 @@ from .microbit.audio import (
77
play as play,
88
stop as stop,
99
AudioFrame as AudioFrame,
10+
SoundEffect as SoundEffect,
1011
)

lang/en/typeshed/stdlib/log.pyi

Lines changed: 33 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -18,44 +18,46 @@ DAYS = 864000
1818
"""Days timestamp format."""
1919

2020
def set_labels(
21-
*args: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS
21+
*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS
2222
) -> None:
2323
"""Set up the log file header.
2424
25-
Example: ``log.set_labels('x', 'y', 'z', timestamp=log.MINUTES)``
25+
Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)``
2626
27-
Each call to this function with positional arguments will generate a new
28-
header entry into the log file.
27+
Ideally this function should be called a single time, before any data is
28+
logged, to configure the data table header once.
2929
30-
If the program starts and a log file already exists it will compare the
31-
labels set up by this function call to the last headers declared in the
32-
file. If the headers are different it will add a new header entry at the
33-
end of the file.
30+
If a log file already exists when the program starts, or if this function
31+
is called multiple times, it will check the labels already defined in the
32+
log file. If this function call contains any new labels not already
33+
present, it will generate a new header row with the additional columns.
3434
35-
:param *args: A positional argument for each log header.
36-
:param timestamp: The timestamp unit that will be automatically added as the first column in every row.
37-
Setting this argument to ``None`` disables the timestamp. Pass the ``log.MILLISECONDS``, ``log.SECONDS``, , ``log.MINUTES``, ``log.HOURS`` or ``log.DAYS`` values defined by this module. An invalid value will throw an exception.
35+
By default the first column contains a timestamp for each row. The time
36+
unit can be selected via the timestamp argument.
37+
38+
:param *labels: Any number of positional arguments, each corresponding to an entry in the log header.
39+
:param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``.
3840
"""
3941
...
4042

4143
@overload
4244
def add(
43-
log_data: Optional[dict[str, Union[str, int, float]]],
45+
data_dictionary: Optional[dict[str, Union[str, int, float]]],
4446
) -> None:
4547
"""Add a data row to the log by passing a dictionary of headers and values.
4648
4749
Example: ``log.add({ 'temp': temperature() })``
4850
4951
Each call to this function adds a row to the log.
5052
51-
Dictionary keys not already specified via the ``set_labels`` function,
52-
or by a previous call to this function, will trigger a new header
53-
entry to be added to the log with the extra label.
53+
New labels not previously specified via the set_labels function, or by a
54+
previous call to this function, will trigger a new header entry to be added
55+
to the log with the extra labels.
5456
55-
Labels previously specified and not present in this function call will be
56-
skipped with an empty value in the log row.
57+
Labels previously specified and not present in a call to this function will
58+
be skipped with an empty value in the log row.
5759
58-
:param log_data: The data to log as a dictionary with a key for each header.
60+
:param data_dictionary: The data to log as a dictionary with a key for each header.
5961
"""
6062
...
6163

@@ -67,12 +69,12 @@ def add(**kwargs: Union[str, int, float]) -> None:
6769
6870
Each call to this function adds a row to the log.
6971
70-
Keyword arguments not already specified via the ``set_labels`` function,
71-
or by a previous call to this function, will trigger a new header entry
72-
to be added to the log with the extra label.
72+
New labels not previously specified via the set_labels function, or by a
73+
previous call to this function, will trigger a new header entry to be added
74+
to the log with the extra labels.
7375
74-
Labels previously specified and not present in this function call will be
75-
skipped with an empty value in the log row.
76+
Labels previously specified and not present in a call to this function will
77+
be skipped with an empty value in the log row.
7678
"""
7779
...
7880

@@ -81,21 +83,22 @@ def delete(full=False):
8183
8284
Example: ``log.delete()``
8385
84-
To add the log headers the ``set_labels`` function has to be called again
85-
after this.
86+
To add the log headers again the ``set_labels`` function should to be called after this function.
87+
88+
There are two erase modes; “full” completely removes the data from the physical storage,
89+
and “fast” invalidates the data without removing it.
8690
87-
:param full: Selects a "full" erase format that removes the data from the flash storage.
88-
If set to ``False`` it uses a "fast" method, which invalidates the data instead of performing a slower full erase.
91+
:param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method.
8992
"""
9093
...
9194

9295
def set_mirroring(serial: bool):
93-
"""Mirrors the data logging activity to the serial output.
96+
"""Configure mirroring of the data logging activity to the serial output.
9497
9598
Example: ``log.set_mirroring(True)``
9699
97-
Mirroring is disabled by default.
100+
Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file.
98101
99-
:param serial: Pass ``True`` to mirror the data logging activity to the serial output, ``False`` to disable mirroring.
102+
:param serial: ``True`` enables mirroring data to the serial output.
100103
"""
101104
...

lang/en/typeshed/stdlib/microbit/__init__.pyi

Lines changed: 44 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
"""Pins, images, sounds, temperature and volume.
22
"""
33

4+
from typing import Any, Callable, List, Optional, Tuple, overload
5+
46
from _typeshed import ReadableBuffer
5-
from typing import Any, Callable, List, Optional, overload
67

8+
# V2 only
79
from . import accelerometer as accelerometer
10+
from . import audio as audio
811
from . import compass as compass
912
from . import display as display
1013
from . import i2c as i2c
@@ -13,9 +16,6 @@ from . import speaker as speaker
1316
from . import spi as spi
1417
from . import uart as uart
1518

16-
# V2 only
17-
from . import audio as audio
18-
1919
def run_every(
2020
callback: Optional[Callable[[], None]] = None,
2121
days: int = 0,
@@ -24,28 +24,36 @@ def run_every(
2424
s: int = 0,
2525
ms: int = 0,
2626
) -> Callable[[Callable[[], None]], Callable[[], None]]:
27-
"""Schedule a function to be called at a given interval **V2 only**.
27+
"""Schedule to run a function at the interval specified by the time arguments **V2 only**.
2828
2929
Example: ``run_every(my_logging, min=5)``
3030
31-
This function can be passed a callback::
32-
33-
run_every(your_function, h=1, min=20, s=30, ms=50)
31+
``run_every`` can be used in two ways:
3432
35-
or used as a decorator::
33+
As a Decorator - placed on top of the function to schedule. For example::
3634
3735
@run_every(h=1, min=20, s=30, ms=50)
38-
def your_function():
39-
pass
36+
def my_function():
37+
# Do something here
38+
39+
As a Function - passing the callback as a positional argument. For example::
40+
41+
def my_function():
42+
# Do something here
43+
run_every(my_function, s=30)
4044
41-
Arguments with different time units are additive.
45+
Each argument corresponds to a different time unit and they are additive.
46+
So ``run_every(min=1, s=30)`` schedules the callback every minute and a half.
4247
43-
:param callback: The callback to invoke. Omit when using as a decorator.
44-
:param days: The interval in days.
45-
:param h: The interval in hours.
46-
:param min: The interval in minutes.
47-
:param s: The interval in seconds.
48-
:param ms: The interval in milliseconds.
48+
When an exception is thrown inside the callback function it deschedules the
49+
function. To avoid this you can catch exceptions with ``try/except``.
50+
51+
:param callback: Function to call at the provided interval. Omit when using as a decorator.
52+
:param days: Sets the day mark for the scheduling.
53+
:param h: Sets the hour mark for the scheduling.
54+
:param min: Sets the minute mark for the scheduling.
55+
:param s: Sets the second mark for the scheduling.
56+
:param ms: Sets the millisecond mark for the scheduling.
4957
"""
5058

5159
def panic(n: int) -> None:
@@ -61,6 +69,21 @@ def panic(n: int) -> None:
6169
def reset() -> None:
6270
"""Restart the board."""
6371

72+
def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float:
73+
"""Converts a value from a range to another range.
74+
75+
Example: ``temp_fahrenheit = scale(30, from_=(0, 100), to=(32, 212))``
76+
77+
This can be useful to convert values between inputs and outputs, for example an accelerometer X value to a speaker volume.
78+
79+
Negative scaling is also supported, for example ``scale(25, from_=(0, 100), to=(0, -200))`` will return ``-50``.
80+
81+
:param value: A number to convert.
82+
:param from_: A tuple to define the range to convert from.
83+
:param to: A tuple to define the range to convert to.
84+
:return: The ``value`` converted to the ``to`` range.
85+
"""
86+
6487
def sleep(n: float) -> None:
6588
"""Wait for ``n`` milliseconds.
6689
@@ -521,6 +544,9 @@ class Image:
521544
SNAKE: Image
522545
"""Snake image."""
523546

547+
SCISSORS: Image
548+
"""Scissors image."""
549+
524550
ALL_CLOCKS: List[Image]
525551
"""A list containing all the CLOCK_ images in sequence."""
526552

lang/en/typeshed/stdlib/microbit/accelerometer.pyi

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,15 @@ def get_values() -> Tuple[int, int, int]:
3939
"""
4040
...
4141

42+
def get_strength() -> int:
43+
"""Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes.
44+
45+
Example: ``accelerometer.get_strength()``
46+
47+
:return: The combined acceleration strength of all the axes, in milli-g.
48+
"""
49+
...
50+
4251
def current_gesture() -> str:
4352
"""Get the name of the current gesture.
4453
@@ -96,3 +105,11 @@ def get_gestures() -> Tuple[str, ...]:
96105
:return: The history as a tuple, most recent last.
97106
"""
98107
...
108+
109+
def set_range(value: int) -> None:
110+
"""Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g.
111+
112+
Example: ``accelerometer.set_range(8)``
113+
114+
:param value: New range for the accelerometer, an integer in ``g``.
115+
"""

0 commit comments

Comments
 (0)