PiicoDev 3-Axis Accelerometer LIS3DH - Getting Started Guide

Updated 28 August 2022

This guide will help you get started with a PiicoDev 3-Axis Accelerometer. We'll walk through some examples to read acceleration, infer tilt angle (from gravity), and detect tapping and shaking. 

An accelerometer is a device that measures acceleration. They're used in Engineering - to measure vibration in cars, buildings, machines. Really high-end accelerometers are used in navigation, and most smartphones contain an accelerometer to keep the display upright when the screen is rotated. Now the effects of gravity on an object are indistinguishable from acceleration, which means an accelerometer at rest on the surface of the Earth will measure a total acceleration of about 9.8 m/s² (1 g) upwards, while an accelerometer in freefall will measure zero.

The PiicoDev accelerometer is a 3-axis device that measures acceleration separately in three orthogonal axes. This is useful because we can analyse these three acceleration components to determine the direction of acceleration; or tilt-angle for a stationary accelerometer.


Hardware and Connections

To follow along you'll need:

Plug your Pico into the expansion board. Make sure it is plugged in the correct orientation - Pin 0 on the expansion board should be to the left of the Pico's USB connector.

Connect your Accelerometer to the expansion board with a PiicoDev Cable.

To follow along you'll need:

Mount the Adapter onto your Pi's GPIO. Make sure it is plugged in the correct orientation - An arrow on the Adapter will point to the Pi's Ethernet connector (on a Pi 3 the Ethernet connector and USB ports are swapped.)

Connect your Accelerometer to the Adapter with a PiicoDev Cable.

 

To follow along you'll need:

Plug your micro:bit into the Adapter, making sure the buttons on the micro:bit are facing up.

Connect your Accelerometer to the Adapter with a PiicoDev Cable.


Setup Thonny

Select your dev board from the tabs above to get ready for programming with Thonny for the first time. 

If you have already programmed with PiicoDev modules before, there's probably no need to follow these steps again.

Let's get set up with scripting in Thonny for the Raspberry Pi Pico.

We'll install Thonny, configure for Pico and write our first script. To follow along you'll need:

Contents

 

Install Thonny

If you're working on a Raspberry Pi 4, you're in luck - Thonny comes pre-installed. For those on another operating system, download Thonny here and run the installer.

Once the installer finishes, run Thonny.

Set up Thonny

Hold the BOOTSEL button on your Pico, and connect your Pico to your computer via USB.

Go to Run > Select interpreter and choose MicroPython (Raspberry Pi Pico).

It's also a good idea to install or update firmware. This will update your Pico with the latest version of MicroPython, or install MicroPython if it wasn't already.

Select Interpreter

REPL interface (Shell)

We can immediately start executing code in the REPL - Enter this code in the shell tab: print("Hello, World!")

The command will be sent to your Pico, which will execute the command and display back the message.

We can also take control of the on-board LED by executing the following code:

from machine import Pin
led = Pin(25, Pin.OUT)
led.toggle()

This code will toggle the LED. If you keep executing led.toggle() the LED will keep changing state.

REPL Interface

LED On

Writing a Script

Create a new script with File > New and paste in the following code:

from machine import Pin
from time import sleep
led = Pin(25, Pin.OUT)
n = 0;
while True:
    led.toggle()
    print("13 x {} = {}".format(n, 13*n)) # print the thirteen-times table
    n = n + 1
    sleep(0.5)

Save the script - you will be prompted to save to your computer OR the pico. Select save to Pico and name the file main.py

Return to the REPL and press Ctrl+D (or use the Stop/Restart button) to restart your Pico. The LED should flash at a steady rate and the shell should begin printing multiples of thirteen.

Script Output

Installing a Package

Packages are reusable pieces of code that another programmer has written for a common task, such as interfacing with a specific piece of hardware. Thonny has support for installing micropython packages from the Python Package Index - aka 'PyPI' directly onto the Raspberry Pi Pico.

To install a package, ensure the Pico is plugged in and go to Tools > Manage Packages, which will show the Manage Packages dialog.

Enter the name of the package you would like to install into the search bar and click 'Search on PyPI'.

In the search results list, click the title of the package you would like to install. A title that's in bold simply indicates a direct search match on the text you entered in the search bar.

The Manage Packages dialog will show an overview of the package you have clicked. Click Install to install the package on your Pico.

You can confirm the package has been installed by checking the 'Raspberry Pi Pico' section of the File View in Thonny. The view should show a new folder named 'lib', and inside this folder will be one or more folders containing the metadata and source code of the library you just installed.

 

An example of installing the micropython-servo libraryAn example of installing the micropython-servo library
An example of installing the micropython-servo library

Conclusion

We've installed Thonny and uploaded scripts to our Raspberry Pi Pico - if you have any questions feel free to start the conversation below, or open a topic in our forums - we're full time makers and happy to help!

