-
-
Notifications
You must be signed in to change notification settings - Fork 436
/
Copy pathboard-examples.md
1531 lines (1173 loc) · 45.4 KB
/
board-examples.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: Examples by Board
description: Find examples that work only with specific boards, such as reading built-in sensors.
author: Karl Söderby
micropython_type: basics
featured: micropython
hero_image: "./hero-banner.png"
---
In this article, you will find examples that works only with specific boards. Each board also has a GPIO map that explains how each pin can be addressed.
## Nano RP2040 Connect

### GPIO Map
The pinout for the **Nano RP2040 Connect** and the **RP2040 microcontroller** varies greatly. For example, if we are to use `D2` according to the Arduino pinout, we would actually need to use **pin 25**.
```python
# Defining "D2" on the Arduino Nano RP2040 Connect
p0 = Pin(25, Pin.OUT)
```
Before you start using the board's pins, it might be a good idea to check out the table below to understand the relationship between Arduino's pinout and the RP2040's pinout.
| Arduino | RP2040 | Usage |
| ------- | ------ | ------------- |
| TX | GPIO0 | UART/TX |
| RX | GPIO1 | UART/RX |
| D2 | GPIO25 | GPIO |
| D3 | GPIO15 | GPIO |
| D4 | GPIO16 | GPIO |
| D5 | GPIO17 | GPIO |
| D6 | GPIO18 | GPIO |
| D7 | GPIO19 | GPIO |
| D8 | GPIO20 | GPIO |
| D9 | GPIO21 | GPIO |
| D10 | GPIO5 | GPIO |
| D11 | GPIO7 | SPI/COPI |
| D12 | GPIO4 | SPI/CIPO |
| D13 | GPIO6 | SPI/SCK |
| D14/A0 | GPIO26 | ADC/RP2040 |
| D15/A1 | GPIO27 | ADC/RP2040 |
| D16/A2 | GPIO28 | ADC/RP2040 |
| D17/A3 | GPIO29 | ADC/RP2040 |
| D18/A4 | GPIO12 | I2C |
| D19/A5 | GPIO13 | I2C |
| D20/A6 | GPIO36 | ADC/NINA-W102 |
| D21/A7 | GPIO35 | ADC/NINA-W102 |
### Sensors
#### IMU (LSM6DSOX)
Prints the accelerometer and gyroscope values in the Serial Monitor.
```python
import time
from lsm6dsox import LSM6DSOX
from machine import Pin, I2C
lsm = LSM6DSOX(I2C(0, scl=Pin(13), sda=Pin(12)))
while (True):
print('Accelerometer: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_accel()))
print('Gyroscope: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_gyro()))
print("")
time.sleep_ms(100)
```
### Microphone (MP34DT05)
Below example can be used with OpenMV's frame buffer window (top right corner).
```python
import image, audio, time
from ulab import numpy as np
from ulab import scipy as sp
CHANNELS = 1
FREQUENCY = 32000
N_SAMPLES = 32 if FREQUENCY == 16000 else 64
SCALE = 2
SIZE = (N_SAMPLES * SCALE) // CHANNELS
raw_buf = None
fb = image.Image(SIZE+(50*SCALE), SIZE, image.RGB565, copy_to_fb=True)
audio.init(channels=CHANNELS, frequency=FREQUENCY, gain_db=16)
def audio_callback(buf):
# NOTE: do Not call any function that allocates memory.
global raw_buf
if (raw_buf == None):
raw_buf = buf
# Start audio streaming
audio.start_streaming(audio_callback)
def draw_fft(img, fft_buf):
fft_buf = (fft_buf / max(fft_buf)) * SIZE
fft_buf = np.log10(fft_buf + 1) * 20
color = (0xFF, 0x0F, 0x00)
for i in range(0, len(fft_buf)):
img.draw_line(i*SCALE, SIZE, i*SCALE, SIZE-int(fft_buf[i]) * SCALE, color, SCALE)
def draw_audio_bar(img, level, offset):
blk_size = (SIZE//10)
color = (0xFF, 0x00, 0xF0)
blk_space = (blk_size//4)
for i in range(0, int(round(level/10))):
fb.draw_rectangle(SIZE+offset, SIZE - ((i+1)*blk_size) + blk_space, 20 * SCALE, blk_size - blk_space, color, 1, True)
while (True):
if (raw_buf != None):
pcm_buf = np.frombuffer(raw_buf, dtype=np.int16)
raw_buf = None
if CHANNELS == 1:
fft_buf = sp.signal.spectrogram(pcm_buf)
l_lvl = int((np.mean(abs(pcm_buf[1::2])) / 32768)*100)
else:
fft_buf = sp.signal.spectrogram(pcm_buf[0::2])
l_lvl = int((np.mean(abs(pcm_buf[1::2])) / 32768)*100)
r_lvl = int((np.mean(abs(pcm_buf[0::2])) / 32768)*100)
fb.clear()
draw_fft(fb, fft_buf)
draw_audio_bar(fb, l_lvl, 0)
draw_audio_bar(fb, l_lvl, 25*SCALE)
if CHANNELS == 2:
draw_audio_bar(fb, r_lvl, 25 * SCALE)
fb.flush()
# Stop streaming
audio.stop_streaming()
```
### Communication
#### I2C
Scans for devices connected to the I2C buses:
```python
import time
from machine import Pin, I2C
i2c_list = [None, None]
i2c_list[0] = I2C(0, scl=Pin(13), sda=Pin(12), freq=100_000)
i2c_list[1] = I2C(1, scl=Pin(7), sda=Pin(6), freq=100_000)
for bus in range(0, 2):
print("\nScanning bus %d..."%(bus))
for addr in i2c_list[bus].scan():
print("Found device at address %d:0x%x" %(bus, addr))
```
#### UART
To read data and write data through TX and RX pins, you can use `uart.write()` and `uart.read()`.
```python
from machine import UART, Pin
import time
uart = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))
while True:
uart.write('hello') # writes 5 bytes
val = uart.read(5) # reads up to 5 bytes
print(val) # prints data
time.sleep(1)
```
### Wireless
Below are examples on wireless connectivity, using the NINA-W102 module onboard the Nano RP2040 Connect.
***In order to use these examples, you may have to upgrade your firmware. You can find instructions on how to in [Upgrading Nano RP2040 Connect NINA firmware](/tutorials/nano-rp2040-connect/rp2040-upgrading-nina-firmware).***
#### Wi-Fi AP Mode
Turn your board into an access point:
```python
# Wi-Fi AP Mode Example
#
# This example shows how to use Wi-Fi in Access Point mode.
import network, socket, sys, time, gc
SSID ='My_Nano_RP2040_Connect' # Network SSID
KEY ='1234567890' # Network key (must be 10 chars)
HOST = '' # Use first available interface
PORT = 8080 # Arbitrary non-privileged port
# Init wlan module and connect to network
wlan = network.WLAN(network.AP_IF)
wlan.active(True)
wlan.config(essid=SSID, key=KEY, security=wlan.WEP, channel=2)
print("AP mode started. SSID: {} IP: {}".format(SSID, wlan.ifconfig()[0]))
def recvall(sock, n):
# Helper function to recv n bytes or return None if EOF is hit
data = bytearray()
while len(data) < n:
packet = sock.recv(n - len(data))
if not packet:
raise OSError("Timeout")
data.extend(packet)
return data
def start_streaming(server):
print ('Waiting for connections..')
client, addr = server.accept()
# set client socket timeout to 5s
client.settimeout(5.0)
print ('Connected to ' + addr[0] + ':' + str(addr[1]))
# FPS clock
clock = time.clock()
while (True):
try:
# Read data from client
data = recvall(client, 1024)
# Send it back
client.send(data)
except OSError as e:
print("start_streaming(): socket error: ", e)
client.close()
break
while (True):
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind and listen
server.bind([HOST, PORT])
server.listen(1)
# Set server socket to blocking
server.setblocking(True)
while (True):
start_streaming(server)
except OSError as e:
server.close()
print("Server socket error: ", e)
```
#### Wi-Fi® Scan
To scan available networks:
```python
# Scan Example
# This example shows how to scan for Wi-Fi networks.
import time, network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
print("Scanning...")
while (True):
scan_result = wlan.scan()
for ap in scan_result:
print("Channel:%d RSSI:%d Auth:%d BSSID:%s SSID:%s"%(ap))
print()
time.sleep_ms(1000)
```
#### HTTP Request
Making an HTTP request (in this case to google):
***Remember to enter your network name and password inside the SSID and KEY variables.***
```python
import network, socket
# AP info
SSID='' # Network SSID
KEY='' # Network key
PORT = 80
HOST = "www.google.com"
# Init wlan module and connect to network
print("Trying to connect. Note this may take a while...")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, KEY)
# We should have a valid IP now via DHCP
print("Wi-Fi Connected ", wlan.ifconfig())
# Get addr info via DNS
addr = socket.getaddrinfo(HOST, PORT)[0][4]
print(addr)
# Create a new socket and connect to addr
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(addr)
# Set timeout
client.settimeout(3.0)
# Send HTTP request and recv response
client.send("GET / HTTP/1.1\r\nHost: %s\r\n\r\n"%(HOST))
print(client.recv(1024))
# Close socket
client.close()
```
#### NTP (Network Time Protocol)
***Remember to enter your network name and password inside the SSID and KEY variables.***
Obtain accurate time and date from the Internet:
```python
# NTP Example
#
# This example shows how to get the current time using NTP
import network, usocket, ustruct, utime
# AP info
SSID='' # Network SSID
KEY='' # Network key
TIMESTAMP = 2208988800
# Init wlan module and connect to network
print("Trying to connect... (may take a while)...")
wlan = network.WLAN()
wlan.active(True)
wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK)
# We should have a valid IP now via DHCP
print(wlan.ifconfig())
# Create new socket
client = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
client.bind(("", 8080))
#client.settimeout(3.0)
# Get addr info via DNS
addr = usocket.getaddrinfo("pool.ntp.org", 123)[0][4]
# Send query
client.sendto('\x1b' + 47 * '\0', addr)
data, address = client.recvfrom(1024)
# Print time
t = ustruct.unpack(">IIIIIIIIIIII", data)[10] - TIMESTAMP
print ("Year:%d Month:%d Day:%d Time: %d:%d:%d" % (utime.localtime(t)[0:6]))
```
In the terminal, we should see it in this format:
```
Year:2021 Month:8 Day:10 Time: 7:56:30
```
#### Bluetooth® Low Energy
This example allows us to connect to our board via our phone, and control the built-in LED. We recommend using the **nRF Connect** applications.
- [nRF desktop](https://www.nordicsemi.com/Products/Development-tools/nrf-connect-for-desktop)
- [nRF mobile](https://www.nordicsemi.com/Products/Development-tools/nrf-connect-for-mobile)
***After loading the script below, your board should be listed as "Nano RP2040 Connect" in the list of available devices. You need to pair in order to control the built-in LED.***
```python
import bluetooth
import random
import struct
import time
from ble_advertising import advertising_payload
from machine import Pin
from micropython import const
LED_PIN = 6
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_FLAG_READ = const(0x0002)
_FLAG_WRITE = const(0x0008)
_FLAG_NOTIFY = const(0x0010)
_FLAG_INDICATE = const(0x0020)
_SERVICE_UUID = bluetooth.UUID(0x1523)
_LED_CHAR_UUID = (bluetooth.UUID(0x1525), _FLAG_WRITE)
_LED_SERVICE = (_SERVICE_UUID, (_LED_CHAR_UUID,),)
class BLETemperature:
def __init__(self, ble, name="NANO RP2040"):
self._ble = ble
self._ble.active(True)
self._ble.irq(self._irq)
((self._handle,),) = self._ble.gatts_register_services((_LED_SERVICE,))
self._connections = set()
self._payload = advertising_payload(name=name, services=[_SERVICE_UUID])
self._advertise()
def _irq(self, event, data):
# Track connections so we can send notifications.
if event == _IRQ_CENTRAL_CONNECT:
conn_handle, _, _ = data
self._connections.add(conn_handle)
elif event == _IRQ_CENTRAL_DISCONNECT:
conn_handle, _, _ = data
self._connections.remove(conn_handle)
# Start advertising again to allow a new connection.
self._advertise()
elif event == _IRQ_GATTS_WRITE:
Pin(LED_PIN, Pin.OUT).value(int(self._ble.gatts_read(data[-1])[0]))
def _advertise(self, interval_us=500000):
self._ble.gap_advertise(interval_us, adv_data=self._payload)
if __name__ == "__main__":
ble = bluetooth.BLE()
temp = BLETemperature(ble)
while True:
time.sleep_ms(1000)
```
## Nano 33 BLE

### GPIO Map
The pinout for the **Nano 33 BLE** and the **NRF52840 microcontroller** varies greatly. For example, if we are to use `D2` according to the Arduino pinout, we would actually need to use **pin 43**.
```python
# Defining "D2" on the Nano 33 BLE
p0 = Pin(43, Pin.OUT)
```
In the MicroPython port of the Nano 33 BLE board, the pinout is the same as the Nordic NRF52840 (the microcontroller). You will find a GPIO Map below that explains how to address the different pins.
| Arduino | nRF52840 |
| ------- | -------- |
| TX | 35 |
| RX | 42 |
| D2 | 43 |
| D3 | 44 |
| D4 | 47 |
| D5 | 45 |
| D6 | 46 |
| D7 | 23 |
| D8 | 21 |
| D9 | 27 |
| D10 | 34 |
| D11 | 33 |
| D12 | 40 |
| D13 | 13 |
| D14/A0 | 4 |
| D15/A1 | 5 |
| D16/A2 | 30 |
| D17/A3 | 29 |
| D18/A4 | 31 |
| D19/A5 | 2 |
| D20/A6 | 28 |
| D21/A7 | 3 |
### LED Control
There are 3 different LEDs that can be accessed on the Nano 33 BLE: **RGB, the built-in LED** and the **power LED**.
They can be accessed by importing the `LED` module, where the RGB and built-in LED can be accessed.
```python
from board import LED
led_red = LED(1) # red LED
led_green = LED(2) # green LED
led_blue = LED(3) # blue LED
led_builtin = LED(4) # classic built-in LED (also accessible through pin 13)
```
To access the **power LED** we need to import the `Pin` module.
```python
from machine import Pin
led_pwr = Pin(41, Pin.OUT)
```
#### RGB
Blink all RGB lights every 0.25 seconds.
```python
from board import LED
import time
led_red = LED(1)
led_green = LED(2)
led_blue = LED(3)
while (True):
# Turn on LEDs
led_red.on()
led_green.on()
led_blue.on()
# Wait 0.25 seconds
time.sleep_ms(250)
# Turn off LEDs
led_red.off()
led_green.off()
led_blue.off()
# Wait 0.25 seconds
time.sleep_ms(250)
```
#### Built-in LED
The classic blink example! Blink the built-in LED every 0.25 seconds.
```python
from board import LED
import time
led_builtin = LED(4)
while (True):
# Turn on LED
led_builtin.on()
# Wait 0.25 seconds
time.sleep_ms(250)
# Turn off LED
led_builtin.off()
# Wait 0.25 seconds
time.sleep_ms(250)
```
### Sensors
#### IMU (LSM9DS1)
Access the `accelerometer`, `magnetometer`, and `gyroscope` data from the LSM9DS1 IMU module.
```python
import time
import lsm9ds1
from machine import Pin, I2C
bus = I2C(1, scl=Pin(15), sda=Pin(14))
lsm = lsm9ds1.LSM9DS1(bus)
while (True):
#for g,a in lsm.iter_accel_gyro(): print(g,a) # using fifo
print('Accelerometer: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_accel()))
print('Magnetometer: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_magnet()))
print('Gyroscope: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_gyro()))
print("")
time.sleep_ms(500)
```
### Wireless
#### Bluetooth® Low Energy
This example allows us to connect to our board via our phone, and control the built-in LED. We recommend using the **nRF Connect** applications.
- [nRF desktop](https://www.nordicsemi.com/Products/Development-tools/nrf-connect-for-desktop)
- [nRF mobile](https://www.nordicsemi.com/Products/Development-tools/nrf-connect-for-mobile)
***After loading the script below, your board should be listed as "Nano 33 BLE" in the list of available devices. You need to pair in order to control the built-in LED.***
```python
# Use nRF Connect from App store, connect to the Nano and write 1/0 to control the LED.
import time
from board import LED
from ubluepy import Service, Characteristic, UUID, Peripheral, constants
def event_handler(id, handle, data):
global periph
global service
if id == constants.EVT_GAP_CONNECTED:
pass
elif id == constants.EVT_GAP_DISCONNECTED:
# restart advertisement
periph.advertise(device_name="Nano 33 BLE", services=[service])
elif id == constants.EVT_GATTS_WRITE:
LED(1).on() if int(data[0]) else LED(1).off()
# start off with LED(1) off
LED(1).off()
notif_enabled = False
uuid_service = UUID("0x1523")
uuid_led = UUID("0x1525")
service = Service(uuid_service)
char_led = Characteristic(uuid_led, props=Characteristic.PROP_WRITE)
service.addCharacteristic(char_led)
periph = Peripheral()
periph.addService(service)
periph.setConnectionHandler(event_handler)
periph.advertise(device_name="Nano 33 BLE", services=[service])
while (True):
time.sleep_ms(500)
```
## Nano 33 BLE Sense

### Pin Map
The pinout for the **Nano 33 BLE Sense** and the **NRF52840 microcontroller** varies greatly. For example, if we are to use `D2` according to the Arduino pinout, we would actually need to use **pin 43**.
```python
# Defining "D2" on the Nano 33 BLE Sense
p0 = Pin(43, Pin.OUT)
```
In the MicroPython port of the Nano 33 BLE Sense board, the pinout is the same as the Nordic NRF52840 (the microcontroller). You will find a pin map below this section that explains how to address the different pins.
| Arduino | nRF52840 |
| ------- | -------- |
| TX | 35 |
| RX | 42 |
| D2 | 43 |
| D3 | 44 |
| D4 | 47 |
| D5 | 45 |
| D6 | 46 |
| D7 | 23 |
| D8 | 21 |
| D9 | 27 |
| D10 | 34 |
| D11 | 33 |
| D12 | 40 |
| D13 | 13 |
| D14/A0 | 4 |
| D15/A1 | 5 |
| D16/A2 | 30 |
| D17/A3 | 29 |
| D18/A4 | 31 |
| D19/A5 | 2 |
| D20/A6 | 28 |
| D21/A7 | 3 |
### LED Control
There are 3 different LEDs that can be accessed on the Nano 33 BLE Sense: **RGB, the built-in LED** and the **power LED**.
They can be accessed by importing the `LED` module, where the RGB and built-in LED can be accessed.
```python
from board import LED
led_red = LED(1) # red LED
led_green = LED(2) # green LED
led_blue = LED(3) # blue LED
led_builtin = LED(4) # classic built-in LED (also accessible through pin 13)
```
To access the **power LED** we need to import the `Pin` module.
```python
from machine import Pin
led_pwr = Pin(41, Pin.OUT)
```
#### RGB
Blink all RGB lights every 0.25 seconds.
```python
from board import LED
import time
led_red = LED(1)
led_green = LED(2)
led_blue = LED(3)
while (True):
# Turn on LEDs
led_red.on()
led_green.on()
led_blue.on()
# Wait 0.25 seconds
time.sleep_ms(250)
# Turn off LEDs
led_red.off()
led_green.off()
led_blue.off()
# Wait 0.25 seconds
time.sleep_ms(250)
```
#### Built-in LED
The classic blink example! Blink the built-in LED every 0.25 seconds.
```python
from board import LED
import time
led_builtin = LED(4)
while (True):
# Turn on LED
led_builtin.on()
# Wait 0.25 seconds
time.sleep_ms(250)
# Turn off LED
led_builtin.off()
# Wait 0.25 seconds
time.sleep_ms(250)
```
### Sensors
There are several sensors onboard the Nano 33 BLE Sense. The scripts below can be used to access the data from each of them.
#### IMU (LSM9DS1)
Access the `accelerometer`, `magnetometer`, and `gyroscope` data from the LSM9DS1 IMU module.
```python
import time
import lsm9ds1
from machine import Pin, I2C
bus = I2C(1, scl=Pin(15), sda=Pin(14))
lsm = lsm9ds1.LSM9DS1(bus)
while (True):
#for g,a in lsm.iter_accel_gyro(): print(g,a) # using fifo
print('Accelerometer: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_accel()))
print('Magnetometer: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_magnet()))
print('Gyroscope: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_gyro()))
print("")
time.sleep_ms(500)
```
#### Temperature & Humidity (HTS221)
Access the `temperature` & `humidity` values from the HTS221 sensor.
```python
import time
import hts221
from machine import Pin, I2C
bus = I2C(1, scl=Pin(15), sda=Pin(14))
hts = hts221.HTS221(bus)
while (True):
rH = hts.humidity()
temp = hts.temperature()
print ("rH: %.2f%% T: %.2fC" %(rH, temp))
time.sleep_ms(100)
```
#### Pressure (LPS22)
Access the `pressure` values from the LPS22 sensor.
```python
import time
import lps22h
from machine import Pin, I2C
bus = I2C(1, scl=Pin(15), sda=Pin(14))
lps = lps22h.LPS22H(bus)
while (True):
pressure = lps.pressure()
temperature = lps.temperature()
print("Pressure: %.2f hPa Temperature: %.2f C"%(pressure, temperature))
time.sleep_ms(100)
```
#### Ambient Light (APDS9960)
Access the `Ambient Light` values from the APDS9960 sensor.
```python
from time import sleep_ms
from machine import Pin, I2C
from apds9960.const import *
from apds9960 import uAPDS9960 as APDS9960
bus = I2C(1, sda=Pin(13), scl=Pin(14))
apds = APDS9960(bus)
print("Light Sensor Test")
print("=================")
apds.enableLightSensor()
while True:
sleep_ms(250)
val = apds.readAmbientLight()
print("AmbientLight={}".format(val))
```
#### Proximity (APDS9960)
Access the `Proximity values` from the APDS9960 sensor.
```python
from time import sleep_ms
from machine import Pin, I2C
from apds9960.const import *
from apds9960 import uAPDS9960 as APDS9960
bus = I2C(1, sda=Pin(13), scl=Pin(14))
apds = APDS9960(bus)
apds.setProximityIntLowThreshold(50)
print("Proximity Sensor Test")
print("=====================")
apds.enableProximitySensor()
while True:
sleep_ms(250)
val = apds.readProximity()
print("proximity={}".format(val))
```
#### Microphone (MP34DT05)
Below example can be used with OpenMV's frame buffer window (top right corner).
```python
import image, audio, time
from ulab import numpy as np
from ulab import scipy as sp
CHANNELS = 1
SIZE = 256//(2*CHANNELS)
raw_buf = None
fb = image.Image(SIZE+50, SIZE, image.RGB565, copy_to_fb=True)
audio.init(channels=CHANNELS, frequency=16000, gain_db=80, highpass=0.9883)
def audio_callback(buf):
# NOTE: do Not call any function that allocates memory.
global raw_buf
if (raw_buf == None):
raw_buf = buf
# Start audio streaming
audio.start_streaming(audio_callback)
def draw_fft(img, fft_buf):
fft_buf = (fft_buf / max(fft_buf)) * SIZE
fft_buf = np.log10(fft_buf + 1) * 20
color = (0xFF, 0x0F, 0x00)
for i in range(0, SIZE):
img.draw_line(i, SIZE, i, SIZE-int(fft_buf[i]), color, 1)
def draw_audio_bar(img, level, offset):
blk_size = SIZE//10
color = (0xFF, 0x00, 0xF0)
blk_space = (blk_size//4)
for i in range(0, int(round(level/10))):
fb.draw_rectangle(SIZE+offset, SIZE - ((i+1)*blk_size) + blk_space, 20, blk_size - blk_space, color, 1, True)
while (True):
if (raw_buf != None):
pcm_buf = np.frombuffer(raw_buf, dtype=np.int16)
raw_buf = None
if CHANNELS == 1:
fft_buf = sp.signal.spectrogram(pcm_buf)
l_lvl = int((np.mean(abs(pcm_buf[1::2])) / 32768)*100)
else:
fft_buf = sp.signal.spectrogram(pcm_buf[0::2])
l_lvl = int((np.mean(abs(pcm_buf[1::2])) / 32768)*100)
r_lvl = int((np.mean(abs(pcm_buf[0::2])) / 32768)*100)
fb.clear()
draw_fft(fb, fft_buf)
draw_audio_bar(fb, l_lvl, 0)
if CHANNELS == 2:
draw_audio_bar(fb, r_lvl, 25)
fb.flush()
# Stop streaming
audio.stop_streaming()
```
### Wireless
#### Bluetooth® Low Energy
This example allows us to connect to our board via our phone, and control the built-in LED. We recommend using the **nRF Connect** applications.
- [nRF desktop](https://www.nordicsemi.com/Products/Development-tools/nrf-connect-for-desktop)
- [nRF mobile](https://www.nordicsemi.com/Products/Development-tools/nrf-connect-for-mobile)
***After loading the script below, your board should be listed as "Nano 33 BLE Sense" in the list of available devices. You need to pair in order to control the built-in LED.***
```python
# Use nRF Connect from App store, connect to the Nano and write 1/0 to control the LED.
import time
from board import LED
from ubluepy import Service, Characteristic, UUID, Peripheral, constants
def event_handler(id, handle, data):
global periph
global service
if id == constants.EVT_GAP_CONNECTED:
pass
elif id == constants.EVT_GAP_DISCONNECTED:
# restart advertisement
periph.advertise(device_name="Nano 33 BLE Sense", services=[service])
elif id == constants.EVT_GATTS_WRITE:
LED(1).on() if int(data[0]) else LED(1).off()
# start off with LED(1) off
LED(1).off()
notif_enabled = False
uuid_service = UUID("0x1523")
uuid_led = UUID("0x1525")
service = Service(uuid_service)
char_led = Characteristic(uuid_led, props=Characteristic.PROP_WRITE)
service.addCharacteristic(char_led)
periph = Peripheral()
periph.addService(service)
periph.setConnectionHandler(event_handler)
periph.advertise(device_name="Nano 33 BLE Sense", services=[service])
while (True):
time.sleep_ms(500)
```
## Portenta H7

***Note that the [Portenta H7 Lite](/hardware/portenta-h7-lite) and [Portenta H7 Lite Connected](/hardware/portenta-h7-lite-connected) boards are compatible with most examples listed here, as they are variations of the Portenta H7.***
### GPIO Map
Most of the pins are referred to via their port name or their function. Please refer to the list below to see which function corresponds to which port on the Portenta H7.
| Arduino | STM32H747 |
| ---------------- | --------- |
| PA0 | PA0 |
| PA1 | PA1 |
| PA2 | PA2 |
| PA3 | PA3 |
| PA4 | PA4 |
| PA5 | PA5 |
| PA6 | PA6 |
| PA7 | PA7 |
| PA8 | PA8 |
| PA9 | PA9 |
| PA10 | PA10 |
| PA11 | PA11 |
| PA12 | PA12 |
| PA13 | PA13 |