# NeoTrellis M4 Noisy Grains of Sand

## Overview

![](https://cdn-learn.adafruit.com/assets/assets/000/071/003/medium800thumb/led_matrices_gos_simple_tilt.jpg?1549899752)

The 'grains of sand' code is a great way to demo any LED matrix with an accelerometer, and the NeoTrellis M4 can make this even more entrancing by adding tactile, tap, and sound interaction as well.

This guide will show you how to get this code up and running on the NeoTrellis M4. A walk through the code will show you how you can get started making your own styles of interactions.

WARNING: This demo can be addictive - do not loan your NeoTrellis M4 running this demo out to others without being prepared to point them to this article and/or buy/setup one for them yourself!

## Parts
### Adafruit NeoTrellis M4 with Enclosure and Buttons Kit Pack

[Adafruit NeoTrellis M4 with Enclosure and Buttons Kit Pack](https://www.adafruit.com/product/4020)
So you've got a cool/witty name for your band, a Soundcloud account,&nbsp;[a 3D-printed Daft Punk helmet](https://learn.adafruit.com/3d-printed-daft-punk-helmet-with-bluetooth)...&nbsp;so what could be missing from your road to stardom? The **NeoTrellis M4 Kit...**

Out of Stock
[Buy Now](https://www.adafruit.com/product/4020)
[Related Guides to the Product](https://learn.adafruit.com/products/4020/guides)
![Demo Video of Hands pressing buttons on lit up NeoTrellis M4.](https://cdn-shop.adafruit.com/product-videos/640x480/4020-00.jpg)

### USB cable - USB A to Micro-B

[USB cable - USB A to Micro-B](https://www.adafruit.com/product/592)
This here is your standard A to micro-B USB cable, for USB 1.1 or 2.0. Perfect for connecting a PC to your Metro, Feather, Raspberry Pi or other dev-board or microcontroller

Approximately 3 feet / 1 meter long

In Stock
[Buy Now](https://www.adafruit.com/product/592)
[Related Guides to the Product](https://learn.adafruit.com/products/592/guides)
![USB cable - USB A to Micro-B - 3 foot long](https://cdn-shop.adafruit.com/640x480/592-01.jpg)

To listen to the sounds, you can choose to use headphones, speakers, or a connection to your own amplifier:

### USB Powered Speakers

[USB Powered Speakers](https://www.adafruit.com/product/1363)
Add some extra boom to your audio project with these powered loudspeakers. We sampled half a dozen different models to find ones with a good frequency response, so you'll get quality audio output for music playback. Simply connect the standard 3.5mm stereo plug into your Raspberry Pi model...

In Stock
[Buy Now](https://www.adafruit.com/product/1363)
[Related Guides to the Product](https://learn.adafruit.com/products/1363/guides)
![Two square-ish USB Powered Speakers](https://cdn-shop.adafruit.com/640x480/1363-07.jpg)

### 3.5mm Male/Male Stereo Cable

[3.5mm Male/Male Stereo Cable](https://www.adafruit.com/product/2698)
Seamlessly transmit high-quality stereo audio with this&nbsp; **3.5mm Male/Male Stereo Cable.&nbsp;**

Ideal for "passing the AUX cord," or&nbsp;connecting audio devices&nbsp;such as&nbsp;smartphones, tablets, MP3 players, car stereos, portable speakers or any other...

In Stock
[Buy Now](https://www.adafruit.com/product/2698)
[Related Guides to the Product](https://learn.adafruit.com/products/2698/guides)
![Black audio cable with 3.5mm audio jacks wrapped like a bow tie.](https://cdn-shop.adafruit.com/640x480/2698-01.jpg)

# NeoTrellis M4 Noisy Grains of Sand

## Install CircuitPython

## Getting Started with CircuitPython

Are you new to using CircuitPython? No worries,&nbsp;[there is a full getting started guide here](https://learn.adafruit.com/welcome-to-circuitpython "Welcome to CircuitPython").

Additionally, Adafruit has made life even easier for you with this&nbsp;[getting started guide for the TrellisM4](https://learn.adafruit.com/adafruit-neotrellis-m4/circuitpython). If you need to install CircuitPython, go to that page and follow the steps.

The great news is that this isn't really any more complicated than copying files to a USB drive! Just make sure you put things in the right place!

## Install Libraries

Check out&nbsp;[the CircuitPython Libraries page of this guide](https://learn.adafruit.com/adafruit-neotrellis-m4/circuitpython-libraries)&nbsp;for a detailed explanation of how to load the library bundle on your board.

For this project, you will also need to install the following libraries according to the instructions above:

- **adafruit\_bus\_device** (folder)
- **adafruit\_fancyled** (folder)
- **adafruit\_adxl34x.mpy** (file)
- **adafruit\_matrixkeypad.mpy** (file)
- **adafruit\_trellism4.mpy** (file)
- **neopixel.mpy** (file)

This will let us take advantage of the features of the TrellisM4, they keypad, the accelerometer, and the blinky lights - all of which we'll need.

Place the libraries in the **/lib** folder of your **CIRCUITPY** drive that shows up when the NeoTrellis M4 is connected to your computer via USB. If the **lib** folder is not on your **CIRCUITPY** drive, create the folder and place the needed libraries inside it.

The contents of the **/lib** folder should look like this:

![](https://cdn-learn.adafruit.com/assets/assets/000/071/007/medium800/led_matrices_GoS_Libs.png?1549900818)

# NeoTrellis M4 Noisy Grains of Sand

## Code

## Install Noisy Grains of Sand code

The code for this project is available in the Adafruit Learning System Github&nbsp;[here](https://github.com/adafruit/Adafruit_Learning_System_Guides/tree/master/NeoTrellis_M4_Grains_of_Sand). In the code listing below, you can click **code.py** and save it to your computer.&nbsp;

Now that you have CircuitPython installed, you simply need to place the **code.py** &nbsp;file onto the NeoTrellis M4 by copying it into the mounted USB folder named **CIRCUITPY.**

Primary: Be sure you have your NeoTrellis plugged-in via a known good USB cable. A disk drive named **CIRCUITPY** should appear in your Finder or File Explorer (depending on your operating system). Copy the **code.py** file to the **CIRCUITPY** drive root directory. That will run the code on the NeoTrellis which had CircuitPython installed in the last step.

## Install Sound File

One of the great things that makes the NeoTrellis M4 different from other LED matrices is that it can play sounds! We should take advantage of that for this grains of sand demo.

I recommend this [water click sound](https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/NeoTrellis/NeoTrellis_M4_Grains_of_Sand/water-click.wav). This is derived from a [Creative Commons](https://creativecommons.org/publicdomain/zero/1.0/) licensed sound [available on FreeSound](https://freesound.org/people/Mafon2/sounds/371274/), and I have processed it to work well on the NeoTrellisM4 (PS - the author of this sound really likes this demo!)

Copy **water-click.wav** onto your **CIRCUITPY** drive in the main directory.

There are many other sound files available which could more humorous or suitable for your application. Please feel free to experiment!

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/NeoTrellis/NeoTrellis_M4_Grains_of_Sand/code.py

## Sanity Check
Assuming you've done everything correctly, your mounted USB folder on your NeoTrellis M4 **CIRCUITPY** drive should look something that what's on the left, with the&nbsp; **code.py** and **water-click.wav** file in place.

![led_matrices_GoS_Files.png](https://cdn-learn.adafruit.com/assets/assets/000/070/996/medium640/led_matrices_GoS_Files.png?1550020637)

If this is the case, you should be up and running - now go play!

# NeoTrellis M4 Noisy Grains of Sand

## Play!

The main thing the 'grains of sand' code does is act like...grains of sand! If you tilt the TrellisM4 in any direction, the motion is detected by the accelerometer and the sand grains 'flow' in the direction of tilt.

![](https://cdn-learn.adafruit.com/assets/assets/000/070/998/medium800thumb/led_matrices_gos_simple_tilt.jpg?1549827665)

A sharp 'tap' anywhere on the NeoTrellis will switch the color mode - there are three modes built in:

- Rapidly cycles through random colors (default)
- A gradient based on the pixel index
- Solid color that changes with a button press

![](https://cdn-learn.adafruit.com/assets/assets/000/070/999/medium800thumb/led_matrices_gos_tap_demo.jpg?1549827925)

In the solid color mode, pushing any button on the NeoTrellis will rapidly change the color randomly. You can hold down for a random color effect, or quickly press to change to a new random color.

![](https://cdn-learn.adafruit.com/assets/assets/000/071/000/medium800thumb/led_matrices_gos_button_push.jpg?1549828131)

## Don't forget the sound!

If you plug headphones into the jack on the NeoTrellis M4, or alternatively plug it into a set of powered speakers, the 'water drop' sound will play each time a sand grain moves.

# NeoTrellis M4 Noisy Grains of Sand

## Code Walkthrough

The code used here was a modification of&nbsp;[the CircuitPython Digital Sand code for the sino:bit](https://learn.adafruit.com/sino-bit-micropython/examples#digital-sand-7-5)&nbsp;by&nbsp;[Tony DiCola](https://learn.adafruit.com/users/tdicola), which was originally developed by [Dave Astels](https://learn.adafruit.com/users/dastels)&nbsp;[for the LSM303 FeatherWing](https://learn.adafruit.com/digital-sand-dotstar-circuitpython-edition/overview)&nbsp;as a CircuitPython port of the [LED Sand](https://learn.adafruit.com/animated-led-sand) code by [Phillip Burgess](https://learn.adafruit.com/users/pburgess).

For the specifics of how the sand grain code works, please refer to the guides above.

I will talk about the specific modifications needed to use this code on the NeoTrellis M4 and to take advantage of its features.

## Setting up for the NeoTrellis M4
```python
import time
import board
import audioio
import audiocore
import busio
import adafruit_trellism4
import math
import random
import adafruit_adxl34x

N_GRAINS = 8 # Number of grains of sand
WIDTH = 8 # Display width in pixels
HEIGHT = 4 # Display height in pixels
```

This bit of the code imports the libraries specifically needed for the NeoTrellis M4, and sets up dimensions of the matrix (8x4 pixels). One of the easiest things you can do to change the code is to modify the number of grains of sand in the demo by changing the `N_GRAINS` variable.

## Setting up the board and accelerometer
```auto
trellis = adafruit_trellism4.TrellisM4Express(rotation=0)
i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
sensor = adafruit_adxl34x.ADXL345(i2c)

sensor.enable_tap_detection(threshold=50)
```

This sets up the NeoTrellis M4 in the state we want, and sets up `sensor`&nbsp;to refer to the ADXL343 on the board.

We also let this sensor know to enable tap detection, since we'll use that to change color modes. This is one of the great features of this sensor, as there are a few additional modes of interaction beyond just reporting acceleration values.

## Audio File Setup
```python
f = open("water-click.wav", "rb")
wav = audiocore.WaveFile(f)
print("%d channels, %d bits per sample, %d Hz sample rate " %
(wav.channel_count, wav.bits_per_sample, wav.sample_rate)) 
audio = audioio.AudioOut(board.A1)
```

Here is the sound file and setup the audio output for the NeoTrellis M4

## Tap Detection to Change Color Mode
```auto
if sensor.events['tap']: color_mode += 1
if color_mode &gt; 2: color_mode = 0
```

This just watches for 'tap' events from the accelerometer and switches the color mode when one is detected. Who would have thought it would take just a few lines of code to set up a tap sensor on a device?

## Color Modes and Button Presses
```auto
if color_mode == 0: trellis.pixels[(i%8, i//8)] = wheel(random.randint(1, 254)) if occupied_bits[i] else (0, 0, 0)

if color_mode == 1: trellis.pixels[(i%8, i//8)] = wheel(i*2) if occupied_bits[i] else (0, 0, 0)

if color_mode == 2: trellis.pixels[(i%8, i//8)] = wheel(color) if occupied_bits[i] else (0, 0, 0)

pressed = set(trellis.pressed_keys)
for press in pressed - current_press:
if press:
print("Pressed:", press)
color = random.randint(1, 254)
print("Color:", color)
```

This sets up the three different color modes, which simply define each of the NeoTrellis M4's NeoPixels to a different color in slightly different ways.&nbsp;  
  
It also watches for pressed buttons to change the color of the solid color mode.

## Accelerometer Value Correction

I struggled the most to port the accelerometer calculation part of the code to the NeoTrellis M4. Ironically, that's because the accelerometer on the NeoTrellis M4 is&nbsp;_easier to use!&nbsp;_

Instead of the raw accelerometer values that this code expects to see, the ADXL343 gives you very nice corrected values. I found the easiest route to port the code was to emulate uncorrected values.

` f_x = int(f_x * 9.80665 * 16704/1000) f_y = int(f_y * 9.80665 * 16704/1000) f_z = int(f_z * 9.80665 * 16704/1000)`

I also had to change the axes around to match the way I set the direction of the matrix up.&nbsp;

` ax2 = ax`  
`ax = -ay`  
`ay = ax2`

## Playing the Sound at the Right Time

I also struggled a bit with deciding when was the right time to play the sound. After some trial and error, I ended up simply doing it every time the 'grains of sand' matrix was modified, and after all the collision detection.

`if oldidx != newidx: audio.play(wav) # If there's an update, play the sound`

## ...and that's it!

When you have a feature-rich board, it can sometimes be a pain to explore and develop code for each of the features. However, one of the remarkable things this code shows is how easy this is to do on the NeoTrellis M4 using CircuitPython.

With just a few lines of code, you have:

- Set up an audio file and played it
- Enabled 'tap' detection on the accelerometer and used it
- Enabled button presses
- Made multi-mode light color changes

That's pretty remarkable - now it's your turn!

# NeoTrellis M4 Noisy Grains of Sand

## Next Steps

There are a lot of ways you can make this code your own - I encourage you to play around with it and add new features.

## Change the colors

There are lots of great [NeoPixel CircuitPython code examples](https://test-circuitpython.readthedocs.io/en/again-docs/docs/esp8266/tutorial/neopixel.html) out there. Modify the code to do different kinds of color cycling or animation!

It's simple to add new color modes to this code, just don't forget to change the following line to increase the number of modes available:

`if color_mode > 2: color_mode = 0`

## Add new interactions

The ADXL343 is capable of detecting more than just taps - you can just as simply detect double-taps and free-fall as well. Can you use these modes for more interactivity?

We've also just used the buttons in a simple way. Can you change the button presses to be more sophisticated, and perhaps change the color of the grains in cleverer ways?

## Add more sounds

I just used one sound - can you add more sounds for different types of grain interactions? Maybe a sound for grain collisions?

## Make it faster

This is not very optimized code, as has been noted before, this should perhaps be called 'grains of snow' rather than 'grains of sand' due to their sluggish movement. Can you make it run faster?

## Break it!

Most of all, I encourage you just to get into the code and break things. Failure is the greatest teacher, and many of us got started in electronics and coding by breaking things others have built and having to put them back together (sorry Mom and Dad). I'd love to see what you do with this code, and please drop me a line if you do something with it, or simply just enjoy it!


## Featured Products

### Adafruit NeoTrellis M4 with Enclosure and Buttons Kit Pack

[Adafruit NeoTrellis M4 with Enclosure and Buttons Kit Pack](https://www.adafruit.com/product/4020)
So you've got a cool/witty name for your band, a Soundcloud account,&nbsp;[a 3D-printed Daft Punk helmet](https://learn.adafruit.com/3d-printed-daft-punk-helmet-with-bluetooth)...&nbsp;so what could be missing from your road to stardom? The **NeoTrellis M4 Kit...**

Out of Stock
[Buy Now](https://www.adafruit.com/product/4020)
[Related Guides to the Product](https://learn.adafruit.com/products/4020/guides)
### USB cable - USB A to Micro-B

[USB cable - USB A to Micro-B](https://www.adafruit.com/product/592)
This here is your standard A to micro-B USB cable, for USB 1.1 or 2.0. Perfect for connecting a PC to your Metro, Feather, Raspberry Pi or other dev-board or microcontroller

Approximately 3 feet / 1 meter long

In Stock
[Buy Now](https://www.adafruit.com/product/592)
[Related Guides to the Product](https://learn.adafruit.com/products/592/guides)
### Analog Potentiometer Volume Adjustable TRRS Headset

[Analog Potentiometer Volume Adjustable TRRS Headset](https://www.adafruit.com/product/3959)
Most modern headphone sets are purely digital - with three volume control buttons in-line with the cable. These headphones are interesting in that they have an _analog_ volume control potentiometer. Perfect for use with electronic projects that don't have volume control, or for...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/3959)
[Related Guides to the Product](https://learn.adafruit.com/products/3959/guides)
### USB Powered Speakers

[USB Powered Speakers](https://www.adafruit.com/product/1363)
Add some extra boom to your audio project with these powered loudspeakers. We sampled half a dozen different models to find ones with a good frequency response, so you'll get quality audio output for music playback. Simply connect the standard 3.5mm stereo plug into your Raspberry Pi model...

In Stock
[Buy Now](https://www.adafruit.com/product/1363)
[Related Guides to the Product](https://learn.adafruit.com/products/1363/guides)
### 3.5mm Male/Male Stereo Cable

[3.5mm Male/Male Stereo Cable](https://www.adafruit.com/product/2698)
Seamlessly transmit high-quality stereo audio with this&nbsp; **3.5mm Male/Male Stereo Cable.&nbsp;**

Ideal for "passing the AUX cord," or&nbsp;connecting audio devices&nbsp;such as&nbsp;smartphones, tablets, MP3 players, car stereos, portable speakers or any other...

In Stock
[Buy Now](https://www.adafruit.com/product/2698)
[Related Guides to the Product](https://learn.adafruit.com/products/2698/guides)

## Related Guides

- [ABC Soundboards with NeoTrellis](https://learn.adafruit.com/abc-soundboards-with-neotrellis.md)
- [Christmas Soundboard with NeoTrellis M4](https://learn.adafruit.com/xmas-sound-board.md)
- [Classic MIDI Synth Control with Trellis M4](https://learn.adafruit.com/classic-midi-synth-control-with-trellis-m4.md)
- [Adafruit NeoTrellis M4 Express](https://learn.adafruit.com/adafruit-neotrellis-m4.md)
- [Trellis M4 Expressive MIDI Controller](https://learn.adafruit.com/trellis-m4-midi-keypad-and-tilt-controller.md)
- [Mu Keyboard Shortcut Cheat Sheets](https://learn.adafruit.com/mu-keyboard-shortcut-cheat-sheets.md)
- [NeoTrellis M4 Bumper](https://learn.adafruit.com/neotrellis-m4-bumper.md)
- [Star Trek Soundboard with NeoTrellis](https://learn.adafruit.com/star-trek-sound-board-with-neotrellism4.md)
- [What is Web MIDI & BLE MIDI?](https://learn.adafruit.com/web-ble-midi.md)
- [iPad Pro Bumper](https://learn.adafruit.com/ipad-pro-bumper.md)
- [Trellis M4 Synth Design Tool](https://learn.adafruit.com/synthesizer-design-tool.md)
- [Program CircuitPython USB Devices with iPhone & iPad](https://learn.adafruit.com/use-circuitpython-devices-with-iphone-ipad.md)
- [NeoTrellis M4 Animated Dice Roller](https://learn.adafruit.com/neotrellis-dice.md)
- [NeoTrellis M4 Arpeggiator Synth](https://learn.adafruit.com/neotrellis-arpeggiator-synth.md)
- [Bringing Back THE VOICE of Speak & Spell](https://learn.adafruit.com/bringing-back-the-voice-of-speak-spell.md)