Good news! Thonny comes pre-installed with Raspberry Pi OS. However, to work with PiicoDev we need to enable I2C communications as follows:

  • Power on your Raspberry Pi.
  • Open the Preferences > Raspberry Pi Configuration, select the Interfaces tab
  • Ensure I2C is Enabled

You only need to do this step for your first PiicoDev project - from here on you probably won't have to repeat this step when using PiicoDev hardware.

Let's get set up with scripting in Thonny for the Micro:bit. We'll install Thonny, configure for Micro:bit, and write our first script.

All you'll need to follow along is a Micro:bit v2 GO kit

Contents

Install Thonny

Download Thonny here and run the installer.

Once the installer finishes, run Thonny.

Set up Thonny

Connect your Micro:bit V2 to your computer with the USB cable.

connect-microbit-to-computer-with-usb-cable

Open Thonny, and in the menu bar find Run > Select interpreter and choose MicroPython (BBC micro:bit)

It's also a good idea to install or update firmware. This will update your micro:bit with the latest version of MicroPython, or install MicroPython if it wasn't already.

select-microbit-interpreter-in-thonny

Make sure the Files pane and Plotter are visible by selecting them in View > Files, and View > Plotter.

REPL interface (Shell)

Click the red STOP button to restart the MicroPython on your micro:bit if necessary. The Shell tab should display a block of text that indicates MicroPython is running:

thonny-shell-restarted

We can immediately start executing code in the REPL - Enter this code in the shell tab: print("Hello, World!")

The command will be sent to your micro:bit, which will execute the command and display back the message - nice!

Next, we can also take control of the on-board speaker by executing the following code:

from microbit import *
import audio
audio.play(Sound.HAPPY)

This code will play a happy tone from the micro:bit's speaker! If you the LED. If you keep executing audio.play(Sound.HAPPY), the tone will repeat.

microbit-thonny-repl-play-audio

Writing a Script

The REPL is great for test-driving some new commands and performing short experiments - the real power is in scripting though.

Create a new script with File > New and paste in the following code:

from microbit import *
import audio

print("Hello!")

multiple = 1 # initialise the counter

while True:
    if button_a.was_pressed(): # get the next multiple of the thirteen
        result = multiple * 13 # Calculate the result
        print("13 times " + str(multiple) + " is " + str(result)) # print the multiplication
        multiple = multiple + 1 # increment the multiple
    
    if button_b.was_pressed(): # Say Hello
        display.show(Image.HAPPY)
        audio.play(Sound.HAPPY)
        display.clear()
        
    sleep(10) # a 10 millisecond delay

Save the script - you will be prompted to save to your computer OR the micro:bit. Select save to micro:bit and name the file main.py

Return to the REPL and press Ctrl+D to restart your micro:bit. If something went wrong, use the Stop/Restart button, then Ctrl+D. 

Now, when we press the A button, the Shell will print the next multiple of 13, or if we press the B-button, our micro:bit gives us a smile and a hello sound.

thonny-example-script-for-microbit

Notice the plot is also showing some lines, and they're colour-coded to numbers in the print statement! In my case:

  • The Blue line is the constant 13,
  • The Orange Line is the multiple variable that increases slowly, and
  • The Red line is the result variable, which increases really quickly.

Useful Tips

  • You can stop a running script by selecting the Shell window and pressing Ctrl+C. This is useful if we want to make changes to the file(s) stored on the micro:bit.
  • Reboot your micro:bit (or other MicroPython device) by selecting the Shell window and pressing Ctrl+D
  • If something goes wrong, you can always click the red STOP button in the menu bar

Uploading and Downloading Files

We've been working with a file stored directly on the micro:bit - if you'd like to keep a copy on your computer, right-click the main.py file and select the 'download' option. Similarly, you can always upload code to your micro:bit by right-clicking files on your computer and selecting the upload button.

download-script-from-microbit-to-computer

Conclusion

We've installed Thonny and uploaded our first script to our micro:bit. The script includes branches depending on which button is pressed and can generate audio tones and perform basic arithmetic. Now we can write scripts, move them between micro:bit and computer, or test code interactively using the REPL.

If you have any questions feel free to start the conversation below or open a topic in our forums - we're full-time makers and happy to help!


Download / Install PiicoDev Modules

To work with PiicoDev hardware, we need to download some drivers. The drivers provide all the functions to easily connect and communicate with PiicoDev hardware. Select your dev board from the options above.

We will need these files to easily drive the PiicoDev 3-Axis Accelerometer:

  • Save the following files to your preferred coding directory - In this tutorial, we save to My Documents > PiicoDev.
  • Upload the files to your Pico. This process was covered in the Setup Thonny section.

