Dit is de klasse die je kan gebruiken om met een micro:bit te verbinden.
Je kan hiermee:
- gegevens over de micro:bit uitlezen
- gegevens van de sensoren van de micro:bit uitlezen of je laten verwittigen van gegevens van sensoren
- componenten op de micro:bit aansturen, bvb de LEDs
Example:
with KaspersMicrobit.find_one_microbit() as microbit:
microbit.buttons.on_button_a(press=pressed, long_press=pressed_long, up=released)
microbit.temperature.notify(lambda temp: print(f'{temp}°C'))
time.sleep(25)
microbit = KaspersMicrobit.find_one_microbit()
try:
microbit.connect()
microbit.buttons.on_button_a(press=pressed, long_press=pressed_long, up=released)
microbit.temperature.notify(lambda temp: print(f'{temp}°C'))
time.sleep(25)
finally:
microbit.disconnect()
Attributes:
-
device_information
(DeviceInformationService
)
–
Om informatie te vragen over de maker van je micro:bit
-
generic_access
(GenericAccessService
)
–
Om informatie te vragen over je micro:bit
-
buttons
(ButtonService
)
–
Om je te laten verwittigen wanneer een van de twee knoppen van de micro:bit worden ingedrukt (of losgelaten)
-
temperature
(TemperatureService
)
–
Om de temperatuur van de omgeving van de micro:bit op te vragen (of je te laten verwittigen)
-
accelerometer
(AccelerometerService
)
–
Om je te laten verwittigen van versnelling (beweging, botsing,...) van de micro:bit
-
events
(EventService
)
–
Om je in te schrijven op het ontvangen van gebeurtenissen van verschillende componenten van de micro:bit
-
uart
(UartService
)
–
Om tekst te sturen naar of te ontvangen van de micro:bit
-
io_pin
(IOPinService
)
–
Bestuur, lees, configureer de I/O contacten (pins) op de micro:bit
-
led
(LedService
)
–
Bestuur de LEDs van de micro:bit
-
magnetometer
(MagnetometerService
)
–
Om de gegevens van de magnetometer uit te lezen, of je ervan te laten verwittigen. De magnetometer meet
het magnetisch veld in de omgeving van de micro:bit (bvb het magnetisch veld van de aarde)
Zie ook: https://makecode.microbit.org/reference/bluetooth
Zie ook: https://makecode.microbit.org/device
Source code in src/kaspersmicrobit/kaspersmicrobit.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210 | class KaspersMicrobit:
"""
This is the class you can use to connect to a micro:bit.
You can do this:
- read data about the micro:bit
- read data from the sensors of the micro:bit or be notified of data from sensors
- control components on the micro:bit, for example the LEDs
Example:
```python
with KaspersMicrobit.find_one_microbit() as microbit:
microbit.buttons.on_button_a(press=pressed, long_press=pressed_long, up=released)
microbit.temperature.notify(lambda temp: print(f'{temp}°C'))
time.sleep(25)
```
```python
microbit = KaspersMicrobit.find_one_microbit()
try:
microbit.connect()
microbit.buttons.on_button_a(press=pressed, long_press=pressed_long, up=released)
microbit.temperature.notify(lambda temp: print(f'{temp}°C'))
time.sleep(25)
finally:
microbit.disconnect()
```
Attributes:
device_information (DeviceInformationService):
To request information about the maker of your micro:bit
generic_access (GenericAccessService):
To request information about your micro:bit
buttons (ButtonService):
To notify you when one of the two buttons on the micro:bit is pressed (or released)
temperature (TemperatureService):
To request the temperature of the environment of the micro:bit (or to be notified)
accelerometer (AccelerometerService):
To notify you of acceleration (movement, collision,...) of the micro:bit
events (EventService):
To subscribe to receive events from various components of the micro:bit
uart (UartService):
To send or receive text to the micro:bit
io_pin (IOPinService):
Control, read, configure the I/O contacts (pins) on the micro:bit
led (LedService):
Control the LEDs of the micro:bit
magnetometer (MagnetometerService):
To read the data from the magnetometer, or to be notified. The magnetometer measures
the magnetic field in the vicinity of the micro:bit (e.g. the magnetic field of the earth)
See Also: https://makecode.microbit.org/reference/bluetooth
See Also: https://makecode.microbit.org/device
"""
def __init__(self, address_or_bluetoothdevice: Union[str, BluetoothDevice]):
"""
Create a KaspersMicrobit object with a given Bluetooth address.
Args:
address_or_bluetoothdevice: the bluetooth address of the micro:bit
"""
if isinstance(address_or_bluetoothdevice, BluetoothDevice):
self._device = address_or_bluetoothdevice
else:
self._device = BluetoothDevice(BleakClient(address_or_bluetoothdevice))
self.device_information = DeviceInformationService(self._device)
self.generic_access = GenericAccessService(self._device)
self.buttons = ButtonService(self._device)
self.temperature = TemperatureService(self._device)
self.accelerometer = AccelerometerService(self._device)
self.events = EventService(self._device)
self.uart = UartService(self._device)
self.io_pin = IOPinService(self._device)
self.led = LedService(self._device)
self.magnetometer = MagnetometerService(self._device)
def __enter__(self):
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.disconnect()
def connect(self) -> None:
"""
Connect to the micro:bit. This establishes a connection. Your micro:bit may not already have (another)
connection.
Troubleshooting:
First try turning the micro:bit off and on again.
If you are not using the "with"-block, but calling .connect() yourself, always make sure that in any case
you call .disconnect() when you don't need the connection anymore
(for instance when you exit your application)
- In case you are using "No pairing required":
Make sure the micro:bit is not paired to your computer, if it was, remove it from the paired bluetooth
devices
- In case you are using "Just works pairing":
Try to remove the micro:bit from the paired bluetooth devices and pairing it your computer again.
See Also: https://support.microbit.org/helpdesk/attachments/19075694226
"""
self._device.connect()
def disconnect(self) -> None:
"""
Disconnect the micro:bit.
You must be connected to this micro:bit to successfully invoke this method.
"""
self._device.disconnect()
def address(self) -> str:
"""
Returns the Bluetooth address of this micro:bit
Returns:
The address of the micro:bit
"""
return self._device.address()
@staticmethod
def find_microbits(timeout: int = 3, loop: BluetoothEventLoop = None) -> List['KaspersMicrobit']:
"""
Scans for Bluetooth devices. Returns a list of micro:bits found within the timeout
Args:
timeout: maximum scanning time (in seconds)
loop (BluetoothEventLoop): you can leave this empty, this determines which thread communicates with the micro:bit.
Returns:
A list of micro:bits found, this can also be empty if no micro:bits were found
"""
loop = loop if loop else ThreadEventLoop.single_thread()
devices = loop.run_async(BleakScanner.discover(timeout)).result()
name_filter = KaspersMicrobit._name_filter()
return [
KaspersMicrobit(BluetoothDevice(BleakClient(d), loop))
for d in devices
if name_filter(d.name)
]
@staticmethod
def find_one_microbit(microbit_name: str = None, timeout: int = 3, loop: BluetoothEventLoop = None) -> 'KaspersMicrobit':
"""
Scans for Bluetooth devices. Returns exactly 1 micro:bit if one is found. You can optionally
Specify a name to search for. If no name is given, and there are multiple micro:bits
active then a found micro:bit will be chosen at random and returned.
Warning:
Only when the micro:bit works with "No pairing required" will the micro:bit advertise a name. So only in
in case you use hex files with "No pairing required" it is useful to set the 'microbit_name' parameter.
This does not work with a micro:bit that is paired.
Args:
microbit_name: the name of the micro:bit. This is a name of 5 letters such as 'tupaz' or 'gatug' or something like that
This is optional.
timeout: maximum scanning time (in seconds)
loop (BluetoothEventLoop): you can leave this empty, this determines which thread communicates with the micro:bit.
Returns:
KaspersMicrobit: The micro:bit found
Raises:
KaspersMicrobitNotFound: if no micro:bit was found
"""
loop = loop if loop else ThreadEventLoop.single_thread()
def name_filter(d, ad):
return KaspersMicrobit._name_filter(microbit_name)(ad.local_name)
device = loop.run_async(BleakScanner.find_device_by_filter(filterfunc=name_filter, timeout=timeout)).result()
if device:
return KaspersMicrobit(BluetoothDevice(BleakClient(device), loop))
else:
raise KaspersMicrobitNotFound(microbit_name, loop.run_async(BleakScanner.discover(timeout)).result())
@staticmethod
def _name_filter(microbit_name: str = None):
return lambda \
device_name: device_name == f'BBC micro:bit [{microbit_name.strip()}]' \
if microbit_name \
else device_name and device_name.startswith('BBC micro:bit')
|
__init__
__init__(
address_or_bluetoothdevice: Union[str, BluetoothDevice]
)
Maak een KaspersMicrobit object met een gegeven bluetooth address.
Parameters:
-
address_or_bluetoothdevice
(Union[str, BluetoothDevice]
)
–
het bluetooth adres van de micro:bit
Source code in src/kaspersmicrobit/kaspersmicrobit.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100 | def __init__(self, address_or_bluetoothdevice: Union[str, BluetoothDevice]):
"""
Create a KaspersMicrobit object with a given Bluetooth address.
Args:
address_or_bluetoothdevice: the bluetooth address of the micro:bit
"""
if isinstance(address_or_bluetoothdevice, BluetoothDevice):
self._device = address_or_bluetoothdevice
else:
self._device = BluetoothDevice(BleakClient(address_or_bluetoothdevice))
self.device_information = DeviceInformationService(self._device)
self.generic_access = GenericAccessService(self._device)
self.buttons = ButtonService(self._device)
self.temperature = TemperatureService(self._device)
self.accelerometer = AccelerometerService(self._device)
self.events = EventService(self._device)
self.uart = UartService(self._device)
self.io_pin = IOPinService(self._device)
self.led = LedService(self._device)
self.magnetometer = MagnetometerService(self._device)
|
connect
Connecteer met de micro:bit. Dit brengt een verbinding tot stand. Je micro:bit mag nog geen (andere)
verbinding hebben.
Probleemoplossing
Probeer eerst de micro:bit uit en weer aan te zetten.
Als je het "with"-blok niet gebruikt, maar zelf .connect() aanroept, zorg er dan altijd voor dat
je .disconnect() oproept wanneer je de verbinding niet meer nodig hebt
(bijvoorbeeld wanneer je je programma beeindigd)
- Als je "No pairing required" gebruikt:
Zorg ervoor dat de micro:bit niet aan uw computer is gekoppeld. Als dit wel het geval is, verwijdert u deze uit de gekoppelde Bluetooth
apparaten
- Als je "Just works pairing" gebruikt:
Probeer de micro:bit van de gekoppelde Bluetooth-apparaten te verwijderen en deze opnieuw met uw computer te koppelen.
Zie ook: https://support.microbit.org/helpdesk/attachments/19075694226
Source code in src/kaspersmicrobit/kaspersmicrobit.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129 | def connect(self) -> None:
"""
Connect to the micro:bit. This establishes a connection. Your micro:bit may not already have (another)
connection.
Troubleshooting:
First try turning the micro:bit off and on again.
If you are not using the "with"-block, but calling .connect() yourself, always make sure that in any case
you call .disconnect() when you don't need the connection anymore
(for instance when you exit your application)
- In case you are using "No pairing required":
Make sure the micro:bit is not paired to your computer, if it was, remove it from the paired bluetooth
devices
- In case you are using "Just works pairing":
Try to remove the micro:bit from the paired bluetooth devices and pairing it your computer again.
See Also: https://support.microbit.org/helpdesk/attachments/19075694226
"""
self._device.connect()
|
disconnect
Verbreek de verbinding met de micro:bit.
Je moet verbonden zijn met deze micro:bit om deze methode succesvol te kunnen oproepen.
Source code in src/kaspersmicrobit/kaspersmicrobit.py
| def disconnect(self) -> None:
"""
Disconnect the micro:bit.
You must be connected to this micro:bit to successfully invoke this method.
"""
self._device.disconnect()
|
address
Geeft het Bluetooth adres van deze micro:bit
Returns:
-
str
–
Het adres van de micro:bit
Source code in src/kaspersmicrobit/kaspersmicrobit.py
138
139
140
141
142
143
144
145 | def address(self) -> str:
"""
Returns the Bluetooth address of this micro:bit
Returns:
The address of the micro:bit
"""
return self._device.address()
|
find_microbits
staticmethod
find_microbits(
timeout: int = 3, loop: BluetoothEventLoop = None
) -> List[KaspersMicrobit]
Scant naar bluetooth toestellen. Geeft een lijst van micro:bits die gevonden werd binnen de timeout
Parameters:
-
timeout
(int
, default:
3
)
–
hoe lang er maximaal gescand wordt (in seconden)
-
loop
(BluetoothEventLoop
, default:
None
)
–
dit mag je leeg laten, dit bepaalt welke thread de communicatie met de micro:bit
uitvoert.
Returns:
-
List[KaspersMicrobit]
–
Een lijst van gevonden micro:bits, deze kan ook leeg zijn, als er geen micro:bits gevonden werden
Source code in src/kaspersmicrobit/kaspersmicrobit.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168 | @staticmethod
def find_microbits(timeout: int = 3, loop: BluetoothEventLoop = None) -> List['KaspersMicrobit']:
"""
Scans for Bluetooth devices. Returns a list of micro:bits found within the timeout
Args:
timeout: maximum scanning time (in seconds)
loop (BluetoothEventLoop): you can leave this empty, this determines which thread communicates with the micro:bit.
Returns:
A list of micro:bits found, this can also be empty if no micro:bits were found
"""
loop = loop if loop else ThreadEventLoop.single_thread()
devices = loop.run_async(BleakScanner.discover(timeout)).result()
name_filter = KaspersMicrobit._name_filter()
return [
KaspersMicrobit(BluetoothDevice(BleakClient(d), loop))
for d in devices
if name_filter(d.name)
]
|
find_one_microbit
staticmethod
find_one_microbit(
microbit_name: str = None,
timeout: int = 3,
loop: BluetoothEventLoop = None,
) -> KaspersMicrobit
Scant naar bluetooth toestellen. Geeft exact 1 micro:bit terug als er een gevonden wordt. Je kan optioneel
een naam opgeven waarop er moet gezocht worden. Als er geen naam gegeven wordt, en er zijn meerdere micro:bits
actief dan wordt er willekeurig een micro:bit gevonden.
Warning
Enkel wanneer de micro:bit werkt met "No pairing required" adverteert de micro:bit een naam. Dus enkel in
het geval je hex bestanden gebruikt met "No pairing required" is het nuttig om de 'microbit_name' parameter
te gebruiken.
Bij een micro:bit die gepaird is werkt dit niet.
Parameters:
-
microbit_name
(str
, default:
None
)
–
de naam van de micro:bit. Dit is een naam van 5 letters zoals bvb 'tupaz' of 'gatug' ofzo
Dit is optioneel.
-
timeout
(int
, default:
3
)
–
hoe lang er maximaal gescand wordt (in seconden)
-
loop
(BluetoothEventLoop
, default:
None
)
–
dit mag je leeg laten, dit bepaalt welke thread de communicatie met de micro:bit
uitvoert.
Returns:
Raises:
Source code in src/kaspersmicrobit/kaspersmicrobit.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203 | @staticmethod
def find_one_microbit(microbit_name: str = None, timeout: int = 3, loop: BluetoothEventLoop = None) -> 'KaspersMicrobit':
"""
Scans for Bluetooth devices. Returns exactly 1 micro:bit if one is found. You can optionally
Specify a name to search for. If no name is given, and there are multiple micro:bits
active then a found micro:bit will be chosen at random and returned.
Warning:
Only when the micro:bit works with "No pairing required" will the micro:bit advertise a name. So only in
in case you use hex files with "No pairing required" it is useful to set the 'microbit_name' parameter.
This does not work with a micro:bit that is paired.
Args:
microbit_name: the name of the micro:bit. This is a name of 5 letters such as 'tupaz' or 'gatug' or something like that
This is optional.
timeout: maximum scanning time (in seconds)
loop (BluetoothEventLoop): you can leave this empty, this determines which thread communicates with the micro:bit.
Returns:
KaspersMicrobit: The micro:bit found
Raises:
KaspersMicrobitNotFound: if no micro:bit was found
"""
loop = loop if loop else ThreadEventLoop.single_thread()
def name_filter(d, ad):
return KaspersMicrobit._name_filter(microbit_name)(ad.local_name)
device = loop.run_async(BleakScanner.find_device_by_filter(filterfunc=name_filter, timeout=timeout)).result()
if device:
return KaspersMicrobit(BluetoothDevice(BleakClient(device), loop))
else:
raise KaspersMicrobitNotFound(microbit_name, loop.run_async(BleakScanner.discover(timeout)).result())
|