NeoPixel

The NeoPixel class controls a NeoPixel strand. We have a blog post that takes a more in depth look at the class. Though the post is for the older API, the function names are almost identical save for the hold method being split into two separate functions and having an explicit stop rotation method.

Initializing a Strand

Before we can interact with a NeoPixel strand, we first need to initialize memory on the MetaWear board to store NeoPixel information. To initialize the strand, call the initializeStrand method. You will need to take into consideration these parameters:

  • Operating frequency (either 800 Hz or 400 Hz)
  • How many LEDs to use
  • What color ordering the strand requires (RGB, GRB, etc.)

When you are done with the strand, call the deinitializeStrand method to clear the internal state.

import com.mbientlab.metawear.module.NeoPixel;
import com.mbientlab.metawear.module.NeoPixel.*;

final byte STRAND= 0, GPIO_PIN= 0;
NeoPixel npModule= mwBoard.getModule(NeoPixel.class);

// Initialize 30 pixels on the first strand (stand 0), with an RGB color ordering,
// with slow strand speed, connected to GPIO pin 0
npModule.initializeStrand(STRAND,  ColorOrdering.MW_WS2811_RGB, StrandSpeed.SLOW, GPIO_PIN,
        (byte) 30);

// Deinitialize the state of strand 0
npModule.deinitializeStrand(STRAND);

Setting Colors

Setting pixel colors is done with the setPixel method. Any calls you make will be immediately seen on the strand unless you enable state holding by calling holdStrand.

// Enable hold to lock the strand state
npModule.holdStrand(STRAND);

// Set pixels 0 - 2 to red, green, and blue respectively
npModule.setPixel(strandId, (byte) 0, (byte) 255, (byte) 0, (byte) 0);
npModule.setPixel(strandId, (byte) 1, (byte) 0, (byte) 255, (byte) 0);
npModule.setPixel(strandId, (byte) 2, (byte) 0, (byte) 0, (byte) 255);

// Disable hold, which will now update the strand with any state changes
npModule.releaseHold(STRAND);

Pattern Rotation

When you have a color pattern on your strand, you can rotate the pattern towards or away from the board with the rotate method. You can have the pattern rotate a fixed number of times or indefinitely as well as control how frequently a rotation should occur. To stop an unlimited rotation, call stopRotation.

// Rotate pattern 16 times, moving away from the board with a period of 500ms
npModule.rotate(STRAND, RotationDirection.AWAY, (byte) 16, (short) 500);

// Rotate pattern indefinitely, moving towards the board with a period of 250ms
npModule.rotate(STRAND, RotationDirection.TOWARDS, (short) 250);

// Stop pattern rotation
npModule.stopRotation(STRAND);