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:
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
)
–
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
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]
)
Create a KaspersMicrobit object with a given Bluetooth address.
Parameters:
-
address_or_bluetoothdevice
(Union[str, BluetoothDevice]
)
–
the bluetooth address of the 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
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
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
Disconnect the micro:bit.
You must be connected to this micro:bit to successfully invoke this method.
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
Returns the Bluetooth address of this micro:bit
Returns:
-
str
–
The address of the 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]
Scans for Bluetooth devices. Returns a list of micro:bits found within the timeout
Parameters:
-
timeout
(int
, default:
3
)
–
maximum scanning time (in seconds)
-
loop
(BluetoothEventLoop
, default:
None
)
–
you can leave this empty, this determines which thread communicates with the micro:bit.
Returns:
-
List[KaspersMicrobit]
–
A list of micro:bits found, this can also be empty if no micro:bits were found
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
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.
Parameters:
-
microbit_name
(str
, default:
None
)
–
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
(int
, default:
3
)
–
maximum scanning time (in seconds)
-
loop
(BluetoothEventLoop
, default:
None
)
–
you can leave this empty, this determines which thread communicates with the micro:bit.
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())
|