The PiicoDev Unified Library is responsible for communicating with PiicoDev hardware, and the device module contains functions for driving specific PiicoDev devices.

 

We will now install/upgrade the PiicoDev python module for Thonny. This module contains all the drivers to work with all current PiicoDev hardware. Even if you have already installed the PiicoDev modules before, it's still worth upgrading to the latest version if one is available.

First, run Thonny by clicking the:

  1. Pi Start Menu
  2. Programming
  3. Thonny IDE

We need to set up a virtual environment to install the PiicoDev module into. This only needs to be done once as Thonny will remember an environment you have already made. If you are unsure if you have already set one up, you can always create a new one by following these steps.

To set up a virtual environment, click on run  > configure interpreter, to open up the interpreter tab.

In this window, we can create a new virtual environment in the bottom right. A notification window will first pop up, just click OK.

In this window, we are going to create a new empty folder in our Home Directory which will be the location of our virtual environment. To do so follow these steps:

  1. Select the Home tab on the left-hand side of the window.
  2. Click the Create Folder button in the top right.
  3. Enter the name of the new folder. You can call it what you want, but we will call ours "myenv". Once you have written the name, click Create next to it.
  4. Click OK in the bottom left.

Thonny will then set up your virtual environment and when it has finished, it will return to the Interpreter tab. Click OK, and you will have successfully set up the environment.

Note: the Python Executable path now points to the environment we just created.

Remember, you only need to do this once as the next time you open Thonny it will use this environment.

Next, open the package manager. From within Thonny click Tools > Manage Packages

Enter "piicodev" and click "Search on PyPI"

Finally, Install PiicoDev. If you already have PiicoDev installed, there may be an Upgrade button instead, to upgrade to a newer version.

 

With the PiicoDev module installed we are now ready to begin programming with PiicoDev hardware.

We will need these files to easily drive the PiicoDev 3-Axis Accelerometer:

  • Save the following files to your preferred coding directory - In this tutorial, we save to My Documents > PiicoDev.
  • Upload the files to your micro:bit. This process was covered in the Setup Thonny section.

The PiicoDev Unified Library is responsible for communicating with PiicoDev hardware, and the device module contains functions for driving specific PiicoDev devices.


Example - Read Acceleration

We're ready to begin reading data! The following example reads acceleration data and prints it to the shell. Acceleration is read from each axis and displayed in m/s². 

"""
PiicoDev Accelerometer LIS3DH
Simple example to read acceleration data
"""

from PiicoDev_LIS3DH import PiicoDev_LIS3DH
from PiicoDev_Unified import sleep_ms # cross-platform compatible sleep function

motion = PiicoDev_LIS3DH() # Initialise the accelerometer
motion.range = 2 # Set the range to +-2g

while True:
    x, y, z = motion.acceleration
    x = round(x,2) # round data for a nicer-looking print()
    y = round(y,2)
    z = round(z,2)
    myString = "X: " + str(x) + ", Y: " + str(y) + ", Z: " + str(z) # build a string of data
    print(myString)

    sleep_ms(100)

 

Experiment with tilting the accelerometer and observe how the readings from each axis change: Laying the accelerometer flat on a level surface will point the z-axis directly up. Data on this axis ought to be pretty close to 9.8 m/s². Since the x- and y-axes are parallel to the floor, they are experiencing no inertial forces and ought to read pretty close to zero. Rotate the accelerometer so the y-axis points up and observe how the data/plot changes. This is the first transition labelled in the plot below.

 What happens when you shake the accelerometer? Can you excite a single axis at a time?


Example - Read Angle

In the last example we read raw accelerometer data from each axis. Did you know it's possible to infer a tilt-angle from the data? There's a bit of math happening behind the scenes, but briefly, you can combine data from two axes (eg. x and z) to read the tilt around the third (in this case, y). For this, we'll use the .angle property. The following example reads three axes of tilt and prints the rotation of the y axis (as per the Right-Hand Rule).

"""
PiicoDev Accelerometer LIS3DH
Simple example to infer tilt-angle from acceleration data
"""

from PiicoDev_LIS3DH import PiicoDev_LIS3DH
from PiicoDev_Unified import sleep_ms # cross-platform compatible sleep function

motion = PiicoDev_LIS3DH()

while True:
    x, y, z = motion.angle # Tilt could be measured with respect to three different axes
    print("Angle: {:.0f}°".format(y)) # Print the angle of rotation around the y-axis
    sleep_ms(50)
    

Imagine you had the accelerometer sitting flat on a desk, with the z-axis facing up. There is no way to accurately measure rotation about the z-axis, since the x- and y-axes are parallel to the floor and both are measuring about 0m/s². It only really makes sense to use the .angle property for an axis that is perpendicular to the direction of inertial forces (gravity).


Example - Detect Tapping

