Introduction
This guide will help you read distance data in millimetres from your PiicoDev Distance Sensor and a Micro:bit.
To follow along, it's best to have:
We'll program with Thonny in this tutorial. If you haven't used Thonny before, check out our guide for Programming a Micro:bit with Thonny. If you prefer, you can program your Micro:bit using python.microbit.org instead (see our guide).
If you prefer not to use the Micro:bit adapter, there are other connection options in our PiicoDev Connection Guide.
Connect the PiicoDev sensor to your Micro:bit
Plug your Micro:bit into the PiicoDev adapter (buttons + LED matrix facing up), connect your distance sensor to the adapter via the PiicoDev cable and connect your Micro:bit to your computer with a USB lead.
If you're unfamiliar with connecting PiicoDev modules, read the PiicoDev Connection Guide before proceeding.
Download the PiicoDev Modules and Example Code
Download the following files and save them to your working directory (Right Click > "Save Link As")
- PiicoDev_Unified.py - The PiicoDev Unified Libraries: Drives I2C communications for PiicoDev modules
- PiicoDev_VL53L1X.py - The device driver.
- main.py - an example script for this PiicoDev Sensor
It will be best to keep this file wherever you like to keep your coding projects eg. Documents > PiicoDev
Example Code
Open Thonny, connect to your micro:bit and upload the three files from the previous step.
Press Ctrl+D to restart your micro:bit and run the main script - distance data should begin streaming up the shell
Above: Distance data (in millimetres) streams up the shell. The plot to the right shows historic data as I move my hand back and forth over the sensor.
Try moving your hand in front of the sensor and watch how the data changes.
Remix - Musical Instrument
Now that we can measure distance, we can use that as the input for a fun musical instrument. The following code measures distance and, depending on the distance, select a different musical note to play on the Micro:bit's speaker - give it a try! Replace the code in main.py with the following code. We'll cover how it works in the video.
from microbit import button_a import music from PiicoDev_VL53L1X import PiicoDev_VL53L1X from PiicoDev_Unified import sleep_ms distSensor = PiicoDev_VL53L1X() notes = ["C4","D4","E4","F4","G4","A5","B5","C5"] while True: if button_a.is_pressed(): dist = distSensor.read() # read the distance in millimetres noteIndex = min(round(dist / 75), 7) # convert distance to a note-number 0-7 print(str(dist) + " mm => note " + notes[noteIndex]) # convert the number to a string and print music.play(notes[noteIndex]) else: sleep_ms(500)
How nice! Now we can measure distance and use that data in creative ways - like making a fun musical instrument.
If you have any questions or uncertainty, start the discussion below. We're full-time makers and here to help!