The .tapped property will allow you to detect single or double-taps.

To tap detection is configured with the .set_tap() function. The following example configures single-tap detection with a threshold of 40. The first argument is the tap-number (1 for single; 2 for double). Depending on your application, you may want to tune this threshold to be more sensitive (tapping far away from the sensor) or less sensitive (reject spurious tap events).

"""
PiicoDev Accelerometer LIS3DH
Simple example to configure single-tap detection.
"""
from PiicoDev_LIS3DH import PiicoDev_LIS3DH
from PiicoDev_Unified import sleep_ms # cross-platform compatible sleep function

motion = PiicoDev_LIS3DH()
motion.set_tap(1, threshold=40) # set up single-tap detection with a tap threshold of 40

while True:
    if motion.tapped:
        print(1)
    else:
        print(0)

    sleep_ms(200)

Double taps can be a little trickier to configure - we've tried to pre-tune double-tap detection to work well by default, so you should just be able to call .set_tap(2) to detect tapping directly onto the accelerometer. If you wish to delve deeper, other parameters you can modify when calling .set_tap() are:

  • threshold=40 (default). How strong a tap needs to be.
  • time_limit=10 (default). The maximum time a tap may be above the threshold.
  • latency=80 (default). The 'dead-time' between the taps.
  • window=255 (default). The maximum time window for a double-tap.

For more information, refer to the LIS3DH Application Note.


Example - Detect Shaking

While a tap is a short, sharp acceleration - a shake is a more sustained action. Detect shakes by calling the .shake() function.

"""
Shake-detection example
shake() can be called without any arguments, but has the following parameters should you need them:
    shake_threshold = 15 (default. Should not be less than 10)
    avg_count = 40 (default)
    total_delay = 100 (default)

"""
from PiicoDev_LIS3DH import PiicoDev_LIS3DH
from PiicoDev_Unified import sleep_ms

motion = PiicoDev_LIS3DH() # Initialise the accelerometer

while True:
    if motion.shake(threshold=15):
        print("shaken!")
    else:
        print("")
    # shake() is blocking, so can be used instead of sleep_ms() to delay a loop.

The .shake() function is tunable with the following parameters:

  • threshold=15 (default). How strong the shaking needs to be
  • avg_count=40 (default). How many samples to average
  • total_delay=100 (default). The total time during which to sample for shaking.

Configure Range and Data-Rate

It is possible to modify the measurement range and data rate of the PiicoDev 3-Axis Accelerometer. You may need to do this if your project is measuring large shocks or bumps.

Range: Defaults to ±2 g. Use the range argument to select ±4, ±8 or ±16 during initialisation.

Rate: Defaults to 400 Hz. Use the rate argument to select from 1, 10, 25, 50, 100, 200, or 400 Hz during initialisation. (rate=0 will shut down the accelerometer)

For example:

motion = PiicoDev_LIS3DH(range=4, rate=100) # set the range to 4g and rate to 100Hz during initialisation

You can also update these parameters at any time, as follows:

motion = PiicoDev_LIS3DH() # Initialise with defaults

motion.range = 8 # set the range to +-8g

motion.rate = 200 # set the data rate to 200Hz

Connecting Multiple Devices

The PiicoDev 3-Axis Accelerometer has two possible addresses - set by the Address SWitch labelled ASW. That means up to two Accelerometers can share a PiicoDev I2C bus, each with address;

  • 0x19 (ASW Off, default)
  • 0x18 (ASW On)

You don't have to remember these numbers though - Just initialise each device separately as follows using the asw argument to encode the state of the switch (0:Off, 1:On). If you prefer to be explicit, you can use the address argument instead which accepts the exact I2C address.

# Initialise two devices, A and B
accelerometer_A = PiicoDev_LIS3DH(asw=0) # initialise the first device with ASW: OFF
accelerometer_B = PiicoDev_LIS3DH(asw=1) # initialise the first device with ASW: ON

# Or be explicit about the I2C address, if you prefer
# accelerometer_A = PiicoDev_LIS3DH(address=0x19) # initialise the first device with ASW: OFF
# accelerometer_B = PiicoDev_LIS3DH(address=0x18) # initialise the first device with ASW: ON

# Now each device can be read independently
xA, yA, zA = accelerometer_A.acceleration
xB, yB, zB = accelerometer_B.acceleration

Conclusion

We can see that simple acceleration measurements can be expanded to provide great utility in a project. From measuring angles to detecting tapping or shaking, accelerometers are pretty versatile instruments.

From here you can make all sorts of useful projects, like a digital spirit level that can indicate whether a surface is level or not. Perhaps a tilt-controlled game, or a locked box that only opens when knocked on in the right pattern.

If you have some questions, or would like to share anything you create then open the discussion below!

Happy Making!

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.