Quantcast
Channel: SparkFun Tutorials
Viewing all 1123 articles
Browse latest View live

APA102 Addressable LED Hookup Guide

$
0
0

APA102 Addressable LED Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t1001

Introduction

The APA102C addressable LEDs employ a 2-wire communication protocol consisting of a clock and data line. While this requires one more wire than standard WS2812 addressable LEDs, the advantage is that the communication with the LEDs have a faster data and refresh rates (great for persistence of vision (a.k.a. POV) projects). They are not as strict with timing compared to the WS2812's.

SMD LED - RGB APA102C-5050 (Pack of 10)

SMD LED - RGB APA102C-5050 (Pack of 10)

COM-14863
$3.95

LED Strips

LED strips can come in sealed and unsealed versions. The SparkFun catalog carries the APA102's in 1M bare and 5M bare strips.

LED RGB Strip - Addressable, 1m (APA102)

LED RGB Strip - Addressable, 1m (APA102)

COM-14015
$15.95
2
LED RGB Strip - Addressable, 5m (APA102)

LED RGB Strip - Addressable, 5m (APA102)

COM-14016
$89.95
2

Matrices, Rings, Sticks, Shields

Depending on the project, they can also be populated on PCBs as a matrix, ring, or stick. These can be useful for marquees or adding unique animations to your project! There are different sizes of APA102's.

SparkFun LuMini LED Matrix - 8x8 (64 x APA102-2020)

SparkFun LuMini LED Matrix - 8x8 (64 x APA102-2020)

COM-15047
$25.95
SparkFun LuMini LED Ring - 2 Inch (40 x APA102-2020)

SparkFun LuMini LED Ring - 2 Inch (40 x APA102-2020)

COM-14966
$15.95
SparkFun LuMini LED Ring - 3 Inch (60 x APA102-2020)

SparkFun LuMini LED Ring - 3 Inch (60 x APA102-2020)

COM-14965
$25.95
3
SparkFun LuMini LED Ring - 1 Inch (20 x APA102-2020)

SparkFun LuMini LED Ring - 1 Inch (20 x APA102-2020)

COM-14967
$9.95
SparkFun Lumenati 8-stick

SparkFun Lumenati 8-stick

COM-14359
$7.95
3
SparkFun Lumenati 8-pack

SparkFun Lumenati 8-pack

COM-14357
$7.95
SparkFun Lumenati 3x3

SparkFun Lumenati 3x3

COM-14360
$7.50
SparkFun Lumenati 4-pack

SparkFun Lumenati 4-pack

COM-14353
$4.95
Pimoroni Blinkt!

Pimoroni Blinkt!

DEV-14038
$5.95
2
SparkFun Lumenati 90R

SparkFun Lumenati 90R

COM-14358
$4.95
SparkFun Lumenati 90L

SparkFun Lumenati 90L

COM-14452
$4.95

Required Materials

To follow along with this tutorial, you will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

APA102-Based LED Board or Strip

Stating the obvious: you'll need a APA102-based board or strip. The more the merrier! In the example hookup, we'll be using a 1M LED strip, but the example should be adaptable to the other APA102-based products. Grab however many you think you'll need for your project, regardless of how many you have, it's not enough.

Microcontroller or Single Board Computer?

To get started, you're going to need a microcontroller or a single board computer. Something that can send the series of 1's and 0's used to control the LEDs. Our go-to is the classic Arduino Uno with the ATmega328P, but any Arduino board that is supported with the library should do. A Teensy, ESP8266, ESP32, or Raspberry Pi can work as well but for the scope of this tutorial, we will be using a 5V Arduino populated with an ATmega328P, the SparkFun RedBoard Qwiic.

Arduino Pro Mini 328 - 5V/16MHz

Arduino Pro Mini 328 - 5V/16MHz

DEV-11113
$9.95
130
SparkFun SAMD21 Mini Breakout

SparkFun SAMD21 Mini Breakout

DEV-13664
$20.95
15
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
4

Logic Level

The APA102C addressable LEDs operate natively with 5V logic, so it will save you trouble to choose a controller that can give you 0-5V, but it can be made to work with 3.3V logic with the use of a level translator. If you are using a 5V microcontroller, you will not need the following.

SparkFun Logic Level Converter - Bi-Directional

SparkFun Logic Level Converter - Bi-Directional

BOB-12009
$2.95
97
SparkFun Level Translator Breakout - PCA9306

SparkFun Level Translator Breakout - PCA9306

BOB-15439
$3.95

Power Supply

You will also need a 5V power supply to run your controller and new lights. Each APA102C can draw as much as 60mA when red, green and blue are all full-on, so you'll want to have something a little beefy. For testing purposes (assuming that you do not turn all the LEDs fully on), you can use a computer's USB port and cable. A wall adapter capable of 2.5A should be plenty for our demonstration if you are placing it in an installation. If you've got a bigger project in mind, check out the Mean Well 5V/20A supply.

Wall Adapter Power Supply - 5.1V DC 2.5A (USB Micro-B)

Wall Adapter Power Supply - 5.1V DC 2.5A (USB Micro-B)

TOL-13831
$7.95
16
Wall Adapter Power Supply - 5V DC 2A (Barrel Jack)

Wall Adapter Power Supply - 5V DC 2A (Barrel Jack)

TOL-12889
$5.95
16
Mean Well Switching Power Supply - 5VDC, 20A

Mean Well Switching Power Supply - 5VDC, 20A

TOL-14098
$25.95

Wires

You'll also need some way to connect the boards and an Arduino. If you are using a breakout board or pieces of the LED strip, you could use a combination of jumper wires (such as M/M or M/F) and breadboard (solderless or solderable). Or you could just go with a few pieces of hookup wire or 4-pin JST-SM pigtail connectors.

SparkFun Solder-able Breadboard

SparkFun Solder-able Breadboard

PRT-12070
$4.95
17
Jumper Wires Premium 6" M/F Pack of 10

Jumper Wires Premium 6" M/F Pack of 10

PRT-09140
$3.95
1
LED Strip Pigtail Connector (4-pin)

LED Strip Pigtail Connector (4-pin)

CAB-14576
$1.50
Breadboard - Translucent Self-Adhesive (Red)

Breadboard - Translucent Self-Adhesive (Red)

PRT-11317
$4.95
1

Tools

Lastly, you are going to need a few tools. A soldering iron, some solder, general soldering accessories, wire, and a wire stripper should do if you are modifying the LED strip or connecting to a breakout board.

Hook-Up Wire - Assortment (Stranded, 22 AWG)

Hook-Up Wire - Assortment (Stranded, 22 AWG)

PRT-11375
$16.95
18
Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

TOL-14456
$14.95
7
Solder Lead Free - 15-gram Tube

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2
Wire Strippers - 22-30AWG

Wire Strippers - 22-30AWG

TOL-14762
$12.95

Suggested Reading

We're tried to make this hookup guide as simple as possible, but you may be lacking some basic information that could help your understanding as we go forward. For more info, check out these tutorials.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

Installing an Arduino Library

How do I install a custom Arduino library? It's easy! This tutorial will go over how to install an Arduino library using the Arduino Library Manager. For libraries not linked with the Arduino IDE, we will also go over manually installing an Arduino library.

Binary

Binary is the numeral system of electronics and programming...so it must be important to learn. But, what is binary? How does it translate to other numeral systems like decimal?

How to Power a Project

A tutorial to help figure out the power requirements of your project.

Logic Levels

Learn the difference between 3.3V and 5V devices and logic levels.

APA102 Hardware Overview

The APA102-based LED is much more than meets the eye. It may look like a common 5050-sized (5x5mm) LED, but there's actually an integrated circuit embedded inside there too. If you look really hard, you can see the tiny black chip hidden in there, along with minuscule gold wires connecting the chip to the LED. Below is a close up of an APA102.

apa102

Pretty nifty view at the guts of the APA102.

Data Transmission Interface

The communication interface between a microcontroller and the APA102 is not as strict WS2812's timing since it uses a 2-wire communication protocol, which consists of a clock and data line. Basically a simplified SPI interface without a slave pin.

APA102 Data and Clock Transmission

APA102 Timing Diagram from the Datasheet

The data frame consists of a start frame, data field for the LEDs, and an end frame. The data field consists of a frame for each LED attached to the strand. Each LED frame starts with three 1's , 5 bits for brightness, 8 bits for blue, 8 bits for green, and 8 bits for red. The larger the value of a specific color is, the brighter it will be. If every color is set to 0, the LED will be off. If every color is set to max -- 255 -- the LED will be as bright and white as can be.

APA102 Data Frame

APA102 Data Frame from the Datasheet

With the added clock line, you can use it with both a real-time processor (i.e. an Arduino) and microprocessor (i.e. Raspberry Pi). You will just need to ensure that you are using a logic level converter for 3.3V systems and make sure there is APA102 support for your architecture.

Lumenati

The Lumenati are breakout boards for the APA102C's. Depending on the board, they can have castellated edges, pads, or through holes to connect. They can be assembled together for elaborate designs and shapes.

Castellated EdgesPadsPlated Through Holes
Castellated EdgesPads on BackPlated Through Holes

For more information, check out this other tutorial.

Lumenati Hookup Guide

October 12, 2017

Lumenati is our line of APA102c-based addressable LED boards. We'll show you how to bring the sparkle to your projects!

LuMini

The LuMini is a miniaturized version of the Lumenati LEDs. The LuMini uses the APA102-2020 size for tight pixel densities. While they have a higher resolution, the tradeoff is there is a limitation in how bright they can be turned on. Having a high brightness can result in damage to the LED and PCB due the ability to dissipate heat with the small package.

LuMini Ring - 2 Inch VersionLuMini Matrix
LuMini Ring - 2 Inch VersionLuMini Matrix

For more information, check out the following tutorials to get started.

LuMini Ring Hookup Guide

January 17, 2019

The LuMini Rings (APA102-2020) are the highest resolution LED rings available.

LuMini 8x8 Matrix Hookup Guide

January 24, 2019

The LuMini 8x8 Matrix (APA102-2020) are the highest resolution LED matrix available.

Addressable LED Strips

If you need an abundance of WS2812 LEDs in a slick, pre-assembled form factor these addressable LED strips might be for you.

1M APA102 Bare LED Strip

The APA102 addressable LED strips come in a few flavors, which vary by size and sealant. You can get them in either 1m or 5m lengths, or high density. For each length the strip, they can be either covered by a waterproof sealant or left bare.

Connecting to the Strips

Each end of the LED strip is terminated with a set of four colored wires: red, blue, green, and yellow. Two wires are for power, one wire for clock, and another wire transmits data either into or out of the strip:

Wire Color
Function
Notes for the APA102
RedVccAPA102 power supply. Should be a regulated supply between 5V and 5.5V.
BlueClockClock
GreenData In/OutSerial data in/out. Look at arrows and labels on strip to check which it is.
YellowGNDGround. 0V.

Each of the wire pigtails are terminated by a four-pin JST SM connector, which you can use to connect string strips together. Typically, the addressable LEDs use a polarized JST SM connector with the male housing receptacle with (female pin sockets) connected to the DI side as shown with the connector on the left side of the image. The female housing receptacle (with male pins) coming connected to the DO side as shown with the connector on the right side of the image.

four pin JST SM connector

For the first strip in a string, you can either connect to a mating connector, or cut and strip the wires, and connect them to your controlling device. To reuse the rest of the LED strip, check out the LED strip pigtail connector to easily connect the cut strips:

LED Strip Pigtail Connector (4-pin)

LED Strip Pigtail Connector (4-pin)

CAB-14576
$1.50

Hardware Hookup

The great thing about these LEDs is they're super easy to chain together. Plus just two pins from your microcontroller is required to control an entire strip of LEDs. In this example, we'll control one 1M LED strip, but you should be safe to increase that ten-fold or even more.

Solder/Wire Something

The first assembly step for each of these products is creating a reliable, electrical connection from the LED to your control board. For a secure connection, you'll need to solder pigtail wires to a protoboard/shield to connect if you decide to place them into a project with a lot of movement or strip if you cut them into strands. You can also strip and splice some hookup wire to connect the LED strips.

How to Solder: Through-Hole Soldering

September 19, 2013

This tutorial covers everything you need to know about through-hole soldering.

Working with Wire

February 8, 2013

How to strip, crimp, and work with wire.

Connecting to an Arduino

This hookup is fairly straightforward. You can power the breakout board(s) with USB power and the Arduino's 5V and GND pins. Then all you need is to send data and clock signal to the LED. Let's go with pin 11 and 13, respectively. We recommend using a hardware pins for your microcontroller for best performance. Simply connect four M/F jumper wires to the RedBoard Qwiic.

Arduino APA102 Hookup

Protect Your APA102's!

In addition to the hookup above, we recommend adding a capacitor as close as possible to your addressable LEDs like the WS2812's to help you get the most out of your APA102-based devices for long strips. Below is an example with an addressable LED strip and separate power supply via the barrel jack connector. Read below for more information on suggested values!

Arduino APA102 Hookup Using Long Strips with Capacitor

Add a Big Smoothing Capacitor

Before connecting the APA102 to a power source, connect a big capacitor from power to ground. A cap between 100µF and 1000µF should be good.

1000uF cap

This cap will help to smooth out your power supply. The current draw of a APA102 can vary wildly, and as current draw grows and shrinks it'll be up to your power source to compensate. The cap will act as a "power reservoir" to store energy in case the supply dips.

Try to place this cap as close to your APA102 as possible by placing it in parallel to the Vcc and GND pins.

Keep Wires Short!

Wires don't conduct perfectly. They'll inevitably induce some voltage loss, especially when they're really long. Try to keep wires between your power supply, Arduino, and APA102 as short as possible to minimize this loss.

Arduino Library Overview

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

For the scope of this tutorial, we'll be using the FastLED library. The library will help you control the APA102's and provides example code to get the most our of your project. You can obtain these libraries through the Arduino Library Manager by searching for FastLED. The library also supports other LED chipsets. The second option is to download the ZIP file below from its GitHub repository to manually install it.

Parameters

When using the FastLED library, certain parameters need to be adjusted at a minimum to be compatible with the chipset. Depending on the example, the DATA_PIN can be referred to as LED_PIN. You may need to define the CLOCK_PIN or it can also be referred to as CLK_PIN. We recommend using a dedicated hardware SPI for best performance. However, if you decide to use a different pin, the library can be reconfigured to bit bang the pins. The LED_TYPE would be defined as the APA102 chipset. There are 60 LEDs per LED strip so NUM_LEDs needs to be set to 60. The COLOR_ORDER is BGR.

Once these parameters are set, you will need to initialize the LED strip configuration using .addLEDs<>() in the setup() function. Depending on the brightness and complexity of the animation, there are several methods to adjust the quality and appearance of the project like the color temperature, dither mode, refresh rate, FPS, or color correction. Below are two methods of setting up the LED strip for the APA102 configuration that we'll be using in this tutorial.

language:c
FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, BGR>(leds, NUM_LEDS);
FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);

Microcontroller

The library is supported on a variety of Arduino compatible platforms. For a list of supported AVR or ARM microcontrollers, check out the list on the library's README.md.

Arduino Example

The FastLED library includes a few examples for a variety of addressable LED chipsets to get started. The following examples will demonstrate how to modify the example to use with the APA102 chipset. For more information, check out the FastLED Library's wiki.

FastLED Blink Modification

For simplicity, let's blink one LED from the APA102 LED strip using the FastLED's Blink.ino example by following the steps listed below. After installing the library, head to File>Examples>FastLED>Blink to open the example in Arduino.

  • First, adjust the number of LEDs (NUM_LEDs) in the strip to 60.
  • Change the DATA_PIN to pin 11.
  • Change CLOCK_PIN to 13.
  • In the setup(),
    • Comment out a line by adding // in front of FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);.
    • Uncomment out the LED arrangement for the APA102 chipset by removing the // before FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);.
  • Modify the color order by changing RGB to BGR.

Once the code is adjusted, select your board and COM port. Then upload the code to blink the first LED of the strand! After uploading, you should see the first LED blink with red.

Now that you have the LED blinking red, try copying and pasting the code in the loop() function two more times to see if you can blink a green and blue. This is useful to test if your APA102 is outputting the correct color before mixing the colors.

Or copy and paste the modified example in an Arduino sketch. Select the COM port and board, and hit the upload button.

language:c
#include <FastLED.h>

// How many leds in your strip?
#define NUM_LEDS 60

// For led chips like Neopixels, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
#define DATA_PIN 11
#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];

void setup() {
  // Uncomment/edit one of the following lines for your leds arrangement.
  // FastLED.addLeds<TM1803, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<TM1804, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<TM1809, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  // FastLED.addLeds<APA104, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<UCS1903, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<UCS1903B, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<GW6205, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<GW6205_400, DATA_PIN, RGB>(leds, NUM_LEDS);

  // FastLED.addLeds<WS2801, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<SM16716, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<LPD8806, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<P9813, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<APA102, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<DOTSTAR, RGB>(leds, NUM_LEDS);

  // FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<SM16716, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<LPD8806, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
  FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, BGR>(leds, NUM_LEDS);
  // FastLED.addLeds<DOTSTAR, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::Red;
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);

  // Turn the LED on, then pause
  leds[0] = CRGB::Green;
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);

  // Turn the LED on, then pause
  leds[0] = CRGB::Blue;
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

There's a variety of pre-defined colors in the FastLED library that you can use. Try looking at the keywords.txt to try out the different colors. Then try adjusting the array number to turn on different LEDs on the strip.

Color Palette Modification

There are a few demos with different animations in the library. Let's try looking at the color palette demo. The color palette cycles the LED strip with few different palettes. The first is a rainbow, rainbow stripes, purple and green stripes, random, white stripes, cloud-like colors, and red/white/blue stripes. There is an option to blend the LED animation for the palettes depending on your preference and project. Head to File>Examples>FastLED>ColorPalette to open the example in Arduino.

  • First, comment out a line by adding // in front of #define LED_PIN 5.
  • We'll define that pin by adding the following line #define DATA_PIN 11.
  • We'll add an additional pin for the clock by adding the following line #define CLK_PIN 13.
  • Adjust the number of LEDs (NUM_LEDS) to 60.
  • Change the LED_TYPE to pin APA102.
  • Modify the color order by changing GRB to BGR.
  • In the setup(),
    • Comment out a line by adding // in front of FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );.
    • Add the LED arrangement for the APA102 chipset by adding the following line FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);.

Or copy and paste the modified example in an Arduino sketch. Or copy and paste the modified example in an Arduino sketch. Select the COM port and board, and hit the upload button.

language:c
   #include <FastLED.h>

//#define LED_PIN     5 // redefined in the next line
#define DATA_PIN     11
#define CLK_PIN     13
#define NUM_LEDS    60
#define BRIGHTNESS  64
#define LED_TYPE    APA102
#define COLOR_ORDER BGR
CRGB leds[NUM_LEDS];

#define UPDATES_PER_SECOND 100

// This example shows several ways to set up and use 'palettes' of colors
// with FastLED.
//
// These compact palettes provide an easy way to re-colorize your
// animation on the fly, quickly, easily, and with low overhead.
//
// USING palettes is MUCH simpler in practice than in theory, so first just
// run this sketch, and watch the pretty lights as you then read through
// the code.  Although this sketch has eight (or more) different color schemes,
// the entire sketch compiles down to about 6.5K on AVR.
//
// FastLED provides a few pre-configured color palettes, and makes it
// extremely easy to make up your own color schemes with palettes.
//
// Some notes on the more abstract 'theory and practice' of
// FastLED compact palettes are at the bottom of this file.



CRGBPalette16 currentPalette;
TBlendType    currentBlending;

extern CRGBPalette16 myRedWhiteBluePalette;
extern const TProgmemPalette16 myRedWhiteBluePalette_p PROGMEM;


void setup() {
    delay( 3000 ); // power-up safety delay
    //FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
    FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
    FastLED.setBrightness(  BRIGHTNESS );

    currentPalette = RainbowColors_p;
    currentBlending = LINEARBLEND;
}


void loop()
{
    ChangePalettePeriodically();

    static uint8_t startIndex = 0;
    startIndex = startIndex + 1; /* motion speed */

    FillLEDsFromPaletteColors( startIndex);

    FastLED.show();
    FastLED.delay(1000 / UPDATES_PER_SECOND);
}

void FillLEDsFromPaletteColors( uint8_t colorIndex)
{
    uint8_t brightness = 255;

    for( int i = 0; i < NUM_LEDS; i++) {
        leds[i] = ColorFromPalette( currentPalette, colorIndex, brightness, currentBlending);
        colorIndex += 3;
    }
}


// There are several different palettes of colors demonstrated here.
//
// FastLED provides several 'preset' palettes: RainbowColors_p, RainbowStripeColors_p,
// OceanColors_p, CloudColors_p, LavaColors_p, ForestColors_p, and PartyColors_p.
//
// Additionally, you can manually define your own color palettes, or you can write
// code that creates color palettes on the fly.  All are shown here.

void ChangePalettePeriodically()
{
    uint8_t secondHand = (millis() / 1000) % 60;
    static uint8_t lastSecond = 99;

    if( lastSecond != secondHand) {
        lastSecond = secondHand;
        if( secondHand ==  0)  { currentPalette = RainbowColors_p;         currentBlending = LINEARBLEND; }
        if( secondHand == 10)  { currentPalette = RainbowStripeColors_p;   currentBlending = NOBLEND;  }
        if( secondHand == 15)  { currentPalette = RainbowStripeColors_p;   currentBlending = LINEARBLEND; }
        if( secondHand == 20)  { SetupPurpleAndGreenPalette();             currentBlending = LINEARBLEND; }
        if( secondHand == 25)  { SetupTotallyRandomPalette();              currentBlending = LINEARBLEND; }
        if( secondHand == 30)  { SetupBlackAndWhiteStripedPalette();       currentBlending = NOBLEND; }
        if( secondHand == 35)  { SetupBlackAndWhiteStripedPalette();       currentBlending = LINEARBLEND; }
        if( secondHand == 40)  { currentPalette = CloudColors_p;           currentBlending = LINEARBLEND; }
        if( secondHand == 45)  { currentPalette = PartyColors_p;           currentBlending = LINEARBLEND; }
        if( secondHand == 50)  { currentPalette = myRedWhiteBluePalette_p; currentBlending = NOBLEND;  }
        if( secondHand == 55)  { currentPalette = myRedWhiteBluePalette_p; currentBlending = LINEARBLEND; }
    }
}

// This function fills the palette with totally random colors.
void SetupTotallyRandomPalette()
{
    for( int i = 0; i < 16; i++) {
        currentPalette[i] = CHSV( random8(), 255, random8());
    }
}

// This function sets up a palette of black and white stripes,
// using code.  Since the palette is effectively an array of
// sixteen CRGB colors, the various fill_* functions can be used
// to set them up.
void SetupBlackAndWhiteStripedPalette()
{
    // 'black out' all 16 palette entries...
    fill_solid( currentPalette, 16, CRGB::Black);
    // and set every fourth one to white.
    currentPalette[0] = CRGB::White;
    currentPalette[4] = CRGB::White;
    currentPalette[8] = CRGB::White;
    currentPalette[12] = CRGB::White;

}

// This function sets up a palette of purple and green stripes.
void SetupPurpleAndGreenPalette()
{
    CRGB purple = CHSV( HUE_PURPLE, 255, 255);
    CRGB green  = CHSV( HUE_GREEN, 255, 255);
    CRGB black  = CRGB::Black;

    currentPalette = CRGBPalette16(
                                   green,  green,  black,  black,
                                   purple, purple, black,  black,
                                   green,  green,  black,  black,
                                   purple, purple, black,  black );
}


// This example shows how to set up a static color palette
// which is stored in PROGMEM (flash), which is almost always more
// plentiful than RAM.  A static PROGMEM palette like this
// takes up 64 bytes of flash.
const TProgmemPalette16 myRedWhiteBluePalette_p PROGMEM =
{
    CRGB::Red,
    CRGB::Gray, // 'white' is too bright compared to red and blue
    CRGB::Blue,
    CRGB::Black,

    CRGB::Red,
    CRGB::Gray,
    CRGB::Blue,
    CRGB::Black,

    CRGB::Red,
    CRGB::Red,
    CRGB::Gray,
    CRGB::Gray,
    CRGB::Blue,
    CRGB::Blue,
    CRGB::Black,
    CRGB::Black
};



// Additional notes on FastLED compact palettes:
//
// Normally, in computer graphics, the palette (or "color lookup table")
// has 256 entries, each containing a specific 24-bit RGB color.  You can then
// index into the color palette using a simple 8-bit (one byte) value.
// A 256-entry color palette takes up 768 bytes of RAM, which on Arduino
// is quite possibly "too many" bytes.
//
// FastLED does offer traditional 256-element palettes, for setups that
// can afford the 768-byte cost in RAM.
//
// However, FastLED also offers a compact alternative.  FastLED offers
// palettes that store 16 distinct entries, but can be accessed AS IF
// they actually have 256 entries; this is accomplished by interpolating
// between the 16 explicit entries to create fifteen intermediate palette
// entries between each pair.
//
// So for example, if you set the first two explicit entries of a compact 
// palette to Green (0,255,0) and Blue (0,0,255), and then retrieved 
// the first sixteen entries from the virtual palette (of 256), you'd get
// Green, followed by a smooth gradient from green-to-blue, and then Blue.

You should see the sequence of colors animating along the strip. There's a few more "preset" palettes defined in the library that you can use. Try looking at the colorpalettes.cpp for more and replacing ChangePalettePeriodically()'s currentPalette value to the preset of your choice. You can also manually define your own palette of your choice depending on your project based on the pre-define colors in the keywords.txt similar to the ones defined after the loop() function.

Demo Reel Modification

Another example that we will look at is the Demo Reel. Head to File>Examples>FastLED>DemoReel100 to open the example in Arduino.

  • First, adjust the DATA_PIN to pin 11.
  • Uncomment the CLK_PIN by removing the // and defining it as pin 13.
  • Change the LED_TYPE to pin APA102.
  • Modify the color order (COLOR_ORDER) by changing GRB to BGR.
  • Adjust the number of LEDs (NUM_LEDS) to 60.
  • In the setup(),
    • Comment out a line by adding // in front of FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);.
    • Add the LED arrangement for the APA102 chipset by removing the // in front of FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);.

Or copy and paste the modified example in an Arduino sketch. Select the COM port and board, and hit the upload button.

language:c
#include <FastLED.h>

FASTLED_USING_NAMESPACE

// FastLED "100-lines-of-code" demo reel, showing just a few 
// of the kinds of animation patterns you can quickly and easily 
// compose using FastLED.  
//
// This example also shows one easy way to define multiple 
// animations patterns and have them automatically rotate.
//
// -Mark Kriegsman, December 2014

#if defined(FASTLED_VERSION) && (FASTLED_VERSION < 3001000)
#warning "Requires FastLED 3.1 or later; check github for latest code."
#endif

#define DATA_PIN    11
#define CLK_PIN     13
#define LED_TYPE    APA102
#define COLOR_ORDER BGR
#define NUM_LEDS    60
CRGB leds[NUM_LEDS];

#define BRIGHTNESS          96
#define FRAMES_PER_SECOND  120

void setup() {
  delay(3000); // 3 second delay for recovery

  // tell FastLED about the LED strip configuration
  //FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
  FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);

  // set master brightness control
  FastLED.setBrightness(BRIGHTNESS);
}


// List of patterns to cycle through.  Each is defined as a separate function below.
typedef void (*SimplePatternList[])();
SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, sinelon, juggle, bpm };

uint8_t gCurrentPatternNumber = 0; // Index number of which pattern is current
uint8_t gHue = 0; // rotating "base color" used by many of the patterns

void loop()
{
  // Call the current pattern function once, updating the 'leds' array
  gPatterns[gCurrentPatternNumber]();

  // send the 'leds' array out to the actual LED strip
  FastLED.show();  
  // insert a delay to keep the framerate modest
  FastLED.delay(1000/FRAMES_PER_SECOND); 

  // do some periodic updates
  EVERY_N_MILLISECONDS( 20 ) { gHue++; } // slowly cycle the "base color" through the rainbow
  EVERY_N_SECONDS( 10 ) { nextPattern(); } // change patterns periodically
}

#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))

void nextPattern()
{
  // add one to the current pattern number, and wrap around at the end
  gCurrentPatternNumber = (gCurrentPatternNumber + 1) % ARRAY_SIZE( gPatterns);
}

void rainbow() 
{
  // FastLED's built-in rainbow generator
  fill_rainbow( leds, NUM_LEDS, gHue, 7);
}

void rainbowWithGlitter() 
{
  // built-in FastLED rainbow, plus some random sparkly glitter
  rainbow();
  addGlitter(80);
}

void addGlitter( fract8 chanceOfGlitter) 
{
  if( random8() < chanceOfGlitter) {
    leds[ random16(NUM_LEDS) ] += CRGB::White;
  }
}

void confetti() 
{
  // random colored speckles that blink in and fade smoothly
  fadeToBlackBy( leds, NUM_LEDS, 10);
  int pos = random16(NUM_LEDS);
  leds[pos] += CHSV( gHue + random8(64), 200, 255);
}

void sinelon()
{
  // a colored dot sweeping back and forth, with fading trails
  fadeToBlackBy( leds, NUM_LEDS, 20);
  int pos = beatsin16( 13, 0, NUM_LEDS-1 );
  leds[pos] += CHSV( gHue, 255, 192);
}

void bpm()
{
  // colored stripes pulsing at a defined Beats-Per-Minute (BPM)
  uint8_t BeatsPerMinute = 62;
  CRGBPalette16 palette = PartyColors_p;
  uint8_t beat = beatsin8( BeatsPerMinute, 64, 255);
  for( int i = 0; i < NUM_LEDS; i++) { //9948
    leds[i] = ColorFromPalette(palette, gHue+(i*2), beat-gHue+(i*10));
  }
}

void juggle() {
  // eight colored dots, weaving in and out of sync with each other
  fadeToBlackBy( leds, NUM_LEDS, 20);
  byte dothue = 0;
  for( int i = 0; i < 8; i++) {
    leds[beatsin16( i+7, 0, NUM_LEDS-1 )] |= CHSV(dothue, 200, 255);
    dothue += 32;
  }
}

The LEDs will begin animating based on the functions defined in the demo. Read through the example code to see how they were written or bask in the glow of the animations running along the strip.

More Examples!

Now that we have some experience using three examples, try modifying and testing out the other code included the FastLED library!

Or you can check out the Lumenati, LuMini ring, and LuMini matrix guides that use the FastLED library.

Lumenati Hookup Guide

Lumenati is our line of APA102c-based addressable LED boards. We'll show you how to bring the sparkle to your projects!

LuMini Ring Hookup Guide

The LuMini Rings (APA102-2020) are the highest resolution LED rings available.

LuMini 8x8 Matrix Hookup Guide

The LuMini 8x8 Matrix (APA102-2020) are the highest resolution LED matrix available.

FastLED Documentation and FAQ

The FastLED is a pretty big and complex library. There are quite a lot of features. Besides looking through the code's comments, check out some of FastLED's documentation and FAQ for more information.

Python Examples

If you are looking to control the LEDs in a different language, try checking out the following tutorials to control the APA's with Python. You can control them via a microcontroller using the LumiDrive or a single board computer using the Raspberry Pi. Check out the following tutorials for more information.

LumiDrive Hookup Guide

January 17, 2019

The LumiDrive LED Driver is SparkFun’s foray into all things Python on micro-controllers. With the SparkFun LumiDrive you will be able to control and personalize a whole strand of APA102s directly from the board itself.

Lumenati Hookup Guide

October 12, 2017

Lumenati is our line of APA102c-based addressable LED boards. We'll show you how to bring the sparkle to your projects!

Resources and Going Further

Accessories

Try writing some additional code and adding more features in order to change the brightness or mode with the APA102 using a potentiometer or button. Or try adding a sensor to trigger animations based on sound to react to the beat of a track!

Trimpot 10K Ohm with Knob

Trimpot 10K Ohm with Knob

COM-09806
$0.95
6
SparkFun Sound Detector (with Headers)

SparkFun Sound Detector (with Headers)

SEN-14262
$11.95
2
Multicolor Buttons - 4-pack

Multicolor Buttons - 4-pack

PRT-14460
$1.60
SparkFun Capacitive Touch Slider - CAP1203 (Qwiic)

SparkFun Capacitive Touch Slider - CAP1203 (Qwiic)

SEN-15344
$5.95

Depending on the design, there are some shields for the Teensy that breakout pins for the APA102. Just make sure to check the wiring to ensure that it matches the connection for the LED strips.

Teensy Prop Shield

Teensy Prop Shield

DEV-13995
$19.95
1
SmartLED Shield V4 for Teensy

SmartLED Shield V4 for Teensy

DEV-15046
$19.95
Teensy Prop Shield LC

Teensy Prop Shield LC

DEV-13996
$8.95

For more information about the APA102, check out the resources below:

Now that you've got the gist of the APA102's, how are you going to use it in a project? Need some inspiration? Check out these tutorials for ideas to diffuse or daisy chain longer strips:

Building Large LED Installations

Learn what it takes to build large LED installations from planning to power requirements to execution.

LED Cloud-Connected Cloud

Make an RGB colored cloud light! You can also control it from your phone, or hook up to the weather!

Mean Well LED Switching Power Supply Hookup Guide

In this tutorial, we will be connecting a Mean Well LED switching power supply to an addressable LED strip controlled by an Arduino.

SparkFun ESP32 DMX to LED Shield

Learn how to utilize your DMX to LED Shield in a variety of different ways.

Or check out some of these blog posts for ideas:


learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado


ATX Power Connector (4-Pin) Breakout Hookup Guide

$
0
0

ATX Power Connector (4-Pin) Breakout Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t967

Introduction

Do you need to power a project with 12V and 5V from one wall adapter? The ATX power connector breaks out the standard 4-pin computer peripheral port for your 12V and 5V devices!

SparkFun ATX Power Connector Breakout Board

SparkFun ATX Power Connector Breakout Board

BOB-15035
$1.95
SparkFun ATX Power Connector Breakout Kit - 12V/5V (4-pin)

SparkFun ATX Power Connector Breakout Kit - 12V/5V (4-pin)

KIT-15701
$14.95

Required Materials

To follow along with this tutorial, you will need the following materials that are included in the kit. The components can be ordered individually if you decide to solder header pins or wires directly to the board. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

SparkFun ATX Power Connector Breakout Kit - 12V/5V (4-pin)

SparkFun ATX Power Connector Breakout Kit - 12V/5V (4-pin)

KIT-15701
$14.95

Tools

You will need a soldering iron, solder, and general soldering accessories.

Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

TOL-14456
$14.95
7
Solder Lead Free - 15-gram Tube

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2
Pocket Screwdriver Set

Pocket Screwdriver Set

TOL-12891
$3.95
5

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

Connector Basics

Connectors are a major source of confusion for people just beginning electronics. The number of different options, terms, and names of connectors can make selecting one, or finding the one you need, daunting. This article will help you get a jump on the world of connectors.

What is a Circuit?

Every electrical project starts with a circuit. Don't know what a circuit is? We're here to help.

Electric Power

An overview of electric power, the rate of energy transfer. We'll talk definition of power, watts, equations, and power ratings. 1.21 gigawatts of tutorial fun!

Polarity

An introduction to polarity in electronic components. Discover what polarity is, which parts have it, and how to identify it.

12V/5V Power Supply Hookup Guide

In this tutorial, we will replace the 12V/5V (2A) power supply's molex connector with two male barrel jacks adapters.

Hardware Overview

ATX Connector Side

The board has the option of soldering a 4-pin right angle ATX power connector.

Right Angle 4-Pin Connector Highlighted on Breakout

Depending on your application, you may want to add a vertical connector. Have no fear! The PTH pads were adjusted so that a 4-pin vertical connector can be added. Just follow the dashed silkscreen that outlines the perimeter of the connector.

Vertical 4-Pin Connector Highlighted on Breakout

5mm Screw Terminals

On the output side of the breakout, there is a spot for two 2-pin 5mm screw terminals.

5mm Screw Terminal for Output

Breadboard Compatible Pins

There is also an option of adding vertical or SMD right angle header pins if you need to connect the breakout to a breadboard or jumper wires.

Straight or SMD Right Angle Headers

Board Dimensions

The board is 1.33in x 1.35in and includes four mounting holes to secure the board on a panel or enclosure.

Board Dimension

Hardware Assembly

You'll need to solder the connectors of your choice to the breakout. If you have not soldered before, check out our tutorial below for tips!

How to Solder: Through-Hole Soldering

September 19, 2013

This tutorial covers everything you need to know about through-hole soldering.

Soldering the Input Connector

You'll need to decide on an ATX connector to solder on the breakout board. The board is compatible with both right angle and vertical connectors. We'll be using the right angle connector since the board is available in SparkFun's catalog. When inserting the right angle connector, make sure to insert the support legs first before inserting the pins into the through hole pads.

Insert Support Leg into BreakoutSliding Pins into Breakout
Insert Support Leg into BreakoutSliding Pins into Breakout

Once you have chosen the ATX connector of your choice, solder each pin to the breakout.

Soldering Connector

Your board should look similar to the image to the left for the right angle connector. If you happen to have a vertical connector from a different distributor, your board should look similar to the image on the right.

Right Angle Connector SolderedVertical Connector Soldered
Right Angle Connector SolderedVertical Connector Soldered

Soldering the Output Connector

Depending on your application, you can solder screw terminals or header pins to the breakout. With the screw terminals you can easily secure fork connectors or wires. If you choose the screw terminal route, you may need to strip wires before tightening the screws down for each respective pin. Should you decide to solder straight header pins, you can insert the board into a breadboard or protoboard. There is also an option to solder right angle SMD headers to the board as well depending on your application. Below are a few configurations depending on the connector and header that you choose. Remember, the SparkFun catalog only has the right angle connector available.

Screw Terminal or Headers Soldered on Breakout for the Output

Power Supply Options

Below are options where you will encounter the 4-pin connector.

ATX Power Supply

ATX power supplies usually have a number of power connectors available to power components for a desktop computer. The connector of interest in the image below is the second connector from the right. This 4-pin power connector is intended to power 12V and 5V computer peripherals (such as disk drives). Depending on the manufacturer of the power supply, the quantity of each connector can vary. If you want to grab some juice for your project from this type of power supply, you'll need to connect the breakout board to this port.

ATX power supply with power connectors

Image Courtesy of User "Smial" on Wikipedia

12V/5V (2A) Power Supply

Certain wall adapters also take advantage of this standard 4-pin port like the 12V/5V (2A) power supply in the catalog. If your project requires either/both 12V and 5V for power you can also connect the breakout board to this power supply.

4-Pin ATX Connector and Wires Inserted to Breakout Board

Examples

Once you have chosen your ATX power supply, you're ready to give your project some life! You can use the board to help power your microcontroller and LEDs from either side depending on your application. Check out the following tutorials below for examples of using a 12V/5V power supply.

RGB Panel Hookup Guide

Make bright, colorful displays using the 32x16, 32x32, and 32x64 RGB LED matrix panels. This hookup guide shows how to hook up these panels and control them with an Arduino.

Touch Potentiometer Hookup Guide

Learn how to use the SparkFun Touch Potentiometer to control lighting, volume or other inputs in your daily life.

Large Digit Driver Hookup Guide

Getting started guide for the Large Digit display driver board. This tutorial explains how to solder the module (backpack) onto the back of the large 7-segment LED display and run example code from an Arduino.

Building a Safe Cracking Robot

How to crack an unknown safe in under an hour.

Resources and Going Further

For more information, check out the resources below:

Need more inspiration for your next project? Check out some of these related tutorials that uses the 12V/5V (2A) power supply.

How to Build a Remote Kill Switch

Learn how to build a wireless controller to kill power when things go... sentient.

12V/5V Power Supply Hookup Guide

In this tutorial, we will replace the 12V/5V (2A) power supply's molex connector with two male barrel jacks adapters.

Or check out some of these blog posts about power supplies.


learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Cryptographic Co-Processor ATECC508A (Qwiic) Hookup Guide

$
0
0

Cryptographic Co-Processor ATECC508A (Qwiic) Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t1003

Introduction

🔒 Note: Please follow through the hookup guide in its entirety before using this board. The chip cannot be re-configured after it is PERMANENTLY locked.

The SparkFun Cryptographic Co-processor Breakout ATECC508A (Qwiic) takes all the great features of the Microchip ATECC508A Cryptographic Authentication Device and adds two Qwiic ports for plug and play functionality. In this tutorial we will cover the fundamentals of cryptographic authentication and how to use the ATECC508A to add a very high level of security to your projects.

SparkFun Cryptographic Co-Processor Breakout - ATECC508A (Qwiic)

SparkFun Cryptographic Co-Processor Breakout - ATECC508A (Qwiic)

DEV-15573
$4.95

The ATECC508A is capable of many cryptographic processes. This tutorial focuses on Elliptic-curve cryptographic digital signatures (ECC) - using asymetric private/public keys. If those last few words are new to you, please read on! We will spend some time explaining in a bit.

🔒 Note:This chip is NOT capable of encrypting and decrypting data. It can however, perform quite a few cryptographic authentication processes such as secure private key creation, secure key storage and digital signature creation and verification.

At a very high level, the purpose of using this chip is to (1) verify that the message received actually came from the true sender and (2) verify that the data received was not tampered with. This technology is used in hyper-critical devices such as rocket launches, medical devices, two factor authentication keys (2FA), ink cartridges, garage door openers and car key FOBs.

Probably it's most important feature: this device can securely store a private ECC key. In fact, this private key will never be accessible - not even to you, the owner. It is created internally on the chip during configuration, and it can never be read from the chip (even if your de-capped the chip). Although you will never know it, you can still command the co-processor to use the secret private key to create a unique signature on some data. With this functionality, it can be used to securely authenticate a message in any kind of communication system. For example, between systems such as a node in an IoT system. Follow along, and you'll be creating 64 byte signatures (yes, bytes) and verifying them securely in no time!

Checkout this video for more details on this tutorial.

Required Materials

To follow along with this tutorial, you will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

Note: To follow this tutorial, an Artemis microcontroller board has to be used with this product due to the buffer size required for the I2C bus.

For more advanced users, other microcontrollers can be used, but the buffer size of Wire library and/or the syntax for the serial print statements will need to be modified. (*This is outside the scope of this tutorial.)

WISHLIST LINK

Suggested Reading

If you aren’t familiar with the following concepts, we recommend you read over these tutorials before continuing.

Serial Communication

Asynchronous serial communication concepts: packets, signal levels, baud rates, UARTs and more!

I2C

An introduction to I2C, one of the main embedded communications protocols in use today.

Artemis Development with Arduino

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!

Hookup Guide for the SparkFun RedBoard Artemis

Get started with the RedBoard Artemis - all the functionality of the SparkFun Artemis module wrapped in the familiar Uno footprint

Cryptographic Authentication

Cryptography is a large subject matter. There many different types of cryptographic processes, each with their own different purpose and type of math. In this tutorial, we are focusing on cryptographic authentication. On a very high level, this usually involves data, digital signatures and verification. First, we must understand what a digital signature is and how it is created. Second we must understand verification which includes the use of a private/public key pair. Let's jump into digital signatures!

Digital signatures

A digital signature is quite similar to a hand-written signature. After you write a letter, you add your signature at the bottom. Just like the hand-written signature, a digital signature is added to your data. When we say "added" we mean that it is included as a separate chunk of data. So when sending some data with a digital signature, you would send the data as one piece of data, and then you would also send the digital signature as a separate piece of data. So this is the first difference to understand: digital signatures are like hand-written signatures, except they don't live on the same piece of paper (they are a separate chunk of data).

Another big difference: to create a digital signature, you need a bit more than a pen. You actually need three things:

  1. Data: This is the data you want to sign. For this co-processor, we are going to sign 32 bytes of data. This is essentially your "letter without a signature".
  2. A Key: Is simply a unique chunk of data. The key lives on a protected part of the co-processors memory. It was created during configuration. We will never have access to it. The idea of a single digital key is pretty straight forward. It parallels the physical door key quite well. The chunk of data is unique, just like the grooves and cuts of a physical key are unique.
  3. An Algorithm: The complex math that we will offload to the co-processor. It is a particular type of cryptographic math called Elliptic Curve Cryptography (ECC). Using our data and key, this algorithm will output a digital signature.

One more thing: digital signatures will be different when you change your message. This is pretty different than the traditional idea of a signature. When we think of hand-written signatures, we think that the entire purpose is for it to be exactly the same every time. The author should be the only one who can hold the pen like so and make that unique signature. With digital signatures we need to think a bit differently. Remember that we are sending our message (and a key) into an algorithm. This will result in a new and different signature if the message or key changes. In most cases, a digital signature is always unique from all other previous digital signatures.

So that was easy enough, right? Good. Digital signatures aren't so scary now. But what would we want to do with one of these? Verify it.

Verification

Verification of a digital signature is quite similar verifying a hand-written signature. In both cases, we want to determine if the signature is authentic. With a hand-written signature, you might just use your eyes to see if it looks correct. With a digital signature we need to use a bit more than our eyes. We need the data, the signature, a key, and an algorithm (sound familiar?). Simple enough, right? Well this is where it starts to get slightly more complex. We need to understand one more concept: the idea of key pairs.

Up until this point, we have called the "key" simply a "key", but to be more accurate, this should be called the private key. And it is part of a key pair. When we configure the co-processor it actually creates a key pair which includes two keys: one private key and one public key. These two keys work together, and they allow us to sign and verify signatures. We use the private key to sign the data, and we use the public key to verify data. This is also known as an asymetric cryptographic process.

Now that we're talking private and public key pairs, let's clearly define what we need to create a digital signature, and what we need to verify a digital signature:

To create a digital signature we need:To verify a digital signature we need:
1. Data
2. Private Key
3. Algorithm
1. Data
2. Signature
3. Public Key
4. Algorithm
Algorithm output: a new digital signature Algorithm output: yes or no

From Alice to Bob

Although you can accomplish a few neat things using only one of these chips (signing data, verifying signatures, creating high-quality random numbers, etc.), the truly powerful communication security starts when you have two of them (we will refer to them as Alice and Bob).

Our Arduino library utilizes the old story of Alice, Bob and Eve. If you read up on cryptography, you will often come across these names. Alice and Bob are always trying to have a private conversation, but Eve keeps eavesdropping (and sometimes trying to impersonate Alice). So Alice and Bob start using cryptography to keep Eve out of the mix.

Side note: In a lot of traditional examples, Alice and Bob are encrypting and decrypting their messages. I want to highlight here again, that this chip utilizes a different cryptographic tool: authentication. With the ATECC508A, we can create and verify signatures. The message is still sent out in the open/public for Eve to clearly read. However, Eve will never have Alice's private key and could never create a valid signature (to authenticate the message). Therefore, Eve can never pretend to be Alice!

In our examples, Alice is sending a message to Bob. Alice can use her own co-processor to create a digital signature. She can then send her message and signature to Bob. Bob can then use his own separate co-processor to verify the message and signature.

Alice and Bob example
An example demonstrating the functionality of an asymmetric key pair (Alice and Bob).

If you are brand new to cryptography, take a minute to watch the above gif loop a couple times. It shows the basic steps necessary to have an authenticated message from Alice to Bob. The use of a private/public key pair can be a bit daunting at first sight, but after going through this tutorial, we hope it can become a piece of cake.

Hardware Overview

Power

There is a power status LED to help make sure that your Cryptographic Co-processor Breakout is getting power. You can power the board either through the polarizedQwiic connector system or the breakout pins (3.3V and GND) provided. This Qwiic system is meant to use 3.3V, be sure that you are NOT using another voltage when using the Qwiic system.

Power Connections
Power connections.

LED

The board includes a red power LED to indicate you have power plugged in properly. Note, there is a jumper on the back to disconnect this from the circuit. This is useful if you really want to conserve current consumption on your system.

Power LED
Power LED.

ATECC508A Cryptographic Co-Processor

The co-processor on this board is the Microchip ATECC508A. It's primary features include creating/storing ECC keys, creating digital signatures and verifying them. It is also capable of doing many other cryptographic processes includeing SHA-256 hash, Diffie-Hellman Key Exchange, and high quality random number generation. For more details on the ATECC508A cryptographic chip, check out the datasheet.

ATECC508A Cryptographic Chip
ATECC508A cryptographic IC.
CharacteristicDescription
Operating Voltage2.0V to 5.5V (Default on Qwiic System: 3.3V)
Current Draw Active: 3 to 16 mA
Idle: 800 µA
Sleep: 30 to 150 nA
Operating Temperature-40 to 85°C
EEPROM Storage Capacity: 10 Kb
Data Retention: >10 years
Write Endurance: 400,000 cycles
Configurable I2C Address (7-bit)0x60 (Default)

Connections

We've included two qwiic connectors for plug and play operation.

Qwiic Connectors
Qwiic connectors.

It also has the pins broken out to 0.1-inch PTH headers, if you'd like a more permanent (soldered) connection to the I2C lines.

Breakout Pins
Breakout pins.
Pin LabelPin FunctionInput/OutputNotes
3.3VPower SupplyInput3.3V on Qwiic system.
GNDGroundInputGround
SDAI2C Data SignalBi-directionalBi-directional data line.
SCLI2C Clock SignalInputMaster-controlled clock signal.

Jumpers

There are two jumpers on this board. The first, connects pull-up resistors to the I2C bus and the other connects the power to the PWR status LED.

Jumper Pads
LED and I2C jumper pads.
NameDescriptionUsage
I2CI2C Pull-Up ResistorsOpening these disables theI2C pull-up resistors used for I2C communication. If multiple I2C devices are being used, these pull-ups should be disabled on all but one device. If these pins (SDA/SCL) are being used for other purposes (UART, LEDs, GPIO), the pull-up resistors should usually be disabled.
LEDEnable/Disable LEDCut this jumper to disconnect the LED and save power!

Board Dimensions

For those interested, the basic board dimensions are shown below, all measurements are in inches and the grid spacing is 0.1". The SparkFun Cryptographic Co-processor PCB itself, measures (approximately) 1x1 inch. Additionially, we have provided a PDF of the dimensional drawing, if necessary.

Dimensions
Board dimensions in inches.

Hardware Hookup

Note: To follow this tutorial, an Artemis microcontroller board has to be used with this product due to the buffer size required for the I2C bus.

For more advanced users, other microcontrollers can be used, but the buffer size of Wire library and/or the syntax for the serial print statements will need to be modified. (*This is outside the scope of this tutorial.)

With the Qwiic connector system, assembling the hardware is fairly simple. For the examples below, all you need to do is connect your Cryptographic Co-Processor Breakout to a RedBoard Artemis with a Qwiic cable. Otherwise, you can use the I2C pins, if you don't have a Qwiic connector on your microcontroller board. Just be aware of your input voltage and any logic level shifting you may need to do. (*Don't forget to plug the Aretemis into a computer with a USB-C cable.)

Hardware Connection with Qwiic Cable
Hardware assembly between the RedBoard Artemis and a Cryptographic Co-Processor Breakout board.

Note, the setup shown here is used for the configuration example and the single-board examples (1,2,3 and 5). For the more advanced examples that involve Alice and Bob (Example 4 and Example 6), you will need to setup two Artemis boards - each with their own co-processor. Additional hardware hookup instructions are included at those sections.

Software Setup

Note: This tutorial assumes you are using the latest stable version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

Installing Arduino

If you haven't used the Arduino IDE before, head on over to our Installing the Arduino IDE tutorial to get set up:

Installing Arduino IDE

March 26, 2013

A step-by-step guide to installing and testing the Arduino software on Windows, Mac, and Linux.

Getting the Arduino Library

To make Configuration and start using your Cryptographic Co-processor, we have written an Arduino Library. It currently supports only the Artemis board family. This is because some of the commands to the Co-processor require a larger I2C buffer. You have two options to install this library:

  • Use the library manager or install in the Arduino IDE

    We recommend using the library manager to tool within the Arduino IDE (Sketch > Include Library > Manage Libraries...). In the Library Manager, search for Sparkfun_Cryptographic. For help installing the library, check out our How to Install an Arduino Library tutorial.

    Installing an Arduino Library

    January 11, 2013

    How do I install a custom Arduino library? It's easy! This tutorial will go over how to install an Arduino library using the Arduino Library Manager. For libraries not linked with the Arduino IDE, we will also go over manually installing an Arduino library.
  • Download the Github repository

    Users can also manually download and install the library from Github. You can Visit the GitHub repository to download the most recent version of the library, or click the link below:

Setting up the Artemis Board

In case you haven't checked out the hookup guide for the RedBoard Artemis, we suggest reviewing it as the features are very different from your standard Arduino Uno.

Installing Artemis Board Package

This tutorial and Arduino Library support the Artemis Boards. You will need to use the Boards manager to install the necessary packages. You can visit the specific section of the Artemis tutorial here, or read the entire tutorial in the link below:

Artemis Development with Arduino

June 20, 2019

Get our powerful Artemis based boards (Artemis Nano, BlackBoard Artemis, and BlackBoard Artemis ATP) blinking in less than 5 minutes using the SparkFun Artemis Arduino Core!

CH340 Driver Installation for the RedBoard Artemis

Don't forget, if you've never connected an CH340 device to your computer before, you may need to install drivers for the USB-to-serial converter. Check out our section on How to Install CH340 Drivers for help with the installation.

How to Install CH340 Drivers

August 6, 2019

How to install CH340 drivers (if you need them) on Windows, Mac OS X, and Linux.

Arduino Library

Note: This code/library has been written and tested on Arduino IDE version 1.8.10. Otherwise, make sure you are using the latest stable version of the Arduino IDE on your desktop.

If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

We've written a library to easily get setup and start using the Cryptographic Co-processor ATECC508A. If you'd like to jump right into signing and verifying, then feel free to skip ahead to Example 1: Configuration However, it's not a bad idea to familiarize yourself a bit with the source code behind the examples, so let's take a closer look at the available functions in the library. You can install this library through the Arduino Library Manager. Search for SparkFun_Cryptographic and you should be able to install the latest version. If you prefer manually downloading the libraries from the GitHub repository, you can grab them here:

Let's get started by looking at the functions that set up the ATECC508A.

Setup

.begin() or .begin(i2caddr, TwoWire)

Creates a connection to an I2C device over the I2C bus using the default or specified I2C address.

Input: i2caddr

Unassigned 7-bit integer for device address. If not defined, the library will use the default I2C address stored in the I2C library (0x60). This can be changed by writing the I2C address to the specific Configuration Zone address (byte 16) prior to locking that zone.

Input: Wire

Wire port assignment. If not defined, the library will use the default Wire port. (*This is only available to change on boards that in fact have multiple Wire Ports (i.e. Artemis). Currently, only the default wire port located on the Qwiic connector is supported on the Artemis.)

Output: Boolean

True- Connected to I2C device on the default (or specified) address.
False- No device found or connected.

Communication

.wakeUp()

Checks to see if a device over the I2C bus is connected. Returns boolean true or false depending on if the slave device has correctly ACK'd to an I2C request and responded with the correct "wake verification" response: 0x11.

Output: Boolean

True- Device present on the default (or specified) address.
False- No device found or transmission error.

.idleMode()

The ATECCX08A goes into the idle mode and ignores all subsequent I/O transitions until the next wake flag. The contents of TempKey and RNG Seed registers are retained. (*Idle Power Supply Current: 800uA.)

Note, it will automatically go into sleep mode after watchdog timer has been reached (1.3-1.7sec).

.receiveResponseData(uint8_t length, boolean debug)

This function receives messages from the ATECCX08a IC (up to 128 Bytes). It will return true if it receives the correct amount of data and good CRCs. What we hear back from the IC is always formatted with the following series of bytes:

COUNT, DATA, CRC[0], CRC[1]

Note, the count number includes itself, the num of data bytes, and the two CRC bytes in the total, so a simple response message from the IC that indicates that it heard the wake condition properly is like so:

EXAMPLE Wake success response: 0x04, 0x11, 0x33, 0x44

Input: length

Unassigned 8-bit integer.
Length of data in bytes (max 32 bytes).
Includes: Count + DATA + 2 CRC bytes.

Output: Boolean

True- Communication complete and message count and CRC are good.
False- Communication failure (count error, CRC error, or no device present)

.checkCount(boolean debug)

This function checks that the count byte received in the most recent message equals countGlobal. Users must call .receiveResponseData and then immediately call this to check the count of the complete message.

Output: Boolean

True- count received and count calculated match (aka inputBuffer[0] == countGlobal)
False- Count error, message invalid.

.checkCrc(boolean debug)

This function checks that the CRC bytes received in the most recent message equals calculated CRCs. Users must call .receiveResponseData then call immediately call this to check the CRCs of the complete message.

Output: Boolean

True- CRC received and CRC calculated match (aka inputBuffer[0] == countGlobal)
False- CRC error, message invalid.

.atca_calculate_crc(uint8_t length, uint8_t *data)

This function calculates CRC. It was copied directly from the App Note provided from Microchip (*it seems to be their own unique implementation of CRC cacluation.).

You're CRC bytes will be located for use at global public variable .crc.

Input: length

Unassigned 8-bit integer. Length number of bytes in buffer.

Input: data

Unassigned 8-bit integer. Data to be used in the CRC calculation.

.sendCommand(uint8_t command_opcode, uint8_t param1, uint16_t param2, uint8_t *data, size_t length_of_data)

Generic function for sending commands to the IC.
This function handles creating the "total transmission" to the IC.
This contains WORD_ADDRESS_VALUE, COUNT, OPCODE, PARAM1, PARAM2, DATA (optional), and CRCs.
Note, it always calls the wake() function, assuming that you have let the IC fall asleep (default 1.7 sec)
Note, for anything other than a command (reset, sleep and idle), you need a different "Word Address Value",
So those specific transmissions are handled in unique functions.
Input: command_opcode

Unassigned 8-bit integer.
COMMAND_OPCODE_INFO - Return device state information.
COMMAND_OPCODE_LOCK - Lock configuration and/or Data and OTP zones.
COMMAND_OPCODE_RANDOM - Create and return a random number (32 bytes of data).
COMMAND_OPCODE_READ - Return data at a specific zone and address.
COMMAND_OPCODE_WRITE - Return data at a specific zone and address.
COMMAND_OPCODE_GENKEY - Create a public and/or private key and store it in a slot.
COMMAND_OPCODE_NONCE - Generates a nonce for use by a subsequent command.
COMMAND_OPCODE_SIGN - Create ECC signature with TempKey and designated private key.
COMMAND_OPCODE_VERIFY - Verify an ECDSA (R,S) signature against data and public key.

Input: param1

Unassigned 8-bit integer. Unique to each command.

Input: param2

Unassigned 16-bit integer. Unique to each command.

Input: data

Unassigned 8-bit integer pointer. Unique to each command.

Input: length_of_data

Unassigned 8-bit integer. Unique to each command.

.read(uint8_t zone, uint16_t address, uint8_t length, boolean debug)

Reads data from the IC at a specific zone and address.
Your data response will be available at .inputBuffer.
Input: zone

Unassigned 8-bit integer.
Zone to be read from.
ZONE_CONFIG - Configuration Zone.
ZONE_OTP - One Time Programming Zone.
ZONE_DATA - Data Zone (for keys and certificates).

Input: address

Unassigned 16-bit integer.
Address within zone be read (must include modification for offset)

Input: length

Unassigned 8-bit integer.
Length of data to be read (can only be 4 bytes or 32 bytes)

Output: Boolean

True- Communication complete and message count and CRC are good.
False- Communication failure or command execution failure.

.write(uint8_t zone, uint16_t address, uint8_t *data, uint8_t length_of_data)

Writes data the IC at a specific zone and address.
Note, once a zone is locked, you can no longer write to it, and this function will return false.
Input: zone

Unassigned 8-bit integer.
Zone to be read from.
ZONE_CONFIG - Configuration Zone.
ZONE_OTP - One Time Programming Zone.
ZONE_DATA - Data Zone (for keys and certificates).

Input: address

Unassigned 16-bit integer.
Address within zone be written to (must include modification for offset)

Input: data

Unassigned 8-bit integer pointer.

Input: length_of_data

Unassigned 8-bit integer.
Length of data to be written (can only be 4 bytes or 32 bytes)

Output: Boolean

True- Communication complete and message count and CRC are good.
False- Communication failure or command execution failure.

Configuration

.writeConfigSparkFun()

Writes the necessary configuration settings to the IC in order to work with the SparkFun Arduino Library examples.
For key slots 0 and 1, this enables ECC private key pairs, public key generation, and external signature verifications.
Output: Boolean

True- All write commands were successful.
False- Communication failure or IC command execution failure.

.lockConfig()

This function sends the LOCK Command with the configuration zone parameter and listens for a successful response (0x00).
Output: Boolean

True- Lock command was successful.
False- Communication failure or IC command execution failure.

.lockDataAndOTP()

This function sends the LOCK Command with the Data and OTP (one-time-programming) zone parameter and listens for a successful response (0x00).
Output: Boolean

True- Lock command was successful.
False- Communication failure or IC command execution failure.

.lockDataSlot0()

This function sends the LOCK Command with the Slot 0 zone parameter and listens for a successful response (0x00).
Output: Boolean

True- Lock command was successful.
False- Communication failure or IC command execution failure.

.lock(uint8_t zone)

This function sends the LOCK Command using the argument zone as parameter 1 and listens for a successful response (0x00).
Input: zone

Unassigned 8-bit integer.
LOCK_MODE_ZONE_CONFIG - Lock only the configuration data zone.
LOCK_MODE_ZONE_DATA_AND_OTP - Lock only the Data and OTP zones.
LOCK_MODE_SLOT0 - Lock only the KEYID data slot 0.

Output: Boolean

True- Lock command was successful.
False- Communication failure or IC command execution failure.

.readConfigZone()

This function reads the entire configuration zone EEPROM memory on the device.
It stores them for viewing in a large global public variable array called .configZone (128 bytes).
In addition to configuration settings, the configuration memory on the IC also
contains the serial number, revision number, lock statuses, and much more.
This function also updates global variables for these other things.

.createNewKeyPair(uint16_t slot)

This function sends the command to create a new key pair (private AND public)
in the slot designated by argument slot (default slot 0).
Sparkfun Default Configuration Sketch calls this, and then locks the data/otp zones and slot 0.
Input: slot

Unassigned 8-bit integer. The KEYID data slot you'd like it to be created in.

Output: Boolean

True- GENKEY command was successful.
False- Communication failure or IC command execution failure.

Sign and Verify

.createSignature(uint8_t *data, uint16_t slot)

Creates a 64-byte ECC signature on 32 bytes of data.
Defauts to use private key located in slot 0.
Your signature will be available at global public variable .signature
Note, the IC actually needs you to store your data in a temporary memory location
called TempKey. This function first loads TempKey, and then signs TempKey. Then it
receives the signature and copies it to signature.
Input: data

Unassigned 8-bit integer pointer. (Max 32 bytes).

Input: slot

Unassigned 8-bit integer. The KEYID data slot you'd like to use for ECC calculation.

Output: Boolean

True- Both load tempKey and signTempkey commands were successful.
False- Communication failure or IC command execution failure.

.verifySignature(uint8_t *message, uint8_t *signature, uint8_t *publicKey)

Verifies an ECC digital signature against a message and an external public key.
Note, the IC actually needs you to store your message in a temporary memory location
called TempKey. This function first loads TempKey with the message, and then sends the verify command
with additional data paramaters: signature and publicKey. Then it listens for result from IC.
Input: message

Unassigned 8-bit integer pointer. (32 bytes).

Input: signature

Unassigned 8-bit integer pointer. (64 bytes)

Input: publicKey

Unassigned 8-bit integer pointer. (64 bytes)

Output: Boolean

True- Both load tempKey and verify commands were successful.
False- Verification failure, Communication failure or IC command execution failure.

Random Number Generator

.random(long max)

This function returns a positive random Long between 0 and max.
Max can be up to the larges positive value of a long: 2147483647
Input: max

Long. (1-2147483647)

Output: Long 32 bits (4 bytes)

.random(long min, long max)

This function returns a random Long between min and max.
Min and max can be positive or negative numbers.
Input: min

Long. (-2147483647 to +2147483647)

Input: max

Long. (-2147483647 to +2147483647)

Output: Long 32 bits (4 bytes)

.getRandomByte(boolean debug)

This function returns a positive random byte.
Output: Byte

.getRandomInt(boolean debug)

This function returns a positive random integer.
Output: Unassigned 16-bit integer

.getRandomLong(boolean debug)

This function returns a Long.
Output: Long 32 bits (4 bytes)r

.updateRandom32Bytes(boolean debug)

This function gets a complete random number from the IC (all 32 bytes).
It stores it in a global public variable array called .random32Bytes
If you wish to access this global variable and use as a 256 bit random number,
then you will need to access this array and combine it's elements as you wish.
Output: Boolean

True- Random command execution successful.
False- Communication failure or IC command execution failure.

Example 1: Configuration

🔒Warning: Configuration settings are PERMANENT. We would like to stress the fact that these cannot be changed later. If you intend to follow along with this tutorial, then configure with SparkFun standard settings.

If you intend to use different features of the co-processor like the Diffie-Hellman Key Exchange and some of its other use cases, please consider designing your own custom configuration. This hookup guide only focuses on digital signature creation and verification.

This example shows how to setup your Cryptographic Co-processor with SparkFun's standard settings. This will allow you to sign data and verify data with external signatures. The type of private keys we use in all of these examples are ECC. We have also included an example to use the random number generator and a challenge example. Beyond these functions, you may need to start with a different custom configuration.

To configure, upload Example1_Configuration.ino and open a serial terminal at 115200 baud. If communication with a fresh chip is successful, your Artemis will print out some useful information about your chip.

It will then prompt you to type a y to configure your device. Note, if you do not wish to configure your device, you can simply unplug at this time. Also, did we mention yet, that if you type a y, there's no going back.

Output in Serial Monitor
Output in the Arduino Serial Monitor.

Example 2: Sign

This example shows how to create a digital signature. To try it out, simply upload the Example2_Sign.ino, and watch your serial terminal at 115200 baud. Note, you may need to hit reset.

Output in Serial Monitor
Output in the Arduino Serial Monitor.

Important things to know about ECC signatures:

  1. ECC signatures are created using a secret private key and the elliptical curve algorithm. For the purpose of this example, we can just ignore the printout of the keys public key at the top - this is part of the printInfo() function. As a side note, we will never know the devices private key. The private key for this device is created, stored and locked up inside the device.

  2. ECC signatures are 64 bytes long.

  3. Contrary to most definitions of signatures, ECC signatures are different every time! ECCs include intentional randomness in the calculation, and so it will always produce a new unique signature. However, every signature that it creates will pass verification (as we will later see in example 3). Try hitting reset on your Artemis a few times and watch the signature values change. Same message + same private key = new signature.

  4. With the ATECC508A, we can only send it 32 bytes of data to sign. If you need to sign something larger, then it is recommended that you create a 32-byte hash of the data first, then you can sign the hash. Basically, when you send a bunch of data into a hashing algorithm (such as SHA256), it will always respond with a unique 32 byte digest. It is very similar to creating a digital signature, however it does not require a key, so anyone can calculate the hash of any data. You may find that for many projects, 32 bytes is enough data, so for now, there's no need to pursue hashes.

The Code

Now lets take a quick look at the important parts of the example code. There are two things worthy of note:

At the very top, we define the message we want to sign.

language:c
// array to hold our 32 bytes of message. Note, it must be 32 bytes, no more or less.
uint8_t message[32] = {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
};

Not much to say here, other than it's a nice array of 32 unsigned 8 bit integers. We chose to make the values simply count from 0 to 32, but these could really be anything.

language:c
//Let's create a digital signature!
atecc.createSignature(message); // by default, this uses the private key securely stored and locked in slot 0.

Well, the comments say it all, but I will mention that by sending the argument "message", we are sending a pointer to the first index (0), of the array. createSignature actually does 4 things for us under the hood:

  1. Loads the message into the co-processor's memory location on the chip called tempKey.

  2. Commands the co-processor to sign the contents of tempKey.

  3. Receives the 64 byte signature and stores it in a public variable accessible at atecc.signature. Note, we created an instance of the ATECCX08A class with the name atecc, but you could choose something different, and then you'd need to modify how you access this signature array.

  4. Prints a nice ready to compile serial debug message showing the signature. Handy for copying and pasting between code.

Example 3: Verify

Note: If you upload the sketch as is, then it will fail to verify. This is because the public key, message and signaure are blank. They are simply place holders at this point. Example three requires that you copy/paste three things from Example 2: public key, message and signature. Please follow along below to get a successful verification.

This Example shows how to verify a signature. In order for the co-processor to do this, it needs three things:

  1. Public Key (of the sender)
  2. Message
  3. Signature

If you have just completed Example2_sign, then you should remember seeing these 3 things printed out on the serial terminal. Before uploading Example3_verify.ino, please ensure you update the public key, message and signature at the top of the sketch.

Also very important: you will need to rename the publicKey[64] array at the top to publicKeyExternal[64]. This is what we will use to verify the message and signature, and so we must clarify that it is external.

Before uploading Example3_Verify.ino, we encourage you to click on the .gif below and watch a couple times. This can help show exactly what to do.

Code Modifications
Copying the publicKey[64], message[32], and signature[64] from the output of Example2_sign.ino to operate Example3_Verify.ino. (Click to Enlarge)

The Code

The fresh code that you see when you open up Example3_Verify.ino has place holders. Notice how all the bytes in each array is simply a bunch of 0x00s.

language:c
uint8_t publicKeyExternal[64] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

uint8_t message[32] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

uint8_t signature[64] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

You will need to delete these and paste in your own unique arrays. You could type them in manually, but it will be much easier to copy and paste them from the terminal output from Example 2.

Also note, when you highlight text within an Arduino serial monitor window, you must use the keyboard to actually copy them (Ctrl + C). It won't let you right-click to copy.

And the actual verification of the signature happens as a single function call. It is located at the bottom of setup().

language:c
// Let's verirfy!
if (atecc.verifySignature(message, signature, publicKeyExternal)) Serial.println("Success! Signature Verified.");
else Serial.println("Verification failure.");

atecc.verifySignature(message, signature, publicKeyExternal) is the actual call. This function will return a boolean true if all three things are good, and a false if something doesn't add up. If you change a single bit in any three of the arguments, then it won't verify.

Two nice things to thing about:

  1. The only place in the world that could create the signature that will verify (using this public key) is inside your one unique co-processor. No one else in the world would ever be able to impersonate it. Pretty cool huh!

  2. If any of the message was changed (even just a single bit flipped), then this verification would fail. This means that you can be very confident that the message was transmitted and received properly. In this way it is acting as a very robust checksum. It also means that if someone actually intercepted this message, they won't be able to change anything in the message. Sweet!

Example 4: From Alice to Bob

Note: There are 2 unique Arduino sketches for this example. Example4_Alice.ino and Example4_Bob.ino. You will need to use both of these to complete this Example. We recommend opening two separate instances of Arduino, this way you can setup each one with its own com port for uploading and [serial terminal](https://learn.sparkfun.com/tutorials/terminal-basics).

Hardware hookup

For Example 4, you will need to setup two Artemis boards with two co-processors, and connect a couple jumper wires between them. Using the Artemis Redboard, there is no soldering required for this setup.

Connect both of your Artemis boards to your computer using USB-C cables. Connect a Cryptographic Co-processor to each board using a Qwiic cable.

The board on the left is Alice. The board on the right is Bob. Connect Alice's TX1 pin to Bob's RX1 pin. Also connect GND to GND for good measure.

Fritzing Diagram
Fritzing diagram for hardware connections.

Note, both Alice and Bob need their own co-processor. So you're complete setup should look something like this:

Hardware Connections
Hardware connections.

Code setup

We will need to copy/paste Alice's public Key into the top of Bob's Sketch. First upload Alice's sketch to Alice, then watch her terminal at 115200. Copy her public key.

Now go over to Bob's sketch. Delete the place holder "blank" public key at the top, and paste in Alice's public key. Upload Bob's sketch to Bob.

Now watch both Alice's and Bob's terminal at 115200. Type a y into Alice's terminal, and she will send a signed message to Bob. Watch Bob's terminal. He will receive the message and verify it.

Watch this looped video to see it all happen. (click to enlarge).

Code Modifications
Operation of Example4_Alice.ino and Example4_Bob.ino working in conjunction. (Click to Enlarge)

Things to note about this:

  1. We are now using two separate co-processors! In this example, Bob is simply using his co-processor as a verification engine. This could be accomplished by any computer that can compute ECC signature verification. But it's really quite nice to offload this calculation to a co-processor, and it will perform the calculations very fast.

  2. Alice signed her message with her private key and she gave her public key to Bob. Hopefully the private vs public thing is starting to sink in.

  3. Bob used an external public key (Alice's) to verify the authenticity of Alice. He could potentially name this anything he wants. And he could store lots of them, if he wanted to be able to verify messages from other senders.

  4. Alice will most likely make her public key truly public and let everyone know about it. Once everyone has it, then she can send authenticated messages to anyone she likes, and they will truly know that it came from Alice.

  5. It does not have to be a one-way street. The example could easily be reversed and Bob could give Alice his public key. With eachother publc keys, they can both send messages and verify.

The Code

As mentioned above, this example has two sketches. The purpose of splitting it up allows us to build upon the first three examples, and communicate securely between two completely separate systems.

Alice's sketch is actually quite similar to the Example2_Sign.ino, although it also sends the message and signature out it's TX1 pin.

Let's take a closer look at the important stuff within Alice's sketch:

language:c
//Let's create a digital signature!
atecc.createSignature(message); // by default, this uses the private key securely stored and locked in slot 0.

// Now let's send the message to Bob.
// this will include three things:
// (1) start header ("$$$") ASCII "$" = 0x24 HEX
// (2) message (32 bytes)
// (3) signature (64 bytes)

// start header
Serial1.print("$$$");

// message
// note, we use "Serial.write" because we are sending bytes of data (not characters)
for (int i = 0; i < sizeof(message) ; i++) Serial1.write(message[i]);

// signature
// Note, in Example4_Alice we are printing the signature we JUST created,
// and it lives inside the library as a public array called "atecc.signature"
for (int i = 0; i < sizeof(atecc.signature) ; i++) Serial1.write(atecc.signature[i]);

At the top of this code block, you can see she is using atecc.createSignature(message), just like in Example2_sign.

Then Alice sends everything to Bob, including a start "header" ($$$). This is simply used to avoid errors during transmission and helps ensure that Bob hears the entire message.

One important thing to note is that when Alice sends her message and signature to Bob, she uses the Serial1.write() function, because she is sending data (not ASCII characters).

Now let's take a closer look at the important stuff in Example4_Bob.ino. Bob's sketch is actually quite similar to Example3_Verify.ino, although he receives the message and signature on his RX1 pin.

language:c
// Delete this "blank" public key,
// copy/paste Alice's true unique public key from her terminal printout in Example4_Alice.

uint8_t AlicesPublicKey[64] = {
0xB4, 0x07, 0x88, 0x28, 0x8C, 0xFA, 0x71, 0xBA, 0x08, 0xE3, 0x38, 0xE0, 0x4A, 0x17, 0x68, 0xCC, 
0x3E, 0xCD, 0x48, 0xA8, 0x11, 0x52, 0xDD, 0x37, 0xA1, 0xC2, 0x55, 0x75, 0x81, 0xBE, 0x4E, 0x7E, 
0x78, 0x98, 0x95, 0xF6, 0x6D, 0xE7, 0x1C, 0x9A, 0x36, 0xE6, 0xB0, 0x14, 0x5D, 0x50, 0x67, 0x91, 
0x7C, 0x41, 0xB8, 0x99, 0x20, 0x75, 0x3A, 0x7D, 0xA1, 0xFB, 0xF5, 0x5E, 0x8A, 0x65, 0xF5, 0x8A
};

At the top, you need to copy in Alice's public key. Bob will need this to verify any messages and signatures he receives. Note, yours will be different than what I'm showing above.

language:c
void loop()
{
  if (Serial1.available() > 0) // listen on Serial1
  {
    // check for start header
    byte input = Serial1.read();
    //Serial.print(input, HEX);
    if (input == '$') headerCount++;
    if (headerCount == 3)
    {
      delay(100); // wait for entire message to come into Serial1 buffer (96 bytes at 9600 baud).

      headerCount = 0; // reset
      Serial.println("Message Received!");
      Serial.println();

      for (int bytes = 0 ; bytes < 32 ; bytes++) message[bytes] = Serial1.read();

      for (int bytes = 0 ; bytes < 64 ; bytes++) signature[bytes] = Serial1.read();

      printMessage();

      printSignature();

      // Let's verirfy!
      if (atecc.verifySignature(message, signature, AlicesPublicKey)) Serial.println("Success! Signature Verified.");
      else Serial.println("Verification failure.");
    }
  }
}

Above, we have Bob's entire loop(). He is listening for incoming data on his RX1 pin. If he hears the expected $$$, then he starts reading in the message and the signature, storing them in variables for later use.

Then Bob uses the atecc.verifySignature() function to see if everything is authentic. Note his third argument to this function - he is using AlicesPublicKey!

Example 5: Random

This example shows how to use the Random Number Generator on the Sparkfun Cryptographic Co-processor. It will print random numbers once a second on the serial terminal at 115200.

This example only requires 1 Artemis and 1 co-processor. If you just completed example 4, you can choose to use Alice or Bob. This example helps set the stage for Example 6, so it's a good idea to check it out and see how the ATECC508A does random numbers - particularly its ability to create 32 bytes of random data!

Output in Serial Monitor
Output in the Arduino Serial Monitor.

Note, this chip is a bit more capable than the built-in Arduino function random().

  • random(max)
  • random(min, max)

It has a basic random(min, max). This will return a random number of type long. Note, it works very similarly to the built-in Arduino random() function, you can send it a single argument as a max, or you can send it two (as min and max).

It also has the following 3 other functions that can be useful in other applications.

  • getRandomByte()
  • getRandomInt()
  • getRandomLong()

Each of these functions return a random number of the type written into the name.

And lastly...

  • updateRandom32Bytes() will create 32 bytes of random data and store it in atecc.random32Bytes[].

After calling updateRandom32Bytes() then your random 32 bytes of data are available at a public variable within the library instance. If your instance was named atecc as in the SparkFun examples, this array would be atecc.random32Bytes[]. This can be useful as a challenge or time-to-live-token (aka NONCE) to send to another device.

Example 6: Challenge

This example shows how to setup a "challenge and response" for authentication between two systems. This is one way to add more security to your communication channel. More specifically, it prevent attackers from intercepting a message and sending it at a later time. This doesn't seem like such a bad thing, but timing of a message is sometimes equally as important as the message itself. Once such interception attack was called the RollJam, and could be used to maliciously open garage doors and unlock cars. After completing this example, you will be able to defend your projects against this type of attack!

Note: If you upload the sketch as is, then it will fail to verify. This is because Bob does not have Alice's public key yet. The array at the top of the sketch is simply place holders at this point. Please follow along below to get a successful challenge and verification.

Hardware Hookup

For Example6_Challenge, you will need to setup two Artemis boards (each with their own co-processors) and connect a few jumper wires between Alice and Bob.

Connect the following pins like so:

Alice (left)Bob (right)
GNDGND
TX1RX1
RX1TX1

Fritzing Diagram
Fritzing diagram for hardware connections.

Note, you're setup will also need to include a co-processor on each side connected via qwiic cables, and should look something like this:

Hardware Connections
Hardware connections.

Code Setup

Like Example 4, this also requires two unique sketches and setups. You will need to use both Example6_Challenge_Alice.ino and Example6_Challenge_Bob.ino.

Again, you will need to copy Alice's public key from her serial terminal, and then paste it into the top of Bob's sketch. Then upload Bob's sketch and watch both terminals.

Output in Serial Monitor
Operation of Example6_Challenge_Alice.ino and Example6_Challenge_Bob.ino working in conjunction.
(Click to Enlarge)

For any new authentication cycle, Alice will initiate. User must reset Alice and send a "y" over serial at 115200. Bob will create a new random array of 32 bytes (this will be called a token - aka NONCE). It is also known as a "time-to-live token", because it will become invalid after a set amount of time. Bob sends the token to Alice. Alice will sign the token using her private ECC key, then send the signature to Bob. Bob will use the token, the signature, and Alice's Public Key to verify everything.

By creating a new random token, Bob now has the ability to control how long he thinks that token should be valid. This means that if an attacker intercepted the message, and they tried to send it later, it would no longer be valid.

Bob will also invalidate the token after a set amount of time. For our example it will be 150ms. This prevents any attacker from intercepting the message, and hanging on to it for later use. So if Alice doesn't respond within the set window of time (150ms), then Bob will clear out the token, and Alice must ask for another.

Because the token is unique every time, that means that Alice's signature will be unique every time. This prevents an attacker from trying to impersonate Alice by recording communications, and then later sending one.

Troubleshooting

For extra guidance, checkout the product video, which also includes the examples, laid out in this tutorial.

Resources and Going Further

Now that you've sent signed message between two systems, you are ready to integrate some security into your projects! In these examples we have used hard-wired serial messages between two Arduinos. That communication channel could be anything: Bluetooth, RFM69s, Wifi and the internet, you name it! Good luck!

Additional Documentation on the Cryptographic Standards (linked from datasheet):

Need inspiration? Check out some of the Qwiic or IoT related tutorials!

Using the PSoC 6 Pioneer Board with the Pioneer IoT Add-on Shield

Cypress's PSoC 6 Pioneer Board is a development tool for the powerful PSoC 6 processor. In this tutorial, we'll show you how to use the PSoC 6 Pioneer Board along with the SparkFun/Digi-Key Pioneer IoT Add-on Shield to send data to a Raspberry Pi via BLE or WiFi.

Qwiic IR Array (MLX90640) Hookup Guide

The Melexis MLX90640 contains a 32x24 array of thermopile sensors creating, in essence, a low resolution thermal imaging camera. In this guide, we’ll go over how to connect your Qwiic Infrared Array with MLX90640 and get it communicating with Processing to produce a nice thermal image.

Qwiic Twist Hookup Guide

Take your volume knob beyond 11 with the Qwiic Twist digital RGB LED encoder via I2C!

SparkFun AS3935 Lightning Detector Hookup Guide (v20)

Are you worried about the looming clouds in the distance, how far away is that storm exactly? Add lightning detection with the AS3935 to your next weather station or your next bike ride!

Loading Debian (Ubilinux) on the Edison

How to load a Debian distribution (specifically Ubilinux) onto the Edison.

LED Cloud-Connected Cloud

Make an RGB colored cloud light! You can also control it from your phone, or hook up to the weather!

IoT Industrial Scale

What does a baby elephant weigh? How much impact force does a jump have? Answer these questions and more by building your very own IoT industrial scale using the SparkFun OpenScale.

Using SparkFun Edge Board with Ambiq Apollo3 SDK

We will demonstrate how to get started with your SparkFun Edge Board by setting up the toolchain on your computer, examining an example program, and using the serial uploader tool to flash the chip.

learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

SparkFun Qwiic Micro (SAMD21E) Hookup Guide

$
0
0

SparkFun Qwiic Micro (SAMD21E) Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t917

Introduction

Looking for a one square inch sized microcontroller to use with the Qwiic system? At it's heart is the powerful and versatile ATSAMD21E18, which is an ARM Cortex M0+, 32-bit microcontroller, with 256KB of flash memory that can run at up to 48MHz. We've programmed it with an UF2 Bootloader making the Qwiic Micro easy to program whether you want to use Arduino or CircuitPython. In this hookup guide we'll walk through all of the features available on the SparkFun Qwiic Micro.

SparkFun Qwiic Micro - SAMD21 Development Board

SparkFun Qwiic Micro - SAMD21 Development Board

DEV-15423
$19.95

Required Materials

In addition to the Qwiic Micro, you'll also need a Micro-B Cable (as if you don't already have dozens in your USB cable drawer!). That's all you'll need to get started. You can also take advantage of its LiPo battery port with a single-cell Lithium Polymer battery. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

USB micro-B Cable - 6 Foot

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
12
SparkFun Qwiic Micro - SAMD21 Development Board

SparkFun Qwiic Micro - SAMD21 Development Board

DEV-15423
$19.95

Suggested Reading

Before continuing on with this tutorial, you may want to familiarize yourself with some of these topics if they’re unfamiliar to you. If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System
Qwiic Connect System

Analog to Digital Conversion

The world is analog. Use analog to digital conversion to help digital devices interpret the world.

What is an Arduino?

What is this 'Arduino' thing anyway?

Installing Arduino IDE

A step-by-step guide to installing and testing the Arduino software on Windows, Mac, and Linux.

SAMD21 Mini/Dev Breakout Hookup Guide

An introduction to the Atmel ATSAMD21G18 microprocessor and our Mini and Pro R3 breakout boards. Level up your Arduino-skills with the powerful ARM Cortex M0+ processor.

Hardware Overview

Before we get into programming the SAMD21, let's first cover some of the features built into the SparkFun Qwiic Micro. The Qwiic Micro is similar to our other SAMD21 boards such as the SAMD21 Dev Breakout, except much much smaller. In this section, we'll cover the hardware on the SparkFun Qwiic Micro, including its I/O pins and the various LEDs. We'll also cover the different options for powering the board.

Supplying Power and Power Switch

The SparkFun Qwiic Micro operates at 3.3 volts which makes it ideal for the Qwiic eco-system. Power can be supplied to the SparkFun Qwiic Micro through micro-USB. It is also possible to supply power through the through holes labeled 3V3 and GND located in the lower right hand section of the board.

This image shows the top of the SparFun Qwiic Micro and highlights the Micro-USB connector, and the lower two pins on the right side header.
The power header pins are not regulated, so make sure that you have a steady 3.3V power supply when providing power through here.

Additionally, we've provided pads for an SMD LiPo battery connector if you have it, see the Optional Circuitry section below. The micro-USB connector should work with one of the many USB phone-charging cables you have lying around, or one of our micro-USB cables. Below is a list of micro-USB options that SparkFun offers.

USB micro-B Cable - 6 Foot

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
12
USB Wall Charger - 5V, 1A (Black)

USB Wall Charger - 5V, 1A (Black)

TOL-11456
$3.95
2
Wall Adapter Power Supply - 5VDC, 2A (USB Micro-B)

Wall Adapter Power Supply - 5VDC, 2A (USB Micro-B)

TOL-15311
$5.95

The power switch on the SparkFun Qwiic Micro controls turns it on and off when put into the on and off position respectively.

This image shows the top of the SparkFun Qwiic Micro and highlights the switch on its' top edge.

Pin Mapping

3.3V Logic Levels! When you start interfacing with the SAMD21's I/O pins using external sensors and other components, keep in mind that each I/O will produce, at most, 3.3V for a high-level output.

When configured as an input, the maximum input voltage for each I/O is 3.6V (VDD+0.3V). If you're interfacing the SAMD21 with 5V devices, you may need some level shifters in between.

The graphical datasheet for the SparkFun Qwiic Micro below, shows the complete functionality of each pin; which pins are analog, digital, where SERCOM ports are located, and which data buses are available. All PWM-capable pins except the DAC are capable of PWM output. The DAC pin provides a true 10-bit analog output. In Example: Analog Input and Output, there are steps on how to take full advantage of this feature.

Graphical Datasheet

Click on image for a closer view.

Qwiic Connector

On the opposite edge of the SparkFun Qwiic Micro is a Qwiic connector.

This image shows the top of the SparkFun Qwiic Micro and highlights the black connector also known as a qwiic connector, located on the lower edge of the board.

If you're not familar with the Qwiic Ecosystem, the short of it is that we have integrated Qwiic Connectors on many sensors and development boards that allow for quick (get it?) I2C connections through cables rather than soldering. It's an extremely useful tool. Check out the banner below for more information.

Qwiic Connect System

LEDs

The SparkFun Qwiic Micro has a red power LED that has become emblematic of our Qwiic eco-system and indicates power is being supplied to the board and that the power switch is in the ON position. Additionally, there is a stat LED that is attached to pin D13 and is labeled D13.

This image shows the top of the SparkFun Qwiic Micro and highlights the two LEDs located on each side of the Qwiic connector on the lower edge of the board.

D13 Stat LED on the Left, Power LED on the right

If you want to minimize the current draw of your Qwiic Micro or just don't like the power LED we've provided a jumper on the underside to disconnect it; see Jumper section below.

Jumper

On the underside of the SparkFun Qwiic Micro just below the power LED we've provided a jumper to disconnect the power LED to help keep the current draw of the microcontroller low. Simply take a hobby knife and cut the trace in between the two pads to sever its' connection. Simply re-solder this jumper to reconnect it. If you need some instructions for working with jumper pads then check out our tutorial.

This image shows the bottom of the SparkFun Qwiic Micro with the USB facing up and highlights a small jumper located in the lower left of the board near the screw hole.

Reset Button

On the topside of the SparkFun Qwiic Micro is a reset button which resets the board when pressed. If you find yourself with a botched Circuit Python installation, or a sketch that has left your board inoperable, then you can tap this button twice to re-enter bootloader mode. You'll know you've done it correctly when the D13 Stat LED is dimming and brightening in a breathing pattern.

This image shows the top of the SparkFun Qwiic Micro and highlights the small reset button located on the right side of the board.

Programming Header

There is a small four pin programming header exposed on both the top and bottom side of the SparkFun Qwiic Micro. This header breaks out the following pins for SWD programming:

Programming Header Top SideProgramming Header bottom side.
Pins from left to right.
TOPBOTTOM
SWDIO RESET
SWCLK GND
GND SWCLK
RESET SWDIO

Programming through this header would allow you to put a different bootloader on the chip, or to configure the SAMD21's flexible SERCOM ports to add another I2C port for example. You can check out this guide to see how this is done.

Optional Circuitry

LiPo Battery

On the underside we've included empty pads for a few optional items. First in the upper right is a space for a LiPo Battery Connector. You'll need to solder connector if you decide to power your project though this connector.

This image shows the bottom of the SparkFun Qwiic Micro and highlights a grouping of SMD pads near the top edge of the board, directly under the micro-USB where a lipo battery connector can be soldered onto.

We provide a number of LiPo battery options when you're ready to integrate the SparkFun Qwiic Micro into your project.

Lithium Ion Battery - 2Ah

Lithium Ion Battery - 2Ah

PRT-13855
$12.95
5
Lithium Ion Battery - 850mAh

Lithium Ion Battery - 850mAh

PRT-13854
$9.95
2
Lithium Ion Battery - 400mAh

Lithium Ion Battery - 400mAh

PRT-13851
$4.95
9
Lithium Ion Battery - 1Ah

Lithium Ion Battery - 1Ah

PRT-13813
$9.95
7
Lithium Ion Battery - 6Ah

Lithium Ion Battery - 6Ah

PRT-13856
$29.95
5
Lithium Ion Battery - 110mAh

Lithium Ion Battery - 110mAh

PRT-13853
$4.95
2

Optional Flash Memory Chip

Just below that is a space for a flash memory chip.

This image shows the bottom of the SparkFun Qwiic Micro and highlights a grouping of SMD pads located in the center the board where a flash chip can be soldered onto.

If you want to add extra memory to the SparkFun Qwiic Micro than you can solder an 8 pin SOIC to these pads. The 4MB flash chip from Winbond: the W25Q32FV which works with the very useful Arduino Library SPI Memory. Check out Example 4: Flash Memory to see how to use an external flash with the SparkFun Qwiic Micro. In addition we've provided CircuitPython firmware for the SparkFun Qwiic Micro that can use this memory as well.

When everything is soldered onto the bottom, it will look like this:

This images shows the bottom of the board with all of the optional circuitry added to it.

Board Dimensions

The board utilizes the standard 1.0"x1.0" square like a majority of the Qwiic enabled sensors. Due to the size of the board, there are three mounting holes on each corner of the board. Grab some standoffs and screws to make a Qwiic sensing tower of boards!

Board Dimensions

UF2 Bootloader and Drivers

The SparkFun Qwiic Micro comes with a UF2 bootloader which has the unique benefit of sidestepping driver installation on modern operating systems like Windows 10, Mac, and Linux! The UF2 bootloader turns the SparkFun Qwiic Micro into a USB mass storage device and so behaves like a flash drive when you plug it into your computer. However in the Arduino IDE, nothing will change: you'll still select its COM Port when uploading your code.

....yes but what is UF2?

UF2 stands for USB Flashing Format, which was developed by Microsoft for PXT (now known as MakeCode) for flashing microcontrollers over the Mass Storage Class (MSC), just like a removable flash drive. The file format is unique, so unfortunately, you cannot simply drag and drop a compiled binary or hex file onto the Qwiic Micro. Instead, the format of the file has extra information to tell the processor where the data goes, in addition to the data itself.

For Arduino users, the UF2 bootloader is BOSSA compatible, which the Arduino IDE expects on ATSAMD boards. For more information about UF2, you can read more from the MakeCode blog, as well as the UF2 file format specifiation.

Setting Up Arduino

While the SAMD21 alone is powerful enough, what truly makes it special is its growing support in the Arduino IDE. With just a couple click's, copies, and pastes, you can add ARM Cortex-M0+-support to your Arduino IDE. This page will list every step required for getting SparkFun Qwiic Micro installed into the Arduino IDE.

Update Arduino! This setup requires at least Arduino version 1.6.4 or later. We've tested it on 1.6.5 and the latest version – 1.8.8. If you're running an older version of Arduino, consider visiting arduino.cc to get the latest, greatest release.

Install Arduino SAMD Board Add-Ons

First, you'll need to install a variety of tools, including low-level ARM Cortex libraries full of generic code, arm-gcc to compile your code, and bossa to upload over the bootloader. These tools come packaged along with Arduino's SAMD board definitions for the Arduino Zero.

To install the Arduino SAMD board definitions, navigate to your board manager (Tools>Board>Boards Manager...), then find an entry for Arduino SAMD Boards (32-bits ARM Cortex-M0+). Select it, and install the latest version (recently updated to v1.8.4).

Installing the Arduino SAMD boards

Downloading and installing the tools may take a couple minutes -- arm-gcc in particular will take the longest, it's about 250MB unpacked.

Once installed, Arduino-blue "Installed" text should appear next to the SAMD boards list entry.

Install SparkFun Board Add-On

Now that your ARM tools are installed, one last bit of setup is required to add support for the SparkFun SAMD boards. First, open your Arduino preferences (File>Preferences). Then find the Additional Board Manager URLs text box, and paste the below link in:

https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json

Arduino IDE Preferences Additional Moard Manager URLs

Then hit "OK", and travel back to the Board Manager menu. You should (but probably won't) be able to find a new entry for SparkFun SAMD Boards. If you don't see it, close the board manager and open it again. ¯\_(ツ)_/¯.

Installing the SparkFun SAMD Boards

This installation should be much faster; you've already done the heavy lifting in the previous section. When writing this tutorial, the board version used in this tutorial should be v1.7.0. You may have a higher version as the board if there are any updates.

Select the Board and Serial Port

Once the board is installed, you should see a new entry in your Tools>Board list. Select your SparkFun Qwiic Micro.

Finally, select the SparkFun Qwiic Micro's port when the board is connected to your computer with the power switch in the ON position. Navigate back up to the Tool>Port menu. The port menu will have the SparkFun Qwiic Micro's port, labeled as such here. On a Windows machine, the serial port should come in the form of "COM#". On a Mac or Linux machine, the port will look like "/dev/cu.usbmodem####".

Board and COM Port Selection in the Arduino IDE

In the picture above my Qwiic Micro is listed under COM93; this is because I've plugged in about as many microcontrollers into my computer, but the one in your port menu should be a lot smaller.

Here's a quick example sketch to get the iconic blinking blue stat LED for Arduino blinking on the SparkFun Qwiic Micro; simply copy and paste from below, then click upload!

language:c
const int LED = 13; // Blue "stat" LED on pin 13

void setup() 
{
  pinMode(LED, OUTPUT); //set pin as output
  digitalWrite(LED, LOW); //turn LED off
}

void loop() 
{

  digitalWrite(LED, HIGH); // Blue LED on
  delay(250);
  digitalWrite(LED, LOW); // Blue LED off
  delay(250);
}

Now that you've passed the Arduino litmus test, you're all set up to start building your first project. If you haven't already, go check out our Qwiic eco-system which allows you to easily connect with sensors and other devices without the need for soldering.

Qwiic Connect System

In addition each add-on board within this eco-system has a library to get you started right away. For example, do you want to turn on a lamp with your SparkFun Qwiic Micro, better yet four lamps, or perhaps you'd like to see how much light your plants are getting? Check out any tutorial tagged with Arduino, sensor, and Qwiic for more ideas!

Qwiic Scale Hookup Guide

Create your own digital scale quickly and easily using the Qwiic Scale!

Qwiic pHAT for Raspberry Pi Hookup Guide

Get started interfacing your Qwiic enabled boards with your Raspberry Pi. The Qwiic pHAT connects the I2C bus (GND, 3.3V, SDA, and SCL) on your Raspberry Pi to an array of Qwiic connectors.

Hookup Guide for the BlackBoard Artemis ATP

Get started with the BlackBoard Artemis ATP - all the functionality of the SparkFun Artemis module wrapped in the Mega Arduino Footprint

Hookup Guide for the Qwiic Motor Driver

Drive things "qwiic"-ly with the SparkFun Qwiic Motor Driver!

Example 2: Serial Ports

One of the SAMD21's most exciting features is SERCOM -- its multiple, configurable serial ports. The Arduino IDE equips the SAMD21 with a hardware serial port, by default, plus a "USB serial port" for communicating between the serial monitor.

Each of these serial ports has a unique Serial object which you'll refer to in code:

Serial ObjectSerial PortRX PinTX Pin
SerialUSBUSB Serial (Serial Monitor)
SerialHardware Serial PortD17D16

There are a couple critical things to notice here. First of all, if you're trying to use the Serial Monitor to debug, you'll need to use SerialUSB.begin(<baud>) and SerialUSB.print(). (Thankfully find/replace exists for adjusting example code.) You can also add #define Serial SerialUSB to the beginning of a sketch. This will tell the IDE to replace "Serial" with "SerialUSB" everywhere it sees it before it compiles.

Here's a quick example demonstrating the differences between Serial Monitor and Serial. It is designed to route data from Serial to the Serial Monitor, and vice-versa.

language:c
void setup()
{
  SerialUSB.begin(9600); // Initialize Serial Monitor USB
  Serial.begin(9600); // Initialize hardware serial port, pins 17/16

  while (!SerialUSB) ; // Wait for Serial monitor to open

  // Send a welcome message to the serial monitor:
  SerialUSB.println("Send character(s) to relay it over Serial");
}

void loop()
{
  if (SerialUSB.available()) // If data is sent to the monitor
  {
    String toSend = ""; // Create a new string
    while (SerialUSB.available()) // While data is available
    {
      // Read from SerialUSB and add to the string:
      toSend += (char)SerialUSB.read();
    }
    // Print a message stating what we're sending:
    SerialUSB.println("Sending " + toSend + " to Serial");

    // Send the assembled string out over the hardware
    // Serial port (TX pin 1).
    Serial.print(toSend);
  }

  if (Serial.available()) // If data is sent from device
  {
    String toSend = ""; // Create a new string
    while (Serial.available()) // While data is available
    {
      // Read from hardware port and add to the string:
      toSend += (char)Serial.read();
    }
    // Print a message stating what we've received:
    SerialUSB.println("Received " + toSend + " from Serial");
  }
}

Then try typing something into the serial monitor. Even with nothing connected to the hardware serial port, you should see what you typed echoed back at you. It should look similar to the image below similar to the SAMD21 breakout.

Example serial monitor

You can further test this sketch out by connecting an 3.3V FTDI Basic or any other serial device to the SAMD21's pins 17 (RX) and 16 (TX). You'll need IC hooks for a quick temporary connection. Otherwise, you'll need to solder pins or wires to the board. By opening up a serial terminal, any data sent from the FTDI should end up in your Arduino Serial Monitor, and data sent to your Arduino Serial Monitor will route over to the FTDI. Here's a table that shows what pins to connect together.

Qwiic Micro Pins3.3V FTDI (or any USB-to-Serial Converter) Pins
D16/TXRXI
D17/RXTXO
GNDGND

Example 3: Analog Input and Output

While it still has PWM-based "analog outputs", the SAMD21 also features true analog output in the form of a digital-to-analog converter (DAC). This module can produce an analog voltage between 0 and 3.3V. It can be used to produce audio with more natural sound, or as a kind of "digital potentiometer" to control analog devices.

The DAC is only available on the Arduino pin A0, and is controlled using analogWrite(A0, <value>). The DAC can be set up to 10-bit resolution (make sure to call analogWriteResolution(10) in your setup), which means values between 0 and 1023 will set the voltage to somewhere between 0 and 3.3V.

In addition to the DAC, the SAMD21's ADC channels also stand apart from the ATmega328: they're equipped with up to 12-bit resolution. That means the analog input values can range from 0-4095, representing a voltage between 0 and 3.3V. To use the ADC's in 12-bit mode, make sure you call analogReadResolution(12) in your setup.

Serial Plotting the DAC

The Serial Plotter in this example requires Arduino 1.6.6 or later. Visit arduino.cc to get the latest, greatest version.

Here's an example that demonstrates both the 10-bit DAC and the 12-bit ADC. To set the experiment up, connect A0 to A1 with a jumper -- we'll drive A0 with an analog voltage, then read it with A1. To keep the board size to a minimum, we were not able to include additional labels for each pin's functions. Therefore, A0 is labeled as D1/DAC and A1 is labeled as D2. Since there are no headers soldered, you will need to hold the jumper wire in place to with your thumb and index finger for a temporary connection. It's the simplest circuit we've ever put in a tutorial:

Jumper Connected to DAC and Analog Pin

Jumping a temporary connection between A0 (our DAC) and A1. On the board, A0 is labeled D1 and A1 is labeled as D2.

Then copy and paste the code below into your Arduino IDE, and upload!

language:c
// Connect A0 to A1, then open the Serial Plotter.

#define DAC_PIN A0 // Make code a bit more legible

float x = 0; // Value to take the sin of
float increment = 0.02;  // Value to increment x by each time
int frequency = 440; // Frequency of sine wave

void setup() 
{
  analogWriteResolution(10); // Set analog out resolution to max, 10-bits
  analogReadResolution(12); // Set analog input resolution to max, 12-bits

  SerialUSB.begin(9600);
}

void loop() 
{
  // Generate a voltage value between 0 and 1023. 
  // Let's scale a sin wave between those values:
  // Offset by 511.5, then multiply sin by 511.5.
  int dacVoltage = (int)(511.5 + 511.5 * sin(x));
  x += increment; // Increase value of x

  // Generate a voltage between 0 and 3.3V.
  // 0= 0V, 1023=3.3V, 512=1.65V, etc.
  analogWrite(DAC_PIN, dacVoltage);

  // Now read A1 (connected to A0), and convert that
  // 12-bit ADC value to a voltage between 0 and 3.3.
  float voltage = analogRead(A1) * 3.3 / 4096.0;
  SerialUSB.println(voltage); // Print the voltage.
  delay(1); // Delay 1ms
}

This sketch produces a sine wave output on A0, with values ranging from 0 to 3.3V. Then it uses A1 to read that output into its 12-bit ADC, and convert it into a voltage between 0 and 3.3V.

You can, of course, open the serial monitor to view the voltage values stream by. But if the the sine wave is hard to visualize through text, check out Arduino's new Serial Plotter, by going to Tools>Serial Plotter.

Arduino IDE Serial Plotter

And take in the majesty of that sine wave. Since we are temporarily holding the jumper wire in place with our fingers, the sine wave may not be perfect whenever you release pressure on the jumper wire.

Sine Wave Output from the SAMD21 DAC on the Arduino IDE's Serial Plotter

Example 4: Flash Memory with SPIMemory

Installing the SPI Memory Arduino Library

Note: If you have not previously installed an Arduino library, please check out our installation guide.

The following example shows you the basic way to start writing information to the optional flash memory that can be soldered to the underside of the SparkFun Qwiic Micro. The example simply shows you how to set up the code to interact with the flash chip and demonstrates this by writing a single number to an address space on it.

To begin you'll first need to download and install the SPIMemory Arduino Library. You can download it directly from the GitHub Repo or download a zip from the button below. If you've never installed a library before then follow our helpful tutorial here for directions on how to do it.

Example Code

The setup is a bit different than the example code supplied by the library because the flash is connected to a seperate SPI bus that is different then the default one broken out to the SparkFun Qwiic Micro's headers. At the top we use the library by calling SPIFlash and creating an instance of the library, calling it flash. Flash takes two arguments: the flash chip's chip select pin, and secondly the alternate SPI port to be used. Since the memory chip is on SPI1, we'll give it that but precede it with an ampersand as demonstrated: &SPI1.

language:c
#include "SPIMemory.h"

const int blinkLED = 13; 
const int flashCS = 21; // Chip select for Flash

SPIFlash flash(flashCS, &SPI1); // Our Flash is on a different SPI bus

unsigned long addr = 0x01; // Random selection
byte data = 0x03; // Random data

In the setup, confirm we enable SPI1 bus with SPI1.begin() and that's all you need! Further into the setup, we erase the address that's going to be written to, and then write to it. We double check this was done correctly by reading that address to the serial monitor. Just make sure to set the baud rate at 115200 to view the output.

language:c
void setup(){

    SPI1.begin(); // Don't forget to begin SPI! 
    flash.begin();
    SerialUSB.begin(115200);
    while(!SerialUSB) {} // Wait until the Serial Port is opened. 
    SerialUSB.println("Hello!");

    if(flash.eraseBlock32K(addr)){ // Erase the blacok
        SerialUSB.println("Block erased.");
    }
    else
        SerialUSB.println("Error.");

    if(flash.writeByte(addr, data, true)){
        SerialUSB.println("Written: ");
        SerialUSB.println(flash.readByte(addr));
    }
    else
        SerialUSB.println("Nothing written");

    }

void loop(){

    digitalWrite(blinkLED, HIGH);
    delay(500);
    digitalWrite(blinkLED, LOW);
    delay(500);

}

CircuitPython

CircuitPython is Adafruit's version of MicroPython. We like it here at SparkFun because of it's support for the SAMD based microcontrollers. If you're not familiar with CircuitPython, then I encourage you to check Adafruit's website for more information.

We've provided two different CircuitPython builds for the Qwiic Micro in the Qwiic Micro's hardware repo, one for those of you have soldered the flash chip sold on SparkFun and one for those without flash chip. You can also get both firmware zip files by clicking the respective buttons below. If you're not familiar with the optional flash chip you can add to the SparkFun Qwiic Micro, head back to the Hardware Overview and take a look.

Inside the zipped file are three different files which all do the same things. One of the files has a .uf2 file extension which is designed to work with UF2 bootloaders. In the next section, we'll focus on installing CircuitPython using this method.

Installing CircuitPython

When you plug the SparkFun Qwiic Micro into your computer, it should pop up in a window titled Qwiic Micro like the one below. If not, press the reset button twice.

Qwiic Micro Showing Up as a Removable Drive

To the right of the SparkFun Qwiic Micro pop up window is the firmware_no_flash.uf2 file from the zipped file's firmware folder that will install CircuitPython. Again, if you've soldered the flash chip, then you'll choose the firmware_with_flash.uf2 file instead. To install the file, simply drag the .uf2 from the desktop into the SparkFun Qwiic Micro window. The window should close and the re-open but this time it will be titled CIRCUITPY.

alt text

That's it!

Reinstalling CircuitPython

If you've installed CircuitPython but have decided to use Arduino instead, but then decided to use CircuitPython again (make up your mind), then use the following instructions to reinstall CircuitPython onto the SparkFun Qwiic Micro. I'll assume you know where to get the CircuitPython firmware files since you had to follow the instructions to install CircuitPython to get to this point. Hint: there in the Installing CircuitPython section above.

Reset Board to Bootloader

We want the board to reset to the UF2 bootloader (which as mentioned above) enables the board to act like a flash drive. After plugging the SparkFun Qwiic Micro into your computer, double tap the reset button. If done correctly, the board will pop up as a removable drive titled Qwiic Micro and the D13 LED will have a slow breathing pattern. Now it's just a matter of dragging the .uf2 Circuit Python file into the Qwiic Micro window. It will close and re-open in a window now titled CIRCUITPY.

Using CircuitPython

If this is your first foray into CircuitPython, then I urge you to visit Adafruit's website to learn about everything CircuitPython.

Troubleshooting

For troubleshooting tips, checkout the SAMD21 Troubleshooting guide here for common issues that you might run into when using the SAMD21 with Arduino. The only exception is that the Qwiic Micro does not require drivers so tips for re-installing drivers will not apply.

Resources and Going Further

There is a wealth of information out there, whether you're looking for datasheets, schematics, or design files. Additional resources, here are a few links you might find handy:

For more information about adding more SERCOM ports for your SAMD-based board, check out the tutorial below.

Adding More SERCOM Ports for SAMD Boards

February 4, 2019

How to setup extra SPI, UART, and I2C serial ports on a SAMD-based boards.

It's a brave new world out there -- Arduinos and ARMs working together! What are you going to create with your powerful, Qwiic Micro? Looking for some inspiration, check out these tutorials!

Installing an Arduino Library

How do I install a custom Arduino library? It's easy! This tutorial will go over how to install an Arduino library using the Arduino Library Manager. For libraries not linked with the Arduino IDE, we will also go over manually installing an Arduino library.

Using GitHub to Share with SparkFun

A simple step-by-step tutorial to help you download files from SparkFun's GitHub site, make changes, and share the changes with SparkFun.

Data Types in Arduino

Learn about the common data types and what they signify in the Arduino programming environment.

SparkFun AS3935 Lightning Detector Hookup Guide (v20)

Are you worried about the looming clouds in the distance, how far away is that storm exactly? Add lightning detection with the AS3935 to your next weather station or your next bike ride!

learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Wireless Controlled Wearable EL Wire Dance Suit

$
0
0

Wireless Controlled Wearable EL Wire Dance Suit a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t772

Introduction

In this tutorial, we will build an EL wire dance suit that can be controlled by a wireless glove controller!

alt text

Suggested Reading

If you aren’t familiar with the following concept, we recommend checking out these before continuing.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

Exploring XBees and XCTU

How to set up an XBee using your computer, the X-CTU software, and an XBee Explorer interface board.

Getting Started with Electroluminescent (EL) Wire

This guide will help you get started with electroluminescent (EL) wire, tape, panel, chasing wire, and bendable wire to let your project glow!

EL Sequencer/Escudo Dos Hookup Guide

A basic guide to getting started with the SparkFun EL Sequencer and Escudo Dos to control electroluminescence (EL) wire, panels, and strips.

Additionally, this project builds upon the following tutorials.

Wireless Glove Controller

Build a wireless glove controller with Arduinos to trigger an LED using XBees!

EL Wire Hoodie

In this tutorial, we will sew standard electroluminescent (EL) wire to a hoodie.

EL Wire Pants

In this tutorial, we will sew standard electroluminescent (EL) wire to a pair of pants.

How to Make a Custom EL Wire Extension Cable

In this tutorial, we will make a custom EL Wire extension cable as an alternative to splicing wire.

Modifying Your EL Wire Inverter

In this tutorial, we will modify the 12V EL wire inverter to power the EL Sequencer/EL Escudo Dos off a single power supply.

Understanding Your Circuit

Glove Controller

If you have not already, make sure to check out this tutorial on making a wireless glove controller.

Wireless Glove Controller

April 24, 2019

Build a wireless glove controller with Arduinos to trigger an LED using XBees!

The XBee configuration and circuit used in the tutorial is the same as the one used to control each of the EL Sequencers.

Wireless GLove Glove Controller

Remote EL Sequencers

Each dancer has a remote EL Sequencer attached to their suit. If you have not already, make sure to check out the following tutorials to controlling each channel of the EL Sequencer, modify your inverter, and to make your own simple EL Wire suit.

EL Sequencer/Escudo Dos Hookup Guide

A basic guide to getting started with the SparkFun EL Sequencer and Escudo Dos to control electroluminescence (EL) wire, panels, and strips.

EL Wire Hoodie

In this tutorial, we will sew standard electroluminescent (EL) wire to a hoodie.

EL Wire Pants

In this tutorial, we will sew standard electroluminescent (EL) wire to a pair of pants.

How to Make a Custom EL Wire Extension Cable

In this tutorial, we will make a custom EL Wire extension cable as an alternative to splicing wire.

Modifying Your EL Wire Inverter

In this tutorial, we will modify the 12V EL wire inverter to power the EL Sequencer/EL Escudo Dos off a single power supply.

Since the EL Sequencer was using the 12V inverter, a solder jumper was added to SJ1. A 9V battery was as sufficient to power the "12V" inverter, XBee, and EL Sequencer. For simplicity, each dancer had one 3M EL Wire attached to the hoodie and and another 3M for the pants. The only difference was the connection in the EL Wire channel. Each student was paired together to have the same two channels.

Full

Here's a quick top view of the wireless controller and each remote EL Sequencer.

alt text

Securing the Electronics

For simplicity, a SparkFun cardboard box was chosen. While it was bulky and not the most comfortable, it was sufficient for the project to hold, protect, and secure the electronics. Using a cardboard box also made it easy to quickly prototype the enclosure.

Two rectangular square holes were cut on the side facing the dancer to easily connect/disconnect the power with the 9V battery. Along the length of a box, holes were cut for easy access to the inverter's switch and all channels of the EL Sequencer. Additional slots on the underside of the enclosure (facing the dancer) were cut to attach strips of elastic to easily remove the enclosure. A screw driver was used to poke holes for each of the EL Sequencer's mounting holes and standoffs. Electrical tape was used to hold down the inverter, 9V battery, and extension cables against the box. Each enclosure was then labeled for each XBee node and dancer.

alt text

alt text

Configuring XBees

To wirelessly control the suits, I decided to use the XBee Series 1 modules. If you have not already, check out the Starting with XCTU section under Exploring XBees and XCTU to configure your XBees.

Exploring XBees and XCTU

March 12, 2015

How to set up an XBee using your computer, the X-CTU software, and an XBee Explorer interface board.

The CH, ID, and DH were set to the same values for all the XBee modules. For the broadcasting XBee (i.e. your controller), the DL was set to FFFF. The receiving XBees on each of the dancers point are set to the MY address of the broadcasting XBee. Each of the XBees had a unique MY address.

SettingAcronymTx XBee Node 1
(Glove Controller)
Rx XBee Node 2
(Dancer 1)
Rx XBee Node 3
(Dancer 2)
Rx XBee Node 4
(Dancer 3)
Rx XBee Node 5
(Dancer 4)
Rx XBee Node 6
(Dancer 5)
Rx XBee Node 7
(Dancer 6)
Rx XBee Node 8
(Dancer 7)
ChannelCHCCCCCCCC
PAN IDID33333333333333333333333333333333
Destination Address HighDH00000000
Destination Address LowDLFFFF1111111
16-bit Source AddressMY12345678

Hardware Hookup

After following the circuit diagrams and enclosure for each dancer, you would simply need to attach the enclosure to the dancer's left hip and leg. If you were following along, the EL wire's connectors from the hoodie and pants should be on the left side of the dancer so that it would be as close to the enclosure as possible. Each dancer's body was different so custom extension cables were used to easily connect.

How to Make a Custom EL Wire Extension Cable

In this tutorial, we will make a custom EL Wire extension cable as an alternative to splicing wire.

Basic Example Code

For a sanity check when I started writing the code, I had the code turn off two channels to ensure that the code was receiving a character. To follow along, check out the GitHub repository for the project here:

Transmitting Glove Controller

You'll need to upload code to send characters out to the EL Sequencers. With the XBee Series 1 configured to broadcast, you would simply send a character out using a UART. In this case, the glove that was built used software serial pins. If the send button is pressed, a character will be broadcasted out. You'll notice that there is additional code to prevent the controller from sending out a character when the button is constantly being pressed down and for debouncing. This code is the simplest in terms of controlling all the channels.

If you have not already, unzip the GitHub repo and open the example code called XBee_ControllerV1.ino. The path of the example code will probably look similar to: ...\Wireless_Controlled_EL_Dance_Suit\Arduino\XBee_Controller\XBee_ControllerV1. You can also copy the code below and paste it into the Arduino IDE. Select the board (in this case the Arduino/Genuino Uno) and COM port that the board enumerated to. Make sure the switch is flipped to the DLINE before hitting the upload button.

language:c
/*******************************************************************
XBee_ELSequencer_ControllerV1.ino
Modified by Ho Yun Bobby Chan @  SparkFun Electronics May 10th, 2017

Taken from SparkFun XBee EL Sequencer Controller Example
Ho Yun Bobby Chan @ SparkFun Electronics June 20, 2014
Updated by Toni Klopfenstein @ SparkFun Electronics April, 2015
https://github.com/sparkfun/EL_Sequencer

Description:
This is a basic test of the wireless controller to control an EL Sequencer.
The wireless controller consists of an RedBoard Programmed with Arduino, XBee Shield,
XBee Series 1 transceiver, and LED Push Button. The EL Sequencer
uses an EL wire, 12V EL inverter, a 9V wall wart, 9V adapter, XBee female sockets soldered,
battery, and a XBee Series 1 transceiver. An XBee Series 2
can be used but the throughput of the Series 1 is much higher. To
reduce latency, I recommend using the XBee Series 1. The basic
configuration of the XBee module with point-to-point configuratin is
based on Digi's Example tutorial
=> http://examples.digi.com/get-started/basic-xbee-802-15-4-chat/ .
Page 5 of the tutorial shows you how to broadcast with
point-to-multipoint configuration so that multiple EL Sequencers
can be controlled.

Connect the XBee Shield to the Arduino with the switch flipped to the
software serial side labelled "DLINE".

By pushing the button, a character is sent from a remote microcontroller.
The corresponding EL Sequencer will receive the character and control
the EL component on a channel that is associated with that character.
A LED push button was used but not necessary for this to operate. A
normal momentary push button can be used.

Connect momentary LED tactile push buttons to Arduino:
     C = pin 13, the cathode (+) of the LED
     A = GND, the anode (-) of the LED
     B1 = GND
     B2 = pin 8

Using a RedBoard Programmed with Arduino, the XBee transceiver is connected to the
Software Serial pins. By pushing the button, the Arduino will
send one character through the XBee. Logic is used to control
how many characters are sent with the push button. The Arduino
will not send another character until the button is pressed again.

Note: This section of the code can be optimized. As the user is not
pressing down on the button, logic can be added so that the XBee is
not continuously sending serial characters to the receiving
EL Sequencer when idle.

Development environment specifics:
Arduino 1.6.5

This code is beerware; if you see me (or any other SparkFun employee) at the local,
and you've found our code helpful, please buy us a round!
Distributed as-is; no warranty is given.
**************************************************************************/

#include <SoftwareSerial.h>

SoftwareSerial xbee(2, 3); //Rx = 2, Tx = 3

//Declare variables and pin definitions

//Send
const int button1Pin = 8; //push button
const int ledPin1 = 13;  //LED on the push button
//variables to check for button1 state
boolean prev_button1State = false;
boolean current_button1State = false;

/*******************Setup Loop***************************/
void setup() {

  //Declare pin modes
  pinMode(button1Pin, INPUT_PULLUP); //use internal pullup resistor with LED
  pinMode (ledPin1, OUTPUT);//LED to indicate when character has been sent

  //Declare serial connections for debugging
  Serial.begin(9600);
  Serial.println("Arduino started sending bytes via XBee");

  xbee.begin(9600);
  Serial.println("EL Sequencer Controller's XBee Ready to Communicate");
}

/*******************Main Loop***************************/
void loop() {
  //initialize variables to read buttons
  int button1State;

  button1State = digitalRead(button1Pin);
  /***button1state
   - LOW or 0 means pressed
   - HIGH or 1 means not pressed
   ****/

  //if button is pressed, it will be pulled low
  if (button1State == LOW) {
    digitalWrite(ledPin1, HIGH); //turn push button LED ON
    current_button1State = true; // button has been pressed once

    if (prev_button1State != current_button1State) //check to see if button is still being pressed
    {
      Serial.println("Button is pressed.");
      xbee.write("A");//Tell Sequencer to change to mode by sending a character
    }
    else {
      //do nothing because finger is still on button
    }
    prev_button1State = current_button1State;
  }

  //button has not been pressed, it will be high again
  else {
    current_button1State = false;
    digitalWrite(ledPin1, LOW); // turn push button LED OFF

    prev_button1State = current_button1State;
  }

}

Receiving EL Sequencer Blink Code

You'll also need to uploade code to receive the characters for each EL Sequencer. You will need another UART to connect to the XBee Series 1 configured to receive characters from the broadcasting XBee. In this case, the EL Sequencer was designed to connect the ATmega328P's hardware UART to the XBee Series 1's UART. Therefore, the Serial was used instead of SoftwareSerial.

Open the example code called XBee_ELSequencerV1.ino. The path of the example code will probably look similar to: ...\Wireless_Controlled_EL_Dance_Suit\Arduino\XBee_ELSequencer\XBee_ELSequencerV1. You can also copy the code below and paste it into the Arduino IDE. Select the board (in this case the Arduino Pro or Pro Mini, ATmega328P (3.3V, 8MHz) but it can also be LilyPad Arduino) and COM port that the USB-to-Serial Converter enumerated to. Hit the upload button.

language:c
    /**********************************************************************
XBee_ELSequencerV1.ino
Created by Ho Yun Bobby Chan @  SparkFun Electronics May 10th, 2017

 * Taken from SparkFun XBee EL Sequencer Demo Sketch
 * Ho Yun Bobby Chan @ SparkFun Electronics June 20, 2014
 * Updated by Toni Klopfenstein @ SparkFun Electronics April, 2015
 * https://github.com/sparkfun/EL_Sequencer
 *
 * Description:
 * This is a basic test of the EL Sequencer to control an EL Sequencer
 * The wireless controller consists of an RedBoard Programmed with Arduino, XBee Shield,
 * XBee Series 1 transceiver, and LED Push Button. The EL Sequencer
 * uses an EL wire, 12V EL inverter, a 9V wall wart, 9V adapter, XBee female sockets soldered,
 * battery, and a XBee Series 1 transceiver. An XBee Series 2
 * can be used but the throughput of the Series 1 is much higher. To
 * reduce latency, I recommend using the XBee Series 1. The basic
 * configuration of the XBee module with point-to-point configuratin is
 * based on Digi's Example tutorial
 * => http://examples.digi.com/get-started/basic-xbee-802-15-4-chat/ .
 * Page 5 of the tutorial shows you how to broadcast with
 * point-to-multipoint configuration so that multiple EL Sequencers
 * can be controlled.
 *
 * By pushing the button, a character is sent from a remote microcontroller.
 * The corresponding EL Sequencer will receive the character and control
 * the EL component on a channel that is associated with that character.
 *
 * EL Sequencer uses the hardware UART of the Atmega328 for communication:
 * pin 0 = Rx
 * pin 1 = Tx
 *
 * Note: Make sure to remove the XBee Series 1 on the EL Sequencer when
 * uploading a new sketch file otherwise it will brick the XBee. You can
 * always use the next generation XCTU software to unbrick and recover
 * the transceiver.
 *
 * Development environment specifics:
 * Arduino 1.6.3
 *
 * This code is beerware; if you see me (or any other SparkFun employee) at the local,
 * and you've found our code helpful, please buy us a round!
 * Distributed as-is; no warranty is given.
 *
 ***********************************************************************/

//Declare character 'val'
char val;

//LED to check if the LED is initialized.
const int status_LED = 13;

/*******************Setup Loop***************************/
void setup() {
  Serial.begin(9600); //Begin Serial communication for debugging
  Serial.println("EL Sequencer's XBee is Ready to Receive Characters");

  val = 'A';// button pressed, therefore sending  letter A

  //Initialize pins
  pinMode(status_LED, OUTPUT); //Set pin mode as output for status LED
  pinMode(2, OUTPUT); //Set pin mode as output for Channel A
  pinMode(3, OUTPUT); //Set pin mode as output for Channel B
  pinMode(4, OUTPUT); //Set pin mode as output for Channel C
  pinMode(5, OUTPUT); //Set pin mode as output for Channel D
  pinMode(6, OUTPUT); //Set pin mode as output for Channel E
  pinMode(7, OUTPUT); //Set pin mode as output for Channel F
  pinMode(8, OUTPUT); //Set pin mode as output for Channel G
  pinMode(9, OUTPUT); //Set pin mode as output for Channel H

  //Status LED to see if the EL Sequencer is initializing  
  for (int i = 0; i < 3; i++) {
    digitalWrite(status_LED, HIGH);//set Status LED on
    delay(50);
    digitalWrite(status_LED, LOW); //set Status LED off
    delay(50);
  }

  digitalWrite(2, HIGH); //Channel A
  digitalWrite(3, HIGH); //Channel B

  digitalWrite(4, LOW); //Channel C
  digitalWrite(5, LOW); //Channel D

  digitalWrite(6, LOW); //Channel E
  digitalWrite(7, LOW); //Channel F

  digitalWrite(8, LOW); //Channel G
  digitalWrite(9, LOW); //Channel H

  delay(1000); //Wait 1 second
}

/*******************Main Loop***************************/
void loop() {

  //Check if XBee is receiving data from other XBee
  if (Serial.available()) {
    val = Serial.read();

    //Check to see if character sent is letter A
    if (val == 'A') {
      digitalWrite(status_LED, LOW); //turn ON Status LED
      digitalWrite(2, LOW); //Channel A
      digitalWrite(3, LOW); //Channel B
      delay(1000);
      Serial.println("Character Received");
    }

    else {
      //rewrote controller code to stop constantly sending Z
      //toggled pins outside of this nested condition statement
    }
  }

  digitalWrite(status_LED, HIGH); //turn OFF Status LED

  digitalWrite(2, HIGH); //Channel A
  delay(50);
  digitalWrite(3, HIGH); //Channel B
}

When finished, you should see the EL Sequencer blink two EL wires connected to the channels when pressing the send button. You probably won't see the EL too well in a well lit room. Below is an image of all the EL Wire hoodies angled with the side of each pair of ppants when the room lights are turned on.

alt text

Turning off the lights, you should see the channels blink clearly.

alt text

Custom Example Code

Listening and Adjusting w/ Audacity

To sync the animation with the music, I had to listen to the music several times just as if I was choreographing moves for a piece. You can also use Audacity or a DJ application visualize the length of the beats. For simplicity, I decided to have three sections over the course of a few counts where the EL Wire suits would animate with the music. With some experimenting and fine tuning the delays, I was able to sync the animation with the music.

Based on the way that I wrote the code with the XBees, I noticed that there were two limitations when syncing the animation with the music. The first limitation that I had to press the send button while also in the correct mode as I was moving. This was quite tricky. The second limitation was that once the sequence began, there was really no way to change the animation until the sequence was finished. Longer sequences and delays made it harder to control which was why I decided to have a three sections over a few counts. I would have had to tediously write more code and test to sync the animations with the music.

Glove Controller Example Code

If you have not already, unzip the GitHub repo and open the example code called XBee_ControllerV3.ino. V2 was a work in progress in case I accidentally broke the code. V3 was the final code that was used for the performance. The path of the example code will probably look similar to: ...\Wireless_Controlled_EL_Dance_Suit\Arduino\XBee_Controller\XBee_ControllerV3. You can also copy the code below and paste it into the Arduino IDE. Select the board (in this case the Arduino/Genuino Uno) and COM port that the board enumerated to. Make sure the switch is flipped to the DLINE before hitting the upload button.

language:c
/*******************************************************************
XBee_ELSequencer_ControllerV3.ino
Created by Ho Yun Bobby Chan @  SparkFun Electronics May 12th, 2017

Taken from SparkFun XBee EL Sequencer Controller
Ho Yun Bobby Chan @ SparkFun Electronics June 20, 2014
Updated by Toni Klopfenstein @ SparkFun Electronics April, 2015
https://github.com/sparkfun/EL_Sequencer

Description:
This is a sketch for the wireless controller used to control 7x EL dance suits.
The wireless controller consists of a RedBoard Programmed with Arduino,
XBee Shield, XBee Series 1 transceiver, diffused RGB Common Cathode LED,
Blue Clear LED, 330Ohm current limiting resistors, a button, 9V battery,
and a 9V adapter.

Each of the 7x EL dance suits contain an EL Sequencer, 2x EL Wires, a
12V EL inverter, XBee female sockets soldered, a 9V battery, 9V adapter,
and a XBee Series 1 transceiver.  An XBee Series 2 can be used but the throughput
of the Series 1 is much higher. To reduce latency, I recommend using the XBee
Series 1. The basic configuration of the XBee module with point-to-point configuratin is
based on Digi's Example tutorial => https://www.digi.com/blog/xbee/basic-xbee-802-15-4-chat/.
page 5 of the tutorial shows you how to broadcast with
point-to-multipoint configuration so that multiple EL Sequencers
can be controlled.

Connect the XBee Shield to the Arduino with the switch flipped to the
software serial side labeled "DLINE".

By pushing the button, a character is sent from a remote microcontroller.
The corresponding EL Sequencer will receive the character and control
the EL component on a channel that is associated with that character.

Using a RedBoard programmed with Arduino, the XBee transceiver is connected to the
Software Serial pins. By pushing the button, the Arduino will
send one character through the XBee. Logic is used to control
how many characters are sent with the push button. The Arduino
will not send another character until the button is pressed again.

Note: This section of the code can be optimized. As the user is not
pressing down on the button, logic can be added so that the XBee is
not continuously sending serial characters to the receiving
EL Sequencer when idle.

Development environment specifics:
Arduino 1.6.5

This code is beerware; if you see me (or any other SparkFun employee) at the local,
and you've found our code helpful, please buy us a round!
Distributed as-is; no warranty is given.
**************************************************************************/

#include <SoftwareSerial.h>

SoftwareSerial xbee(2, 3); //Rx = 2, Tx = 3

//Declare variables and pin definitions

char send_CHAR = 'A'; //default send character

int pattern = 0; //pattern that we are going to send

//SEND Button
const int button1Pin = 4; //push button
const int ledPin1 = 13;  //LED to indicate when a character has been sent
//variables to check for button1 state
boolean prev_button1State = false;
boolean current_button1State = false;

//LED Status Indicator
int ledR = 5; //hardware PWM
int ledG = 6; //hardware PWM
int ledB = 9; //hardware PWM

//UP Button
const int button2Pin = 11; //push button to move ahead to next sequence
//variables to check for button2 state
boolean prev_button2State = false;
boolean current_button2State = false;

//DOWN Button
const int button3Pin = 12;//push button to move back a sequence
//variables to check for button3 state
boolean prev_button3State = false;
boolean current_button3State = false;

/*******************Setup Loop***************************/
void setup() {
  //Declare buttons and status LEDs

  pinMode (ledPin1, OUTPUT); //send LED
  pinMode(button1Pin, INPUT_PULLUP); //SEND button, use internal pullup resistor

  // initialize the digital pins as an output for status LED
  pinMode(ledR, OUTPUT);
  pinMode(ledG, OUTPUT);
  pinMode(ledB, OUTPUT);
  pinMode(button2Pin, INPUT_PULLUP); //UP button, use internal pullup resistor
  pinMode(button3Pin, INPUT_PULLUP); //DOWN button, use internal pullup resistor

  //Declare serial connections for debugging
  Serial.begin(9600);
  Serial.println("Arduino started sending bytes via XBee");

  //Declare software serial conenction with XBee
  xbee.begin(9600);
  Serial.println("EL Sequencer Controller's XBee Ready to Communicate");

  sequenceTest();//visually initialization to see that we have finished initializing
}

/*******************Main Loop***************************/
void loop() {
  //initialize variables to read buttons
  int button1State;
  int button2State;
  int button3State;

  button1State = digitalRead(button1Pin);
  button2State = digitalRead(button2Pin);
  button3State = digitalRead(button3Pin);
  /*buttonXstate
   - LOW or 0 means pressed
   - HIGH or 1 means not pressed
   */

  //-----------Check If SENT Button Has Been Pressed----------
  //if SENT button is pressed, it will be pulled low
  if (button1State == LOW) {
    digitalWrite(ledPin1, HIGH); //turn LED indicating if a character has been sent ON
    current_button1State = true; // button has been pressed once

    if (prev_button1State != current_button1State) //check to see if button is still being pressed
    {
      Serial.println("Button is pressed.");
      xbee.write(send_CHAR);//Tell Sequencer to change mode
    }
    else {
      //do nothing because finger is still on button
    }
    prev_button1State = current_button1State;
  }

  //sent button has not been pressed, it will be high again
  else {
    current_button1State = false;
    digitalWrite(ledPin1, LOW); // turn push button LED OFF

    prev_button1State = current_button1State;
  }//-----------End Check for SENT Button----------

  //-----------Check If UP Button Has Been Pressed----------
  if (button2State == LOW) {
    current_button2State = true; //UP button has been pressed once

    if (prev_button2State != current_button2State) { //check to see if button is still being pressed
      pattern = pattern + 1; //change LED pattern after button has been pressed
      if (pattern < 0 || pattern > 5) {
        //reset pattern
        pattern = 0;
      }

    }
    else { //do nothing because finger is still on button
    }
    prev_button2State = current_button2State;
  }
  //UP button has not been pressed, it will be high
  else {
    current_button2State = false;
    prev_button2State = current_button2State;
  }//-----------End Check for Up Button----------

  //-----------Check If DOWN Button Has Been Pressed----------
  if (button3State == LOW) {
    current_button3State = true; //button has been pressed once

    if (prev_button3State != current_button3State) { //check to see if button is still being pressed
      pattern = pattern - 1; //change LED pattern after button has been pressed
      if (pattern < 0 || pattern > 5) {
        //reset pattern
        pattern = 5;
      }
    }
    else { //do nothing because finger is still on button
    }
    prev_button3State = current_button3State;
  }
  //button has not been pressed, it will be high
  else {
    current_button3State = false;
    prev_button3State = current_button3State;
  }//-----------End Check for DOWN Button----------

  delay(50);

  //save send character into variable depending on button press and change status LED
  switch (pattern) {
    case 1:
      greenON();
      send_CHAR = 'B';
      break;
    case 2:
      blueON();
      send_CHAR = 'C';
      break;
    case 3:
      allOFF();//blink status LED
      delay(50);
      blueON();
      delay(50);
      send_CHAR = 'D';
      break;
    case 4:
      blueON();
      send_CHAR = 'E';
      break;
    default:
      redON();
      send_CHAR = 'A';
      break;
  }

}//end loop


/*Below are the modular functions for changing the color of a RGB LED.
 This will be used to help identify what mode we are currently in:
 ROYGBIV
 Note: A 9V battery is not able to fully power all three LEDs simultaneously...
 MODE
 1.) red              = red[HIGH]
 .) tangerine orange = red[HIGH]+ green[50]
 2.) yellow           = red[HIGH]+ green[HIGH]
 3.) green            =          + green[HIGH]
 4.) clear blue       =          + green[HIGH] + blue[HIGH]
 5.) blue             =                        + blue[HIGH]
 6.) magenta          = red[HIGH]+             + blue[HIGH]
 .) white            = red[HIGH]+ green[HIGH] + blue[HIGH]
 */

void allOFF() {
  analogWrite(ledR, 0);
  analogWrite(ledG, 0);
  analogWrite(ledB, 0);
}

void redON() { //Seq 1
  analogWrite(ledR, 255);
  analogWrite(ledG, 0);
  analogWrite(ledB, 0);
}

void greenON() { //Seq 2
  analogWrite(ledR, 0);
  analogWrite(ledG, 255);
  analogWrite(ledB, 0);
}

void blueON() { //Seq 3
  analogWrite(ledR, 0);
  analogWrite(ledG, 0);
  analogWrite(ledB, 255);
}

void yellowON() {
  analogWrite(ledR, 255);
  analogWrite(ledG, 255);
  analogWrite(ledB, 0);
}

void clearblueON() { 
  analogWrite(ledR, 0);
  analogWrite(ledG, 255);
  analogWrite(ledB, 255);
}

void magentaON() {
  analogWrite(ledR, 255);
  analogWrite(ledG, 0);
  analogWrite(ledB, 255);
}

void sequenceTest() {
  redON();
  delay(50);
  allOFF();
  delay(50);

  yellowON();
  delay(50);
  allOFF();
  delay(50);

  greenON();
  delay(50);
  allOFF();
  delay(50);

  clearblueON();
  delay(50);
  allOFF();
  delay(50);

  blueON();
  delay(50);
  allOFF();
  delay(50);

  magentaON();
  delay(50);
  allOFF();
  delay(50);

  //whiteON();//white drains too much power from a 9V, commenting out.
  //delay(50);
  //allOFF();
  //delay(50);

}

EL Sequencers Example Code

Open the example code called XBee_ELSequencerV3.ino. The path of the example code will probably look similar to: ...\Wireless_Controlled_EL_Dance_Suit\Arduino\XBee_ELSequencer\XBee_ELSequencerV3. You can also copy the code below and paste it into the Arduino IDE. Select the board (in this case the Arduino Pro or Pro Mini, ATmega328P (3.3V, 8MHz) but it can also be LilyPad Arduino) and COM port that the USB-to-Serial Converter enumerated to. Hit the upload button.

language:c
/**********************************************************************
  XBee_ELSequencerV3.ino
  Modified by Ho Yun Bobby Chan @  SparkFun Electronics May 12th, 2017

   Taken from the SparkFun XBee EL Sequencer Demo Sketch
   Ho Yun Bobby Chan @ SparkFun Electronics June 20, 2014
   Updated by Toni Klopfenstein @ SparkFun Electronics April, 2015
   https://github.com/sparkfun/EL_Sequencer

   Description:
   This is a modified sketch for the EL Sequencer with a wireless controller.
   The wireless controller consists of a RedBoard Programmed with Arduino,
   XBee Explorer, XBee Series 1 transceiver, diffused RGB Common Cathode LED,
   Blue Clear LED, 330Ohm current limiting resistors, 3x buttons,
   a 9V battery, and a 9V adapter.

   Each of the 7x EL dance suits contain an EL Sequencer, 2x EL Wires, a
   12V EL inverter, XBee female sockets soldered, a 9V battery, 9V adapter,
   and a XBee Series 1 transceiver.  An XBee Series 2 can be used but the throughput
   of the Series 1 is much higher. To reduce latency, I recommend using the XBee
   Series 1. The basic configuration of the XBee module with point-to-point configuratin is
   based on Digi's Example tutorial => https://www.digi.com/blog/xbee/basic-xbee-802-15-4-chat/.
   Page 5 of the tutorial shows you how to broadcast with
   point-to-multipoint configuration so that multiple EL Sequencers
   can be controlled.

   By pushing the button, a character is sent from a remote microcontroller.
   The corresponding EL Sequencer will receive the character and control
   the EL component on a channel that is associated with that character.

   EL Sequencer uses the hardware UART of the Atmega328 for communication:
   pin 0 = Rx
   pin 1 = Tx

   Note: Make sure to remove the XBee Series 1 on the EL Sequencer when
   uploading a new sketch file otherwise it will brick the XBee. You can
   always use the next generation XCTU software to unbrick and recover
   the transceiver.

   Development environment specifics:
   Arduino 1.6.5

   This code is beerware; if you see me (or any other SparkFun employee) at the local,
   and you've found our code helpful, please buy us a round!
   Distributed as-is; no warranty is given.

 ***********************************************************************/

char val; //Declare character 'val' when Slave XBee receives a character
char temp_delete; //used to delete buffer and prevent false triggers when Master XBee sends character more than once

//LED to check if the LED is initialized.
const int status_LED = 13;

int counter = 0; //adding counter to prevent false triggers for a small period of time
boolean XBee_sent = false; //flag to see if we have received any characters after a certain period of time

/*******************Setup Loop***************************/
void setup() {
  Serial.begin(9600); //Begin Serial communication and debugging
  Serial.println("EL Sequencer's XBee is Ready to Receive Characters");

  val = 'A'; //save as default character

  //Initialize pins
  pinMode(status_LED, OUTPUT); //Set pin mode as output for status LED
  pinMode(2, OUTPUT); //Set pin mode as output for Channel A
  pinMode(3, OUTPUT); //Set pin mode as output for Channel B
  pinMode(4, OUTPUT); //Set pin mode as output for Channel C
  pinMode(5, OUTPUT); //Set pin mode as output for Channel D
  pinMode(6, OUTPUT); //Set pin mode as output for Channel E
  pinMode(7, OUTPUT); //Set pin mode as output for Channel F
  pinMode(8, OUTPUT); //Set pin mode as output for Channel G
  pinMode(9, OUTPUT); //Set pin mode as output for Channel H

  //Status LED to see if the EL Sequencer is initializing
  for (int i = 0; i < 3; ++i) {
    digitalWrite(status_LED, HIGH);//set Status LED on
    delay(50);
    digitalWrite(status_LED, LOW); //set Status LED off
    delay(50);
  }

  all_ON();//turn on all EL channels

  delay(100); //Wait a little
}

/*******************Main Loop***************************/
void loop() {
  if (XBee_sent == false) {
    //we have not received a character yet after a certain period of time, we can see if the Master XBee has sent any characters
    if (Serial.available()) {
      //check if slave XBee is receiving data from master XBee
      val = Serial.read();//save whatever is in the buffer to the variable
      counter = 0;        //set counter to 0 to prevent false button presses
      XBee_sent = true;   //we have received a character

      //if debugging, we can see what character is recevied
      Serial.print("Character Received = ");
      Serial.println(val);

      //Check to see if character sent is any of the recognized characters and jump to the sequence
      if (val == 'A') {
        Seq_0();
      }
      else if (val == 'B') {
        Seq_1();
      }
      else if (val == 'C') {
        Seq_2();
      }
      else if (val == 'D') {
        Seq_3();
      }
      else if (val == 'E') {
        Seq_4();
      }

    }//end buffer check
  }//end check to see if we have not received a character after a certain period of time

  if (counter >= 10) {//this section of code will reset the flag "XBee_Sent" so we can begin listening for characters again
    if (XBee_sent == true) {
      Serial.println("Counter = 10, we are ready to receive characters again");
    }
    XBee_sent = false;
  }

  if (XBee_sent == true) {//this section of code is used as a delay to prevent false button presses
    counter = ++counter;//keep adding until we reach 10, then we can reset flag and begin receiving again

    //if connected to a computer, check to see the duration of the delay
    Serial.print("Counter = ");
    Serial.println(counter);

    temp_delete = Serial.read();//try to clear false triggers in buffer provided by Master XBee until counter resets
  }

}//end loop()

//**********MODULAR SEQUENCED FUNCTIONS**********

void all_ON() {
  //this function is used to turn all channels ON
  //Bobby
  digitalWrite(2, HIGH); //Channel A, hoodie
  digitalWrite(3, HIGH); //Channel B, pants
  //Antuan, Kaden
  digitalWrite(4, HIGH); //Channel C, hoodie
  digitalWrite(5, HIGH); //Channel D, pants
  //Mireku, Talon
  digitalWrite(6, HIGH); //Channel E, hoodie
  digitalWrite(7, HIGH); //Channel F, pants
  //Madi, Henry
  digitalWrite(8, HIGH); //Channel G, hoodie
  digitalWrite(9, HIGH); //Channel H, pants
}


void all_OFF() {
  //this function is used to turn all channels OFF
  //Bobby
  digitalWrite(2, LOW); //Channel A, hoodie
  digitalWrite(3, LOW); //Channel B, pants
  //Antuan, Kaden
  digitalWrite(4, LOW); //Channel C, hoodie
  digitalWrite(5, LOW); //Channel D, pants
  //Mireku, Talon
  digitalWrite(6, LOW); //Channel E, hoodie
  digitalWrite(7, LOW); //Channel F, pants
  //Madi, Henry
  digitalWrite(8, LOW); //Channel G, hoodie
  digitalWrite(9, LOW); //Channel H, pants
}

void Seq_0() {
  //function used to flash Bobby's suit with the beat at 5 seconds into the edited C2C track

  digitalWrite(status_LED, LOW); //turn OFF Status LED
  digitalWrite(2, LOW); //Channel A
  digitalWrite(3, LOW); //Channel B
  delay(500);

  digitalWrite(status_LED, HIGH); //turn on Status LED

  digitalWrite(2, HIGH); //Channel A
  delay(500);
  digitalWrite(3, HIGH); //Channel B
  delay(500);
  digitalWrite(2, LOW); //Channel A
  digitalWrite(3, LOW); //Channel B
  delay(500);
  digitalWrite(2, HIGH); //Channel A
  digitalWrite(3, HIGH); //Channel B

  delay(500);
  digitalWrite(2, LOW); //Channel A
  digitalWrite(3, LOW); //Channel B
  delay(250);
  digitalWrite(2, HIGH); //Channel A
  digitalWrite(3, HIGH); //Channel B

  delay(500);

  digitalWrite(2, LOW); //Channel A
  digitalWrite(3, LOW); //Channel B
  delay(500);
  digitalWrite(2, HIGH); //Channel A
  digitalWrite(3, HIGH); //Channel B

  delay(250);
  digitalWrite(2, LOW); //Channel A
  digitalWrite(3, LOW); //Channel B
  delay(250);
  digitalWrite(2, HIGH); //Channel A
  digitalWrite(3, HIGH); //Channel B
  delay(250);
  digitalWrite(2, LOW); //Channel A
  digitalWrite(3, LOW); //Channel B
  delay(250);
  digitalWrite(2, HIGH); //Channel A
  digitalWrite(3, HIGH); //Channel B
  delay(250);
  digitalWrite(2, LOW); //Channel A
  digitalWrite(3, LOW); //Channel B
  delay(250);
  digitalWrite(2, HIGH); //Channel A
  digitalWrite(3, HIGH); //Channel B
  delay(250);
  digitalWrite(2, LOW); //Channel A
  digitalWrite(3, LOW); //Channel B
  delay(250);
  digitalWrite(2, HIGH); //Channel A
  digitalWrite(3, HIGH); //Channel B

  all_ON();//turn everything back on
}

void Seq_1() {
  //function used to toggle the channels back & forth and hit the beat at 45 seconds into the edited C2C track

  for (int i = 0; i < 8; ++i) {
    //Bobby
    digitalWrite(2, HIGH); //Channel A, hoodie
    digitalWrite(3, LOW); //Channel B, pants
    //Antuan, Kaden
    digitalWrite(4, HIGH); //Channel C, hoodie
    digitalWrite(5, LOW); //Channel D, pants
    //Mireku, Talon
    digitalWrite(6, LOW); //Channel E, hoodie
    digitalWrite(7, HIGH); //Channel F, pants
    //Madi, Henry
    digitalWrite(8, LOW); //Channel G, hoodie
    digitalWrite(9, HIGH); //Channel H, pants
    delay(250);

    //Bobby
    digitalWrite(2, LOW); //Channel A, hoodie
    digitalWrite(3, HIGH); //Channel B, pants
    //Antuan, Kaden
    digitalWrite(4, LOW); //Channel C, hoodie
    digitalWrite(5, HIGH); //Channel D, pants
    //Mireku, Talon
    digitalWrite(6, HIGH); //Channel E, hoodie
    digitalWrite(7, LOW); //Channel F, pants
    //Madi, Henry
    digitalWrite(8, HIGH); //Channel G, hoodie
    digitalWrite(9, LOW); //Channel H, pants
    delay(250);
  }

  all_ON();
  delay(750);
  all_OFF();
  delay(100);
  all_ON();

}

void Seq_2() {
  //this function turns all the channels ON just in case something happens

  all_ON();
}

void Seq_3() {
  //function used to as a ripple effect and turn on the channels to the beat scratch at 2 minutes 10 seconds into the edited C2C track

  all_OFF();
  delay(100);
  //Madi, Henry
  digitalWrite(8, HIGH); //Channel G, hoodie
  digitalWrite(9, LOW); //Channel H, pants
  delay(100);
  //Antuan, Kaden
  digitalWrite(4, HIGH); //Channel C, hoodie
  digitalWrite(5, LOW); //Channel D, pants
  delay(100);
  //Bobby
  digitalWrite(2, HIGH); //Channel A, hoodie
  digitalWrite(3, LOW); //Channel B, pants

  //Mireku, Talon
  digitalWrite(6, HIGH); //Channel E, hoodie
  digitalWrite(7, LOW); //Channel F, pants
  delay(100);

  //Madi, Henry
  digitalWrite(8, HIGH); //Channel G, hoodie
  digitalWrite(9, HIGH); //Channel H, pants
  delay(100);
  //Antuan, Kaden
  digitalWrite(4, HIGH); //Channel C, hoodie
  digitalWrite(5, HIGH); //Channel D, pants
  delay(100);
  //Bobby
  digitalWrite(2, HIGH); //Channel A, hoodie
  digitalWrite(3, HIGH); //Channel B, pants

  //Mireku, Talon
  digitalWrite(6, HIGH); //Channel E, hoodie
  digitalWrite(7, HIGH); //Channel F, pants
  delay(100);

}

void Seq_4() {
  //this function turns all the channels ON just in case something happens

  all_ON();
}

By hitting the send button, the first sequence should animate to the beat from the beginning. By toggling the next mode, the LED should change to indicate that the next mode is ready to be sent. By hitting the send button again, you should see the EL wire attached to the hoodie and pants switching on and off as shown in the GIF below. I had my students in a certain formation when the sequence started.

alt text

By toggling the mode again and hitting the button again, the EL wire individually lit up on the hoodies and then the pants as shown in the GIF below.

alt text

Template Example Code

While the code was useful for my application, you'll need to write your own code to sync the effects with the music. I made a quick template for an EL Sequencer with a few simple modes to control two channels. The modes will sequence the channels to turn them all on, blink (off-on), turn off, alternate, ripple, and stack (i.e. light up each channel one at a time).

Glove Controller Example Code

The code for the glove controller is the same but with one added condition statement. Feel free to add more depending on your application. Open the example code called XBee_ControllerTemplate.ino. V2 was a work in progress in case I accidentally broke the code. V3 was the final code that was used for the performance. The path of the example code will probably look similar to: ...\Wireless_Controlled_EL_Dance_Suit\Arduino\XBee_Controller\XBee_ControllerTEMPLATE. You can also copy the code below and paste it into the Arduino IDE. Select the board (in this case the Arduino/Genuino Uno) and COM port that the board enumerated to. Make sure the switch is flipped to the DLINE before hitting the upload button.

language:c
/*******************************************************************
XBee_ELSequencer_ControllerTEMPLATE.ino
Created by Ho Yun Bobby Chan @  SparkFun Electronics May 12th, 2017

Taken from SparkFun XBee EL Sequencer Controller
Ho Yun Bobby Chan @ SparkFun Electronics June 20, 2014
Updated by Toni Klopfenstein @ SparkFun Electronics April, 2015
https://github.com/sparkfun/EL_Sequencer

Description:
This is a sketch for the wireless controller used to control 7x EL dance suits.
The wireless controller consists of a RedBoard Programmed with Arduino,
XBee Shield, XBee Series 1 transceiver, diffused RGB Common Cathode LED,
Blue Clear LED, 330Ohm current limiting resistors, a button, 9V battery,
and a 9V adapter.

Each of the 7x EL dance suits contain an EL Sequencer, 2x EL Wires, a
12V EL inverter, XBee female sockets soldered, a 9V battery, 9V adapter,
and a XBee Series 1 transceiver.  An XBee Series 2 can be used but the throughput
of the Series 1 is much higher. To reduce latency, I recommend using the XBee
Series 1. The basic configuration of the XBee module with point-to-point configuratin is
based on Digi's Example tutorial => https://www.digi.com/blog/xbee/basic-xbee-802-15-4-chat/.
page 5 of the tutorial shows you how to broadcast with
point-to-multipoint configuration so that multiple EL Sequencers
can be controlled.

Connect the XBee Shield to the Arduino with the switch flipped to the
software serial side labeled "DLINE".

By pushing the button, a character is sent from a remote microcontroller.
The corresponding EL Sequencer will receive the character and control
the EL component on a channel that is associated with that character.

Using a RedBoard programmed with Arduino, the XBee transceiver is connected to the
Software Serial pins. By pushing the button, the Arduino will
send one character through the XBee. Logic is used to control
how many characters are sent with the push button. The Arduino
will not send another character until the button is pressed again.

Note: This section of the code can be optimized. As the user is not
pressing down on the button, logic can be added so that the XBee is
not continuously sending serial characters to the receiving
EL Sequencer when idle.

Development environment specifics:
Arduino 1.6.5

This code is beerware; if you see me (or any other SparkFun employee) at the local,
and you've found our code helpful, please buy us a round!
Distributed as-is; no warranty is given.
**************************************************************************/

#include <SoftwareSerial.h>

SoftwareSerial xbee(2, 3); //Rx = 2, Tx = 3

//Declare variables and pin definitions

char send_CHAR = 'A'; //default send character

int pattern = 0; //pattern that we are going to send

//SEND Button
const int button1Pin = 4; //push button
const int ledPin1 = 13;  //LED to indicate when a character has been sent
//variables to check for button1 state
boolean prev_button1State = false;
boolean current_button1State = false;

//LED Status Indicator
int ledR = 5; //hardware PWM
int ledG = 6; //hardware PWM
int ledB = 9; //hardware PWM

//UP Button
const int button2Pin = 11; //push button to move ahead to next sequence
//variables to check for button2 state
boolean prev_button2State = false;
boolean current_button2State = false;

//DOWN Button
const int button3Pin = 12;//push button to move back a sequence
//variables to check for button3 state
boolean prev_button3State = false;
boolean current_button3State = false;

/*******************Setup Loop***************************/
void setup() {
  //Declare buttons and status LEDs

  pinMode (ledPin1, OUTPUT); //send LED
  pinMode(button1Pin, INPUT_PULLUP); //SEND button, use internal pullup resistor

  // initialize the digital pins as an output for status LED
  pinMode(ledR, OUTPUT);
  pinMode(ledG, OUTPUT);
  pinMode(ledB, OUTPUT);
  pinMode(button2Pin, INPUT_PULLUP); //UP button, use internal pullup resistor
  pinMode(button3Pin, INPUT_PULLUP); //DOWN button, use internal pullup resistor

  //Declare serial connections for debugging
  Serial.begin(9600);
  Serial.println("Arduino started sending bytes via XBee");

  //Declare software serial conenction with XBee
  xbee.begin(9600);
  Serial.println("EL Sequencer Controller's XBee Ready to Communicate");

  sequenceTest();//visually initialization to see that we have finished initializing
}

/*******************Main Loop***************************/
void loop() {
  //initialize variables to read buttons
  int button1State;
  int button2State;
  int button3State;

  button1State = digitalRead(button1Pin);
  button2State = digitalRead(button2Pin);
  button3State = digitalRead(button3Pin);
  /*buttonXstate
   - LOW or 0 means pressed
   - HIGH or 1 means not pressed
   */

  //-----------Check If SENT Button Has Been Pressed----------
  //if SENT button is pressed, it will be pulled low
  if (button1State == LOW) {
    digitalWrite(ledPin1, HIGH); //turn LED indicating if a character has been sent ON
    current_button1State = true; // button has been pressed once

    if (prev_button1State != current_button1State) //check to see if button is still being pressed
    {
      Serial.println("Button is pressed.");
      xbee.write(send_CHAR);//Tell Sequencer to change mode
    }
    else {
      //do nothing because finger is still on button
    }
    prev_button1State = current_button1State;
  }

  //sent button has not been pressed, it will be high again
  else {
    current_button1State = false;
    digitalWrite(ledPin1, LOW); // turn push button LED OFF

    prev_button1State = current_button1State;
  }//-----------End Check for SENT Button----------

  //-----------Check If UP Button Has Been Pressed----------
  if (button2State == LOW) {
    current_button2State = true; //UP button has been pressed once

    if (prev_button2State != current_button2State) { //check to see if button is still being pressed
      pattern = pattern + 1; //change LED pattern after button has been pressed
      if (pattern < 0 || pattern > 5) {
        //reset pattern
        pattern = 0;
      }

    }
    else { //do nothing because finger is still on button
    }
    prev_button2State = current_button2State;
  }
  //UP button has not been pressed, it will be high
  else {
    current_button2State = false;
    prev_button2State = current_button2State;
  }//-----------End Check for Up Button----------

  //-----------Check If DOWN Button Has Been Pressed----------
  if (button3State == LOW) {
    current_button3State = true; //button has been pressed once

    if (prev_button3State != current_button3State) { //check to see if button is still being pressed
      pattern = pattern - 1; //change LED pattern after button has been pressed
      if (pattern < 0 || pattern > 5) {
        //reset pattern
        pattern = 5;
      }
    }
    else { //do nothing because finger is still on button
    }
    prev_button3State = current_button3State;
  }
  //button has not been pressed, it will be high
  else {
    current_button3State = false;
    prev_button3State = current_button3State;
  }//-----------End Check for DOWN Button----------

  delay(50);

  //save send character into variable depending on button press and change status LED
  switch (pattern) {
    case 1:
      greenON();
      send_CHAR = 'B';
      break;
    case 2:
      blueON();
      send_CHAR = 'C';
      break;
    case 3:
      allOFF();//blink status LED
      delay(50);
      blueON();
      delay(50);
      send_CHAR = 'D';
      break;
    case 4:
      allOFF();//blink status LED
      delay(50);
      greenON();
      delay(50);
      send_CHAR = 'E';
      break;
    default:
      redON();
      send_CHAR = 'A';
      break;
  }

}//end loop


/*Below are the modular functions for changing the color of a RGB LED.
 This will be used to help identify what mode we are currently in:
 ROYGBIV
 Note: A 9V battery is not able to fully power all three LEDs simultaneously...
 MODE
 1.) red              = red[HIGH]
 .) tangerine orange = red[HIGH]+ green[50]
 2.) yellow           = red[HIGH]+ green[HIGH]
 3.) green            =          + green[HIGH]
 4.) clear blue       =          + green[HIGH] + blue[HIGH]
 5.) blue             =                        + blue[HIGH]
 6.) magenta          = red[HIGH]+             + blue[HIGH]
 .) white            = red[HIGH]+ green[HIGH] + blue[HIGH]
 */

void allOFF() {
  analogWrite(ledR, 0);
  analogWrite(ledG, 0);
  analogWrite(ledB, 0);
}

void redON() { //Seq 1
  analogWrite(ledR, 255);
  analogWrite(ledG, 0);
  analogWrite(ledB, 0);
}

void greenON() { //Seq 2
  analogWrite(ledR, 0);
  analogWrite(ledG, 255);
  analogWrite(ledB, 0);
}

void blueON() { //Seq 3
  analogWrite(ledR, 0);
  analogWrite(ledG, 0);
  analogWrite(ledB, 255);
}

void yellowON() {
  analogWrite(ledR, 255);
  analogWrite(ledG, 255);
  analogWrite(ledB, 0);
}

void clearblueON() { 
  analogWrite(ledR, 0);
  analogWrite(ledG, 255);
  analogWrite(ledB, 255);
}

void magentaON() {
  analogWrite(ledR, 255);
  analogWrite(ledG, 0);
  analogWrite(ledB, 255);
}

void sequenceTest() {
  redON();
  delay(50);
  allOFF();
  delay(50);

  yellowON();
  delay(50);
  allOFF();
  delay(50);

  greenON();
  delay(50);
  allOFF();
  delay(50);

  clearblueON();
  delay(50);
  allOFF();
  delay(50);

  blueON();
  delay(50);
  allOFF();
  delay(50);

  magentaON();
  delay(50);
  allOFF();
  delay(50);

  //whiteON();//white drains too much power from a 9V, commenting out.
  //delay(50);
  //allOFF();
  //delay(50);

}

EL Sequencer Example Code

Open the example code called XBee_ELSequencertemplate.ino. The path of the example code will probably look similar to: ...\Wireless_Controlled_EL_Dance_Suit\Arduino\XBee_ELSequencer\XBee_ELSequencerTEMPLATE. You can also copy the code below and paste it into the Arduino IDE. Select the board (in this case the Arduino Pro or Pro Mini, ATmega328P (3.3V, 8MHz) but it can also be LilyPad Arduino) and COM port that the USB-to-Serial Converter enumerated to. Hit the upload button.

language:c
/**********************************************************************
  XBee_ELSequencerTEMPLATE.ino
  Modified by Ho Yun Bobby Chan @  SparkFun Electronics May 12th, 2017

   Taken from the SparkFun XBee EL Sequencer Demo Sketch
   Ho Yun Bobby Chan @ SparkFun Electronics June 20, 2014
   Updated by Toni Klopfenstein @ SparkFun Electronics April, 2015
   https://github.com/sparkfun/EL_Sequencer

   Description:
   This is a modified sketch for the EL Sequencer with a wireless controller.
   The wireless controller consists of a RedBoard Programmed with Arduino,
   XBee Explorer, XBee Series 1 transceiver, diffused RGB Common Cathode LED,
   Blue Clear LED, 330Ohm current limiting resistors, 3x buttons,
   a 9V battery, and a 9V adapter.

   Each of the 7x EL dance suits contain an EL Sequencer, 2x EL Wires, a
   12V EL inverter, XBee female sockets soldered, a 9V battery, 9V adapter,
   and a XBee Series 1 transceiver.  An XBee Series 2 can be used but the throughput
   of the Series 1 is much higher. To reduce latency, I recommend using the XBee
   Series 1. The basic configuration of the XBee module with point-to-point configuratin is
   based on Digi's Example tutorial => https://www.digi.com/blog/xbee/basic-xbee-802-15-4-chat/.
   Page 5 of the tutorial shows you how to broadcast with
   point-to-multipoint configuration so that multiple EL Sequencers
   can be controlled.

   By pushing the button, a character is sent from a remote microcontroller.
   The corresponding EL Sequencer will receive the character and control
   the EL component on a channel that is associated with that character.

   EL Sequencer uses the hardware UART of the Atmega328 for communication:
   pin 0 = Rx
   pin 1 = Tx

   Note: Make sure to remove the XBee Series 1 on the EL Sequencer when
   uploading a new sketch file otherwise it will brick the XBee. You can
   always use the next generation XCTU software to unbrick and recover
   the transceiver.

   Development environment specifics:
   Arduino 1.6.5

   This code is beerware; if you see me (or any other SparkFun employee) at the local,
   and you've found our code helpful, please buy us a round!
   Distributed as-is; no warranty is given.

 ***********************************************************************/

char val; //Declare character 'val' when Slave XBee receives a character
char temp_delete; //used to delete buffer and prevent false triggers when Master XBee sends character more than once

//LED to check if the LED is initialized.
const int status_LED = 13;

int counter = 0; //adding counter to prevent false triggers for a small period of time
boolean XBee_sent = false; //flag to see if we have received any characters after a certain period of time

/*******************Setup Loop***************************/
void setup() {
  Serial.begin(9600); //Begin Serial communication and debugging
  Serial.println("EL Sequencer's XBee is Ready to Receive Characters");

  val = 'A'; //save as default character

  //Initialize pins
  pinMode(status_LED, OUTPUT); //Set pin mode as output for status LED
  pinMode(2, OUTPUT); //Set pin mode as output for Channel A
  pinMode(3, OUTPUT); //Set pin mode as output for Channel B
  pinMode(4, OUTPUT); //Set pin mode as output for Channel C
  pinMode(5, OUTPUT); //Set pin mode as output for Channel D
  pinMode(6, OUTPUT); //Set pin mode as output for Channel E
  pinMode(7, OUTPUT); //Set pin mode as output for Channel F
  pinMode(8, OUTPUT); //Set pin mode as output for Channel G
  pinMode(9, OUTPUT); //Set pin mode as output for Channel H

  //Status LED to see if the EL Sequencer is initializing
  for (int i = 0; i < 3; ++i) {
    digitalWrite(status_LED, HIGH);//set Status LED on
    delay(50);
    digitalWrite(status_LED, LOW); //set Status LED off
    delay(50);
  }

  all_ON();//turn on all EL channels

  delay(100); //Wait a little
}

/*******************Main Loop***************************/
void loop() {
  if (XBee_sent == false) {
    //we have not received a character yet after a certain period of time, we can see if the Master XBee has sent any characters
    if (Serial.available()) {
      //check if slave XBee is receiving data from master XBee
      val = Serial.read();//save whatever is in the buffer to the variable
      counter = 0;        //set counter to 0 to prevent false button presses
      XBee_sent = true;   //we have received a character

      //if debugging, we can see what character is recevied
      Serial.print("Character Received = ");
      Serial.println(val);

      //Check to see if character sent is any of the recognized characters and jump to the sequence
      if (val == 'A') {
        Seq_0();
      }
      else if (val == 'B') {
        Seq_1();
      }
      else if (val == 'C') {
        Seq_2();
      }
      else if (val == 'D') {
        Seq_3();
      }
      else if (val == 'E') {
        Seq_4();
      }

    }//end buffer check
  }//end check to see if we have not received a character after a certain period of time

  if (counter >= 10) {//this section of code will reset the flag "XBee_Sent" so we can begin listening for characters again
    if (XBee_sent == true) {
      Serial.println("Counter = 10, we are ready to receive characters again");
    }
    XBee_sent = false;
  }

  if (XBee_sent == true) {//this section of code is used as a delay to prevent false button presses
    counter = ++counter;//keep adding until we reach 10, then we can reset flag and begin receiving again

    //if connected to a computer, check to see the duration of the delay
    Serial.print("Counter = ");
    Serial.println(counter);

    temp_delete = Serial.read();//try to clear false triggers in buffer provided by Master XBee until counter resets
  }

}//end loop()

//**********MODULAR SEQUENCED FUNCTIONS**********

void all_ON() {
  //this function is used to turn all channels ON
  //Bobby
  digitalWrite(2, HIGH); //Channel A, hoodie
  digitalWrite(3, HIGH); //Channel B, pants
  //Antuan, Kaden
  digitalWrite(4, HIGH); //Channel C, hoodie
  digitalWrite(5, HIGH); //Channel D, pants
  //Mireku, Talon
  digitalWrite(6, HIGH); //Channel E, hoodie
  digitalWrite(7, HIGH); //Channel F, pants
  //Madi, Henry
  digitalWrite(8, HIGH); //Channel G, hoodie
  digitalWrite(9, HIGH); //Channel H, pants
}


void all_OFF() {
  //this function is used to turn all channels OFF
  //Bobby
  digitalWrite(2, LOW); //Channel A, hoodie
  digitalWrite(3, LOW); //Channel B, pants
  //Antuan, Kaden
  digitalWrite(4, LOW); //Channel C, hoodie
  digitalWrite(5, LOW); //Channel D, pants
  //Mireku, Talon
  digitalWrite(6, LOW); //Channel E, hoodie
  digitalWrite(7, LOW); //Channel F, pants
  //Madi, Henry
  digitalWrite(8, LOW); //Channel G, hoodie
  digitalWrite(9, LOW); //Channel H, pants
}

void Seq_0() {
  //this function turns everything off
  all_OFF();
}

void Seq_1() {
  //this function turns everything back on
  all_ON();

}

void Seq_2() {
  //this function blinks off then back on

  all_OFF();
  delay(100);
  all_ON();
}

void Seq_3() {
  //function used to alternate between the hoodie and pants before turning back on
  //this really depends on how the EL is sewn on
  all_OFF();

  delay(100);

  //Madi, Henry
  digitalWrite(8, HIGH); //Channel G, hoodie
  digitalWrite(9, LOW); //Channel H, pants
  //Antuan, Kaden
  digitalWrite(4, HIGH); //Channel C, hoodie
  digitalWrite(5, LOW); //Channel D, pants
  //Bobby
  digitalWrite(2, HIGH); //Channel A, hoodie
  digitalWrite(3, LOW); //Channel B, pants
  //Mireku, Talon
  digitalWrite(6, HIGH); //Channel E, hoodie
  digitalWrite(7, LOW); //Channel F, pants

  delay(300);

  //Madi, Henry
  digitalWrite(8, LOW); //Channel G, hoodie
  digitalWrite(9, HIGH); //Channel H, pants
  //Antuan, Kaden
  digitalWrite(4, LOW); //Channel C, hoodie
  digitalWrite(5, HIGH); //Channel D, pants
  //Bobby
  digitalWrite(2, LOW); //Channel A, hoodie
  digitalWrite(3, HIGH); //Channel B, pants
  //Mireku, Talon
  digitalWrite(6, LOW); //Channel E, hoodie
  digitalWrite(7, HIGH); //Channel F, pants

  delay(300);

  all_ON();// this line can be commented out to continue alternating using by adding "//"

  delay(100);
}

void Seq_4() {
  //function used to as a ripple effect similar to a jar filling with water
  //this really depends on how the EL is sewn on and where the dancer is located for this effect
  all_OFF();

  delay(100);

  //Madi, Henry
  digitalWrite(8, HIGH); //Channel G, hoodie
  digitalWrite(9, LOW); //Channel H, pants
  delay(100);
  //Antuan, Kaden
  digitalWrite(4, HIGH); //Channel C, hoodie
  digitalWrite(5, LOW); //Channel D, pants
  delay(100);
  //Bobby
  digitalWrite(2, HIGH); //Channel A, hoodie
  digitalWrite(3, LOW); //Channel B, pants
  delay(100);
  //Mireku, Talon
  digitalWrite(6, HIGH); //Channel E, hoodie
  digitalWrite(7, LOW); //Channel F, pants
  delay(100);

  //Madi, Henry
  digitalWrite(8, HIGH); //Channel G, hoodie
  digitalWrite(9, HIGH); //Channel H, pants
  delay(100);
  //Antuan, Kaden
  digitalWrite(4, HIGH); //Channel C, hoodie
  digitalWrite(5, HIGH); //Channel D, pants
  delay(100);
  //Bobby
  digitalWrite(2, HIGH); //Channel A, hoodie
  digitalWrite(3, HIGH); //Channel B, pants
  delay(100);
  //Mireku, Talon
  digitalWrite(6, HIGH); //Channel E, hoodie
  digitalWrite(7, HIGH); //Channel F, pants
  delay(100);
}

Stress Testing in the Field

Benchtop Tests

The 9V battery was sufficient to power the controller and suits. The amount of current that the controller pulled from the 9V battery was about ~88mA when idle and ~93mA-~96mA when transmitting a signal. Each suit pulled about ~140mA when idle and powering 6 meters of EL wire. When receiving a signal from the controller, each suit pulled about ~115mA when animating the channels. When the 6 meters of EL wire was powered and receiving a character, each suit pulled about ~147mA. In comparison with the LED strips used on the previous performances, this setup used less power. However, this required the suits to be used when the auditorium lights were turned off since the EL wire was not as bright as the LED strips. There was this nice neon glow from each of the suits during the performance.

Studio Tests and Rehearsals

After testing the setup, everything worked out as planned during the rehearsals and the EL wire survived the strain each time we used the suits.

EL Wire Suits on Dancers

Show Time!

When the time came for the show, I had extra batteries, scissors, electrical tape, a multimeter, and extra extension cables in case I needed to do some last minute troubleshooting. How did the performance go? Overall, it went well. However, I found it difficult to dance and control the suits simultaneously. One of the sections that I decided to sync the animation with had a lot going on. The music was fast music and there was lot of movement. This was not ideal as the controller had to be in the correct mode before I was able to hit the send button. What I could have done differently with this setup would have been to not to have as much movement when hitting the send button.

Backstage

Making It Better

There’s always room for improvement. I would probably explore additional upgrades and improvements from the following:

  • Sew More EL Wire - Now that the suits have been made, I could try to sew more EL wire to the suits and utilize more channels for each dancer. I'd probably sew more intricate shapes instead of just outlining part of the arm and leg with the additional EL Wire.
  • Automating the Animation to the Music - Individually programming each channel to the beat was tedious and time consuming. Automating the sequence and syncing it with an audio track using Vixen instead of manually programming the EL Sequencers to trigger the channels would be better and fun to explore in the future for the next iteration.
  • Headless - While the suits were able to light up, each dancer's head lacked any lighting. I'd probably would have added few LEDs to a mask so that the dancers are not headless in the dark (which was later added to Mark V).
  • Alternative Wireless Module - It would be interesting to try to use the nRF24L01+, ESP32, ESP8266, or RFM69 to broadcast a signal to the respective EL Sequencers. That would require a slight modification in the code to work with the modules and testing the modules to see if the EL Sequencers were receiving serial.
  • Rechargeable Batteries - A 9V alkaline battery was sufficient to power the project. I'd probably try to find a rechargable battery solution.
  • 3D Model and Printed Enclosure - The cardboard enclosure was a quick solution but it was a bit bulky. Making a 3D model of an smooth enclosure that had a clip to easily open and close the box would have been better.
  • Leg Pouch - A leg pouch or a belt bag/fanny pack would also have been a good alternative to a cardboard box to hold the electronics with the enclosure. If there was more time, I would have sewn a few together or looked into buying it for each student.
  • Parachute Buckles - The elastic strips were nice but the students had to tie the enclosure to their waist and leg. A combination of strap adjusters and parachute buckles would have been quicker to attach the enclosure to each student.

Resources and Going Further

For more information, check out the resources below:

Or check out how others are incorporating EL or lighting effects to their wearable projects:

Need some inspiration for your next project? Check out some of these related tutorials on our site:

EL Wire Light-Up Dog Harness

Learn how to create a light-up dog harness using EL wire for when you need to take your four-legged friend for a walk in the dark.

Heartbeat Straight Jacket

An EL project that displays one person's heartbeat on another person's costume.

EL Wire Pants

In this tutorial, we will sew standard electroluminescent (EL) wire to a pair of pants.
New!

Wireless Controlled Wearable EL Wire Dance Suit

In this tutorial, we will build an EL wire dance suit that can be controlled by a wireless glove controller!

Or check out the following blog posts for ideas to light up your wearables:


learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Qwiic Pro Kit Project Guide

$
0
0

Qwiic Pro Kit Project Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t903

Introduction

The Qwiic Pro Kit was designed to allow users to get started with Arduino without the need for soldering or a breadboard. We've included three inputs (a joystick, accelerometer, and proximity sensor) and one display that can be daisy chained to your Arduino. Hooking up a handful of inputs and outputs to an Arduino has never been so easy with the Qwiic system!

SparkFun Qwiic Pro Kit

SparkFun Qwiic Pro Kit

KIT-15349
$59.95

Suggested Reading

If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System
Qwiic Connect System

We would also recommend taking a look at the following tutorials to set up the RedBoard Turbo and get a feel for each Qwiic component.

RedBoard Turbo Hookup Guide

January 24, 2019

An introduction to the RedBoard Turbo. Level up your Arduino-skills with the powerful SAMD21 ARM Cortex M0+ processor!

Qwiic Micro OLED Hookup Guide

Get started displaying things with the Qwiic Micro OLED.

Qwiic Accelerometer (MMA8452Q) Hookup Guide

Freescale’s MMA8452Q is a smart, low-power, three-axis, capacitive micro-machined accelerometer with 12-bits of resolution. It’s perfect for any project that needs to sense orientation or motion. We’ve taken that accelerometer and stuck it on a Qwiic-Enabled breakout board to make interfacing with the tiny, QFN package a bit easier.

Qwiic Joystick Hookup Guide

Looking for an easy way to implement a joystick to your next Arduino or Raspberry Pi project? This hookup guide will walk you through using the Qwiic Joystick with the Arduino IDE on a RedBoard Qwiic and in Python on a Raspberry Pi.

Qwiic Proximity Sensor (VCNL4040) Hookup Guide

The SparkFun Qwiic Proximity Sensor is a great, qualitative proximity (up to 20 cm) and light sensor. This hookup guide covers a few examples to retrieve basic sensor readings.

Kit Contents

You will find the following parts in the kit.

Qwiic Pro Kit Contents

Hardware Hookup

The Qwiic connection system makes it easy to connect the boards together. Simply grab a Qwiic cable of your choice to connect. If you are using the demo code from this tutorial to play micro pong, you will need to connect all the boards together. We recommend using longer cable lengths for users using the Qwiic boards to control each paddle and placing them on opposite sides of the micro OLED. We also found it easier to add the accelerometer at the end of the daisy chain since the board requires movement. Additionally, you will need to orient the micro OLED so that the paddle is on the side of the player's Qwiic board after uploading the example code.

Qwiic Boards Daisy Chained

Installing the Board Add-Ons and Drivers

Note: This code/library has been written and tested on Arduino IDE version v1.8.8. Otherwise, make sure you are using the latest stable version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE.

There are a few board add-ons to install before you are able to upload code to your RedBoard Turbo. If you have not already, make sure to check out the RedBoard Turbo's hookup guide to install the SAMD21 and SparkFun board add-ons.

Drivers

The RedBoard Turbo is now easier than ever to program, thanks the UF2 bootloader. With this bootloader, the RedBoard Turbo shows up on your computer as a USB storage device without having to install drivers for Windows 10, Mac, and Linux!

However, if you are using a Windows 7 OS, you will need to install SAMD drivers. Head to the RedBoard Turbo's hookup guide for more information about installing drivers for Windows 7.

Installing the Library

Note:If you have not previously installed an Arduino library, please check out our installation guide.

SparkFun has written a library for the Qwiic enabled joystick, triple axis accelerometer (MMA8452Q), proximity sensor (VCNL4040), and 64x48 micro OLED. You can obtain these libraries through the Arduino Library Manager. Search for the following terms to automatically install the latest versions of each library. If you have issues compiling, you may need to download the respective library versions listed below.

If you prefer downloading the libraries manually, you can grab them from each of the respective GitHub repositories.

Example Code

We recommend grabbing the code from its the GitHub repository. Otherwise, you can download the zipped file from the link below.

After downloading, unzip the files and open the QwiicStarterExample.ino sketch. It should be located in the downloads folder similar to this path: .../Firmware/Arduino/QwiicStarterExample/QwiicStarterExample.ino. Open the code up in the Arduino IDE, select the board (i.e. the SparkFun RedBoard Turbo), and the COM port that the board enumerated on. Then hit the upload button.

With a friend, try rocking the accelerometer back and forth along the x-axis or moving your hand above the proximity sensor to control each paddle. You will need to orient the micro OLED so that the paddle is on the side of the player's Qwiic board. The game will continue as long as the ball hits the paddle and bounces to the other side. A player will win a round as soon as the other player fails to bounce the ball back to the other side. The current score will be briefly displayed before the next game. Try to rack up more points than your opponent!

Qwiic Pro Kit Demo

The default code uses the accelerometer as player 1 and the proximity sensor as player 2. Try adjusting the code to use the joystick for one of the players by adding and removing the single line comments. The joystick will control the paddle along the "vertical" y-axis. Each board can only have one player assigned. See if you can try to remove the unused Qwiic board from the daisy chain and commenting out each instance of the related board.

Resources and Going Further

Now that you've successfully got your Qwiic Starter Kit up and running, what will else will you build? For more information, check out the resource below:

Need some inspiration for your next project? Check out some of these related tutorials:

AS726X NIR/VIS Spectral Sensor Hookup Guide

It's now easier than ever to measure and characterize how different materials absorb and reflect different wavelengths of light. The AS726X spectral sensors allow you to detect wavelengths in the visible range (VIS) and near infrared range (NIR)!

GPS-RTK Hookup Guide

Find out where you are! Use this easy hook-up guide to get up and running with the SparkFun high precision GPS-RTK board.

Hookup Guide for the BlackBoard Artemis ATP

Get started with the BlackBoard Artemis ATP - all the functionality of the SparkFun Artemis module wrapped in the Mega Arduino Footprint

Hookup Guide for the SparkFun RedBoard Artemis Nano

Get started with the powerful RedBoard Artemis Nano

learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Qwiic TMP117 High Precision Digital Temperature Sensor Hookup Guide

$
0
0

Qwiic TMP117 High Precision Digital Temperature Sensor Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t916

Introduction

The TMP117 is a high precision, digital temperature sensor. What makes the TMP117 stand out is it's ability to be accurate down to ±0.1°C (from -20°C to 50°C). The measurements can also have a resolution of 0.0078°C! This is great for projects that require more stable temperature readings. There's also additional features that come with the TMP117. Some of these features include offsetting the temperature, entering low-power mode, and averaging the readings.

SparkFun High Precision Temperature Sensor - TMP117 (Qwiic)

SparkFun High Precision Temperature Sensor - TMP117 (Qwiic)

SEN-15805
$13.95

Required Materials

To follow along with this tutorial, you will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
4
Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
USB micro-B Cable - 6 Foot

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
12

Suggested Reading

Before continuing on with this tutorial, you may want to familiarize yourself with some of these topics if they’re unfamiliar to you. If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System
Qwiic Connect System

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing. Make sure to install the appropriate drivers before uploading code. In this case, we'll need to make sure that the CH340 drivers are installed for the RedBoard Qwiic.

I2C

An introduction to I2C, one of the main embedded communications protocols in use today.

RedBoard Qwiic Hookup Guide

This tutorial covers the basic functionality of the RedBoard Qwiic. This tutorial also covers how to get started blinking an LED and using the Qwiic system.

How to Install CH340 Drivers

How to install CH340 drivers (if you need them) on Windows, Mac OS X, and Linux.

Hardware Overview

TMP117

The TMP117 is located on a tiny, isolated island between two slots that are cut into the PCB. This minimizes heat generated from components on the PCB and any errors that may result when taking temperature readings.

TMP117 surrounded by slots cut on the breakout board

Power

The sensor has a low power consumption and is operates between 1.8V to 5.5V. To power the sensor on the breakout board, it utilizes 3.3V from the Qwiic connector. Depending on your application, you can also connect a power via the plated through holes for 3.3V and GND. The corresponding PWR LED will light up to indicate if the sensor is being powered.

Power Pins and Qwiic Connector HighlightedPower LED

I2C Pins

To communicate with the sensor, you will need an I2C bus. The Qwiic system makes it easy to connect the TMP117 to your projects via the Qwiic connector. You can add a Qwiic cable between the sensor and development board to start experimenting with the sensor in your projects. Depending on your application, you can also connect to the I2C pins via the plated through holes for SDA and SCL.

I2C Pins and Qwiic Connector Highlighted

Interrupt Pin (a.k.a. Alert Pin)

The INT pin on the board is connected to the TMP117's "alert" pin. When the pin is active, it will be pulled LOW by default. If the TMP117's temperature limits are configured and the sensor exceeds the values, the alert pin will pulled LOW.

Interrupt Pin

Jumpers

The board has a few jumper pads on the board. If you have not worked with jumper pads, make sure to check out the tutorial on "How to Work with Jumper Pads and PCB Traces" for more information.

How to Work with Jumper Pads and PCB Traces

April 2, 2018

Handling PCB jumper pads and traces is an essential skill. Learn how to cut a PCB trace, add a solder jumper between pads to reroute connections, and repair a trace with the green wire method if a trace is damaged.

Address Select

The default address of the board is 0x48. If you need to adjust the address of the sensor, you can cut the trace connecting to the default address and add a solder jumper to the respective pads to change the address to 0x49, 0x4A, or 0x4B.

TMP117 Address Select

LED

If you need to disable the PWR LED to make the board inconspicuous, conserve more power, or ensure that you are minimizing any heat generated from the LED, you can cut the jumper connecting to the LED.

Jumper to Disable the LED

Pull-Up Resistors

The board also includes jumpers to disable the pull-up resistors on the I2C bus line. If you are using a few I2C devices on the same bus that already have pull-up resistors on their respective boards, you may want to cut the jumpers to disconnect. This is for special use cases when daisy chaining about 7x I2C devices on the same bus. Keep in mind that you will want to avoid heavy bypass traffic on the I2C bus if you are trying to take accurate readings.

Jumpers to Disable the I2C Pull-Up Resistors

There is also a pull-up resistor on the INT pin if you need to disable the it as well.

Jumper to Disable Interrupt Pull-Up Resistor

Dimensions

The board uses the standard Qwiic 1.0"x1.0" board size with four mounting holes.

Board Dimensions

Hardware Hookup

This board is an I2C based board and so we've included a Qwiic connector on the breakout board. Hooking the sensor up is easy. Just plug one end of the Qwiic cable into the Qwiic TMP117 and the other to your development board. In this case, it's the RedBoard Qwiic. You'll be ready to upload a sketch and start reading temperature values. It seems like it's too easy too use, but that's why we made it that way!

TMP117 easily connected to a RedBoard Qwiic with a Qwiic cable

If you need to temporarily access the pins via the standard breadboard spaced 0.1" PTH pads, you can connect some IC hooks to the through holes. In the image below, the interrupt pin needed to be measured with a multimeter so two IC hooks were connected to the board as a temporary connection. For a secure connection, you'll need to solder headers to the PTH pads.

IC Hooks connected to the TMP117's interrupt and ground pins

Arduino Library

Note: If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

SparkFun has written a library to control the Qwiic TMP117. You can obtain these libraries through the Arduino Library Manager. By searching for TMP117, you will get two results. Click on the one written by SparkFun Electronics and you should be able to install the latest version. If you prefer downloading the libraries manually you can grab them from the GitHub repository:

Arduino Example Code

Basic Readings Example1_BasicReadings.ino

This example prints out the temperature in degrees Celsius and Fahrenheit. Te beginning of the code is pretty much the same for the examples. The code initializes the I2C bus and serial UART to pass the data to our Arduino serial monitor. We'll want to set the bus to fast mode as recommended by the datasheet. Once initialized, we'll check to see if the address matches the TMP117. By default, this is 0x48. If it matches, we'll continue running the sketch.

This particular example will check to see if the TMP117 measured and averaged the temperature readings. If there is data ready, the TMP117 will notify us from the configuration register. When ready, we'll read the temperature registers and output it out to the Arduino serial monitor.

If you have already, open the example up. Select your board and COM port. Hit the upload button. Open the serial monitor at 115200 baud to begin seeing the output. Try heating the sensor with your finger or lightly breathe some air across the sensor to watch the temperature values change!

Finger on TMP117

Alert Status Example2_AlertStatuses.ino

This example configures the serial I2C and UART like the first example. We'll set alert function mode and temperature limits. When ready, we'll check to see if the temperature exceeds the high or low limits. By default, the alert function mode is set to alert mode. We set it again just in case. If we above the high limit, the high alert flag will be raised and we will output high alert.. If we are below the low limit, the high alert flag will be raised and we will output the low alert. Otherwise, we will have message indicating that there is no alert.

Set Offset Temperature Example3_SetOffsetTemperatureValue.ino

In this example, you can adjust the offset temperature of the TMP117. This is useful if you need to adjust the temperature readings based on your system in case the location you are measuring is warmer or colder than the surrounding environment.

Set Conversion Mode Example4_SetConversionMode.ino

You can change the continuous conversion mode to either one-shot or shutdown mode for low power applications. In one-shot mode, the TMP117 will take one temperature reading. After one temperature reading, the sensor will enter low power shutdown mode. When the TMP117 is set to shutdown mode, all temperature conversions are aborted and the TMP117 will enter low power shutdown mode.

Set Conversion Cycle Time Example6_SetConversionCycleTime.ino

In this example, you can adjust the conversion cycle bit and the conversion averaging mode. By adjusting these values, you can reduce the amount of noise to provide stable temperature readings. You'll want to adjust these based on your application.

More Examples

There's a few more examples in the library. Make sure to read through the description and comments in the code before trying out the additional examples that were not explained earlier!

Resources and Going Further

Now that you've successfully got your Qwiic TMP117 up and running, it's time to incorporate it into your own project! For more information, check out the resources below:

Need some inspiration for your next project? Check out some of these related tutorials using temperature sensors:

MAX31855K Thermocouple Breakout Hookup Guide

Learn how to take readings with a k-type thermocouple using the MAX31855K cold-junction-compensated k-type thermocouple-to-digital converter.

LilyPad Temperature Sensor Hookup Guide

How to hook up the LilyPad Temperature Sensor as well as some project ideas and example code.

TMP102 Digital Temperature Sensor Hookup Guide

How to connect and use the SparkFun Digital Temperature Sensor Breakout - TMP102 with an Arduino.

SparkFun Inventor's Kit Experiment Guide - v4.1

The SparkFun Inventor's Kit (SIK) Experiment Guide contains all of the information needed to build all five projects, encompassing 16 circuits, in the latest version of the kit, v4.1.

learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Magnetic Levitation

$
0
0

Magnetic Levitation a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t1098

Introduction

Let there be light! In this tutorial we'll build a basic magnetic levitator. This guide will go over some of the theory, how to use a magnetic field sensor, and how to use one to build a basic levitation circuit. Finally, we'll go a bit further and build a wireless power floating light.

Required Materials

To follow along with the examples in this tutorial you will need the following materials:

The other parts used that we don't carry are:

Required tools

The tools needed for this project is a multimeter and soldering iron, but having access to an oscilloscope will help with testing as well.

Digital Multimeter - Basic

Digital Multimeter - Basic

TOL-12966
$14.95
20
Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

TOL-14456
$14.95
7
Tool Kit - Screwdriver and Bit Set

Tool Kit - Screwdriver and Bit Set

TOL-10865
$9.95
5

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing.

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

How to Use a Breadboard

Welcome to the wonderful world of breadboards. Here we will learn what a breadboard is and how to use one to build your very first circuit.

How to Use a Multimeter

Learn the basics of using a multimeter to measure continuity, voltage, resistance and current.

Introduction to Operational Amplifiers with LTSpice

Picking up where we left off in "Getting Started with LTSpice," we delve a little deeper into LTSpice through an introduction of Operational Amplifiers (OpAmps).

Theory Basics

When it comes to magnetic levitation, there are two kinds of levitation: attractive and repulsive. In this guide, we're going to use an attractive levitation circuit as it's a lot easier to get working. As we know, a magnet has two poles, north and south. Magnetic fields with the same polarity repel each other, whereas opposite poles attract. With magnetic levitation we need a fixed magnetic field, provided by permanent magnets, and a magnetic field that we can control to position the permanent magnets.

magnetic dipole model

To create a magnetic field that can be controlled, we can use an inductor. Inductors store energy similar to capacitors; while capacitors store voltage in the form of an electric field, inductors store current by generating a magnetic field. Here we'll be using the magnetic field of an inductor to interact with the magnets. With attractive levitation the inductor is used to oppose the force of gravity which then attracts the magnet up to the inductor.

If the magnet gets too close to the inductor, the magnet's field strength will be strong enough to stick to the inductor regardless of how much current is passing through the inductor. However, if the magnet is too far away from the inductor, the magnetic field strengths will be too weak relative to gravity to be pulled back up. So the trick is to find the window where magnet isn't strong enough to pull itself up on it's own, but with the attraction of the inductor's opposing field the magnet is able to overcome gravity. To keep track of it's position, we'll use a magnetic field sensor, called a hall effect sensor.

Hall Effect Sensor

A hall effect sensor is a device that is used to measure the strength of a magnetic field. The output of the sensor is directly proportional to the magnetic field strength passing through it. The sensor we'll need is the SS494B, which has an analog voltage output. There are other hall effect sensors that act as a switch and only turn on or off in the presence of a magnetic field. In the next section we'll see how the sensor responds to the presence of our magnets.

Testing The Hall Effect Sensor

Let's first test to see how the sensor works. With a breadboard, connect 5V to the supply voltage pin, ground to ground, and on the output pin, connect either an oscilloscope probe to watch the voltage change, or we can use a multimeter in voltage mode to watch the voltage change.

SS494 Pinout

Without a magnet present, the output voltage sits at around 2.5V. With one side of the magnet, as the magnet gets closer to the sensor, the voltage decreases. If you flip the magnet around and bring it closer to the sensor, you'll see output voltage increase. Make note of which side causes the voltage to decrease. It might help to make a mark with a permanent marker, which will be useful in our next test.

magnet with marked side facing up

Before moving on to the next test however we'll need to extend the leads of our sensor by adding some wire. It's a good idea to add heatshrink tubing around each of the solder joints to make sure they don't short together, but a little bit of electrical tape around the leads will work as well. In the image below, the sensor has a red wire for the positive voltage supply, black for the negative, and yellow wire for the analog output.

Sensor Leads Soldered

While the soldering iron is hot, now is also a good time solder wire to the inductor as well. Using different colors for the two pins of the inductor may help with troubleshooting later on.

Inductor with wires soldered

Building The Control Circuit

As mentioned in the Theory Basics, it's important that the magnet is positioned close enough to the inductor's magnetic field that it is able to interact with the magnet, but not so close that the magnet's own magnetic field is able to pull itself up to the inductor regardless of the power. What we need is a way to control the inductor so that when the magnet is too far away, the inductor will pull the magnet closer, but turn off when it gets too close, so that gravity can still pull it back down.

Before we start wiring up electronics, a stand has to be made to hold the inductor above the ground. This guide isn't going to go over making a stand, but below is a photo of the stand used for reference. The inductor hangs about 5 inches above the table, and a 8-32 bolt (~1.5 inches in length) and nut are used to attach the inductor to the stand.

Levitator Stand

Once the inductor is mounted, we'll need to attach the hall effect sensor to the head of the bolt. If there's any exposed metal from the sensor, use a piece of electrical tape to insulate the sensor from the bolt and secure the sensor with more electrical tape as shown below. Note that the curved side of the sensor is facing away from the inductor.

Sensor mounted to the stand

The Comparator Circuit

To control the inductor we're going to use an op-amp in a configuration called a comparator, which compares the output of the hall effect sensor to a reference voltage that is connected to the other input pin. The reference voltage is set with a potentiometer acting as a voltage divider - this creates an adjustable analog voltage between 0V and 5V. The voltage of the potentiometer represents what voltage we want the hall effect sensor to read, which is based on how far away the magnet is.

This circuit uses two voltage rails, 5V and 12V. The 12V rail is powering the inductor and op-amp, and the 5V rail is used for the voltage reference and hall effect sensor. Two power supplies are ideal, because if the 12V rail goes into current limiting mode, and the voltage drops, the hall effect sensor won't have a high enough voltage to detect when the magnet is close enough. You can, however, get away with a single power supply rail using a LM7805 linear voltage regulator. If you plan on using two power supplies, make sure you connect the grounds together, otherwise the circuit won't work correctly.

comparator schematic

Schematic of Comparator Circuit

comparactor circuit fritzing diagram

Fritzing Image of Comparator Circuit

Once the circuit is built, we'll use a multimeter to measure the voltage at the non-inverting input (pin 2 of the op-amp) and turn the knob on the potentiometer until it reads 0V. Next, we'll position the magnet about 2cm away from the sensor, or about a thumb's thickness. Essentially, the magnet needs to be in the "sweet spot" - a position a bit further away than the position where the magnet wants to pull up on its own and stick to the inductor.

Looking at the output voltage of the op-amp (pin 1), it should be reading 9-12V. With the magnet still in position, we're going to slowly turn the potentiometer and increase the reference voltage until we see the voltage change from 12V to 0V. Moving the magnet up and down a little should change the output of the op-amp from high to low and low to high.

The comparator is trying to keep the voltages between the input pins equal and driving the output high or low so that the sensor value matches the reference value. In the next step we'll attach our inductor to the output of the op-amp and try to make a magnet levitate!

Levitating A Magnet

Now that we understand how the comparator is going to control the inductor, let's try and levitate a magnet. Op-amps are good at controlling signals, but for larger current applications like this, we'll need to use a mosfet. Turn off power to the circuit we built in the last section and and wire up the following circuit. Make sure not to skip the diode! When an inductor switches off, the magnetic field it created collapses, which can cause a large voltage spike, and may damage the mosfet. The schematic lists a 1N4007 diode, but the 1N5401 diode should work better with flyback current spikes.

Schematic of Comparator Circuit With Inductor

Schematic of Comparator Circuit With The Inductor

Fritzing Image with Inductor

Fritzing Image Of The Comparator Circuit With The Inductor

With the power still off, turn the potentiometers's knob all the way to one side, such that the reference voltage is set to 5V. Next, turn the power on and verify that the output of the op-amp is reading 0V. Position the magnets between your thumb and middle finger, as shown below. Your thumb will be able to catch the magnet if it gets pulled up to the inductor, and your middle finger is there to balance the magnets and catch them if the magnets fall.

Magnet Balancing

With your other hand, slowly decrease the reference voltage. As you get close to the transition point from the Building the Control Circuit, the magnets should start to levitate. If the magnets jump up to your thumb, increase the voltage again, and then try again. With some practice and small but precise movements, the magnets should be able to levitate.

Being able to read the current from the 12V power supply is a good way to see where the levitation point is. When the magnet is too close, the current should be less than 10mA. With the magnets I'm using, the amount of current being used is around 80mA and I'm able to levitate in a window of 2-3cm from the inductor. With a little bit of practice you should be able to get your magnets to levitate too!

Photo Of Levitating Magnet

Wireless Power

If levitating a magnet isn't cool enough, you can add even more complexity by adding a wirelessly powered LED. This step requires a few more tools that not everyone has. For this section you'll need the following:

Building the transmission coil

The inductor used to levitate the magnets only provides enough power to keep the magnet in position. To transfer power wirelessly, we'll need to make a second inductor that we'll wind ourselves using magnet wire. Magnet wire is thin gauge wire with an even thinner insulating layer. This allows the coils of the wires to get even closer together and increases the inductance created as compared to the same number of turns of normally insulated wire.

Wireless power transfer works on the same principal as a transformer, where you have one inductor induce a current on another inductor, except instead of using an iron core to couple the flux from one inductor to another, it uses air, similar to a tesla coil. One of the problems with wireless power transfer is that it's very inefficient. The primary side of the transformer will use a lot of power to generate a little bit of power on the secondary.

Making The Primary

The primary is made with 25 turns of 30 gauge magnet wire with a center diameter of 1 inch. Because engineers are incapable of throwing anything away, I used an empty hookup wire spool with one end cut off to slide off the magnet wire.

Hand Winding the Primary

To keep the coil from unwinding, you can cut off a small piece of extra magnet wire and wrap it around the primary on two of the sides so that it will hold its shape. The enamel coating on the wire makes it hard for solder to stick to the wire. So with a little bit of sand paper, file off some of the enamel so that you can solder on a couple of pins as shown below, or solder wire directly to the coil to reach the breadboard.

Wireless Power Transfer Primary Inductor

Making The Secondary

The secondary side was made in the same way, except using 100 turns of magnet wire this time, along with a diode and two capacitors to convert the AC power to DC power for the LED. Refer to the schematic below.

Wireless Power Transfer Secondary Schematic

Schematic for Creating the Wireless Power Transfer Secondary

Cut off some extra pieces of magnet wire to hold the secondary together as was done with the primary. Cut off larger pieces this time to loop around the heatsink of the LED to hold in the center of the secondary. A piece of double sided tape was used to hold the magnets to the bottom of the LED heatsink. Make sure when positioning the magnets that the mark on the magnets is facing away from the LED.


Assembled Secondary - Top Assembled Secondary - Bottom

Building the Primary Driver and Testing

In order to induce a current across the secondary coil, we need to generate an AC signal using a function or frequency generator that will allow us to find the best frequency to use with these inductors we made. Just like with the op-amp for the levitation circuitry, the function generator cannot source very much current, so we'll need to use another mosfet to drive our primary coil. The circuit is pretty simple, with the square wave input signal having an amplitude of 5V, and a DC offset of 2.5V (what we want is a square wave which goes high to 5V and low to 0V). Make sure to attach a heatsink to this mosfet, as they get pretty hot, pretty quickly.

Primary Driver Schematic

To find the best frequency to use, I used my LCR meter, which can measure the inductance of my secondary coil, along with getting an accurate value for the C1 from the schematic, and calculated the resonant frequency to be around 80kHz. There's a balance between the frequency and current draw from the power supply. The lower the frequency, the brighter the LED will be, but the efficiency is extremely low and the mosfet driving the primary coil will get extremely hot. The best approach to this problem is to determine how high of a frequency can you use and still have sufficient LED brightness.

Testing LED brightness

Attaching the Primary to the Levitating Inductor

Now that the wireless power transfer is working, it's time to attach the wireless power primary inductor to the levitation inductor. With a little bit of electrical tape, attach the 25 turn inductor we made on the bottom of levitation inductor where the hall effect sensor is.

Attaching the primary to the levitation inductor

Finding the New Levitation Distance

The weight of the light and magnets is now significantly heavier than with the magnets alone. With the wireless power primary disconnected from the rest of the circuit, use the reference voltage potentiometer to adjust the levitation distance. Because of the mass, the magnets will need to be significantly closer, around 1cm. Turning the voltage down on the potentiometer will decrease the levitation distance. Once you have the light levitating, you can reconnect the primary and turn the output of the function generator on and off to control the LED.

Floating LED on and off

I mentioned earlier that this was inefficient. Just how inefficient though? I measured the current to be around 50mA, and the voltage across the LED was 2.72V, so the circuit is receiving around 136mW of power. The power supply is set to 12V, and with the magnet levitating and the light on, the circuit is drawing 886mA, or 10.6 watts, which makes the efficiency 1.3%. To be fair though, the levitation circuit is drawing about 450mA, so the wireless power transfer efficiency is really about 2.5%. Now that we know what frequency our wireless power circuit can run at, the function generator could be replaced with a new circuit using a 555 timer to generate the square wave signal.

Resources and Going Further

Congratulations! We've made a levitating LED light! If you'd like more information on any of the concepts presented in this tutorial, check out the link below:

Need more inspiration? Check out these other great tutorials from SparkFun:

Build an Auduino Step Sequencer

Make a Step Sequencer using an Arduino, the Auduino firmware, and a handful of hardware.

Hacker in Residence: The Harmonic Skew Zoetrope

Check out Hacker in Residence, Jesse's awesome Harmonic Skew Zoetrope in this project tutorial.

Bare Conductive Musical Painting

Learn how to make a musical painting using the Bare Conductive Touch Board and Conductive Paint.

Using Artnet DMX and the ESP32 to Drive Pixels

In this tutorial, we'll find out how to use Resolume Arena, a popular video jockey software, to control custom-made ArtNet DMX fixtures.

learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado


RED-V RedBoard Hookup Guide

$
0
0

RED-V RedBoard Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t1032

Introduction

SparkFun is pleased to welcome its a whole new instruction set architecture (ISA) to its family, the RISC-V ISA (pronounced “risk-five”), and along with it, introduce the RED-V RedBoard (pronounced “red-five”). In this tutorial, we'll be focusing on the hardware.

 SparkFun RED-V RedBoard - SiFive RISC-V FE310 SoC

SparkFun RED-V RedBoard - SiFive RISC-V FE310 SoC

DEV-15594
$39.95

"The force is strong with this one." (Star Wars: A New Hope, 1977)

What sets the RISC-V ISA from the rest is that it is completely open-source; including the instruction set architecture (ISA). That means anyone can make full use the microcontroller without requiring royalties, licenses, or non-disclosure agreements (NDAs). The RED-V comes in the familiar Arduino Uno form factor and includes the SiFive Freedom E310 core, 32MB of QSPI flash, an NXP K22 ARM Cortex-M4 for USB connectivity and operating as a JTAG interface, and a Qwiic connector.

Required Materials

To follow along with this tutorial, you will need the following materials and software. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary. Here is what you would need to get started:

Hardware

  • RED-V - You'll definitely need this; otherwise, you are probably on the wrong tutorial page (wink).
  • USB 3.1 Cable A to C - 3 Foot - The USB interface serves two purposes: it powers the board and allows you to upload programs to it. (You might even have a few of these in you drawer!)

You Will Also Need

To utilize all the features of the development board, you may need the following accessories.

Click the buttons above to toggle the additional materials based on the tasks you
wish to perform. Feel free to modify the items in your cart to fit your needs.

Jumper Modification

If you would like to modify the 3.3V/5V I/O jumper or A4/A5 Qwiic connector jumpers, you will need soldering equipment and/or a knife.

Solder Lead Free - 100-gram Spool

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Weller WLC100 Soldering Station

Weller WLC100 Soldering Station

TOL-14228
$44.95
1
Chip Quik No-Clean Flux Pen  - 10mL

Chip Quik No-Clean Flux Pen - 10mL

TOL-14579
$7.95
2
Hobby Knife

Hobby Knife

TOL-09200
$2.95
2

Qwiic Example

If you would like to follow along with the examples below to interact with the physical world, you will also need the following items:

Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
SparkFun Qwiic 12 Bit ADC - 4 Channel (ADS1015)

SparkFun Qwiic 12 Bit ADC - 4 Channel (ADS1015)

DEV-15334
$9.95
Magnetic Screwdriver Set (20 Piece)

Magnetic Screwdriver Set (20 Piece)

TOL-15003
$6.95
1

Headers & Accessories

If you would like to add headers to your board, check out some of the following items:

Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
SparkFun Beginner Tool Kit

SparkFun Beginner Tool Kit

TOL-14681
$54.95
Feather Stackable Header Kit

Feather Stackable Header Kit

PRT-15187
$1.50

Below is a sample selection of our other headers and soldering tools in our catalog. For a full selection of our available Headers or Soldering Tools, click on the associated link.

Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
Female Headers

Female Headers

PRT-00115
$1.50
7
Arduino Stackable Header Kit - R3

Arduino Stackable Header Kit - R3

PRT-11417
$1.50
12
Break Away Male Headers - Right Angle

Break Away Male Headers - Right Angle

PRT-00553
$1.95
4
Weller WE1010 Soldering Station

Weller WE1010 Soldering Station

TOL-14734
$129.00
1
Insulated Silicone Soldering Mat

Insulated Silicone Soldering Mat

TOL-14672
$9.95
5
Solder - 1/4lb Spool (0.020") Special Blend

Solder - 1/4lb Spool (0.020") Special Blend

TOL-10242
$29.95
7
Solder Lead Free - 100-gram Spool

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7

ARM Programmers

If you would like to debug or flash your ARM processor on your own, here are some of our ARM Programmers:

J-Link BASE Compact Programmer

J-Link BASE Compact Programmer

PGM-15347
$378.00
J-Link EDU Mini Programmer

J-Link EDU Mini Programmer

PGM-15345
$18.00
1
J-Link EDU Base Programmer

J-Link EDU Base Programmer

PGM-15346
$60.00
JTAG USB OCD Programmer/Debugger for ARM processors

JTAG USB OCD Programmer/Debugger for ARM processors

PGM-07834
$71.95
1

Suggested Reading

Before continuing on with this tutorial, you may want to familiarize yourself with some of these topics if they’re unfamiliar to you:

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

Logic Levels

Learn the difference between 3.3V and 5V devices and logic levels.

I2C

An introduction to I2C, one of the main embedded communications protocols in use today.

ARM Programming

How to program SAMD21 or SAMD51 boards (or other ARM processors).
Qwiic Connect System


One of the new, advanced features of the board is that it takes advantage of the Qwiic connect system. We recommend familiarizing yourself with the Logic Levels and I2C tutorials (above) before using it, as all Qwiic sensors utilize an I2C communication protocol. Click on the banner above to learn more about Qwiic products.

Hardware Overview

Power & Programming

There are a few different ways to power the SparkFun RED-V RedBoard:

  • USB-C
  • barrel jack connector
  • power pins broken out on the edge of the board

The easiest way (which will also allow you to program your board) is to simply plug it into your computer via USB-C. This will provide 5V to the board and will also allow you access to the super cool USB-to-JTAG interface for programming. Once you've programmed your RED-V however, you may want to have it running off of a different power supply. If you use a wall wart on the USB-C connector, make sure it outputs a regulated 5V DC. You can also use the black barrel jack, in which case you'll need any wall adapter between 7 & 15 Volts DC. Or you can also power the board through the header pins broken out on the edge of the board. If you are using VIN and GND, follow the same practice as using a wall adapter and stick to between 7 & 15 Volts. If you are using 5V and GND or 3v3 and GND, make sure that your voltage is regulated when applying power to the 5V or 3.3V pins, respectively.

USB, Barrel Jack, and Power Pins

Always-On Core

The FE310 contains an Always-On (AON) block that allows easy power control of the FE310. It includes its own real-time clock and is also attached to the WAKE button on the board. This allows you to put the FE310 to sleep and wake it up upon a time-generated or user-generated interrupt.

FE310 IC

Buttons

The RED-V has two buttons: a RESET button and a WAKE button. The RESET button is pretty self explanatory and is used to reset the FE310. A single tap of the RESET button will run the code loaded onto the FE310's QSPI flash. A quick double tap will put the FE310 into safe bootloader mode, which will allow you to flash new code to the RED-V if you've managed to really mess things up (i.e. Oops I put the core to sleep and forgot to add a way to wake it up). The pin is also broken out on the edge of the board. Adding a jumper wire from this pin to GND will reset the board as well.

Reset Button and Pin

The RED-V is also equipped with an Always-On or AON core (mentioned above) which can be programmed to shut down the main core of the FE310 and wake it up upon a button-generated or user-generated interrupt. The WAKE button can be configured in software to wake the FE310 from deep sleep. This button is also broken out to the header pin nearest the barrel jack if you'd like to use an external source to wake the FE310. Adding a jumper wire from this pin to GND will wake the board as well.

Wake Button and Pin

Jumpers

The FE310 has a few jumpers as well, all of which are open by default. The two jumpers located next to the I2C label is for the I2C pull-up resistors. These resistors are not attached by default as there are I2C pull-up resistors on all SparkFun Qwiic slaves. If you're using a 3rd party board, you may need to close these jumper by the Qwiic connector to attach the pull-ups to the I2C bus. The jumper by the USB-C connector is for bypassing the 0.5A PTC fuse. This is for special cases where you need a lot current. Most of the time, you can leave this jumper open.

Pull-Up Resistors and By-Pass jumper

Dimensions

The RED-V RedBoard uses the Arduino Uno footprint. There are four mounting holes on the board.

Dimensions

Resources and Going Further

Now that you've successfully got started with your RED-V RedBoard, it's time to incorporate it into your own project! For more information, check out the resources below:


learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

RED-V Thing Plus Hookup Guide

$
0
0

RED-V Thing Plus Hookup Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t1099

Introduction

SparkFun is pleased to welcome its a whole new instruction set architecture (ISA) to its family, the RISC-V ISA (pronounced “risk-five”), and along with it, introduce the RED-V Thing Plus (pronounced “red-five”). In this tutorial, we'll be focusing on the hardware.

SparkFun RED-V Thing Plus - SiFive RISC-V FE310 SoC

SparkFun RED-V Thing Plus - SiFive RISC-V FE310 SoC

DEV-15799
$29.95

"The force is strong with this one." (Star Wars: A New Hope, 1977)

What sets the RISC-V ISA from the rest is that it is completely open-source; including the instruction set architecture (ISA). That means anyone can make full use the microcontroller without requiring royalties, licenses, or non-disclosure agreements (NDAs). The RED-V comes in the familiar SparkFun Thing Plus form factor and includes the SiFive Freedom E310 core, 32MB of QSPI flash, an NXP K22 ARM Cortex-M4 for USB connectivity and operating as a JTAG interface, and a Qwiic connector.

Required Materials

To follow along with this tutorial, you will need the following materials and software. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary. Here is what you would need to get started:

Hardware

  • RED-V Thing Plus - You'll definitely need this; otherwise, you are probably on the wrong tutorial page (wink).
  • USB 3.1 Cable A to C - 3 Foot - The USB interface serves two purposes: it powers the board and allows you to upload programs to it. (You might even have a few of these in you drawer!)

You Will Also Need

To utilize all the features of the development board, you may need the following accessories.

Click the buttons above to toggle the additional materials based on the tasks you
wish to perform. Feel free to modify the items in your cart to fit your needs.

Jumper Modification

If you would like to modify the 3.3V/5V I/O jumper or A4/A5 Qwiic connector jumpers, you will need soldering equipment and/or a knife.

Solder Lead Free - 100-gram Spool

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Weller WLC100 Soldering Station

Weller WLC100 Soldering Station

TOL-14228
$44.95
1
Chip Quik No-Clean Flux Pen  - 10mL

Chip Quik No-Clean Flux Pen - 10mL

TOL-14579
$7.95
2
Hobby Knife

Hobby Knife

TOL-09200
$2.95
2

Qwiic Example

If you would like to follow along with the examples below to interact with the physical world, you will also need the following items:

Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
SparkFun Qwiic 12 Bit ADC - 4 Channel (ADS1015)

SparkFun Qwiic 12 Bit ADC - 4 Channel (ADS1015)

DEV-15334
$9.95
Magnetic Screwdriver Set (20 Piece)

Magnetic Screwdriver Set (20 Piece)

TOL-15003
$6.95
1

Headers & Accessories

If you would like to add headers to your board, check out some of the following items:

Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
SparkFun Beginner Tool Kit

SparkFun Beginner Tool Kit

TOL-14681
$54.95
Feather Stackable Header Kit

Feather Stackable Header Kit

PRT-15187
$1.50

Below is a sample selection of our other headers and soldering tools in our catalog. For a full selection of our available Headers or Soldering Tools, click on the associated link.

Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
Female Headers

Female Headers

PRT-00115
$1.50
7
Arduino Stackable Header Kit - R3

Arduino Stackable Header Kit - R3

PRT-11417
$1.50
12
Break Away Male Headers - Right Angle

Break Away Male Headers - Right Angle

PRT-00553
$1.95
4
Weller WE1010 Soldering Station

Weller WE1010 Soldering Station

TOL-14734
$129.00
1
Insulated Silicone Soldering Mat

Insulated Silicone Soldering Mat

TOL-14672
$9.95
5
Solder - 1/4lb Spool (0.020") Special Blend

Solder - 1/4lb Spool (0.020") Special Blend

TOL-10242
$29.95
7
Solder Lead Free - 100-gram Spool

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7

ARM Programmers

If you would like to debug or flash your ARM processor on your own, here are some of our ARM Programmers:

J-Link BASE Compact Programmer

J-Link BASE Compact Programmer

PGM-15347
$378.00
J-Link EDU Mini Programmer

J-Link EDU Mini Programmer

PGM-15345
$18.00
1
J-Link EDU Base Programmer

J-Link EDU Base Programmer

PGM-15346
$60.00
JTAG USB OCD Programmer/Debugger for ARM processors

JTAG USB OCD Programmer/Debugger for ARM processors

PGM-07834
$71.95
1

Suggested Reading

Before continuing on with this tutorial, you may want to familiarize yourself with some of these topics if they’re unfamiliar to you:

How to Solder: Through-Hole Soldering

This tutorial covers everything you need to know about through-hole soldering.

Logic Levels

Learn the difference between 3.3V and 5V devices and logic levels.

I2C

An introduction to I2C, one of the main embedded communications protocols in use today.

ARM Programming

How to program SAMD21 or SAMD51 boards (or other ARM processors).
Qwiic Connect System


One of the new, advanced features of the board is that it takes advantage of the Qwiic connect system. We recommend familiarizing yourself with the Logic Levels and I2C tutorials (above) before using it, as all Qwiic sensors utilize an I2C communication protocol. Click on the banner above to learn more about Qwiic products.

Hardware Overview

Power & Programming

There are a few different ways to power the SparkFun RED-V Thing Plus:

  • USB-C
  • JST connector (battery power)
  • power pins broken out on the edge of the board

The easiest way (which will also allow you to program your board) is to simply plug it into your computer via USB-C. This will provide 5V to the board and will also allow you access to the super cool USB-to-JTAG interface for programming. Once you've programmed your RED-V however, you may want to have it running off of a different power supply. If you use a wall wart on the USB-C connector, make sure it outputs a regulated 5V DC. You can also use the black JST connector to provide battery power from a LiPo battery. There is an on-board LiPo charger with the current rate set to 500mA. Make sure to use LiPo batteries that have a capacity greater than 500mAh when charging. If you decide to power the board via the VUSB or VBAT pins, make sure to not exceed 6.5V since this is the absolute maximum for the 3.3V voltage regulator. Or you can power the board through the breakout pins on the edge of the board. If you are using 3V3 and GND, make sure that your voltage is regulated when applying power to the pin.

USB, JST, and Power Pins

Always-On Core

The FE310 contains an Always-On (AON) block that allows easy power control of the FE310. It includes its own real-time clock and is also attached to the WAKE button on the board. This allows you to put the FE310 to sleep and wake it up upon a time-generated or user-generated interrupt.

alt text

Buttons

The RED-V has two buttons: a RESET button and a WAKE button. The RESET button is pretty self explanatory and is used to reset the FE310. A single tap of the RESET button will run the code loaded onto the FE310's QSPI flash. A quick double tap will put the FE310 into safe bootloader mode, which will allow you to flash new code to the RED-V if you've managed to really mess things up (i.e. Oops I put the core to sleep and forgot to add a way to wake it up). The pin is also broken out on the edge of the board. Adding a jumper wire from this pin to GND will reset the board as well.

Reset Button and Pin

The RED-V is also equipped with an Always-On or AON core (mentioned above) which can be programmed to shut down the main core of the FE310 and wake it up upon a button-generated or user-generated interrupt. The WAKE button can be configured in software to wake the FE310 from deep sleep.

Wake Button

Jumpers

The FE310 has a few jumpers as well, all of which are open by default. The two jumpers located next to the I2C label is for the I2C pull-up resistors. These resistors are not attached by default as there are I2C pull-up resistors on all SparkFun Qwiic slaves. If you're using a 3rd party board, you may need to close these jumper by the Qwiic connector to attach the pull-ups to the I2C bus. The jumper by the USB-C connector (next to the Segger logo) is for bypassing the 0.5A PTC fuse. This is for special cases where you need a lot current. If you need to connect the NC pin to GND, you can also add a solder jumper on the pads as well. Most of the time, you can leave the bypass and NC jumpers open.

Pull-Up Resistors and By-Pass jumper

Dimensions

The RED-V Thing Plus measures at 2.3"x0.90".

Dimensions

Resources and Going Further

Now that you've successfully got started with your SAMD51 Thing Plus, it's time to incorporate it into your own project! For more information, check out the resources below:


learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

RED-V Development Guide

$
0
0

RED-V Development Guide a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t1101

Introduction

This guide will help you get the RED-V RedBoard or Thing Plus up and running for the exhaust port. Depending on personal preference, there are a few environments to get started with the boards. All wings report in... we're going in full-throttle.

GIF of Targeting Retical
Warning: Do NOT attempt to reprogram the NXP K22 ARM Cortex-M4. It has proprietary Segger firmware flashed onto the chip, which allows it to upload programs the SiFive Freedom E310 core. Reprogramming the NXP K22 ARM Cortex-M4 will overwrite the firmware and you will no longer be able to reprogram the board. To replace the firmware, you will need to purchase a license from Segger along with one of their programmers.

Required Software

Computer with Freedom Studio installed on it or a Zephyr RTOS build environment set up - that is how we will program the board and interface with it.

Suggested Reading

If you aren't familiar with the RED-V hardware, we recommend checking out these tutorials before continuing.

New!

RED-V RedBoard Hookup Guide

November 22, 2019

This guide will go over the hardware of the RED-V RedBoard.
New!

RED-V Thing Plus Hookup Guide

November 22, 2019

This guide will go over the hardware of the RED-V Thing Plus.

What is RISC-V?

RISC-V (pronounced “risk-five”) is a free and open instruction set architecture (ISA) developed by the Computer Science Division of the University of California, Berkeley. The RISC-V ISA is designed to provide "a new level of free, extensible software and hardware freedom on architecture." According to the RISC-V Foundation, the key benefits of RISC-V are:

  • "Software architects / firmware engineers / software developers
    • RISC-V is much more than an open ISA, it is also a frozen ISA. The base instructions are frozen and optional extensions which have been approved are also frozen. Because of the stability of the ISA, software development can confidently be applied to RISC-V knowing that your investment will be preserved. Software written for RISC-V will run on all similar RISC-V cores forever. The frozen ISA provides a solid foundation that software managers can depend on to preserve their software investments. Because the RISC-V ISA is open, this translates to hardware engineers having more flexibility over the processor implementation. With this power, software architects can become more influential in the final hardware implementation. They can provide input to hardware designers to make the RISC-V core more software centric.
  • CTOs / Chip designers / System Architects
    • Innovation is the key enabler of RISC-V. Because the ISA is open, it is the equivalent of everyone having a micro architecture license. One can optimize designs for lower power, performance, security, etc. while keeping full compatibility with other designs. Because there is significantly more control over the hardware implementation, all technical recipients of the architecture can make suggestions at a much earlier point than previously was possible. The result is a solution with significantly fewer compromises. RISC-V also supports custom instructions for designs which require particular acceleration or specialty functions.
  • Board designers
    • In addition to the frozen ISA benefits, RISC-V’s open ISA can provide several additional benefits. For example, if engineers are implementing a soft RISC-V core in an FPGA, often the RTL source code is available. Since RISC-V is royalty free this creates significant flexibility to port a RISC-V based design from an FPGA to an ASIC or another FPGA without any software modifications. Designers who are concerned with security from a trust perspective will also appreciate RISC-V. When the RTL source code is available, this enables deep inspection. With the ability to inspect the RTL, one can establish trust."

For more information about RISC-V, head to the RISC-V Foundation website.

Software Installation (Freedom Studio)

Troubleshooting Tip: The Freedom Studio and E SDK has been tested to work with Windows 10, 64-bit. You are free to follow the open source guides to use the OS of your choice, but our technical knowledge is limited to the content of this tutorial.

In this section, we're going to figure out how to get started developing on our SparkFun RED-V development board. There are a handful of development environments out there that are compatible with the RED-V but we're going to be checking out Freedom Studio and Zephyr RTOS. Both development environments have a decent assembly of example code to help get you up and learning RISC-V.

Installing Freedom Studio

The quickest way to get started programming your RED-V is through SiFive's Eclipse-based Freedom Studio. If you have not already, head over to SiFive's website to download Freedom Studio for your operating system and unzip the files.

You'll need to scroll down to the section where it says Freedom Studio and click on your respective operating system.

Download Freedom Studio from SiFive

Click on image for a closer view.

The Freedom Studio bundle contains some pretty lengthy paths in our system which can occasionally cause problems during extraction on Windows systems. Due to this, it's important to enable long paths as well as unzip to a location like C:/FreedomStudio/ to keep your paths as short as possible. To enable long paths, simply download and double click the below registry file. This is only necessary on a Windows machine. Follow the prompts to install the paths.

Drivers (Freedom Studio)

With the software installed, you'll need to make sure that the drivers are installed for your computer. If you have a Windows operating system, you will need to install the drivers in order to upload code or send serial data to the FE310.

Windows

To install the drivers, head to the Freedom Studio program's driver folder. The drivers should be located under the following path:

language:bash
C:\FreedomStudio\SiFive\jlink-6.52.5-2019.08.0\USBDriver

The drivers are dependent on the operating system that you are using. For 64-bit based OS, you'll need to click on the Windows version with the x64 in the folder name. For 32-bit based OS, you'll need to click on the one with the x86 in the folder name. We'll be using a Windows 10 64-bit based OS, so we'll click on the folder named x64 and then dpinst_x64.exe

image of folder open with driver highlighted on Windows 10

Click on image for a closer view.

After clicking on the driver executable, follow the prompts to install the drivers for your Windows.

Examples (Freedom Studio)

Example: Hello World!

Once everything is unzipped, you'll simply need to run 'FreedomStudio.exe' to install the application. Upon opening Freedom Studio, we'll want to create a new project from one of our example templates. To do this, go to File>New>Freedom E SDK Software Project.

New Freedom E SDK Software Project

Click on image for a closer view.

SparkFun's RED-V RedBoard and Thing Plus are very similar to to SiFive's HiFive1 RevB, so we'll be selecting the HiFive1 Rev B (sifive-hifive-revb) as our target board selection.

Board Selection

Click on image for a closer view.

To start, let's keep it simple by flashing the "Hello World" example to our RED-V and see some serial output.

Select Hello Example

Click on image for a closer view.

Select hello from the drop down menu. Hit Finish to load the example. You'll need to wait a little as the example project builds.

Example Template

Click on image for a closer view.

Run

After the sketch builds, a window will open to edit the debug configuration. For now, click on the Close button. Now that the example is built, hit the run button to upload and execute the code on the RED-V. If you have more than one project saved, simply click on the drop down menu next to the run button to select the project to compile and run.

Run button

Click on the image for a closer view.

Freedom Studio will then attempt to flash and run the sketch. However, your GDB server might be configured incorrectly to be able to flash code through Freedom Studio. To fix this, go to Run ->Run Configurations... from the menu.

Run Configuration

Click on the image for a closer view.

Open the SiFive GDB SEGGER J-Link Debugging tree on the left hand side of the window, select your project, and hit the Run button. This will flash the code over USB and begin running your code as well.

Run Configurations

Click on the image for a closer view.

Drag and Drop

Another way to flash is using the shortcut CTRL+B to build all the files; this will generate a *.hex file in the Project Explorer under src ->debug ->hello.hex .

HEX file location

Click on the image for a closer view.

You may have noticed that the RED-V shows up as a flash drive when you plug it into your computer. With the window for the drive opened, drag and drop the *.hex directly onto this drive to program the RED-V.

Drag and drop HEX file into RED-V Drive Folder

Click on the image for a closer view.

What You Should See

The program will begin running once the code has been uploaded to the RED-V RedBoard. To see the serial output, you'll need a serial terminal. While you could connect using your favorite serial terminal, we'll use the one built into the Freedom Studio. In the Freedom Studio software, you'll notice a window on the bottom right of the software. Click on the tab labeled as Terminal and then the icon with the monitor.

Open Serial Terminal

Click on the image for a closer view.

A new window will pop up asking for you to choose your serial terminal and the settings. Click on the Choose terminal: menu and select Serial Terminal. The board will show up as two COM ports on your computer: one for the bootloader and another one for the example program. Most likely the COM port will show up as the one with the second to highest number. The default baud rate of the example projects are set to 115200 baud (8 data bits, no parity, 1 stop bit, default encoding). With the correct settings, hit the OK button to connect. The example code will print "Hello World!" once so we'll need to hit the reset button on the board one time.

You'll some serial output as the RED-V boots up. Once it enters the example program, the RED-V RedBoard will output the familiar message that all programmers know and love: "Hello, World!"

language:bash
Bench Clock Reset Complete

ATE0--> Send Flag error: #255 #255 #255 #255 AT+BLEINIT=0--> Send Flag error: #255 #255 #255 #255 AT+CWMODE=0--> Send Flag error: #255 #255 #255 #255 
Hello, World!

Hello World Success!

Click on the image for a closer view.

Example: Blink

Now that we have output some serial to a terminal window, let's try to blink the LED on the RED-V. Let's just use the example project that we have open already in Freedom Studio. Copy and paste the example below into the text editor.

language:c
/******************************************************************************
    RED-V_blink.c

    WRITTEN BY: Ho Yun "Bobby" Chan and "Tron Monroe"
    @ SparkFun Electronics
    DATE:  11/21/2019

    DEVELOPMENT ENVIRONMENT SPECIFICS:
      Firmware developed using Freedom Studio v4.12.0.2019-08-2
      on Windows 10

    ========== RESOURCES ==========
    Freedom E SDK

    ========== DESCRIPTION ==========
    Using the built-in LED. To test with different pin,
    simply modify the reference pin and connect a standard LED
    and 100?O resistor between the respective pin and GND.

    LICENSE: This code is released under the MIT License (http://opensource.org/licenses/MIT)
  ******************************************************************************/


#include <stdio.h>      //include Serial Library
#include <time.h>       //include Time library
#include <metal/gpio.h> //include GPIO library, https://sifive.github.io/freedom-metal-docs/apiref/gpio.html

//custom write delay function since we do not have one like an Arduino
void delay(int number_of_microseconds){ //not actually number of seconds

// Converting time into multiples of a hundred nS
int hundred_ns = 10 * number_of_microseconds;

// Storing start time
clock_t start_time = clock();

// looping till required time is not achieved
while (clock() < start_time + hundred_ns);

}

int main (void) {
  printf("RED-V Example: Blink\n");

  struct metal_gpio *led0; //make instance of GPIO

  //Note: The sequence of these commands matter!

  //Get gpio device handle, i.e.) define IC pin here where IC's GPIO = 5, pin silkscreen = 13
  //this is the GPIO device index that is referenced from 0, make sure to check the schematic
  led0 = metal_gpio_get_device(0);

  // quick check to see if we set the metal_gpio up correctly, this was based on the "sifive-welcome.c" example code
  if (led0 == NULL) {
    printf("LED is null.\n");
    return 1;
  }
  //Pins are set when initialized so we must disable it when we use it as an input/output
  metal_gpio_disable_input(led0, 5);

  //Set as gpio as output
  metal_gpio_enable_output(led0, 5);

  //Pins have more than one function, make sure we disconnect anything connected...
  metal_gpio_disable_pinmux(led0, 5);

  //Turn ON pin
  metal_gpio_set_pin(led0, 5, 1);


  while (1) {//loop through, sort of like an Arduino loop()

      //Turn OFF pin
      metal_gpio_set_pin(led0, 5, 0);
      //Use custom "delay" function
      delay(2000000); //2000000 "micro-seconds" ~ 1 second, through experimentation...
      //Turn ON pin
      metal_gpio_set_pin(led0, 5, 1);
      //Use custom "delay" function
      delay(2000000);

  }

  // return
  return 0;
}

When ready, hit the run button to compile and upload. You can also compile and drag the *.hex into the drive.

What You Should See

There'll be an output on the terminal window indicating that we are using the blink code. What we are more interested in is if the LED is turning on and off. Check your board and you should see the built-in LED begin to blink about once a second! Make sure to check out the comments in the example code. Toggling the LED is not as intuitive and straight forward as controlling an LED on an Arduino.

Software Installation (Zephyr RTOS)

Troubleshooting Tip: The Zephyr RTOS has been tested to work with Linux (Ubuntu v18.04.3, 64-bit) . You are free to follow the open source guides to use the OS of your choice, but our technical knowledge is limited to the content of this tutorial.

Again, there are a handful of development environments out there that are compatible with the RED-V but for the scope of this tutorial, we're going to be checking out Freedom Studio and Zephyr RTOS. Both development environments have a decent assembly of example code to help get you up and learning RISC-V. Let's check out the Zephyr RTOS software.

Installing Python

The next method to get started is using Zephyr RTOS. We've had the best luck using Zephyr on Linux-based operating systems, so we'd recommend using your favorite Linux distro. From there, we want to make sure we have Python 3 and pip installed, so run the following commands.

language:bash
sudo apt-get install python3
sudo apt-get install python3-dev python python3-pip
sudo pip3 install ipython
sudo pip3 install numpy
sudo pip3 install pyelftools

Installing CMake and Ninja

We'll need quite a few things like CMake and Ninja to compile things, so run the below code to get all of your dependencies set up.

language:bash
sudo apt-get install --no-install-recommends git cmake ninja-build gperf \
ccache dfu-util device-tree-compiler wget \
python3-pip python3-setuptools python3-tk python3-wheel xz-utils file \
make gcc gcc-multilib

We'll also need to update CMake on our system, go ahead and download the package here. We used version 3.15.4 on Ubuntu v18.04.3 when writing this tutorial.

Run the below commands to extract, make, and install it.

language:bash
cd ~/Downloads
tar xvzf cmake-3.15.4.tar.gz
cd cmake-3.15.4
./configure
make
sudo make install

Installing West and Zephyr RTOS

Zephyr uses a tool called west to build code for and flash the RED-V, we'll want to install this as root to avoid any permissions issues. We used version 0.6.3 on Ubuntu v18.04.3 when writing this tutorial.

language:bash
sudo pip3 install west

We'll then want to create and initialize our west project, to do this, run the following.

language:bash
west init zephyrproject
cd zephyrproject
west update
sudo pip3 install -r zephyr/scripts/requirements.txt

We'll need the Zephyr SDK as well as this is where all of our toolchains are bundled. Grab it from GitHub and install it in your home directory. If you'd like to install a different version of the SDK, simply change the version number everywhere it shows up.

language:bash
cd ~/
wget https://github.com/zephyrproject-rtos/sdk-ng/releases/download/v0.10.3/zephyr-sdk-0.10.3-setup.run
chmod +x zephyr-sdk-0.10.3-setup.run
./zephyr-sdk-0.10.3-setup.run -- -d ~/zephyr-sdk-0.10.3
export ZEPHYR_TOOLCHAIN_VARIANT=zephyr
export ZEPHYR_SDK_INSTALL_DIR=$HOME/zephyr-sdk-0.10.3

We'll also need to update our device tree compiler, follow the link below to find an appropriate download.

Run the commands below to install the new DTC.

language:bash
cd ~/Downloads
sudo apt install ./device-tree-compiler_1.4.7-1_amd64.deb

Drivers (Zephyr RTOS)

We'll need some J-Link software so we can communicate with the Segger J-Link OB on the RED-V. Head to Segger to download the software under "J-Link Software and Documentation pack for Linux, DEB installer, 64-bit." Read through the license agreement before accepting the terms and hit the "Download software" button. We used version 6.56a on Ubuntu v18.04.3 when writing this tutorial.

We should still be in the Downloads folder, so installing the software is as simple as running the below command. Depending on the software package, you may need to update the version name.

language:bash
sudo apt install ./JLink_Linux_V646a_x86_64.deb

Examples (Zephyr RTOS)

Examples: Hello World

Phew, that's all done. Now we can move to the directory that was earlier created when we ran west init zephyrproject and build a project.

language:bash
cd ..
cd zephyrproject/zephyr
west build -b hifive1_revb samples/hello_world

We can now check to make sure our RED-V is connected. You should see a SEGGER device pop up when you run lsusb. If it's connected, go ahead and run west flash. Note that this may take a couple of tries, sometimes it helps to give the ol' reset button a tap or two and try again.

language:bash
west flash

What You Should See

Once uploaded, try opening a serial terminal to connect to the RED-V. Let's use the GNU screen. If you don't have it installed yet, type the following in the command line.

language:bash
sudo apt-get install screen

There are two serial ports that the RED-V enumerates to when inserted into the USB port. Type the following command to view the serial ports connected.

language:bash
dmesg | grep tty

Unplug and replug the RED-V to your USB port and type the command again. The messages that appear multiple times will be the RED-V. In this case, it should either be ttyACM0 or ttyACM1.

Serial Ports Available

Connect to one of the ports using the following command set at 115200 baud.

language:bash
screen /dev/ttyACM0 115200

Since the example code only prints the message once, we'll need to hit the reset button once on the RED-V. You should see something similar to the Hello Wold example in Freedom Studio.

language:bash
Bench Clock Reset Complete

ATE0--> Send Flag error: #255 #255 #255 #255 AT+BLEINIT=0--> Send Flag error: #255 #255 #255 #255 AT+CWMODE=0--> Send Flag error: #255 #255 #255 #255 
***** Booting Zephyr OS build v2.1.0-rc1-259-g77006e896ba0 *****
Hello, World! hifive1_revb

Hello World Output

To disconnect CTRL + A and then \. You'll be asked by the application if you would like to exit. Type y and ENTER to exit the session.

If you want to build a different project, simply delete the build directory using the following command to delete the folder. Then run west build again for your other project.

language:bash
rm -rv build/

For those that prefer the GUI, just head to the folder and to manually delete.

Delete Build Folder

Examples: Blinky

Let's try to control the build-in LED on the RED-V. Head to the blink example and modify for GPIO pin 5.

language:bash
cd ~/zephyrproject/zephyr/samples/basic/blinky/src
gedit main.c

You can also navigate to the example using the GUI to open the blink example.

Head to the Blinky Example Folder

Once the modified.c file is open, change the definition for LED from DT_ALIAS_LED0_GPIOS_PIN to 5. We'll need to use the GPIO pin reference for the FE310 as opposed to the silkscreen label on the RED-V. You can also copy and paste the following into the file.

language:c
/*
 * Copyright (c) 2016 Intel Corporation
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <zephyr.h>
#include <device.h>
#include <drivers/gpio.h>

#define LED_PORT    DT_ALIAS_LED0_GPIOS_CONTROLLER
#define LED     5

/* 1000 msec = 1 sec */
#define SLEEP_TIME  1000

void main(void)
{
    u32_t cnt = 0;
    struct device *dev;

    dev = device_get_binding(LED_PORT);
    /* Set LED pin as output */
    gpio_pin_configure(dev, LED, GPIO_DIR_OUT);

    while (1) {
        /* Set pin to HIGH/LOW every 1 second */
        gpio_pin_write(dev, LED, cnt % 2);
        cnt++;
        k_sleep(SLEEP_TIME);
    }
}

After changing, save the changes and hit CTRL+C in the terminal window. Head back to the zephyr folder to delete the build folder if you have not already. Then recompile the blink example and flash it to your RED-V board.

language:bash
cd ~/zephyrproject/zephyr/
rm -rv build/
west build -b hifive1_revb samples/basic/blinky
west flash

What You Should See

Check the built-in LED on the RED-V board. You should see the build-in LED blink every second!

Troubleshooting

Freedom Studio

Below is an issue that you may run into when using the RED-V in Freedom Studio.

Issues Uploading to the RED-V Again

There are a few reasons why if you have problems uploading code. If you recently uploaded code and the board is still connected to your computer, you'll need to make sure to hit terminate (i.e. the button that looks like a red square) before uploading again. This is because Freedom Studio is still connected to the board in debug mode.

Upload Error

If you uploaded several times to the board and have issues uploading after clicking on the terminate button, try disconnecting the RED-V from your USB port. Then re-insert the board back.


Zephyr RTOS

Below is one issue that you may run into when using the RED-V in Zephry RTOS.

Issues Compiling

If you have issues compiling, you may have missed a step when installing the software for the Zephry RTOS. Try going through the command lines again to ensure that the software and tools are installed correctly. You also may need to run the west build command a few more times to compile.

Resources and Going Further

Now that you've successfully got your RED-V up and running, it's time to incorporate it into your own project! For more information, check out the resources below:


learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

Basic LED Animations for Beginners (Arduino)

$
0
0

Basic LED Animations for Beginners (Arduino) a learn.sparkfun.com tutorial

Available online at: http://sfe.io/t999

Introduction

The control of light has been a quest for humankind older than written history. The power of illumination stirs a biological feeling in us all. We've evolved from chemical combustion of energy stored in wood to the greater volatility of gasoline vapor. The physical flame was then replaced by warm, glowing, delicate, metal coils. My favorite method of light is as simple as the humble electron shedding energy through the process of Electroluminescence. Light Emitting Diodes, LEDs, are vastly more energy efficient than past methods and provides near endless possibilities for combating the darkness.

LED Projects

In this tutorial, we will revisit some concepts about using LEDs and make some fun effects using the RedBoard Qwiic to control the individual LEDs.

Required Materials

To follow along with this tutorial, you will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

This list is just a trimmed down list from our new SparkFun Inventor's Kit featuring the RedBoard Qwiic. If you'd rather purchase the full set for more electrical goodies, please feel free.

SparkFun Inventor's Kit - v4.1

SparkFun Inventor's Kit - v4.1

KIT-15267
$99.95
2

Revisit Basics

Let's keep in mind a couple of key notes about LEDs:

  1. Like any other diode, current will only flow in ONE direction.
  • High enough voltages will make it flow either way, but only for a split moment, you know, the magic smoke...
  • Also, like any other diode, there is a 'minimum' voltage needed to work.
  • Lastly, the 'blue-r' the light, the more energy we're using.
  • If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing. Many of these notes listed above were covered in an earlier tutorial explaining basics circuit rules using LEDs. If you want to revisit that tutorial, please feel free to check it out.

    Light-Emitting Diodes (LEDs)

    August 12, 2013

    Learn the basics about LEDs as well as some more advanced topics to help you calculate requirements for projects containing many LEDs.

    If you're new to Arduino, breadboards, or other electronic basics, please take a minute to visit these other tutorials and guides that are full of goodies.

    How to Use a Breadboard

    Welcome to the wonderful world of breadboards. Here we will learn what a breadboard is and how to use one to build your very first circuit.

    What is Electricity?

    We can see electricity in action on our computers, lighting our houses, as lightning strikes in thunderstorms, but what is it? This is not an easy question, but this tutorial will shed some light on it!

    SparkFun Inventor's Kit Experiment Guide - v4.1

    The SparkFun Inventor's Kit (SIK) Experiment Guide contains all of the information needed to build all five projects, encompassing 16 circuits, in the latest version of the kit, v4.1.

    Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE.

    If you've never connected an CH340 device to your computer before, you may need to install drivers for the USB-to-serial converter. Check out our section on How to Install CH340 Drivers" for help with the installation.

    Forward Voltage

    LEDs, like other diodes, require a 'minimum' voltage to work. In circuit analysis, we call this a voltage drop. With diodes, we consider that forward voltage 'using' a chunk of the available voltage. Troubleshooting tip #1:

    • Check that the voltage on the anode and cathode meets the minimum forward voltage for operation. I use the term minimum loosely because you can touch an old dying battery to the LED terminals and still see a faint light.

    Currently, There's Too Much Current

    We've established that there are minimum requirements for LEDs, but there are maximums as well. In most physics books, the analog example for current is water. Well, if you've ever had a pipe burst then you'll know the dangers of too much, too soon. Again, check the datasheet for your LED's and make sure you're not applying too much voltage. If you up the voltage, you up the current. Troubleshooting tip #2:

    • If you see a blip of light followed by a dark spot inside the LED, then we've done and busted it. (Also, remember this tip if you have old LEDs that can't seem to light up, maybe someone made an oopsie.)

    Resistance Can Be a Force for Good

    A big key point for the first two topics is using resistors to limit the current. If your voltage is too high, then using the right resistor can drop that down to a safer level when used in series with the LED. Let's say that the voltage is fine but the diode keeps blowing and you're low on LEDs. While it's not ideal, there are resistors designed to blow at high current: fuse resistor.

    Resistors

    April 1, 2013

    A tutorial on all things resistors. What is a resistor, how do they behave in parallel/series, decoding the resistor color codes, and resistor applications.

    Simple ON/OFF with GPIO

    It’s simple enough to just touch LED pins to a coin-cell, even add a little tape and you have a super simple flashlight. What about control, what about the pizzazz? Just because LEDs only allow current in one direction doesn’t mean you can only go one direction. We’re going to put together some simple components and play around with what microcontrollers can do to for our lighting needs.

    Let’s first talk about GPIOs. These are General Purpose Input and Outputs, meant simply for input and output. This means that depending on how we set it up, that pin will receive a voltage signal or put out a voltage signal. On the RedBoard, our “On” (or output) voltage is a super useful 5 Volts. We make the ATMEGA IC do this by writing digitalWrite(PIN_NUMBER, HIGH); in our Arduino code. However, you'll notice that won't really work if you just copy paste that into the loop section. We have to declare what we want that pin to be. So we make a variable to easily reference our pin number: PIN_NUMBER. For the simplicity, we'll use the defualt pin 13 on the RedBoard Qwiic. Then up in setup() function, we need to write pinMode(PIN_NUMBER, OUTPUT);. What this means is that our IC is dedicating that pin to be an output. So when we write that digital high, the IC knows exactly what to do. If you hooked up an multimeter, or oscilloscope, that pin would be at 5V relative the GND (0V) until you declare it LOW with digitalWrite(PIN_NUMBER, LOW);. In a nutshell, that's a blink, off to on and then back to off. We can add time delays for different effects.

    language:c
    //This example turn a GPIO pin ON and OFF with a delay.
    
    const int PIN_NUMBER = 13; //Replace 'PIN_NUMBER' with a physical pin, we'll use the built-in LED on pin 13 on the RedBoard Qwiic
    
    void setup() {
      pinMode(PIN_NUMBER, OUTPUT);    //set digital pin as output
    }
    
    void loop() {
    
      digitalWrite(PIN_NUMBER, HIGH); //LED connected to pin 13 comes ON
      delay(5000);                    //delay(Milliseconds), so '5000' is 5 seconds
      digitalWrite(PIN_NUMBER, LOW);  //LED connected to pin 13 goes OFF
      delay(5000);                    //delay(Milliseconds), so '5000' is 5 seconds
    
    }
    

    "Ok, What Does this Mean for Me?"

    This demonstrates that these "auxillary pins" can be for input, or in our case for output. There are so many options after we make this step. From this point forward, we're going to explore what some fun arrangements, effects, and practical uses for LEDs can be.

    I may be hammering home too much about pins on the microcontroller. They warrant their own slew of tutorials, but we're not here for those. I'm pushing them because they will be the web of control for our multiple LEDs.

    The big picture is that at some spot in our circuit, there is a point of voltage. If this point of voltage is high enough (and not too high, so we don't blow the LED) then we can illuminate our LED. The output of a GPIO pin is a power source for our needs. One could think of them as fancy switches in a room full of switches and bulbs.

    Lights, Camera, ACTION

    Blink like Booyah

    Check out the circuit diagram below to see how everything is connected.

    Circuit Diagram Multiple LEDs Blinking

    Having a hard time seeing the circuit? Click on the image for a closer look.

    I had a liberty with having some fun with this one. We're turning on each LED set one by one. Once the set is turned on, we'll turn them each off one by one before moving to the next set.

    Copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

    language:c
    //This example turns on each LED set one by one. Once the set is turned on, we'll turn them each off one by one before moving to the next set. 
    
    //Declare pins
    const int GREEN_A = 8;
    const int GREEN_B = 7;
    const int GREEN_C = 6;
    const int RED_A = 5;
    const int RED_B = 4;
    const int RED_C = 3;
    const int BLUE_A = 11;
    const int BLUE_B = 10;
    const int BLUE_C = 9;
    
    const int turn_time = 300;      //Play with this integer!!
    
    void setup() {
      // initialize pins as output
      pinMode(GREEN_A, OUTPUT);
      pinMode(GREEN_B, OUTPUT);
      pinMode(GREEN_C, OUTPUT);
      pinMode(RED_A, OUTPUT);
      pinMode(RED_B, OUTPUT);
      pinMode(RED_C, OUTPUT);
      pinMode(BLUE_A, OUTPUT);
      pinMode(BLUE_B, OUTPUT);
      pinMode(BLUE_C, OUTPUT);
    }
    
    void loop() {  
      //These sequences just turn on 3 of the same color one by one. Then turn them off
      //one by one.
      digitalWrite(BLUE_A, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(BLUE_B, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(BLUE_C, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(BLUE_A, LOW);    // turn the LED off by making the voltage LOW
      delay(turn_time);                       // wait for a second
      digitalWrite(BLUE_B, LOW);    // turn the LED off by making the voltage LOW
      delay(turn_time);                       // wait for a second
      digitalWrite(BLUE_C, LOW);    // turn the LED off by making the voltage LOW
      delay(turn_time);                       // wait for a second
    
      digitalWrite(GREEN_A, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(GREEN_B, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(GREEN_C, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(GREEN_A, LOW);   // turn the LED off (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(GREEN_B, LOW);   // turn the LED off (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(GREEN_C, LOW);   // turn the LED off (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
    
      digitalWrite(RED_A, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(RED_B, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(RED_C, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(turn_time);                       // wait for a second
      digitalWrite(RED_A, LOW);    // turn the LED off by making the voltage LOW
      delay(turn_time);                      // wait for a second
      digitalWrite(RED_B, LOW);    // turn the LED off by making the voltage LOW
      delay(turn_time);                      // wait for a second
      digitalWrite(RED_C, LOW);    // turn the LED off by making the voltage LOW
      delay(turn_time);                      // wait for a second
    
    }
    

    We should play with this one a bit. Change the value of turn_time. The delay() function takes these integer inputs and they represent milliseconds. 50 will go really quick, 5000 will go really slow.

    Demo of LEDs Blinking

    Hypno-Toad

    Check out the circuit diagram below to see how everything is connected.

    Circuit Diagram LEDs Fading In and Out

    The Arduino IDE has really great entry level examples aside from blink. A favorite of mine is an LED Fade. We're going to modify it to fade two LEDs and use them as eyes. The fade function relies on analogWrite(). This function outputs a Pulse Width Modulation (PWM) signal. At low integer values the signal will make the LED dim, and will make the LED bright at high integer values.

    Copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

    language:c
    //This example fades an LED on and off. Then the other LED will fade in and out. 
    
    //Declare pins and variables
    const int ledA = 9;
    const int ledB = 10;
    int brightness = 0;
    int fadeAmount = 5;
    
    void setup() {
    
      //Declare pins as outputs
      pinMode(ledA, OUTPUT);
      pinMode(ledB, OUTPUT);
    }
    
    void loop() {
    
      //ledA will fade on
      for (int i = 0; i <= 255;) {
        analogWrite(ledA, brightness);
        brightness += fadeAmount;
        i += fadeAmount;
        delay(30);
      }
    
      //ledA will fade off
      for (int i = 255; i >= 0;) {
        analogWrite(ledA, brightness);
        brightness -= fadeAmount;
        i -= fadeAmount;
        delay(30);
      }
    
      //ledB will fade on
      for (int j = 0; j <= 255;) {
        analogWrite(ledB, brightness);
        brightness += fadeAmount;
        j += fadeAmount;
        delay(30);
      }
    
      //ledB will fade off
      for (int j = 255; j >= 0;) {
        analogWrite(ledB, brightness);
        brightness -= fadeAmount;
        j -= fadeAmount;
        delay(30);
      }
    
    }
    

    You should see one LED fade on and off. Then the other LED will fade in and out. I printed a popular cartoon image and punched holes through the eyes for the LEDs. Try searching the Internet for a fun image and make some holes yourself. You may need to adjust the size of the image and position of the LEDs to align the eyes. Go crazy with it!

    Fading LED Eyes

    Binary Counter

    A not so glamorous topic in computer science are binary numbers, a.k.a the infamous 1's and 0's. When we count in binary, we represent numbers with arrangments of 1's and 0's. For example, if I wanted to write the number 4, I would need a 'binary sentence' of 0100. If you'd like to learn more about binary numbers, we have a tutorial about binary numbers that you can explore for more information here.

    Binary

    February 7, 2013

    Binary is the numeral system of electronics and programming...so it must be important to learn. But, what is binary? How does it translate to other numeral systems like decimal?

    The binary project we'll run today will use the LEDs to represent 1's and 0's. An LED that's on is a 1, off will be a 0. Also, a special note about the code, we'll be using switch statements instead of if() statements. If you're not familiar with switch statements, please make sure to check out the Arduino reference language to familiarize yourself.

    Check out the circuit diagram below to see how everything is connected.

    Circuit Diagram Binary Counter

    Copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

    language:c
    //This example toggles uses LEDs as a binary counter.
    
    //Declare pins
    const int ledA = 3; //In binary, this pin will be the right-most digit or 1st position
    const int ledB = 4; //2nd position
    const int ledC = 5; //3rd position
    const int ledD = 6; //4th position
    
    void setup() {
      //Declare pins as outputs
      pinMode(ledA, OUTPUT);
      pinMode(ledB, OUTPUT);
      pinMode(ledC, OUTPUT);
      pinMode(ledD, OUTPUT);
    }
    
    void loop() {
      for (int i = 0; i < 16; i++) {
        switch (i) {
          case 0:  //0 = 0b0000
            delay(1000);
            digitalWrite(ledA, LOW);
            digitalWrite(ledB, LOW);
            digitalWrite(ledC, LOW);
            digitalWrite(ledD, LOW);
            break;
    
          case 1: //1 = 0b0001
            digitalWrite(ledA, HIGH);
            delay(1000);
            digitalWrite(ledA, LOW);
            break;
    
          case 2: //2 = 0b0010
            digitalWrite(ledB, HIGH);
            delay(1000);
            digitalWrite(ledB, LOW);
            break;
    
          case 3: //3 = 0b0011
            digitalWrite(ledA, HIGH);
            digitalWrite(ledB, HIGH);
            delay(1000);
            digitalWrite(ledA, LOW);
            digitalWrite(ledB, LOW);
            break;
    
          case 4: //4 = 0b0100
            digitalWrite(ledC, HIGH);
            delay(1000);
            digitalWrite(ledC, LOW);
            break;
    
          case 5: //5 = 0b0101
            digitalWrite(ledA, HIGH);
            digitalWrite(ledC, HIGH);
            delay(1000);
            digitalWrite(ledA, LOW);
            digitalWrite(ledC, LOW);
            break;
    
          case 6: //6 = 0b0110
            digitalWrite(ledB, HIGH);
            digitalWrite(ledC, HIGH);
            delay(1000);
            digitalWrite(ledB, LOW);
            digitalWrite(ledC, LOW);
            break;
    
          case 7: //7 = 0b0111
            digitalWrite(ledA, HIGH);
            digitalWrite(ledB, HIGH);
            digitalWrite(ledC, HIGH);
            delay(1000);
            digitalWrite(ledA, LOW);
            digitalWrite(ledB, LOW);
            digitalWrite(ledC, LOW);
            break;
    
          case 8: //8 = 0b1000
            digitalWrite(ledD, HIGH);
            delay(1000);
            digitalWrite(ledD, LOW);
            break;
    
          case 9: //9 = 0b1001
            digitalWrite(ledA, HIGH);
            digitalWrite(ledD, HIGH);
            delay(1000);
            digitalWrite(ledA, LOW);
            digitalWrite(ledD, LOW);
            break;
    
          case 10: //10 = 0b1010
            digitalWrite(ledB, HIGH);
            digitalWrite(ledD, HIGH);
            delay(1000);
            digitalWrite(ledB, LOW);
            digitalWrite(ledD, LOW);
            break;
    
          case 11: //11 = 0b1011
            digitalWrite(ledA, HIGH);
            digitalWrite(ledB, HIGH);
            digitalWrite(ledD, HIGH);
            delay(1000);
            digitalWrite(ledA, LOW);
            digitalWrite(ledB, LOW);
            digitalWrite(ledD, LOW);
            break;
    
          case 12: //12 = 0b1100
            digitalWrite(ledC, HIGH);
            digitalWrite(ledD, HIGH);
            delay(1000);
            digitalWrite(ledC, LOW);
            digitalWrite(ledD, LOW);
            break;
    
          case 13: //13 = 0b1101
            digitalWrite(ledA, HIGH);
            digitalWrite(ledC, HIGH);
            digitalWrite(ledD, HIGH);
            delay(1000);
            digitalWrite(ledA, LOW);
            digitalWrite(ledC, LOW);
            digitalWrite(ledD, LOW);
            break;
    
          case 14: //14 = 0b1110
            digitalWrite(ledB, HIGH);
            digitalWrite(ledC, HIGH);
            digitalWrite(ledD, HIGH);
            delay(1000);
            digitalWrite(ledB, LOW);
            digitalWrite(ledC, LOW);
            digitalWrite(ledD, LOW);
            break;
    
          case 15: //15 = 0b1111
            digitalWrite(ledA, HIGH);
            digitalWrite(ledB, HIGH);
            digitalWrite(ledC, HIGH);
            digitalWrite(ledD, HIGH);
            delay(1000);
            digitalWrite(ledA, LOW);
            digitalWrite(ledB, LOW);
            digitalWrite(ledC, LOW);
            digitalWrite(ledD, LOW);
            break;
        }
      }
      delay(500);
    }
    

    With the blue LEDs to your left, you should see the LEDs slowly count up in binary and repeat the sequence. Try adding more LEDs and switch cases to see if you can increase the binary counter!

    Demo Binary Blink

    One for the Road

    Last exercise is for a taste of using LEDs as indicators for a sensor as opposed to toggling or fading an LED. Sensor indicating lights are a very simple and effective form of user interface. So we'll trigger a 'stoplight' sequence when the proximity sensor detects something getting too close.

    Check out the circuit diagram below to see how everything is connected.

    Stoplight example using using RYB LEDs and a distance sensor

    Copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

    language:c
    //This example will trigger a 'stoplight' sequence when the proximity sensor detects something getting too close.
    
    //Declare pins and variables
    int trigger = 13;
    int echo = 12;
    int red = 2;
    int yellow = 3;
    int green = 4;
    
    void setup() {
      Serial.begin(9600);               //Initialize serial monitor at 9600 baud
      pinMode(trigger, OUTPUT);         //Output to initiate sensor cycle
      pinMode(echo, INPUT);             //Input to do math from for distance
      pinMode(red, OUTPUT);
      pinMode(yellow, OUTPUT);
      pinMode(green, OUTPUT);
    
      digitalWrite(green, HIGH);
    }
    
    void loop() {
      long duration, distance;
      digitalWrite(trigger, LOW);
      delayMicroseconds(2);
      digitalWrite(trigger, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigger, LOW);
      duration = pulseIn(echo, HIGH);   //Reads PWM
      distance = (duration / 2) / 29.1; //Take half of duration and divide by 29.1
      Serial.print(distance);
      Serial.println(" cm");
      delay(750);
    
      if (distance <= 15) {
        //Stoplight Animation
        digitalWrite(green, LOW);
        digitalWrite(yellow, HIGH);
        delay(2000);
        digitalWrite(yellow, LOW);
        digitalWrite(red, HIGH);
        delay(3500);
        digitalWrite(red, LOW);
        digitalWrite(green, HIGH);
        delay(3500);
      }
    }
    

    When the code initializes, the LED will have the green LED turned on. Once an object gets too close to the ultrasonic sensor, the stoplight sequence will start animating. This is a simplified example of how a stoplight works using an ultrasonic sensor to trigger the LEDs. Depending on the designer, a traffic control system may use image processing with cameras, radar, infrared sensors, magnetometers, or inductive loops to detect when a car is trying to cross an intersection. If a car is detected, the stoplight will trigger to notify other cars across from the intersection to slow down and stop. After a few sections, the LED will reset to green and run through the sequence again if there still is an object in front of the ultrasonic sensor.

    Try adjusting the code to keep the red LED on as long as the object is in front of the ultrasonic sensor as opposed to reseting to green. The circuit is just a miniature prototype of a traffic control system. Try mounting the LEDs in a cardboard enclosure to make your own miniature intersection for two, one-way streets. Then try adding more LEDs and adjusting the code to control LEDs for a four-way intersection.

    Demo LEDs Sequencing in a Stoplight a Hand Gets too Close to the Proximity Sensor

    Resources and Going Further

    For more information, check out the resources below.

    LEDs can be fun and easy to add to any circuit. There are tons of options! Power indicators, signal indicators, or just downright cool lighting effects. Play around with the Arduino code and make some cool effects. Maybe some illumination may spark something even better. Need some inspiration for your next project? Check out some of these related tutorials using LEDs.

    Using the Serial 7-Segment Display

    How to quickly and easily set up the Serial 7-Segment Display and the Serial 7-Segment Display Shield.

    LED Butterfly Pop Up Card

    Craft an illuminated butterfly pop up card with copper tape, two LEDs, and a battery.

    Lumenati Hookup Guide

    Lumenati is our line of APA102c-based addressable LED boards. We'll show you how to bring the sparkle to your projects!

    Mean Well LED Switching Power Supply Hookup Guide

    In this tutorial, we will be connecting a Mean Well LED switching power supply to an addressable LED strip controlled by an Arduino.

    learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

    Qwiic SHIM for Raspberry Pi Hookup Guide

    $
    0
    0

    Qwiic SHIM for Raspberry Pi Hookup Guide a learn.sparkfun.com tutorial

    Available online at: http://sfe.io/t1065

    Introduction

    The SparkFun Qwiic SHIM for Raspberry Pi is a small, easily removable breakout to add a Qwiic connector to your Raspberry Pi. The SHIM (short for Shove Hardware in the Middle) design allows you to plug directly to the Pi's I2C bus with no soldering required and the thin PCB design allows for it to be sandwiched on your Pi GPIO with other HATS. The Qwiic SHIM works great when you do not need the full capabilities of the Qwiic pHAT for Raspberry Pi or if you want to add a Qwiic connector to your Pi but do not have room for yet another HAT.

    SparkFun Qwiic SHIM for Raspberry Pi

    SparkFun Qwiic SHIM for Raspberry Pi

    DEV-15794
    $0.95

    Required Materials

    To follow along with this tutorial, you will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

    Single Board Computer

    You will need Raspberry Pi with 2x20 male headers installed.

    Raspberry Pi 3 B+

    Raspberry Pi 3 B+

    DEV-14643
    $39.95
    30
    Raspberry Pi 4 Model B (4 GB)

    Raspberry Pi 4 Model B (4 GB)

    DEV-15447
    $59.95
    3
    Raspberry Pi 4 Model B (2 GB)

    Raspberry Pi 4 Model B (2 GB)

    DEV-15446
    $49.95

    A Pi Zero W will also work but you will need to make sure to solder some male headers to it.

    Raspberry Pi GPIO Male Header - 2x20

    Raspberry Pi GPIO Male Header - 2x20

    PRT-14275
    $0.95
    Raspberry Pi Zero W

    Raspberry Pi Zero W

    DEV-14277
    $10.00
    27

    Or you could connect it to any single board computer (like the NVIDIA Jetson Nano) that utilizes the 40-pin Raspberry Pi GPIO header footprint.

    NVIDIA Jetson Nano Developer Kit

    NVIDIA Jetson Nano Developer Kit

    DEV-15297
    $99.00
    13
    Google Coral Development Board

    Google Coral Development Board

    DEV-15318
    $167.95
    1

    Qwiic Board

    Now you probably wouldn't buy the Qwiic SHIM if you didn't have any Qwiic products to use with it, right? If you don't have any Qwiic products, the following might not be a bad place to start.

    SparkFun Micro OLED Breakout (Qwiic)

    SparkFun Micro OLED Breakout (Qwiic)

    LCD-14532
    $16.95
    3
    SparkFun Atmospheric Sensor Breakout - BME280 (Qwiic)

    SparkFun Atmospheric Sensor Breakout - BME280 (Qwiic)

    SEN-15440
    $14.95
    SparkFun Proximity Sensor Breakout - 20cm, VCNL4040 (Qwiic)

    SparkFun Proximity Sensor Breakout - 20cm, VCNL4040 (Qwiic)

    SEN-15177
    $6.95
    SparkFun Qwiic Keypad - 12 Button

    SparkFun Qwiic Keypad - 12 Button

    COM-15290
    $9.95
    3

    Finally, you'll need our handy Qwiic cables to easily connect sensors to your Qwiic SHIM. Below are a few options.

    Qwiic Cable - 100mm

    Qwiic Cable - 100mm

    PRT-14427
    $1.50
    Qwiic Cable - 200mm

    Qwiic Cable - 200mm

    PRT-14428
    $1.50
    Qwiic Cable - 500mm

    Qwiic Cable - 500mm

    PRT-14429
    $1.95
    Qwiic Cable - 50mm

    Qwiic Cable - 50mm

    PRT-14426
    $0.95

    Required Setup Tools

    If you are using your Pi (or other single-board computer) as a desktop, these peripherals are required:

    Suggested Reading

    If you aren't familiar with the Qwiic system, we recommend reading here for an overview of everything Qwiic:

    Qwiic Connect System
    Qwiic Connect System

    We would also recommend taking a look at the following tutorials if you aren't familiar with the content covered in them.

    I2C

    An introduction to I2C, one of the main embedded communications protocols in use today.

    Serial Terminal Basics

    This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.

    Raspberry Pi 3 Starter Kit Hookup Guide

    Guide for getting going with the Raspberry Pi 3 Model B and Raspberry Pi 3 Model B+ starter kit.

    Getting Started with the Raspberry Pi Zero Wireless

    Learn how to setup, configure and use the smallest Raspberry Pi yet, the Raspberry Pi Zero - Wireless.

    Hardware Overview

    The Qwiic SHIM uses a unique friction-based connector that wedges itself onto the GPIO header for a secure, solderless connection. As you would expect, it has a single Qwiic connector that connects to your Pi's I2C bus (SDA, SCL, 5V and Ground). The SHIM also has a 3.3V regulator so it will work with all Qwiic devices.

    Top view of the qwiic shim.
    Top View Photo of Qwiic SHIM

    Press Fit Header

    The Press Fit Header on the Qwiic SHIM allows you to easily place the Qwiic SHIM on to your Pi (or other Single-Board Computer with the Pi GPIO) aligning the square pin on the Qwiic SHIM with Pin 1 of your GPIO. Pin one on the GPIO can be identified by the square pin or the beveled corner on the silkscreen. We will cover that in more detail in the Hardware Hookup section.

    Press Fit Header highlighted.
    Press Fit Header

    Voltage Regulator

    For you savvy readers out there, you may wonder why not just connect directly to the 3.3V rail on the Pi GPIO? A simple answer is the Pi's 5V rail is able to source more current than the 3.3V rail so the regulator allows you to connect more devices to the I2C bus without needing to worry about overtaxing your Pi.The on board AP2112K 3.3V regulator provides a clean 3.3V out for all attached Qwiic devices and can source up to 600mA@3.3V so you should have plenty of available current for your Qwiic project.

    Voltage regulator is on the right side of the top of the board, between two capacitors

    Voltage Regulator


    Board Dimensions

    Eagle File Photo with Dimensions.

    Eagle File Photo with dimensions

    Hardware Hookup

    Getting started with the Qwiic SHIM is a snap (well, actually it's more like a push but you get the idea). Making sure to align the Qwiic SHIM's Pin 1 with Pin 1 on your Pi's GPIO header, press the Qwiic SHIM down onto the header. Pin 1 on both the Qwiic SHIM and the Pi GPIO will be marked with a square pin. There is also a beveled corner on the Pi GPIO header indicating Pin 1 from the top of your Pi. That's it! With the SHIM in place you can now attach all your Qwiic devices to your Pi with space to spare for other Pi HATs.

    Old and New Pi Model Pinouts

    GPIO Configuration for old and new model Raspberry Pi from the Raspberry Pi GPIO Tutorial.



    With your Qwiic SHIM mounted on your Pi it should look like this:

    Qwiic SHIM mounted on a Pi 4.Qwiic SHIM mounted on a Pi Zero W.
    Qwiic SHIM mounted on a Pi 4.Qwiic SHIM mounted on a Pi Zero W.


    With the Qwiic SHIM in place, you can now stack all the HATs you would like on top. With a HAT on top of the SHIM, the press fit header will make an even better connection and the thin PCB allows any HAT to still connect fully to the GPIO header.

    The Qwiic SHIM on a Pi 4 with the SparkFun Pulsed Radar Breakout.

    The Qwiic SHIM is seen here nicely wedged by the SparkFun Pulsed Radar Breakout

    alt text

    And here you can see it shoved in the middle with the SparkFun Pi Servo HAT.

    Setting up I2C on Raspberry Pi

    OS and Library Install

    If you're starting from scratch, with a blank microSD card, you'll want to install Raspbian. If you've already got a working Raspbian system, skip ahead to step 3.

    1. Download the latest version of the NOOBS image. As of this writing, that is version 3.2.1.
    2. Follow the official installation instructions.
    3. Follow the Wiring Pi Instructions to get git, update and upgrade your Rasbpian packages, then install WiringPi.

    Be patient -- each of these steps takes a while.

    Once you've got wiringPi installed, run the gpio commands shown below.

    language:bash
    >gpio -v
    >gpio readall
    

    It should respond with some information about the wiringPi version and the Pi that its running on, then draw a table illustrating the configuration for the pins in the 40-pin connector.

    Configuration

    Like the SPI peripheral, I2C is not turned on by default. Again, we can use raspi-config to enable it.

    1. Run sudo raspi-config.
    2. Use the down arrow to select 5 Interfacing Options
    3. Arrow down to P5 I2C.
    4. Select yes when it asks you to enable I2C
    5. Select OK and then Finish

    Once you return to terminal, enter this command:

    language:bash
    >ls /dev/*i2c*
    

    The Pi should respond with:

    language:bash
    /dev/i2c-1
    

    Which represents the user-mode I2C interface.

    Utilities

    There is a set of command-line utility programs that can help get an I2C interface working. You can get them with the apt package manager.

    language:bash
    sudo apt-get install -y i2c-tools
    

    In particular, the i2cdetect program will probe all the addresses on a bus, and report whether any devices are present. Call i2cdetect -y 1 to probe the first I2C bus, which is what the Qwiic SHIM is connected to.

    language:bash
    pi@raspberrypi:~/$ i2cdetect -y 1
         0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
    00:          -- -- -- -- -- -- -- -- -- -- -- -- --
    10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    60: 60 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    70: -- -- -- -- -- -- -- --
    

    This map indicates that there is a peripheral at address 0x60. We can read and write its registers using the i2cget, i2cset and i2cdump commands.

    Qwiic Py Drivers

    Now that you have I2C set up on your Pi, you can start programming your Qwiic devices on your Pi or if you'd like to start with some examples, we have a host of Python drivers for Qwiic breakouts available in the GitHub repository linked below. You can read more about Python for the SparkFun Qwiic system in this blog post.

    Resources and Going Further

    For more information, check out the resources below:

    Now that you have your Qwiic SHIM ready to go, it's time to check out some of Qwiic enabled products.

    SparkFun Real Time Clock Module - RV-1805 (Qwiic)

    SparkFun Real Time Clock Module - RV-1805 (Qwiic)

    BOB-14558
    $15.95
    SparkFun Transparent OLED HUD Breakout (Qwiic)

    SparkFun Transparent OLED HUD Breakout (Qwiic)

    LCD-15079
    $99.95
    SparkFun 9DoF IMU Breakout - ICM-20948 (Ding and Dent)

    SparkFun 9DoF IMU Breakout - ICM-20948 (Ding and Dent)

    DD-15182
    $8.95
    SparkFun Servo pHAT for Raspberry Pi

    SparkFun Servo pHAT for Raspberry Pi

    DEV-15316
    $10.95
    1

    But I Already Have Sensors!

    If you already have a handful of SparkFun sensors and parts? SparkFun has been putting our standard GND/VCC/SDA/SCL pinout on all our I2C boards for many years. This makes it possible to attach a Qwiic Adapter that will get your SparkFun I2C sensor or actuator onto the Qwiic system.

    Here is the list of the boards that have the standard I2C pinout and will work with the Qwiic adapter board:

    Check out this related tutorial:

    Raspberry Pi SPI and I2C Tutorial

    October 29, 2015

    Learn how to use serial I2C and SPI buses on your Raspberry Pi using the wiringPi I/O library for C/C++ and spidev/smbus for Python.

    learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

    Programming the SparkFun Edge with Arduino

    $
    0
    0

    Programming the SparkFun Edge with Arduino a learn.sparkfun.com tutorial

    Available online at: http://sfe.io/t1103

    Introduction

    When we released the SparkFun Edge Development Board powered by TensorFlow, we knew that we were releasing it slightly ahead of the software wave that was promised to follow. One of the downsides that people mentioned was the fact that they had to learn a new SDK with which they were completely unfamiliar.

    SparkFun Edge Development Board - Apollo3 Blue

    SparkFun Edge Development Board - Apollo3 Blue

    DEV-15170
    $14.95$13.46
    10

    With the promise it holds, offering AI and machine learning on a board sporting an ARM-Cortex-M4F, a camera connector, dual MEMS microphones, a Qwiic connector, Bluetooth antenna and much more, users were anxious to start experimenting, but not quite as eager to learn a new development environment. So with no small effort from our engineering department, and with help from Pete Warden, Google's lead engineer for TensorFlow Lite and Tiny ML, it is now possible to start programming several experiments using AI and machine learning on the SparkFun Edge board through the familiar Arduino IDE.

    Set Up for Success

    Required Materials

    To follow along with this tutorial, you will need the following materials.

    SparkFun Serial Basic Breakout - CH340C and USB-C

    SparkFun Serial Basic Breakout - CH340C and USB-C

    DEV-15096
    $8.95
    2
    Himax CMOS Imaging Camera - HM01B0

    Himax CMOS Imaging Camera - HM01B0

    SEN-15570
    $9.95
    SparkFun Edge Development Board - Apollo3 Blue

    SparkFun Edge Development Board - Apollo3 Blue

    DEV-15170
    $14.95$13.46
    10
    Reversible USB A to C Cable - 2m

    Reversible USB A to C Cable - 2m

    CAB-15424
    $7.95

    NOTE: You can also use the USB-micro version of the Serial Basic Breakout, and a micro-USB cord, as well as the FTDI version (as opposed to the CH310 version listed), which may be a better option on macOS.

    Before going on, you’ll want to make sure you’ve gone through the original SparkFun Edge Hookup Guide. Setting up the Ambiq Apollo3 SDK isn’t necessary for this tutorial, however, you will want to roll up your sleeves and dig into it at some point to utilize the full potential of this board.

    At this point it is assumed that you have the Arduino IDE installed on your machine, but if not, or if you need to upgrade to the latest release, you can get that from Arduino’s website.

    Installing the Libraries

    The examples utilize the TensorFlowLite Arduino library, which is installed using the Arduino Library Manager, and the Person Detection example also uses the Himax HM01B0 Camera Library.

    To install this library, use the following steps:

    • In Arduino, select the "Manage Libraries..." menu item. Tools > Manage Libraries...
    • In the Library Manager interface, search for tensorflow
    • Select the library Arduino_TensorFlowLite by TensorFlow Authors
    • Select the non-precompiled version of the library
    • Select the Install button to install the library

    alt text

    NOTE: It is imperative that you install the non-precompiled version of the library. Installing the pre-compiled library will only lead to failure and sadness.

    To install the Himax HM01B0 Camera Library:

    • While still in the Library Manager interface, search for Himax
    • Select the SparkFun Himax HM01B0 Camera Library
    • Select the Install button to install the library
    • Close the dialog window

    Installing the SparkFun Boards Package

    To install the necessary boards package, use the following steps:

    • In Arduino, open the Preferences menu item. File > Preferences, (macOS) Arduino > Preferences
    • Add the following path to the Additional Boards Manager URLs: path in preferences.

    https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json
    • Select the OK button to save the preferences.

    alt text

    Once the location of the SparkFun boards package is set in the preferences, the board definition package for the SparkFun Apollo3 boards must be installed. To install package, use the following steps:

    • In Arduino, open the Board Manager. Tools > Board "..."> Manage Boards...
    • Search for Apollo3
    • Select the **SparkFun Apollo3 Boards" package
    • Select the Install button to install the library
    • Close the dialog window

    alt text

    Running the Examples

    Get the Code

    We have three examples written for the Edge board using TensorFlow Lite and programmed with Arduino. They can be cloned or downloaded and unzipped from here:

    https://github.com/sparkfun/Tensorflow_AIOT2019

    With your Edge Board connected to your computer (via your Serial Breakout), go to your Tools>Board"...", and select SparkFun Edge. Next, you'll need to select the port to which your board is connected.That can be found under Tools>Port>. It will look slightly different depending on your OS.

    • Windows - "COM Port"
    • macOS - "/dev/cu.usbserial*" (Note: You might have to check permissions)
    • Linux - "/dev/ttyUSB*"

    You're now ready to open your first example. Go to the folder where you downloaded (and unzipped, if necessary) the examples folder.

    Micro Speech

    From the micro_speech folder in your TensorFlow_AIOT2019-master folder, open the file micro_speech.ino. Full disclosure - this is the sketch that comes pre-loaded on your SparkFun Edge Board, so you should already see the blue LED blinking. If you open the Serial Monitor of your Arduino IDE, saying "Yes" will return something like "Heard yes (203) @4032ms," accompanied by a single blink of the yellow onboard LED; saying "No" will return a statement similar to "Heard no (209) @7936ms," along with a blink of the red onboard LED. Any other word or statement that the mics pick up will return "Heard unknown (212) @50304ms." I've noticed that a more percussive "yes" seems be be picked up a little better, and a slightly slower, more drawn out "no" tends to be better recognized by the model. The model used for this example is called from within the void:setup(), here:

    alt text

    The Upload Sequence

    By default, when you power up the SparkFun Edge Board, it immediately goes to Run mode and runs whatever file has been uploaded to it. In order to upload something new, we need to put it in bootloader mode. This is done using the two buttons on the Edge Board in a specific sequence. When you are ready to upload your code, take the following steps:

    • Press and hold the Reset button
    • While still holding down the Reset button, press and hold the 14 button
    • Release the Reset Button
    • Release the 14 button
    • Hit Upload in the Arduino IDE (or use your keyboard shortcut)

    These files will take a bit longer than your standard Arduino sketches to compile and upload, so be patient. If you want to see what's going on during all that time, you can always go back into your Arduino preferences and check the boxes for verbose output.

    alt text

    The Arduino IDE will make three attempts to upload the sketch to your board. Ideally, when it finished, you should see "Upload complete!" in the output pane. However, we've noticed that this process can sometimes be a little finicky. You may get a message that reads "Tries = 3; Upload failed!" You can always reset and try again, or lower the SVL Baud Rate down to 460800. We've yet to nail down a specific reason for this issue - wind direction, pollen count, still not entirely sure - but a little patience should get you up and running.

    Person Detection

    This example uses an imaged captured by a camera for the classification process. The model is trained to recognize when a person is present. When the model analyzes an image, the serial monitor will display scores for "human detected" and "no human detected." Keep in mind that this isn't motion detection, nor is it reading pixel differences from frame to frame. The model here is looking for what it perceives to be a human figure based on its training model.

    alt text

    The upload protocol is the same as it was for the first example. The only difference is that you need the camera module attached. When attaching it to the Edge Board, make sure that the lens is facing out over the back, or battery side of the Edge Board, as in the image below.

    alt text

    This is by far the largest of the three packages, and will therefore take the longest to upload. It sends the 284776 bytes in 140 frames of 2048 bytes each (except for the final frame, which only contains 104 bytes). Occasionally it will choke up about halfway through the upload. We've found that, especially on Macs, adjusting the SVL Baud Rate (under "Tools>") down to 460800 may do the trick, or sometimes it just needs a retry at the same speed. Once it uploads, reset your board and see how it does.

    alt text

    Here you can see how it did with me - never really 100 percent sure I was a person, although once I put a little light on myself (the final score), it felt pretty sure that I was, in fact, human.

    Magic Wand

    Time to get your Harry Potter on! For the final example, open the magic_wand sketch. This example uses a 20KB neural network and TensorFlowLite to recognize gestures. It reads data from the Edge Board's on-board accelerometer, and the recognized gestures are output to the serial monitor, as well as the on-board LEDs. This sketch recognizes three distinct gestures, which we're calling a wing, a ring and a slope.

    alt text

    Note the direction of each gesture, as it does make a difference. For example, a counter-clockwise ring movement will not work. Go ahead and upload the sketch in the same fashion as the other two. Once that's done, you'll want to hold the board with the serial connector to your left, camera port away from you. In order for the board to properly read the gestures, you'll have the best luck if you keep your wrist rigid, and move your arm from the elbow. Arpit Shah, the Director of Technology & Partner Enablement at Ambiq Micro (makers of the Apollo3 chip on the Edge Board) who helped with the workshop we lead at the ARM AIoT Dev Summit, found he had the best luck taping or rubber banding the board to the end of a drumstick. (Apparently he was out of unicorn hair and/or dogwood). Hold the board still to allow it to orient itself, then make one of the gestures, holding at the end for a second as well. It may take a little practice to get it consistent, but isn't that true of all magic?

    alt text

    More magic please!

    If you're ready to dig deeper, and want to start adding additional gestures to your magical repertoire, you can find a good starting off point at TensorFlow's GitHub repository.

    https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/experimental/micro/examples/magic_wand/train.

    This is quite a bit more than just running a simple Arduino sketch, so be prepared to do some heavy brain lifting here.

    Troubleshooting

    Resources and Going Further

    Now that you are familiar with the hardware and setup, you should be able to start integrating the Edge Board into your projects. If you want more information on the Ambiq Apollo3 or the SparkFun Edge Board, check out some of the links below:

    SparkFun Edge:

    Working with the Apollo 3:

    Need some inspiration for your next project? Check out some of these IoT tutorials!

    SparkFun Blocks for Intel® Edison - UART Block

    A quick overview of the features of the UART Block.

    Photon Development Guide

    A guide to the online and offline Particle IDE's to help aid you in your Photon development.

    Sparcade: Edison as a Web Server for Browser Games

    Turn the Intel® Edison into an access point that serves a simple browser-based game. High scores from the game are displayed on a character LCD.

    Simultaneous RFID Tag Reader Hookup Guide

    A basic guide to getting started with the RFID Tag Reader breakout and how to read and write multiple RFID tags over multiple feet!

    Or check out this blog post for ideas.


    learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

    Basic Autonomous Kit for Sphero RVR

    $
    0
    0

    Basic Autonomous Kit for Sphero RVR a learn.sparkfun.com tutorial

    Available online at: http://sfe.io/t1033

    Introduction

    The SparkFun Basic Autonomous Kit for Sphero RVR is an expansion set of sensors to the Sphero RVR platform and is a great way to start driving the Sphero RVR, either remotely or autonomously. The pan-tilt camera provides an excellent base for a video streaming interface while the GPS module provides accurate data for navigation. The Raspberry Pi Zero runs your programming and passes the information to the RVR. Setup is fairly simple but there are a few confusing spots. This tutorial will go over how to properly assemble the kit on the mounting plate provided with the RVR. While we feel it's the best way to set this up, it's not necessarily the only way, so feel free to experiment with different configurations.

    SparkFun Basic Autonomous Kit for Sphero RVR

    SparkFun Basic Autonomous Kit for Sphero RVR

    KIT-15302
    $119.95

    Required Materials

    To follow along with this tutorial, you will really only need a phillips-head screwdriver. We have quite a few to choose from - but our Pocket Screwdriver Set is a great option.

    Electric Hobby Screwdriver Set

    Electric Hobby Screwdriver Set

    TOL-15548
    $39.95
    Pocket Screwdriver Set

    Pocket Screwdriver Set

    TOL-12891
    $3.95
    5
    Tool Kit - Screwdriver and Bit Set

    Tool Kit - Screwdriver and Bit Set

    TOL-10865
    $9.95
    5
    iFixit Essential Electronics Toolkit

    iFixit Essential Electronics Toolkit

    TOL-15256
    $29.99

    Before We Begin

    If you haven't already, start charging the RVR battery. It takes a while to charge, so now would be a good time to get it going.

    Pan Tilt Mechanism

    Note: Before assembling the pan-tilt mechanism, it is recommended that users follow the instructions for the servo pre-alignment in the getting started guide to avoid issues later.

    Assembling the pan-tilt rig is by far the most involved part of this tutorial. Take your time and read the instructions carefully. Be mindful of the materials you are working with as well - using too much torque or force when tightening screws or fitting parts together can result in broken parts. On a final note, take extra care to make sure the servos are aligned correctly when mounting them.

    Here are the parts of the pan-tilt rig that come in this kit. You won't be needing the servo horns that come packaged with the servo motors, just the ones that come packaged separately. You will also not need the base plate that comes with the pan-tilt framework package.

    Pan-Tilt mechanism parts

    Click the image for a closer look.

    First, identify the larger self-tapping screws. These will be used for assembling the bottom part of the mechanism or the "Pan" part.

    Self-tapping Screws

    Find the Pan Brackets - these are the two brackets that sandwich together. Place one of the servos in the center and connect the two brackets. Take note of the orientation of the servo in the brackets below as it's important.

    Brackets around Servo

    Here are the brackets together. Try to make sure the servo is centered.

    Brackets fitted together around servo

    Take the larger self-tapping screws and affix the two brackets together like in the image below. Take extra care not to over-torque the screws and damage the plastic.

    Side view of bracket with screw

    You'll now need the single arm servo horn with 5 holes, as shown in the image below. If, for some reason, the single arm servo with 5 holes was not included in the kit, you have two options. You can either contact Customer Service to have them send you a part, or you can modify one of the 6-hole servo horns that were packaged separately. If you are shortening the 6 hole horn, start by clipping off one hole and checking to see if it fits the mold on the tilt bracket. Be careful when clipping and make sure that you do not clip off too much of the horn.

    5 hole single-arm horn on the bracket

    Install the single arm servo horn as shown below. You'll need two of the small self-tapping screws to affix it to the mechanism.

    Installation of single-arm horn

    Next, you'll need the second servo motor and the Tilt Bracket.

    Tilt bracket with servo next to it

    The image below shows the relative orientation of these two pieces:

    Servo installed on tilt bracket

    Now, find the longest machine screws in the bag, as shown below. You may find that there are more of these than you need.

    Machine screws

    Thread these screws through the stand off wings on the servo motor and into the last piece of the mechanism. You can use nuts for these if you like, but I've found it to be unnecessary as they thread into the mechanism quite snugly without the nut.

    Screws affixing servo to tilt bracket

    Now connect the two major pieces of the assembly together. The image below shows the orientation of these two parts. You may need to assemble and disassemble these two parts a couple of times to find the right rotational position of the servo motor so that the tilting portion has its full range of motion. Do this by connecting the two parts and carefully turning the "Tilt" servo back and forth until it's able to get the most unobstructed range while the mid-point of this range falls when the two servos are perpendicular to each other.

    Pan and tilt mechanisms lined up next to each other

    Here's an image of what it should look like with the two mechanisms attached.

    Pan and tilt mechanisms attached

    Sometimes the pan and tilt parts won't line up evenly. if this is the case, add a nut (provided in the bag) between the servo and the plastic part of the tilt mechanism as shown below.

    Standoff screw between the servo and bracket for the tilt mechanism

    Take the final screw that you identified above as a horn attaching screw and use it to secure the horn to the servo motor. You do NOT need much torque here - be very gentle!

    Affixing the pan bracket to the tilt bracket

    Congratulations! You've finished the most difficult part of this build. The rest should be a breeze! Put the pan-tilt mechanism to the side, we'll connect it to the cover plate of the RVR at a later time in the build.

    Standoffs and Mounting for the Pi Zero

    The Pi Zero W mounts to the cover plate with two 4-40 nuts. It uses two of the holes made for the full Raspberry Pi footprint.

    Raspberry Pi Zero and mounting hardware

    This keeps the camera connector within reach of the pan-tilt rig, yet not in a position to tangle itself.

    First, we'll affix the 1/2 inch screws to the Raspberry Pi Zero with two 4-40 nuts. This will provide a small standoff from the RVR cover plate which allows room for the pins on the bottom side of the Raspberry Pi Zero.

    Raspberry Pi Zero with standoff nuts

    From there, we'll affix the Pi Zero to the RVR cover plate with a second set of nuts.

    Raspberry Pi Zero mounted on cover plate for the RVR

    Mounting the GPS Board

    The GPS Qwiic board mounts next to the Pi Zero W. For the Qwiic cable to work, the Qwiic connectors need to be facing front and back in relation to the RVR. We'll use 2 of the 1/4 inch screws and 2 of the 4-40 nuts.

    GPS board mounted to the cover plate along with the Raspberry Pi Zero

    Mounting Pan - Tilt Camera to the Cover Plate

    The pan-tilt rig will mount to the forward-most servo footprint on the cover plate.

    Servo footprint on RVR cover plate

    The horn goes under the cover plate. Use two of the self-tapping screws included with the horn to mount the horn to the plate from the top (see pictures below) using the holes that line up.

    Servo horn positioning

    Mounting the horn to the bottom of the plate using screws

    It’s important that the rig is mounted so that the middle of the servo travel faces forward. This will take some trial and error, but you want the servo to be able to move an equal amount in either direction when facing directly forward (it’s okay to move the servo when it isn’t powered, just don’t force it).

    Fully affixed horn as shown from the bottom of the cover plate

    When mounted, it should look similar to this.

    Pan-tilt rig mounted to RVR cover plate

    Plugging in the pHAT and Cables

    The Servo pHAT is the interface for both the pan-tilt rig and the Qwiic sensors. The pHAT plugs in so it’s stacked directly above the Pi Zero.

    Servo pHAT plugged into the GPIO header of the Raspberry Pi Zero

    The Qwiic cable that connects the GPS Board to the Servo HAT runs underneath the cover plate as shown below. It’s best to plug this in at this step as the pan-tilt cables will impede it later.

    GPS module plugged into the Servo pHAT with a Qwiic cable

    The servo cables for the pan-tilt rig will run underneath the mounting plate, under the board and pop out on the opposite side. The bottom servo plugs into ROW 0 and the top servo into ROW 1.

    Row 0 and Row 1 highlighted

    The brown wires should be on the pins closest to GPS board. See the image below:

    Pan-tilt servos plugged into the Servo pHAT

    Click the image for a closer look.

    You can also run these cables underneath the cover plate but be sure it won't impede the movement of the pan-tilt mechanism.

    Plugging in the Camera

    You'll need to mount the Raspberry Pi Camera to the pan-tilt mechanism using the included square of double sided tape. However, I recommend you plug in the camera to the ribbon cable before securing the camera to the tape square.

    To connect the ribbon cable, you'll need to carefully slide the flexible ribbon cable connector's locking tab out. The locking tab slides out parallel to the board so you'll need to push each side of the tab with your fingernails. The image below highlights where you would need to place your fingernails to slide the tab out.

    Highlighted camera connector tabs

    Once the locking tab is out, you can insert the camera connector into the slot. Face the camera's exposed contacts toward the PCB in order to make a connection with the connector's pins. Then insert the cable until it is firmly into the connector. Care must be taken to ensure that the ribbon cable does not have any sharp bends when installing the camera.

    Inserting the camera connector ribbon into the camera connector slot

    When ready, carefully slide the tab back into the locking position using your fingernails.

    Gently push the locking mechanism back into place

    Now you can mount the Raspberry Pi Camera to the pan-tilt mechanism. Make sure the correct side is facing up. Once mounted, it should look something like what we see here:

    Mounting the Raspberry Pi Camera onto the Pan-tilt mechanism

    You'll also need to connect the camera ribbon cable to the Pi Zero W. The locking mechanism for the cable is exactly the same as the one on the camera breakout. Again, make sure the contacts of the ribbon are faced correctly. This part can be tricky - take your time and make sure there are no sharp bends in the cable.

    Camera cable plugged into the Camera and Raspberry Pi Zero

    Plugging the System into the RVR

    You've built the entire system! Now it's time to connect it to the RVR. Gently clip the RVR Cover Plate into place. We'll then connect the 4 pin Ribbon Cable from the four pin connector on the Servo pHAT to the UART Connector on the RVR.

    4 pin cable plugged into the RVR UART connector and the Servo pHAT

    Congratulations! You've completed the kit and are ready to start coding!

    Troubleshooting

    Resources and Going Further

    So you've got this amazing looking robot. Now what? Time to program it! Head on over to the Getting Started with the Autonomous Kit for the Sphero RVR Tutorial to get coding.

    New!

    Getting Started with the Autonomous Kit for the Sphero RVR

    December 13, 2019

    Want to get started in robotics? Look no further than the SparkFun autonomous kit for the Sphero RVR! Whether you purchased the Basic or Advanced kit, this tutorial will get you rolling...

    Need more information on the components included in this kit? We've got it!

    Need more inspiration? Check out some of these other great SparkFun tutorials!

    SparkFun Line Follower Array Hookup Guide

    Learn how to connect the RedBot Line-Following Sensor Bar to an Arduino-type microcontroller. Use the example sketches to read data from the bar, and try out a simple line-following algorithm.

    Continuous Rotation Servo Trigger Hookup Guide

    How to use the SparkFun Continuous Rotation Servo Trigger with continuous rotation servos, without any programming!

    Serial Controlled Motor Driver Hookup Guide

    Hookup guide for the Serial Controlled Motor Driver

    SparkFun 5V/1A LiPo Charger/Booster Hookup Guide

    This tutorial shows you how to hook up and use the SparkFun 5V/1A LiPo Charger/Booster circuit.

    learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado


    Advanced Autonomous Kit for Sphero RVR

    $
    0
    0

    Advanced Autonomous Kit for Sphero RVR a learn.sparkfun.com tutorial

    Available online at: http://sfe.io/t1034

    Introduction

    The SparkFun Advanced Autonomous Kit for Sphero RVR provides all the functionality of the basic kit with the addition of time-of-flight distance sensing in the front and rear. Based around Raspberry Pi’s small yet powerful Zero W model, the kit provides distance sensing, global positioning, and vision to the Sphero RVR. In this tutorial we'll cover assembly of the kit's hardware. Most of the steps are fairly straight forward and just require a little bit of patience.

    SparkFun Advanced Autonomous Kit for Sphero RVR

    SparkFun Advanced Autonomous Kit for Sphero RVR

    KIT-15303
    $164.95

    Required Materials

    To follow along with this tutorial, you will really only need a phillips-head screwdriver. We have quite a few to choose from - but our Pocket Screwdriver Set is a great option.

    Electric Hobby Screwdriver Set

    Electric Hobby Screwdriver Set

    TOL-15548
    $39.95
    Pocket Screwdriver Set

    Pocket Screwdriver Set

    TOL-12891
    $3.95
    5
    Tool Kit - Screwdriver and Bit Set

    Tool Kit - Screwdriver and Bit Set

    TOL-10865
    $9.95
    5
    iFixit Essential Electronics Toolkit

    iFixit Essential Electronics Toolkit

    TOL-15256
    $29.99

    Before We Begin

    If you haven't already, start charging the RVR battery. It takes a while to charge, so now would be a good time to get it going.

    Pan Tilt Mechanism

    Note: Before assembling the pan-tilt mechanism, it is recommended that users follow the instructions for the servo pre-alignment in the getting started guide to avoid issues later.

    You will need to build up the Pan-Tilt mechanism. We have instructions over in the Pan-Tilt Mechanism Section of our basic guide - head on over there now as you'll need to have this assembled in order to move forward with this tutorial!

    New!

    Basic Autonomous Kit for Sphero RVR

    December 12, 2019

    Get your Basic Autonomous Kit for Sphero RVR all hooked up with this guide!
    Assembling the Pan-Tilt Mechanism Hookup Instructions

    GPS Module and Mux

    The GPS board and Mux board are the only two boards that will mount directly to the cover plate. It’s best to put these boards on first as the additional mounting plate obscures part of the board. We'll do this using two of the 1/4 inch screws and 2 nuts for each board.

    Parts, Boards, and RVR Cover Plate

    The antenna (the beige part on the board) will need to be unobstructed and pointed towards the sky, so we'll mount it off to the side and near the front of the cover plate on the inner set of slide holes. The Qwiic cable that runs from the Servo pHAT to the GPS will use the outer set of holes later. If you have the means, putting the GPS board up higher always helps, but be sure not to obscure the pan-tilt camera rig.

    GPS Board mounted on RVR Cover Plate

    The Mux board will mount to the two screw holes in the middle of the RVR Cover Plate. it's important that the "Main" Connector is facing away from the labeled connector port on the RVR Cover Plate (see photo below).

    Mux board mounted on the RVR Cover Plate along with the GPS board

    Once the Mux board is in place, we'll plug in the 50mm Qwiic cables (these might be 2x 100mm cables and 1 50mm cable in your kit) into the Mux board. We'll want one cable running from rear-facing Qwiic connector on the GPS board to the "Main" Qwiic connector on the Mux board. Then we'll plug one cable into connector 3 and a separate one into connector 4 on the Mux board (where you'll use the 2 100mm cables if you have them). We'll plug these into the Time of Flight sensors later in the tutorial. It's important to use connectors 3 and 4 (3 for the front facing Time of Flight sensor and 4 for the rear) as this corresponds to code in the example. If you want to change which connectors you're using, you'll have to change some parts of the code.

    50mm Qwiic cables plugged into the Mux board

    Raspberry Pi Zero

    For the advanced kit, all four mounting points on the Pi Zero W will be used. Due to the through hole pins soldered to the Pi Zero W, you need to add a set of nuts between the board and the mounting plate. For this we'll use (4) 1/2 inch screws and (8) 4-40 nuts.

    Raspberry Pi Zero with Screws and 4-40 Nuts

    When complete, the Raspberry Pi Zero should look like this:

    Raspberry Pi Zero with 4-40 Standoff Nuts

    Do not mount the Raspberry Pi Zero yet, that will come at a later step.

    Mounting Plate and Time of Flight Sensor Brackets

    If you have not already, peel the protective layer off of the front and back of the acrylic plate.

    peeling the protective layer off the plate

    The metal standoffs attach to the mounting plate with the 4-40 nuts. The threaded end of the standoffs will be facing up. Take extra care in tightening the nuts as you can crack the plate if you over-tighten them.

    The time of flight sensors will need to be facing forward and backwards unobstructed. 4 right-angle mounting brackets have been included so the sensors can be mounted in the proper position on the mounting plate. The sensors can be added later, but it’s best to get these on the board before the pan-tilt rig is mounted. They're fastened to the mounting plate with a 1/4" screws and a 4-40 nut (for each bracket).

    Standoffs and Brackets affixed to mounting plate

    Note that the right-angle brackets have one threaded and one un-threaded hole. The threaded holes are smaller than the un-threaded holes, and if you look closely, you'll see the threads in the smaller holes.

    Right-angle brackets

    It’s important that the threaded holes are perpendicular to the plate, those will be the holes the screws that hold the sensor board in place use.

    Mounting the Servo Horn

    While the pan-tilt will be facing up, the servo horn (which the servo will be affixed to) is mounted on the bottom of the plate.

    Line up the small holes on the plate with the small holes in the servo horn the same. Use the small, self-tapping screws to mount it in place from the top of the mounting plate.

    Fastening servo horn to the mounting plate

    Two of the small self-tapping screws will suffice, but if desired you can use all four.

    Adding the Pan/Tilt Camera and Raspberry Pi Zero

    Once the horn is mounted in place, you can use the larger self-tapping screws to mount the pan-tilt rig. It’s important that the rig is mounted so that the middle of the servo travel faces forward. This will take some trial and error, but you want the servo to be able to move an equal amount in either direction when facing directly forward (it’s okay to move the servo when it isn’t powered, just don’t force it).

    Pan-tilt mechanism mounted to mounting plate

    Add the Pi Zero W (with the spacer nuts installed) to the mounting plate with another 4 of the 4-40 nuts. For the best access to all the connectors on the Pi Zero, make sure the USB and HDMI Connectors are facing the back of the plate and the pins are facing the pan-tilt rig.

    Raspberry Pi Zero mounted to mouting plate

    Attaching the Raspberry Pi Zero Camera Cable

    You'll need to mount the Raspberry Pi Camera to the pan-tilt mechanism using the included square of double sided tape. However, I recommend you plug in the camera to the ribbon cable before securing the camera to the tape square.

    To connect the ribbon cable, you'll need to carefully slide the flexible ribbon cable connector's locking tab out. The locking tab slides out parallel to the board so you'll need to push each side of the tab with your fingernails. The image below highlights where you would need to place your fingernails to slide the tab out.

    Highlighted camera connector tabs

    Once the locking tab is out, you can insert the camera connector into the slot. Face the camera's exposed contacts toward the PCB in order to make a connection with the connector's pins. Then insert the cable until it is firmly into the connector. Care must be taken to ensure that the ribbon cable does not have any sharp bends when installing the camera.

    Inserting the camera connector ribbon into the camera connector slot

    When ready, carefully slide the tab back into the locking position using your fingernails.

    Gently push the locking mechanism back into place

    Now you can mount the Raspberry Pi Camera to the pan-tilt mechanism. Make sure the correct side is facing up. Once mounted, it should look something like what we see here:

    mounting camera to RVR pan tilt mechanism

    You'll also need to connect the camera ribbon cable to the Pi Zero W. The locking mechanism for the cable is exactly the same as you saw above. Make sure the pads point upward as you see here:

    Raspberry Pi Zero camera cable plugged into camera and pi

    Connecting the Servo pHAT and Servos

    The Servo pHAT is the interface for both the pan-tilt rig and the Qwiic sensors. The pHAT plugs in so that it's stacked directly above the Pi Zero.

    Servo pHAT plugged into Raspberry Pi Zero GPIO header

    Click the image for a closer look.

    The servo cables for the pan-tilt rig will run underneath the mounting plate, under the board and pop out on the opposite side. The bottom servo plugs into ROW 0 and the top servo into ROW 1.

    Highlighted Row 0 and Row 1

    The brown wires should be on the pins closest to GPS board. See the image below.

    Servo cables from pan-tilt mechanism plugged in

    Click the image for a closer look.

    The Qwiic cable that connects the GPS Board to the Servo pHAT through the time of flight sensor becomes obscured by the cover plate. It’s best to plug in the 50mm Qwiic cable to the GPS Board Qwiic connector facing the center of the cover plate at this point (don't plug it into the time of flight sensor quite yet).

    Time of Flight Sensors

    Next, we'll mount the time of flight sensors to the mounting plate. The holes from the metal bracket should line up with the holes on the top of the board as to not interfere with the pan-tilt mechanism. It should look like this:

    Time of flight sensor mounted to metal mounting brackets on mounting plate

    Affixing the Mounting Plate to the RVR and Connecting the Remaining Qwiic Cables

    Take four of the remaining 1/4 inch screws and fasten the mounting plate to the cover plate of the RVR. The holes should lineup like this from below the cover plate:

    Bottom of the RVR Cover Plate with the Mounting Plate Affixed

    Again, be mindful with how tight you make the screws so as to not crack the acrylic plates.

    With all the boards in place, we can plug in the remaining boards to the Qwiic bus. The two 50mm Qwiic cables connected to connectors 3 and 4 on the Mux board will plug into the front and rear facing Time of Flights sensors (respectively).

    The remaining unplugged Qwiic connectors sticking out from under the mounting plate

    The 50mm Qwiic Cables plugged into the Time of Flight Sensors

    The rear Time of Flight sensor plugged into connector 4 on the Mux board

    Finally, we'll plug the GPS board into the Servo pHAT. Take the 200mm Qwiic cable and plug it into the Qwiic connector on the Servo pHAT. Then, we'll run the cable through the slot in the mouting plate, then down through the slot directly underneath it in the RVR Cover Plate.

    200mm Qwiic cable plugged into the Servo pHAT and run down through the slots into to below the RVR Cover Plate

    On your build, the camera cable will be plugged in, we removed it for this photo to give you a better view of the Qwiic cable plugged in

    Next, we'll run the cable back up through the outside slot next to the GPS board mentioned in the first steps. Plug the cable into the Qwiic connector on the GPS board facing forward.

    200mm Qwiic Cable plugged into the GPS board

    We'll take any slack from the 200mm cable and pull it gently under the RVR Cover Plate giving the system a cleaner look from the visible side.

    Bottom of the RVR Cover Plate showing the 200mm Qwiic cable running underneath

    Congratulations! You've built the entire system. Now it's time to connect it to the RVR. Gently clip the RVR Cover Plate into place.

    RVR Cover Plate with the system built on top

    Plugging the System into the RVR

    In the final step we'll then connect the 4 pin Ribbon Cable from the four pin connector on the Servo pHAT to the UART Connector on the RVR.

    To keep the UART cable from obscuring the view for the pan-tilt camera, I run it under the mounting plate. Refer to the images below - feel free to click on an image to see it more closely!


    Cable outside the mounting plateCable run under the mounting plate

    Congratulations! You've completed the kit and are ready to start coding!

    Troubleshooting

    Resources and Going Further

    So you've got this amazing looking robot. Now what? Time to program it!

    Head on over to the Getting Started with the Autonomous Kit for the Sphero RVR Tutorial to get coding.

    New!

    Getting Started with the Autonomous Kit for the Sphero RVR

    December 13, 2019

    Want to get started in robotics? Look no further than the SparkFun autonomous kit for the Sphero RVR! Whether you purchased the Basic or Advanced kit, this tutorial will get you rolling...

    Need more information on the components included in this kit? We've got it!

    Need more inspiration? Check out some of these other great SparkFun tutorials!

    Hackers In Residence - The Tethered Quad

    Our first-ever "Hackers in Residence" Tara Tiger Brown and Sean Bonner created a quadcopter that stays tethered to the ground. Here's how they did it!

    SparkFun 5V/1A LiPo Charger/Booster Hookup Guide

    This tutorial shows you how to hook up and use the SparkFun 5V/1A LiPo Charger/Booster circuit.

    Clap On Lamp

    Modify a simple desk lamp to respond to a double clap (or other sharp noise) using parts from the SparkFun Inventor's Kit v4.0.

    SparkFun Inventor's Kit Experiment Guide - v4.1

    The SparkFun Inventor's Kit (SIK) Experiment Guide contains all of the information needed to build all five projects, encompassing 16 circuits, in the latest version of the kit, v4.1.

    learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

    Getting Started with the Autonomous Kit for the Sphero RVR

    $
    0
    0

    Getting Started with the Autonomous Kit for the Sphero RVR a learn.sparkfun.com tutorial

    Available online at: http://sfe.io/t1100

    STEP 1: Connect the Sphero RVR to the App!

    Although the Sphero RVR (pronounced: rover or ˈrōvər) is NOT included with these kits, in our collaboration with Sphero, they made it abundantly clear that it was imperative for users to perform this action before connecting a Raspberry Pi to the RVR. So, before you proceed any further, please be sure to connect your Sphero RVR to the Sphero EDU App to update the firmware.

    Important: Update Your Firmware to Unlock Your RVR

    First things first, you must connect your RVR to the EDU App before connecting it to a development board (i.e. Raspberry Pi, Arduino, or micro:bit), in order to ensure that it has the most up-to-date firmware.

    You can always check back on the Sphero SDK firmware update page for firmware version updates or, if you want Sphero to do all the legwork, add yourself to Sphero's updates email list to get notifications about all of the stuffs. Sphero will always try to keep things backwards compatible, but there are instances where it will be imperative that they repair something that simply won't align with previous versions of the firmware, since Sphero doesn't want that getting in the way of your fun.


    Sphero EDU App Icon

    Sphero Edu

    Program all Sphero Robots
    Supported Platforms
    (*For more details, check out Sphero's SDK webpage; they also have a support page if you get stuck.)
    Note: Users will need to log-in/register an account on the app (if you are a teacher or an administrator we recommend at minimum performing this step before class/distributing out your Sphero RVRs). Also, don't forget to power on the Sphero RVR and enable the Bluetooth functionality on your computer or mobile device.

    Introduction

    Note: Before assembling the SparkFun autonomous kit for the Sphero RVR, users should configure their Raspberry Pi and verify the hardware is functional. These steps can be performed with the kit fully assembled; however, to avoid pitfalls and spending time troubleshooting, it is recommended that the instructions be followed as written.

    Pre-Order Update: Those that placed a pre-order will notice a change in the GPS hardware. The GPS module was updated due to I2C clock stretching issues, inherent in the SAM-M8Q, which were incompatible with the Raspberry Pi Zero W. Not to worry, the GPS module has been upgraded to the Titan X1, which we have verified works.

    Congratulations, you are on your way to getting started with the SparkFun autonomous kit for the Sphero RVR. Whether you have purchased the Basic or Advanced kit, this tutorial will walk you through the hardware included and their functions, the software configuration needed to get started, and some basic examples to test out the hardware.

    SparkFun Basic Autonomous Kit for Sphero RVR

    SparkFun Basic Autonomous Kit for Sphero RVR

    KIT-15302
    $119.95
    SparkFun Advanced Autonomous Kit for Sphero RVR

    SparkFun Advanced Autonomous Kit for Sphero RVR

    KIT-15303
    $164.95

    These kits were created in partnership with Sphero, whom, you may already be familiar with. Most notably, their BB-8 robot that was released in conjunction with the Disney movie. Their latest product, the Sphero RVR, is a more versatile, educational tool that is compatible with third-party hardware (i.e. the Raspberry Pi Zero W included in these kits).

    Required Materials

    To follow along with this guide some materials are required in addition to the autonomous kits, as noted below.

    Sphero RVR

    Note: These kits do NOT include the Sphero RVR itself. If you do not already have a Sphero RVR, please, make sure to include one with your purchase.
    Sphero RVR - Programmable Robot

    Sphero RVR - Programmable Robot

    ROB-15304
    $249.99

    Assembly Tools

    To assemble the hardware, a few tools are necessary: a jewelery or precision Phillips-head screw drivers and a 1/4" socket or wrench (a small pair of pliers also works).

    Electric Hobby Screwdriver Set

    Electric Hobby Screwdriver Set

    TOL-15548
    $39.95
    Needle Nose Pliers

    Needle Nose Pliers

    TOL-08793
    $2.95
    1
    Tool Kit - Screwdriver and Bit Set

    Tool Kit - Screwdriver and Bit Set

    TOL-10865
    $9.95
    5
    Magnetic Screwdriver Set (20 Piece)

    Magnetic Screwdriver Set (20 Piece)

    TOL-15003
    $6.95
    1

    Autonomous Kit Hardware

    In addition to the materials included in these kits, either a micro-B USB cable, USB-C cable, or a µSD card reader/adapter is required.

    • Most users may already have a micro-B USB cable lying around in a drawer somewhere, just make sure that it is capable of transferring data (i.e. not a charging only cable).
    • Otherwise, most those familiar with the Raspberry Pi may already have a µSD card reader/adapter.
    • A USB-C cable is included with the Sphero RVR; feel free to use that cable instead of purchasing one.
    USB micro-B Cable - 6 Foot

    USB micro-B Cable - 6 Foot

    CAB-10215
    $4.95
    12
    microSD USB Reader

    microSD USB Reader

    COM-13004
    $4.95
    8
    USB 3.1 Cable A to C - 3 Foot

    USB 3.1 Cable A to C - 3 Foot

    CAB-14743
    $4.95
    2

    A computer is also necessary to interface with the Raspberry Pi Zero W in the SparkFun Autonomous kits.

    Computer Requirements

    • Access to the same network (switch or wireless router) as the Raspberry Pi Zero W used in the kit.
    • Serial terminal interface or the ability to modify files from a USB drive to configure the Raspberry Pi Zero W.
    • SSH access to interface with the Raspberry Pi Zero W; and then Sphero RVR through the Sphero SDK.
    • A web browser with Flash to stream the camera video feed.

    Click the button above to toggle a list of replacement parts that are available from our catalog.

    Replacement Parts

    In the event that users loose or break any parts, the components of the kits are linked below. (Unfortunately, the mounting plate and 3/4" 4-40 standoffs for advanced kit are unavailable at this time.)
    Main Components:
    SparkFun Distance Sensor Breakout - 4 Meter, VL53L1X (Qwiic)

    SparkFun Distance Sensor Breakout - 4 Meter, VL53L1X (Qwiic)

    SEN-14722
    $21.95
    7
    SparkFun GPS Breakout - XA1110 (Qwiic)

    SparkFun GPS Breakout - XA1110 (Qwiic)

    GPS-14414
    $49.95
    5
    SparkFun Qwiic Cable Kit

    SparkFun Qwiic Cable Kit

    KIT-15081
    $7.95
    1
    microSD Card - 16GB (Class 10)

    microSD Card - 16GB (Class 10)

    COM-15051
    $19.95
    Raspberry Pi Camera Module V2

    Raspberry Pi Camera Module V2

    DEV-14028
    $29.95
    9
    SparkFun Qwiic Mux Breakout - 8 Channel (TCA9548A)

    SparkFun Qwiic Mux Breakout - 8 Channel (TCA9548A)

    BOB-14685
    $11.95
    Pan/Tilt Bracket Kit (Single Attachment)

    Pan/Tilt Bracket Kit (Single Attachment)

    ROB-14391
    $6.95
    4
    SparkFun Servo pHAT for Raspberry Pi

    SparkFun Servo pHAT for Raspberry Pi

    DEV-15316
    $10.95
    1
    Raspberry Pi Zero Camera Cable

    Raspberry Pi Zero Camera Cable

    PRT-14272
    $5.95
    Jumper Wire - 0.1", 4-pin, 6"

    Jumper Wire - 0.1", 4-pin, 6"

    PRT-10369
    $1.50
    Raspberry Pi Zero W (with Headers)

    Raspberry Pi Zero W (with Headers)

    DEV-15470
    $14.00
    1
    Mounting Components:
    Screw - Phillips Head (1/4", 4-40, 10 pack)

    Screw - Phillips Head (1/4", 4-40, 10 pack)

    PRT-10453
    $1.50
    Nut - Metal (4-40, 10 pack)

    Nut - Metal (4-40, 10 pack)

    PRT-10454
    $1.50
    Screw - Phillips Head (1/2", 4-40, 10 pack)

    Screw - Phillips Head (1/2", 4-40, 10 pack)

    PRT-10452
    $1.50
    Angle Bracket - 4-40

    Angle Bracket - 4-40

    PRT-10228
    $0.50

    Optional Accessories

    In addition to the items included in the kit here are a few accessories that may be of interest (none of these are required to use the autonomous kits). These products are only recommended for those that prefer to use the Pixel desktop on the Raspberry Pi Zero W and/or want a wall adapter to charge the Sphero RVR battery.

    Wall Adapter Power Supply - 5.1V DC 2.5A (USB Micro-B)

    Wall Adapter Power Supply - 5.1V DC 2.5A (USB Micro-B)

    TOL-13831
    $7.95
    16
    USB Wall Charger - 5V, 1A (Black)

    USB Wall Charger - 5V, 1A (Black)

    TOL-11456
    $3.95
    2
    microSD Card with Adapter - 64GB (Class 10)

    microSD Card with Adapter - 64GB (Class 10)

    COM-14833
    $29.95
    Mini HDMI Cable - 3ft

    Mini HDMI Cable - 3ft

    CAB-14274
    $4.95
    2
    Multimedia Wireless Keyboard

    Multimedia Wireless Keyboard

    WIG-14271
    $29.95
    3
    USB OTG Cable - Female A to Micro B - 5in

    USB OTG Cable - Female A to Micro B - 5in

    CAB-14276
    $2.95
    1

    Suggested Reading

    Below are several tutorials and hookup guides covering various topics that we suggest users get familiar with while following this guide.

    Hardware Basics

    GPS Basics

    The Global Positioning System (GPS) is an engineering marvel that we all have access to for a relatively low cost and no subscription fee. With the correct hardware and minimal effort, you can determine your position and time almost anywhere on the globe.

    Connector Basics

    Connectors are a major source of confusion for people just beginning electronics. The number of different options, terms, and names of connectors can make selecting one, or finding the one you need, daunting. This article will help you get a jump on the world of connectors.

    Hobby Servo Tutorial

    Servos are motors that allow you to accurately control the rotation of the output shaft, opening up all kinds of possibilities for robotics and other projects.

    Power Basics

    How to Power a Project

    A tutorial to help figure out the power requirements of your project.

    Electric Power

    An overview of electric power, the rate of energy transfer. We'll talk definition of power, watts, equations, and power ratings. 1.21 gigawatts of tutorial fun!

    What is a Battery?

    An overview of the inner workings of a battery and how it was invented.

    Getting Started with the Raspberry Pi and Python

    Getting Started with the Raspberry Pi Zero Wireless

    Learn how to setup, configure and use the smallest Raspberry Pi yet, the Raspberry Pi Zero - Wireless.

    Python Programming Tutorial: Getting Started with the Raspberry Pi

    This guide will show you how to write programs on your Raspberry Pi using Python to control hardware.

    Serial Communication Basics

    Serial Communication

    Asynchronous serial communication concepts: packets, signal levels, baud rates, UARTs and more!

    Serial Terminal Basics

    This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.

    Headless Raspberry Pi Setup

    Configure a Raspberry Pi without a keyboard, mouse, or monitor.

    How to Install CH340 Drivers

    How to install CH340 drivers (if you need them) on Windows, Mac OS X, and Linux.

    I2C and Qwiic Devices

    Qwiic Connect System

    These kits take advantage of our Qwiic system to interface with all the peripheral devices and sensors. For more details, we recommend users familiarize themselves with the Logic Levels and I2C tutorials. Click on the banner above to learn more about our Qwiic products.

    Logic Levels

    Learn the difference between 3.3V and 5V devices and logic levels.

    I2C

    An introduction to I2C, one of the main embedded communications protocols in use today.

    Raspberry Pi SPI and I2C Tutorial

    Learn how to use serial I2C and SPI buses on your Raspberry Pi using the wiringPi I/O library for C/C++ and spidev/smbus for Python.

    Setting Up the Pi Zero Wireless Pan-Tilt Camera

    This tutorial will show you how to assemble, program, and access the Raspberry Pi Zero as a headless wireless pan-tilt camera.

    SparkFun GPS Breakout - XA1110 (Qwiic) Hookup Guide

    Figure out where in the world you are with the Qwiic SparkFun GPS Breakout - XA1110.

    Qwiic Distance Sensor (VL53L1X) Hookup Guide

    The Qwiic VL53L1X time of flight sensor is capable of several modes, as well as having a range of 4M. Let's hook it up and find out just how far away that thing over there is.

    Qwiic MUX Hookup Guide

    Have a bunch of sensors with the same I2C address? Put them on the Qwiic MUX (TCA9548A) to get them all talking on the same bus!

    Pi Servo pHAT (v2) Hookup Guide

    This hookup guide will get you started with connecting and using the Pi Servo pHAT on a Raspberry Pi.

    shpero logo

    Sphero has provided an SDK (software development kit) to interface the RVR with different development platforms: the Raspberry Pi, Arduino, and micro:bit. In this tutorial the Raspberry Pi - Python version of the SDK will be utilized.

    (*The Sphero logo, SDK icon, and RVR images are property of Sphero and were pulled from their SDK webpage.)

    Hardware Overview

    For a brief overview of each component, check out the product videos; otherwise, for a more in-depth look at their operation, check out their hookup guides.

    Raspberry Pi Zero W (with Headers)

    The Raspberry Pi Zero W is the brains of this kit. The Raspberry Pi Zero W is a single board computer (SBC), with WiFi and Bluetooth connectivity, and a CSI camera interface. Below is an annotated image, highlighting components of the hardware that users will want to be familiar with.

    Annotated image of Raspberry Pi
    Annotated image of Raspberry Pi.

    Getting Started with the Raspberry Pi Zero Wireless

    July 13, 2017

    Learn how to setup, configure and use the smallest Raspberry Pi yet, the Raspberry Pi Zero - Wireless.

    Pi Camera (v2)

    The Pi Camera is the eyes of this kit. With a 8MP sensor, the camera module can be used to take high-definition video, as well as stills photographs. Below is an annotated image, highlighting components of the hardware that users will want to be familiar with. Primarily, users should note that the contacts on the ribbon cable face towards the image sensor.

    Annotated image of camera
    Annotated image of Pi Camera v2.

    Setting Up the Pi Zero Wireless Pan-Tilt Camera

    September 14, 2017

    This tutorial will show you how to assemble, program, and access the Raspberry Pi Zero as a headless wireless pan-tilt camera.

    Pi Servo pHat

    The Pi Camera is the heart or body of this kit. Excluding the Pi Camera, it interfaces between the Raspberry Pi Zero W and the rest of the hardware included in this kit. Below is an annotated image, highlighting components of the hardware that users will want to be familiar with.

    Annotated image of Pi Servo pHat
    Annotated image of Pi Servo pHat.

    Users should note the position of the serial switch, when using the Sphero RVR. Special care should also be taken when connecting the serial UART cable from the Sphero RVR or the servo cables to the Pi Servo pHat. Neither of these connections are polarized and can be easily connected in reverse. The silk screen on the board labels the proper pin connections.

    Pi Servo pHAT (v2) Hookup Guide

    July 11, 2019

    This hookup guide will get you started with connecting and using the Pi Servo pHAT on a Raspberry Pi.

    Pan-Tilt Servos

    The pan-tilt servo assembly is the neck of the kit, for panning and tilting the Pi Camera. The servos control the orientation of the bracket assembly. Below is an annotated image, highlighting wiring of the hardware that users should be familiar with.

    Servo Wiring
    Annotated image of servo wiring harness.

    Users should note that the wiring harness (sleeving) may come in a variety of color combinations. The image, above, illustrates the more commonly used colors. (*For more details, check out our hobby servo tutorial.)

    Setting Up the Pi Zero Wireless Pan-Tilt Camera

    September 14, 2017

    This tutorial will show you how to assemble, program, and access the Raspberry Pi Zero as a headless wireless pan-tilt camera.

    GPS (Titan X1) Module

    The GPS module is the geospatial awareness of the kit. Once a lock is acquired, the Titan GPS receiver is able to determine it's location to within a 3m radius. Below is an annotated image, highlighting components of the hardware that users will want to be familiar with.

    Annotated image of GPS module
    Annotated image of the GPS Breakout- XA1110 (Qwiic).

    Users should note that the PPS LED can be used as a general indicator for when a satellite lock is initially established. Additionally, the GPS module primarily only works when it has a direct view of the sky (i.e. outside; not through a window), to receive satellite signals. (*For more details on GPS receivers, check out our GPS basics tutorial.)

    SparkFun GPS Breakout - XA1110 (Qwiic) Hookup Guide

    October 19, 2017

    Figure out where in the world you are with the Qwiic SparkFun GPS Breakout - XA1110.

    ToF (VL53L1X) Distance Sensors (Advanced Kit Only)

    The ToF sensors provide an additional level of geospatial awareness for the kit. The sensor uses IR laser pulses to detect possible obstacles in front of the sensor. Below is an annotated image, highlighting components of the hardware that users will want to be familiar with.

    Annotated image of ToF sensor
    Annotated image of the Distance Sensor Breakout - 4 Meter, VL53L1X (Qwiic).

    Users should note that ToF sensors do have performance limitations. For example, the sensor FOV, the target properties (i.e. size, color, reflectivity, etc.), and the ambient light all affect the sensor performance and reliability. (*For more details, check out these related product support articles from Garmin: How the Garmin LIDAR-Lite Products Work with Reflective Surfaces and Effects of distance, target size, aspect, and reflectivity on LIDAR-Lite v3/v3HP returned signal strength .)

    Additionally, the product brochure for the VL53L1X ToF module lists that laser beams are safe enough that eye protection is not required. However, we still recommend users avoid staring into the sensor module (or beam path) anyways. (*For more details on the VL53L1X, check out the datasheet.)

    Qwiic Distance Sensor (VL53L1X) Hookup Guide

    June 18, 2018

    The Qwiic VL53L1X time of flight sensor is capable of several modes, as well as having a range of 4M. Let's hook it up and find out just how far away that thing over there is.

    Qwiic Mux (TCA9548A) (Advanced Kit Only)

    The mutiplexer (mux) is a simple switch control device for the I2C bus. This component allows users to access the VL53L1X ToF sensors individually, as they share the same I2C address on power up. Below is an annotated image, highlighting components of the hardware that users will want to be familiar with.

    Annotated image of MUX
    Annotated image of the Qwiic Mux Breakout - 8 Channel (TCA9548A).

    Qwiic MUX Hookup Guide

    July 19, 2018

    Have a bunch of sensors with the same I2C address? Put them on the Qwiic MUX (TCA9548A) to get them all talking on the same bus!

    Sphero RVR

    Note: These kits do NOT include the Sphero RVR itself. If you do not already have a Sphero RVR, please, make sure to include one with your purchase.

    The Sphero RVR is a third-party product that is used as a vehicular platform (or legs) for the SparkFun Autonomous Kits. The primary interface for these kits, is the 4-pin serial UART connection on the Sphero RVR. However, users can also operate the Sphero RVR with a mobile device through Bluetooth with the Sphero EDU app.

    RVR getting started slip
    Ports on RVR

    4-pin serial port and USB port on Sphero RVR. (Click to enlarge)

    On the front, "port" side of the Sphero RVR, there is the 4-pin serial UART connector and USB port. There is a clear plastic lid covering these connections, which users will need to open. Users should also not the arrangement of the pin connections, as labeled on the printed circuit board (PCB) behind the clear cover.

    (*The connector images, SDK icon, and product video are property of Sphero.)

    Software Overview: Part 1 - Raspbian OS

    Raspbian is a Debian based, Linux operating system (OS) that has been optimized for the Raspberry Pi and it's ARM "CPU". Although Raspbian was primarily created through the efforts of Mike Thompson (mpthompson) and Peter Green (plugwash) as an independent project, it has since been adopted as the official OS of the Raspberry Pi Foundation1.

    While there are many aspects of the Raspbian OS and the Raspberry Pi that could be covered, this section will primarily focus on the necessities for the SparkFun autonomous kits. This includes some basic commands and tools for the Raspbian OS.

    (*More information on the Raspberry Pi and the Rasbian OS can be found on the Raspberry Pi Foundation's website.)

    1. For more details, check out https://www.raspbian.org/RaspbianAbout.

    Suggested Tutorials:

    For users who have never used Python, this is a great tutorial to start with.

    Getting Started with the Raspberry Pi Zero Wireless

    July 13, 2017

    Learn how to setup, configure and use the smallest Raspberry Pi yet, the Raspberry Pi Zero - Wireless.

    Raspberry Pi SPI and I2C Tutorial

    October 29, 2015

    Learn how to use serial I2C and SPI buses on your Raspberry Pi using the wiringPi I/O library for C/C++ and spidev/smbus for Python.

    Command-Line or Terminal

    The command-line interface (CLI) or terminal allow users to access the Linux console. From the command-line, users can access and configure all the necessary parts of this kit. To begin, here are a few simple commands that users should familiarize themselves with.

    (*More information on the terminal can be found on the Raspberry Pi Foundation's website.)

    Privileges

    sudo (pronounced sue-due or su-doo)

    A prefix that allows users to execute tasks with the security privileges of another user (default: the superuser). Often referred to as superuser do or substitute user do. For this kit, users will primarily need to use these privileges for configuration purposes. Otherwise, the other two most common usages are for shutting down and rebooting the Raspberry Pi.

    • sudo shutdown now- Commands system to shutdown without a delay.
    • sudo reboot- Commands system to reboot.

    Directory Navigation

    cd

    The change directory command allows users to easily change current working directory in order to navigate through the file system. For this command, there are common usages:

    • cd ~- Reverts back to the home directory.
    • cd ..- Moves up a directory towards the root folder.
    • cd folder- Moves the current working directory down into folder.

    ls

    The list command allows users to list files in the current working directory.

    pwd

    The print working directory command display where in the file system, the current working directory is located.

    WiFi

    hostname -I

    Allows a user to look up the domain name (or IP address) of the system.

    ifconfig

    A system administrative utility for the network interface configuration. It displays the configuration settings of all network interfaces, including the IP address of the system.

    ping

    A computer network utility that is used to test the connection to a host (IP address). It displays with the response time for the system to reach the host and ping back (in ms).

    • ping <IP Address>- Pings IP Address, commonly found in a 192.168.X.X format for home WiFi networks.

    (*For other common commands, check out the Raspberry Pi Foundation's website.)

    Applications & Tools

    nano

    Nano is a simple text editor.

    • nano filename.ext- Modify filename with .ext extension in text editor.
    • To exit and save changes- Ctrl + X, at prompt Y, and then Enter or Return

    i2c-tools

    An I2C bus probing tool for Linux.

    • i2cdetect -y 1- Pings the I2C bus and returns a list of I2C address, where devices have responded.

    Depending on how the the I2C device operates, the following commands may not work:

    • i2cdump -y 1 <I2C Address>- A dump of the values stored in the available registers.
    • i2cget -y 1 <I2C Address> <Register>- A read operation to retrieve a byte stored in a specific register, at the I2C address.
    • i2cset -y 1 <I2C Address> <Register> <Value>- A write operation to set a byte to a specific register, at the I2C address.

    Keyboard Commands

    • Ctrl + C- Kill process (sends interrupt command).
    • Ctrl + D- Exit (sends end of file command).

    (*More information on the Linux OS can be found on the Raspberry Pi Foundation's website.)

    Configure the Raspberry Pi

    Note: Before assembling the SparkFun autonomous kit for the Sphero RVR, users should configure their Raspberry Pi and verify the hardware is working. (These steps can be performed with the kit fully assembled; however, avoid any unnecessary troubleshooting or pitfalls, it is recommended that the instructions be followed as laid in this section and the hardware verification section leading up to the Hardware Assembly.)

    In this kit, a pre-configured image of Raspbian Buster (release date: 2019-09-26) is provided with all the necessary software packages installed. Unfortunately, there are still a few remaining steps to finish configuring the Raspberry Pi so that it can be accessed remotely.

    Overclocking Notice: The image is pre-configured to overclock the Raspberry Pi Zero W and was written to only affects Pi Zero Ws. This configuration modifies the hardware; therefore, even if the µSD card is swapped, the Pi Zero W would still be overclocked on the next boot.

    Instructions to remove/undo the overclock configuration are included in the troubleshooting section below. However, users should be aware of this modification. It is necessary to overclock the Raspberry Pi Zero in order to minimize the latency/lag on the camera video feed, while it is being streamed to the web interface and the Sphero SDK is in operation.

    Note: In case users accidentally format their SD card in the excitement to get started, need to start over with a fresh image, or if they just want to build their own image... we have got you covered. In the troubleshooting section below, our pre-configured image is available and we have included some basic instructions to build our image from scratch. Users can also download the pre-configured image by clicking on the button below.

    Setup the WiFi Connection

    The one thing we couldn't do is pre-configure the wireless connection for users. The setup process is detailed in the three separate methods below, depending on user's preferences. In order to provide as many options as conveniently, possible to setup the WiFi, the serial console (or login shell) was left enabled. However, in order for Sphero's SDK to utilize the serial port (without permissions), the serial console must be disabled; therefore, instructions for disabling the login shell are also detailed for each method, in the next section.

    WiFi Network Considerations:

    • The Raspberry Pi Zero W supports 2.4GHz 802.11n wireless LAN. This is compatible with 802.11b/g/n networks, but only at 2.4GHz; it will not run on a 5GHz WiFi network. If you are a administrator or teacher trying to use this product, be sure to consult your IT department and/or network administrator for assistance with network privileges, compatibility, coverage, etc.
    • The web camera interface, in its default configuration, isn't extremely demanding, but it does require a fairly decent network speed and bandwidth. It is recommended that users connect their computers or laptops directly to the network (that the Raspberry Pi is setup on) with an Ethernet cable for the best performance in streaming the camera video feed to avoid any latency or lag.
    • At all costs, avoid using USB WiFi dongles! (*Trust me, I spent a week tracking down various ghosts only to learn all the issues stemmed from poor performance with the different WiFi dongles I was using.)
    • Additionally, it is preferable to avoid using enterprise networks as they can be troublesome to configure and/or troubleshoot issues.

    (*More information on configuring the wireless connectivity can be found on the Raspberry Pi Foundation's website.)

    SD Card Reader

    This is the simplest method as only two files need to be modified; however, it does require a µSD card adpter/reader. Those that are acquainted with the Raspberry Pi should already have one stashed somewhere (under a stack of papers?). The only downside to this method is that the IP address for the Raspberry Pi won't be accessible. (*There are options to configure a static IP address, but that is beyond the scope of this tutorial.)

    Insert the pre-configured µSD card into the adapter and plug the adapter into a computer. Depending on the computer's OS, the µSD card may appear as several USB drives; however, only the boot drive can be accessed/modified.

    WiFi Configuration

    To configure the WiFi network interface, the wpa_supplicant.conf file needs to be modified in the boot USB drive of the µSD card. On boot up, the kernel will automatically, move the wpa_supplicant.conf file into the appropriate directory of the Linux root file system and use those settings to setup the wireless network. (*On Linux operating systems, the µSD card might get mounted as a disk drive. In that situation, the kernel will probably move the wpa_supplicant.conf file. Therefore, users will need to create a new file.)

    SD card as USB Drive
    SD card shown as a USB Drive (boot partition highlighted). (Click to enlarge)

    Modify the wpa_supplicant.conf file using the default text editor of the operating system. If the file isn't there, you can just create a new one (it should just overwrite the previous file when the kernel moves it).

    wpa_supplicant file
    wpa_supplicant.conf file in boot partition of SD card. (Click to enlarge)
    Support Tip: On Windows, Notepad or Visual Studio Code are recommended, as they save files with arbitrary file extensions. On MacOS, TextWrangler seems to be the easiest. For Linux, the default system text editor should be fine.

    For secured networks, the wpa_supplicant.conf file will should follow this format:

    language:bash
    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    update_config=1
    country=<Insert country code here>
    
    network={
     ssid="<Name of your WiFi>"
     psk="<Password for your WiFi>"
    }
    
    • Insert the appropriate ISO code of your country (replace<Insert country code here>). See Wikipedia for a list of country codes (US is the ISO code for the United States of America).
    • Insert the credentials for the WiFi network that this kit will be utilized on (replace<Name of your WiFi>and<Password for your WiFi>).
    • When creating a wpa_supplicant.conf file, make sure to utilize the .conf file extension.

    Before unplugging the SD card, move on to the Disabling the Serial Console/Login Shell section below.

    (*More information on the wpa_supplicant.conf file can be found on the Raspberry Pi Foundation's website.)

    Serial Interface

    The second method is to use the serial interface (or login shell). For most users, this will be the primary method to configure the Raspberry Pi without needing to purchase additional equipment. Users will need an additional micro-B USB cable or USB-C cable, but one a USB-C cable should already be included with the purchase of a Sphero RVR to charge the battery.

    Suggested Tutorials:

    For users who have never used a serial terminal and accessed a Raspberry Pi in a headless setup, please review the following tutorials prior to beginning this method. Users will also need to install the CH340C driver on their computers to interface with the Raspberry Pi through a serial terminal.

    How to Install CH340 Drivers

    August 6, 2019

    How to install CH340 drivers (if you need them) on Windows, Mac OS X, and Linux.

    Serial Terminal Basics

    September 9, 2013

    This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.

    Headless Raspberry Pi Setup

    April 23, 2018

    Configure a Raspberry Pi without a keyboard, mouse, or monitor.

    Using the serial interface (or login shell), allows users to directly interface with the command-line interface (CLI) through another computer's serial terminal. With access to the command-line, users could use a text editor to modify the files mentioned in the previous method; however, that is not the simplest way to configure the Raspberry Pi through the Linux console. A more convenient method is through the raspi-config application, a console based, configuration tool provides a straightforward way to initially configure a Raspberry Pi.

    In order to access the serial interface, users must first ensure that they have the proper CH340C driver installed. (*This allows user's computers to recognize the CH340C USB-to-serial adapter on the Pi Servo pHat.) Users will also need have a serial terminal (emulator) installed on their computer (*the serial monitor of the Arduino IDE will not work in this situation). For instructions on how to install the CH340 driver and how to install a serial terminal on their computer, use the tutorials linked above.

    Once the driver and serial terminal are installed on the computer, users will need to assemble the Raspberry Pi Zero W, µSD card, Pi Servo pHat, and USB-C cable.

    1. Carefully, insert the µSD card into the µSD card slot on the Raspberry Pi Zero W.
    2. Attach the Pi Servo pHat onto the Raspberry Pi Zero W.
    3. Ensure that the switch on the Pi Servo pHat is moved from RVR to USB to enable serial communication through the USB-C connector. See hookup guide for more details.
      Serial Switch on Pi Servo pHat
      Move serial switch to USB. (Click to enlarge)
    4. Insert the USB-C cable into the Pi Servo pHat and a USB port on the computer.
      Serial interface setup
      Serial interface setup. (Click to enlarge)

    To begin, users will need to access the serial console (login shell) through the serial terminal (emulator) on thier computer. To do this, users should connect to the COM port of the CH340C with a baud rate of 115200. Once connected, press the Enter or Return key to bring up the login promt. (The username and password are the default for the Raspberry Pi: Username = pi and Password = raspberry.)

    Login prompt
    Login prompt for the Raspberry Pi. (Click to enlarge)

    (*More information on setting up a Raspberry Pi (headless) can be found on the Raspberry Pi Foundation's website.)

    WiFi Configuration

    After the Linux console appears, users only need to enter sudo raspi-config to pull up the configuration tool. (Users outside the US will want to configure their localization settings first.)

    raspi-config command
    Access the Raspberry Pi configuration tool. (Click to enlarge)

    To configure the WiFi connection, scroll down to 2 Network Options using the arrow keys and hit enter.

    Select Network Options
    Select 2 Network Options. (Click to enlarge)

    Then, select N2 Wi-fi.

    Select WiFi
    Select N2 Wi-fi. (Click to enlarge)

    Once prompted, enter the SSID and passphrase for the wifi network.

    enter network credentials
    Enter the WiFi network credentials. (Click to enlarge)

    Before exiting the raspi-config tool, move on to the Disabling the Serial Console/Login Shell section below.

    (*More information on the raspi-config tool can be found on the Raspberry Pi Foundation's website. They also provide additional information for setting up the WiFi via the command line)

    Note: For users wanting to edit the configuration file directly, use the following command: sudo nano /etc/wpa_supplicant/wpa_supplicant.conf. (To use a preferred text editor, modify the command accordingly.)

    Pixel Desktop

    The most user friendly way to configure the Raspberry Pi is with the (one-time) setup wizard and configuration application on the Pixel desktop. However, it is the least convenient of the options as it requires the most additional hardware and setup. Users will need the need the following accessories to access the Pixel desktop:

    (Users should modify/change the monitor and adapter cable according to the available inputs. Users may also need an additional USB hub.)

    Assemble the hardware and accessories as shown below (don't forget to plug the power supply in last).

    Desktop setup
    Desktop setup. (Click to enlarge)

    WiFi Configuration

    Once the Raspberry Pi has booted to the Linux console, use the startx command to initialize the Pixel desktop and the initial configuration wizard will pop up. Follow the prompts to set-up the WiFi connection. (*The initial configuration wizard is a one-time tool; to bring it up again, use the sudo piwiz command in the Terminal.)

    Pi Wizard
    Initial configuration wizard.

    A warning prompt will pop up, if SSH is enabled and the Raspberry Pi is still configured with the default user credentials. User can change the user name and password later, it is fine to close this dialog box for now.

    SSH Warning
    SSH warning pop up. (Click to enlarge)

    Users can also setup the WiFi connection through the network icon on the taskbar (*the icon changes based on the network connection type and status).

    No Network
    No network connection.
    LAN network connection
    LAN network connection.
    WiFi network connection
    WiFi network connection.

    Note: Again, users can use the Terminal application or the Linux console to modify the files directly or access the raspi-config tool as mentioned in the Serial Interface method.

    Once completed, the wizard will want to reboot the Raspberry Pi; click NO and move on to the Disabling the Serial Console/Login Shell section below. (*It is not an issue if users click yes, they will just have to wait for the Raspberry Pi to reboot and have to initialize the Pixel desktop again.)

    (*More information on the first-boot setup wizard can be found on the Raspberry Pi Foundation's website.)

    Disabling the Serial Console/Login Shell

    In order to provide as many options as conveniently, possible to setup the WiFi, the serial console (or login shell) was left enabled. However, in order for Sphero's SDK to utilize the serial port (without permissions), the serial console must be disabled. Therefore, instructions for disabling the login shell are also detailed below.

    SD Card Reader

    Disabling the Login Shell

    To disable the login shell, the cmdline.txt file needs to be modified in the boot USB drive of the µSD card. During boot, the Linux kernel accepts a command-line of parameters set in the cmdline.txt file of the boot partition.

    cmdline file
    cmdline.txt file in boot partition of SD card. (Click to enlarge)

    Below, is the default configuration of the cmdline.txt file in the pre-configured image:

    console=serial0,115200 console=tty1 root=PARTUUID=5e3da3da-02 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait quiet init=/usr/lib/raspi-config/init_resize.sh splash plymouth.ignore-serial-consoles
    
    • Users will need to remove the console=serial0,115200 portion of the text.

    (*More information on the cmdline.txt file can be found on the Raspberry Pi Foundation's website.)

    Once both modifications have been made and the µSD card has been safely ejected from the computer, move on to the servo alignment part of this section.

    Serial Interface

    Disabling the Login Shell

    To enable/configure the serial port, scroll down to 5 Interfacing Options using the arrow keys and hit enter.

    select interface options
    Select 5 Interfacing Options. (Click to enlarge)

    Then, select P6 Serial.

    Select serial
    Select P6 Serial. (Click to enlarge)

    Once prompted: Would you like a login shell to be accessible over serial?, select <NO>.

    select no
    Select <NO> on login shell prompt. (Click to enlarge)

    Would you like the serial port hardware to be enabled?, select <YES>.

    select yes
    Select <YES> on serial port prompt. (Click to enlarge)

    Once configured, the configuration tool should display:

    The serial login shell is disabled
    The serial interface is enabled
    

    Select <Ok> to proceed back to the main menu.

    configuration confirmation
    Select <Ok> to proceed back to the main menu. (Click to enlarge)

    With both the WiFi and serial port modifications made, use the Tab key to select <Finish>.

    select finish
    Select <Finish> on close the raspi-config tool. (Click to enlarge)

    When prompted Would you like to reboot now?, select <NO>.

    reboot promt
    Select <NO> on reboot prompt. (Click to enlarge)

    (*More information on the raspi-config tool can be found on the Raspberry Pi Foundation's website.)

    Selecting <NO> will allow users to check the IP address of the Raspberry Pi on the WiFi network before rebooting. Users should move on to the Retrieving the IP Address of the Raspberry Pi section below. (*On the next power up, the serial console will be disabled.)

    Note: For users wanting to edit the configuration files directly, use the following commands:

    sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
    sudo nano /boot/config.txt

    (To use a preferred text editor, modify the commands accordingly.)

    Pixel Desktop

    Disabling the Login Shell

    To disable the login shell, click on the raspberry icon on the task bar. Scroll to Preferences>Raspberry Pi Configuration. In the configuration menu, select the Interfaces tab and then disable the Serial Console.

    Pi desktop configuration settings
    Raspberry Pi configuration settings.
    (Click to enlarge)
    Interface Settings
    Interface configuration settings. (Click to enlarge)

    Note: Again, users can use the Terminal application or the Linux console to modify the files directly or access the raspi-config tool.

    Retrieving the IP Address of the Raspberry Pi

    Once users are done with the WiFi and serial port configuration process, pull up the IP address for the Raspberry Pi; using the Terminal or Linux console (in not already open). With either the hostname -I or ifconfig commands, users can retrieve the IP address. (*Users who followed the SD card method obviously, will not be able to access the Linux console in order to retrieve the IP address. Don't worry, there are special instructions for these users in the following sections.)

    IP lookup
    IP address lookup. (Click to enlarge)

    Once the IP address has been retrieved, users can shutdown the Raspberry Pi with the sudo shutdown now command.

    shutdown command
    Shutdown the Raspberry Pi. (Click to enlarge)

    Note: Don't forget to make sure that the Raspberry Pi is completely done shutting down before disconnecting the power. This is to avoid corrupting the SD card while the Raspberry Pi is in the middle of its power down cycle. Users should see the ACT LED blink 10 times steadily before a long "on" blink; about 5-10 seconds after, it should be safe to disconnect the power.

    Pi Camera Assembly
    ACT LED indicating the end of the power down sequence, right before the power can be disconnected. The ACT LED will blink 10 times, followed by a long "on" blink. (Click to enlarge)

    Remote Access with SSH

    Secure Shell (SSH) is a network protocol that allows users to remotely access the Raspberry Pi from another computer, through the WiFi network. Accessing the Raspberry Pi is a relatively simple process:

    Suggested Tutorials:

    For users who have never accessed a Raspberry Pi in a headless setup, please review this tutorial.

    Headless Raspberry Pi Setup

    April 23, 2018

    Configure a Raspberry Pi without a keyboard, mouse, or monitor.

    SSH Client Access

    1. To access the Raspberry Pi, users will need the IP address of the Pi. (*For users that used the SD card method, don't worry. The Raspberry Pi can still be accessed; however, only one Raspberry Pi can be powered at a time.)
      • More information on determining the Raspberr Pi's IP address can be found on the Raspberry Pi Foundation's website.
    2. On the computer used to remotely access the Pi, pull up the SSH Client, Terminal, Linux Console, or Command Prompt (Windows 10 with October 2018 Update or later).
    3. Use the following command to test if the Raspberry Pi can be accessed:

      • ping <IP Address>
      • ping raspberrypi.local (if the SD card method was used)

      ping device
      ping the Raspberry Pi to confirm that is has connected to the WiFi network. (Click to enlarge)
    4. If a connection is made, a print out of the response times will display. (If needed, press Ctrl+C to kill the process.)
    5. To SSH into the Raspberry Pi, use the following command:

      • ssh pi@<IP Address> (pi is the username of the account that will be accessed.)
      • ssh pi@raspberrypi.local (if the SD card method was used)

      ping device
      ssh into the Raspberry Pi, using the default credentials. (Click to enlarge)
    6. The Raspberry Pi will prompt users for the password for the pi user. The username and password are the default for the Raspberry Pi:
      • Username = pi
      • Password = raspberry

    (*More information on remotely accessing the Raspberry Pi through SSH can be found on the Raspberry Pi Foundation's website. Additionally, there also is information on other remote access methods.)

    Software Overview: Part 2 - Python

    Python is a popular and fairly intuitive programming language, used by various industries, including Fortune 100 companies. What makes Python so popular isn't the simplicity of the high-level, language architecture, but rather the adaptability to deploy code across various platforms. Python is an interpreted language, which essentially means that as long as a platform (i.e. computer, server, etc.) has an interpreter, it can execute Python code. (*This is an over generalization of how Python operates; for more details check out this GeeksforGeeks article and the Inside The Python Virtual Machine eBook.) A perfect example of Python's cross-platform functionality is that a program written on a Windows PC does not need to be rewritten to work on a Mac or a Linux machine. This adaptability, has allowed Python spread across various markets and become widely adopted. Another benefit is that Python is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. Now, there are a few drawbacks to working with Python, but they are greatly overshadowed by its benefits for the purposes of this kit.

    (*More information on the Python can be found on the Python Software Foundation's website.)

    How is Python used with the Raspberry Pi?

    Specifically, with the Raspberry Pi, Python allows users to interact with the physical world through the general purpose input/outputs (GPIO). The GPIO is an interface that users can electrically connect various sensors and devices to, which can be operated through the Raspberry Pi, using Python. Essentially, this means that:

    1. Users can connect a GPS module (Like the one included in these kits) to the GPIO of the Raspberry Pi.
    2. Through the Raspbian OS, users can interface and control the GPIO with Python.
    3. This grants users direct access to the GPS module with Python, allowing users to retrieve GPS coordinate data.

    Now that we have been established that Python is the software, which is used to interface with the hardware connected to the Raspberry Pi. This section will briefly overview the Python application and how it is used with this kit. (This section, barely skims the surface of Python and how it can be used with the Raspberry Pi.)

    (*More information on using Python with the Raspberry Pi can be found on the Raspberry Pi Foundation's website.)

    Suggested Tutorials:

    For users who have never used Python, this is a great tutorial to start with.

    Python Programming Tutorial: Getting Started with the Raspberry Pi

    June 27, 2018

    This guide will show you how to write programs on your Raspberry Pi using Python to control hardware.

    Raspberry gPIo

    October 29, 2015

    How to use either Python or C++ to drive the I/O lines on a Raspberry Pi.

    Raspberry Pi SPI and I2C Tutorial

    October 29, 2015

    Learn how to use serial I2C and SPI buses on your Raspberry Pi using the wiringPi I/O library for C/C++ and spidev/smbus for Python.

    Installing Packages

    pip3

    A package management system for installing Python 3 packages hosted on PyPI.

    • pip3 install <Package Name>- Installs a Python package (and any linked dependencies) hosted on PyPI.
    • pip3 uninstall <Package Name>- Removes a Python package hosted on PyPI.
    • pip3 install --upgrade <Package Name>- Updates a Python package hosted on PyPI.

    Python Applications and Tools

    ipython3

    A simple shell program for Python 3 to write and execute line by line Python instructions.

    • Once inside the shell, users can execute instructions line by line as if it were an actual Python script. This is useful for:
      • Code development.
      • Catching errors.
      • Debugging, where an output error might be suppressed.
    • On loops (i.e. for or while) and if statements, users will need to hit Enter twice to close the loop or statement.
    • Ctrl + C- Terminate proccess (or keyboard interrupt).
    • exit() or Ctrl + D- Exit shell.
    • %save <Filename> <Line Numbers>- Save Line Numbers to Filename.py
      • %save -r test 1-10- Saves lines 1 to 10 to test.py

    python3

    Executes programs using Python 3.

    • python3 filename.py- Executes filename.py with Python 3.
    • Ctrl + C- Terminate proccess/script (or keyboard interrupt).

    pipenv

    A packaging tool for Python that is designed to consolidate and simplify a development workflow. This is primarily for the Sphero SDK.

    • pipenv shell- Launches shell for virtual environment.
    • exit or Ctrl + D- Exit shell.

    Keyboard Commands

    • Ctrl + C- Kill process (sends interrupt command).
    • Ctrl + D- Exit (sends end of file command).

    Initial Hardware Tests

    This section contains instructions for testing all the hardware in the kit to verify that everything is working. These are individualized tests for the hardware, which can be used to help troubleshoot these devices later on. It is recommended that users test components individually (as laid out in this section) to reduce the number of unknown variables.

    Raspberry Pi

    The first component to test is the Raspberry Pi. Assemble the Raspberry Pi, Pi Servo pHat, and SD card as shown below. Users can power the device either through the 4-pin connector or the USB-C cable on the Pi Servo pHat.

    Pi test assembly
    Assembly for testing the Raspberry Pi Zero W. (Click to enlarge)

    It should power on, boot, connect to the WiFi network (configured previously), and be accessible through the SSH protocol when working properly.

    Power and Boot

    Once powered, you should see a green LED turn on. While the Raspberry Pi Zero W is booting, the green will flash indicating that the SD card is being accessed.

    ACT LED working
    An example with the ACT LED operating properly. (Click to enlarge)

    WiFi Network Connection

    It will take a minute or two for the Raspberry Pi to finish booting and connect to the WiFi network. Once connected to the WiFi network, the Raspberry Pi can either be pinged or mapped from another computer (on the same network). The simplest method is to ping the Raspberry Pi using the following command in your Terminal or Command Prompt. Users that have the IP address of the Raspberry Pi, should ping that IP address; otherwise, if users have forgotten or used the SD card method, they can ping the domain name raspberrypi.local. The limiting factor to using the domain name, is that only ONE Raspberry Pi can be on the network at a time; otherwise, users will run into contention issues and will likely connect to the wrong Raspberry Pi.

    • ping <IP ADDRESS> or ping raspberrypi.local

    Ping Raspberry Pi
    Verifying Raspberry Pi is on WiFi network. (Click to enlarge)

    (*More information on determining the Raspberr Pi's IP address can be found on the Raspberry Pi Foundation's website.)

    SSH Access

    Once users have pinged the Raspberry Pi and verified that it is connected to the network, they can access it remotely through the SSH protocol. On a modern computer OS, this can be done through the Terminal or Command-Prompt. However, users with more outdated systems will need to use an SSH client like Putty (see the Headless Raspberry Pi Setup tutorial). Using the Command-Prompt or Terminal, enter the following command:

    • ssh pi@<IP ADDRESS> or ssh pi@raspberrypi.local

    Again, if users have forgotten the IP address or used the SD card method, they can ping the domain name raspberrypi.local (the same limiting factor applies).

    SSH Login
    SSH access and login to Raspberry Pi. (Click to enlarge)

    Once connected, users will be prompted to login. If the login prompt doesn't show up after few moments, press the Enter or Return key to bring up the login prompt. The username and password are the default for the Raspberry Pi: Username = pi (used in ssh command) and Password = raspberry.

    Support Tip:
    • For users creating a new SSH connection, there may also be an authentication prompt. Type yes to continue.

      The authenticity of host '[IP Address]' can't be established.
      ECDSA key fingerprint is SHA256: [Bunch of numbers and letters].
      Are you sure you want to continue connecting (yes/no)?
    • To retrieve the IP address of the Pi, once users are connected, use the ifconfig or hostname -I commands as mentioned in the Software Overview: Part 1 - Raspbian OS section.

    Once users have remotely access the Raspberry Pi, the test is complete. Shutdown the Raspberry Pi using the sudo shutdown now command as mentioned in the Software Overview: Part 1 - Raspbian OS section. (*Remember... before unplugging the power or removing the SD card, be sure to verify that the Raspberry Pi has completely shutdown to avoid corrupting the SD card.)

    servo test assemblyShutting down the Raspberry Pi. (Click to enlarge)
    Pi Camera AssemblyACT LED indicating the end of the power down sequence, right before the power can be disconnected. (Click to enlarge)

    Pi Camera & Camera Web Interface

    Once users have verified that the they can remotely access the Raspberry Pi, it is time to test the Raspberry Pi camera web interface. Connect the Raspberry Pi camera to the Raspberry Pi Zero W as shown below (take note of what side the gold contacts are on).

    servo test assembly
    Pi Camera test assembly. (Click to enlarge)
    Pi Camera Assembly
    Pi Camera (v2) attached to a Raspberry Pi.

    Pi closeup-front
    Camera closeup-front
    Pi closeup-back
    Camera closeup-back
    Close ups of the Pi Camera (v2) and Raspberry Pi with the camera cable. (Click to enlarge)

    Once the camera is connected and the Raspberry Pi is powered on (via the Pi Servo pHat), wait for the Raspberry Pi to finish booting and connecting to the WiFi network. Then, remotely access the Raspberry Pi using the SSH protocol from another computer and login.

    SSH Login
    SSH access and login to Raspberry Pi. (Click to enlarge)

    Once logged in, users will want to test the Pi Camera web interface.

    1. Change the current working directory to the RPI_Cam_Web_Interface folder.

      • Users can use cd RPI_Cam_Web_Interface from the home directory.
      • Otherwise, user can also cd ~/RPI_Cam_Web_Interface from any other location.

      cd to RPI_Cam_Web_Interface
      Change the directory to the RPI_Cam_Web_Interface folder. (Click to enlarge)
    2. Initializing and terminating the web camera interface is simple. Below, are the two available commands to use, once users are in the RPI_Cam_Web_Interface directory:
      • ./start.sh - Start the Camera
      • ./stop.sh - Stop the Camera
    3. Use ./start.sh to initialize the stream for the video feed from the Pi Camera.

      start web interface video feed
      Start the video feed from the Pi Camera to the web interface. (Click to enlarge)
    4. While the web camera interface is running, pull up a web browser with enter the following URL: <IP ADDRESS>/html. (Again, if users have forgotten the IP address or used the SD card method, they can use the domain name raspberrypi.local in place of the <IP address>.) Users should see something similar to the images below.
      IP web interface
      Domain web interface
      Examples of the Pi Camera's web interface. (Click to enlarge)
    1. Users should be able to see the video feed from the Pi Camera on the webpage.
    2. Once users are finished testing the Pi Camera, use ./stop.sh to terminate the video feed.

      stop web interface video feed
      End the video feed from the Pi Camera to the web interface. (Click to enlarge)

    Once video feed is terminated, shutdown the Raspberry Pi using the sudo shutdown now command as mentioned in the Software Overview: Part 1 - Raspbian OS section. (*Remember... before unplugging the power or removing the SD card, be sure to verify that the Raspberry Pi has completely shutdown to avoid corrupting the SD card.)

    servo test assemblyShutting down the Raspberry Pi. (Click to enlarge)
    Pi Camera AssemblyACT LED indicating the end of the power down sequence, right before the power can be disconnected. (Click to enlarge)

    Pi Servo pHat

    The Pi Servo pHat plays a central roll for connecting everything to the Raspberry Pi. After testing the Raspberry Pi, above, users should have already verified that power is being passed through the Pi hat (pHat). This section will focus on the servo control of the Pi Servo pHat; the following Qwiic Devices section will verify the I2C functionality through the pHat.

    Qwiic Test

    Although the Pi Servo pHat isn't actally a Qwiic device, the servo controller IC does use the I2C bus. A simple test to verify that it is responding is to use the i2cdetect -y 1 command to ping the I2C bus. By default, the servo controller IC should be at the 0x40 I2C address. If the general call address is enabled, the 0x70 I2C address may appear as well.

    Ping the I2C bus
    Ping the I2C bus. (Click to enlarge)

    Servo Test

    This test will verify that the Pi Servo pHat can control the servos and that the servos are functioning properly. Additional instructions are also provided, below, to assist in pre-alignment of the pan-tilt servos prior to assembly. This will help to avoid damaging the servo on their inaugural operation as well as streamline the assembly process.

    Users will need to assemble the Raspberry Pi Zero W with the Pi Servo pHat and attach a servo to Channel 0. Double check that the wiring is aligned properly.

    servo test assembly
    Domain web interface

    Assembly for the individual servo test. (Click to enlarge)

    Once the everything is assembled and the Raspberry Pi is powered on, wait for the Raspberry Pi to finish booting and connecting to the WiFi network. Then, remotely access the Raspberry Pi using the SSH protocol from another computer and login.

    SSH Login
    SSH access and login to Raspberry Pi. (Click to enlarge)

    Once logged in, users will want to run the servo example code.

    1. Change the current working directory to the sparkfun_autonomous_kit folder.

      • Users can use cd sparkfun_autonomous_kit from the home directory.
      • Otherwise, user can also cd ~/sparkfun_autonomous_kit from any other location.

      cd to sparkfun_autonomous_kit
      Change the directory to the sparkfun_autonomous_kit folder. (Click to enlarge)
    2. Inside the sparkfun_autonomous_kit directory is the qwiic_library_examples folder. Change the current working directory to the qwiic_library_examples folder.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. Use the cd qwiic_library_examples command.

      cd to qwiic_library_examples
      Change the directory to the qwiic_library_examples folder. (Click to enlarge)
    3. Inside the qwiic_library_examples directory is the PiServoHat folder. Change the current working directory to the PiServoHat folder.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. Use the cd PiServoHat command.

      cd to PiServoHat
      Change the directory to the PiServoHat folder. (Click to enlarge)
    4. Inside the PiServoHat directory is the ex1_full_sweep_with_90_deg_servo.py example code. Execute the example code.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. To execute the example code, run python3 ex1_full_sweep_with_90_deg_servo.py.

      run ex1_full_sweep_with_90_deg_servo.py
      Execute the ex1_full_sweep_with_90_deg_servo.py example code. (Click to enlarge)
    5. If it is working properly, users should see the servo moving back and forth. It may be helpful to attach one of the servo horns to verify that the swing range is ~90°. Once users are finished testing, use Ctrl+C to terminate the script.
      cd to sparkfun_autonomous_kit
      servo actuating
      Running the servo test example. (Click to enlarge)
    1. Shutdown the Raspberry Pi using the sudo shutdown now command as mentioned in the Software Overview: Part 1 - Raspbian OS section. Then, swap the servos. (*Remember... before unplugging the power or removing the SD card, be sure to verify that the Raspberry Pi has completely shutdown to avoid corrupting the SD card.)
      • Users should shutdown and unplug the Raspberry Pi before swapping the servos.
      • Hot swapping the servos (swapping the servos while the Raspberry Pi is powered) can create a power failure issue, which could possibly corrupt the SD card.
      servo test assemblyShutting down the Raspberry Pi. (Click to enlarge)
      Pi Camera AssemblyACT LED indicating the end of the power down sequence, right before the power can be disconnected. (Click to enlarge)
    1. Repeat the process to test the other servo.
      • To jump directly to the PiServoHat directory:
        • Users can use cd sparkfun_autonomous_kit/qwiic_library_examples/PiServoHat from the home directory.
        • Otherwise, user can also cd ~/sparkfun_autonomous_kit/qwiic_library_examples/PiServoHat from any other location.

    That completes the Pi Servo pHat hardware test, shutdown the Raspberry Pi using the sudo shutdown now command as done previously. Users can choose pre-align their servos (recommended) or move on to testing the Qwiic devices.

    Aligning Servos (Optional)

    To help users avoid damaging their servos for the pan-tilt bracket, an example pre-alignment code has been provided. The example code will align the pan (or horizontal movement) servo at 45° and the tilt (or vertical movement) servo at 37°. To pre-align the servos, users will need to assemble the Raspberry Pi Zero W with the Pi Servo pHat and two servos.

    Alignment assembly
    Assembly for servo pre-alignment. (Click to enlarge)

    Once the everything is assembled and the Raspberry Pi is powered on, wait for the Raspberry Pi to finish booting and connecting to the WiFi network. Then, remotely access the Raspberry Pi using the SSH protocol from another computer and login.

    SSH Login
    SSH access and login to Raspberry Pi. (Click to enlarge)

    Once logged in, users will want to run the servo pre-alignment example.

    1. Change the current working directory to the sparkfun_autonomous_kit folder.

      • Users can use cd sparkfun_autonomous_kit from the home directory.
      • Otherwise, user can also cd ~/sparkfun_autonomous_kit from any other location.

      cd to sparkfun_autonomous_kit
      Change the directory to the sparkfun_autonomous_kit folder. (Click to enlarge)
    2. Inside the sparkfun_autonomous_kit directory is the servo_pre_alignment.py example code. Execute the example code.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. To execute the example code, run python3 servo_pre_alignment.py.

      run servo_pre_alignment.py
      Execute the servo_pre_alignment.py example code. (Click to enlarge)
    3. The example code will align the pan (or horizontal movement) servo at 45° and the tilt (or vertical movement) servo at 37°. This position is ideal for the standard forward facing position. The Channel 0 is configured for the pan servo and Channel 1 is configured for the tilt servo.
      90 deg postion Standard forward facing or 90° postion.
      (Click to enlarge)
      standard position on chassis Standard forward facing position on chassis.
      (Click to enlarge)
    1. Users should mark these positions with a marker. These marks should streamline the assembly process. Additionally, aligning the tilt servo at 37°, will hopefully prevent it from over-extending its position and thereby striping out the gears when it is moved to 0° or 90°.
      Marking Servo
      Marking the position on a servo. (Click to enlarge)
      Marked Servo
      A marked servo. (Click to enlarge)
    1. Once completed, shutdown the Raspberry Pi using the sudo shutdown now command as mentioned in the Software Overview: Part 1 - Raspbian OS section. (*Remember... before unplugging the power or removing the SD card, be sure to verify that the Raspberry Pi has completely shutdown to avoid corrupting the SD card.)
      servo test assemblyShutting down the Raspberry Pi. (Click to enlarge)
      Pi Camera AssemblyACT LED indicating the end of the power down sequence, right before the power can be disconnected. (Click to enlarge)

    Qwiic Devices

    By now, users should have verified the functionality of the Raspberry Pi, the Pi Servo pHat, and the I2C bus. This section will verify the I2C functionality from the Pi Servo pHat with each Qwiic device, individually.

    Qwiic Test

    A simple test for users to check the connectivity of any attached I2C devices can be performed by pinging them with i2c-tools. In the command-line enter i2cdetect -y 1 and a readout of any detected devices will appear. For example, the servo controller IC should be at the 0x40 I2C address. (If the general call address is enabled, the 0x70 I2C address may appear as well.)

    Ping the I2C bus
    Ping the I2C bus with just the Pi Servo pHat. (Click to enlarge)

    This is a table of the default I2C addresses for the hardware included in these kits.

    Hardware Pi Servo pHat
    (Not a Qwiic Device)
    Titan GPS ModuleQwiic Mux (TCA9548A)VL53L1X ToF Sensor
    Default I2C Address0x400x100x700x29

    GPS (Titan X1) Module

    For this test users will want to be in a location with their WiFi network coverage and a clear view of the sky. Access to an open window, is a feasible option; however, it is not guaranteed to work. For example, on the bottom floor of a tall building, even if users stuck the GPS module out the window, it may still have issues getting a positional lock. If possible, a clearing or field, just outside a house or building, where there is still WiFi coverage is the ideal testing location.

    Users will need to assemble the Raspberry Pi Zero W with the Pi Servo pHat and attach the Titan (X1) GPS module using a Qwiic cable. To power the setup, users can use 4-pin UART cable and the Sphero RVR to make the test setup portable and carry it outside.

    GPS assembly
    Portable assembly for testing the GPS module. (Click to enlarge)

    Once the everything is assembled, to power the Raspberry Pi, press the power button on the side of the Sphero RVR. Wait for the Raspberry Pi to finish booting and connecting to the WiFi network. Then, remotely access the Raspberry Pi using the SSH protocol from another computer and login.

    SSH Login
    SSH access and login to Raspberry Pi. (Click to enlarge)

    Once logged in, users will want to run the GPS example code.

    1. Change the current working directory to the sparkfun_autonomous_kit folder.

      • Users can use cd sparkfun_autonomous_kit from the home directory.
      • Otherwise, user can also cd ~/sparkfun_autonomous_kit from any other location.

      cd to sparkfun_autonomous_kit
      Change the directory to the sparkfun_autonomous_kit folder. (Click to enlarge)
    2. Inside the sparkfun_autonomous_kit directory is the hardware_pre_test folder. Change the current working directory to the hardware_pre_test folder.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. Use the hardware_pre_test command.

      cd to hardware_pre_test
      Change the directory to the hardware_pre_test folder. (Click to enlarge)
    3. Inside the hardware_pre_test directory is the TitanX1 folder. Change the current working directory to the TitanX1 folder.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. Use the cd TitanX1 command.

      cd to TitanX1
      Change the directory to the TitanX1 folder. (Click to enlarge)
    4. Inside the TitanX1 directory is the gps_data.py example code. Execute the example code.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. To execute the example code, run python3 gps_data.py.

      run gps_data.py
      Execute the gps_data.py example code. (Click to enlarge)
    5. If it is working properly, users should see clear readout from the GPS module. It may take a minute or two for the GPS module to get an initial lock; the PPS LED is usually a good general indicator of a possible initial lock on the modules position. (The PPS LED is not necessarily an absolute indication that the module has a fix on its position.)

      Additionally, the backup battery has enough energy for the GPS module to store pertinent data for a few days. Therefore, if the module has had a recent positional lock in the area, it may re-acquire its position a lot quicker.

      Once users are finished testing, use Ctrl+C to terminate the script.

      running gps example
      Running the GPS test example. (Click to enlarge)
      PPS LED
      PPS LED blinking. (Click to enlarge)
    1. That completes the GPS hardware test. Shutdown the Raspberry Pi using the sudo shutdown now command as mentioned in the Software Overview: Part 1 - Raspbian OS section. (*Remember... before unplugging the power or removing the SD card, be sure to verify that the Raspberry Pi has completely shutdown to avoid corrupting the SD card.)
      • Users should shutdown and unplug the Raspberry Pi before swapping the servos.
      • Hot swapping the servos (swapping the servos while the Raspberry Pi is powered) can create a power failure issue, which could possibly corrupt the SD card.
      servo test assemblyShutting down the Raspberry Pi. (Click to enlarge)
      Pi Camera AssemblyACT LED indicating the end of the power down sequence, right before the power can be disconnected. (Click to enlarge)

    Users who purchase the Basic kit should move on to the Hardware Assembly section. Otherwise, users that purchased the Advanced kit should continue below to finish testing the VL53L1X ToF sensors and the Qwiic Mux.

    ToF (VL53L1X) Distance Sensors (Advanced Kit Only)

    For this test users will want to be in an indoor location. Although, the ToF sensor should be more than powerful enough to operate in daylight conditions, it would be advisable to test indoors to remove ambient light as a variable for the testing conditions. Users will need to assemble the Raspberry Pi Zero W with the Pi Servo pHat and attach one of the VL53L1X ToF distance sensors using a Qwiic cable.

    ToF assembly
    Assembly for testing the VL53L1X ToF distance sensor. (Click to enlarge)

    Once the everything is assembled, to power the Raspberry Pi and wait for it to finish booting and connecting to the WiFi network. Then, remotely access the Raspberry Pi using the SSH protocol from another computer and login.

    SSH Login
    SSH access and login to Raspberry Pi. (Click to enlarge)

    Once logged in, users will want to run the distance sensor example code.

    1. Change the current working directory to the sparkfun_autonomous_kit folder.

      • Users can use cd sparkfun_autonomous_kit from the home directory.
      • Otherwise, user can also cd ~/sparkfun_autonomous_kit from any other location.

      cd to sparkfun_autonomous_kit
      Change the directory to the sparkfun_autonomous_kit folder. (Click to enlarge)
    2. Inside the sparkfun_autonomous_kit directory is the qwiic_library_examples folder. Change the current working directory to the qwiic_library_examples folder.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. Use the cd qwiic_library_examples command.

      cd to qwiic_library_examples
      Change the directory to the qwiic_library_examples folder. (Click to enlarge)
    3. Inside the qwiic_library_examples directory is the VL53L1X folder. Change the current working directory to the VL53L1X folder.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. Use the cd VL53L1X command.

      cd to VL53L1X
      Change the directory to the VL53L1X folder. (Click to enlarge)
    4. Inside the VL53L1X directory is the ex1_read_distance.py example code. Execute the example code.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. To execute the example code, run python3 ex1_read_distance.py.

      run ex1_read_distance.py
      Execute the ex1_read_distance.py example code. (Click to enlarge)
    5. If it is working properly, users should see clear readout from the VL53L1X ToF distance sensor. If users have a cellphone camera that does not have an IR filter, the camera can be used to detect the pulses of the IR laser. Once users are finished testing, use Ctrl+C to terminate the script.
      running example codeRunning the distance sensor test code.
      (Click to enlarge)
      detecting IR laserDetecting pulses of IR laser. (Click to enlarge)
    1. Shutdown the Raspberry Pi using the sudo shutdown now command as mentioned in the Software Overview: Part 1 - Raspbian OS section. Then, swap the ToF sensors. (*Remember... before unplugging the power or removing the SD card, be sure to verify that the Raspberry Pi has completely shutdown to avoid corrupting the SD card.)
      • Users should shutdown and unplug the Raspberry Pi before swapping the sensors.
      servo test assemblyShutting down the Raspberry Pi. (Click to enlarge)
      Pi Camera AssemblyACT LED indicating the end of the power down sequence, right before the power can be disconnected. (Click to enlarge)
    1. Repeat the process to test the other ToF sensor.
      • To jump directly to the VL53L1X directory:
        • Users can use cd sparkfun_autonomous_kit/qwiic_library_examples/VL53L1X from the home directory.
        • Otherwise, user can also cd ~/sparkfun_autonomous_kit/qwiic_library_examples/VL53L1X from any other location.

    This completes the VL53L1X ToF distance sensor test, shutdown the Raspberry Pi using the sudo shutdown now command as done previously. Users should move on to testing the Qwiic Mux, below.

    Qwiic Mux (Advanced Kit Only)

    This is the last and final test! The VL53L1X ToF distance sensor has a "software" configurable I2C address; however it is "volatile", upon re-powering the device, it will automatically reset to the default I2C address. This is where the Qwiic Mux comes in. It is used to isolate the sensors, initially, so that the I2C address of one of the sensors can be reconfigured on power up. Again, since this test will use the VL53L1X sensors, users will want to be in an indoor location.

    Users will need to assemble the Raspberry Pi Zero W with the Pi Servo pHat and attach the Qwiic Mux with a Qwiic cable. Then, on the Qwiic Mux, users should attach one of the VL53L1X ToF distance sensors to channels 0or4, using the Qwiic cables.

    Mux assembly
    Assembly for testing the Qwiic Mux; use either channel 0 or 4. (Click to enlarge)

    Once the everything is assembled, to power the Raspberry Pi and wait for it to finish booting and connecting to the WiFi network. Then, remotely access the Raspberry Pi using the SSH protocol from another computer and login.

    SSH Login
    SSH access and login to Raspberry Pi. (Click to enlarge)

    Once logged in, users will want to run the VL53L1X address change example code.

    1. Change the current working directory to the sparkfun_autonomous_kit folder.

      • Users can use cd sparkfun_autonomous_kit from the home directory.
      • Otherwise, user can also cd ~/sparkfun_autonomous_kit from any other location.

      cd to sparkfun_autonomous_kit
      Change the directory to the sparkfun_autonomous_kit folder. (Click to enlarge)
    2. Inside the sparkfun_autonomous_kit directory is the vl53l1x_change_i2c_address.py example code. Execute the example code.

      1. Use the ls command list the files in the directory and to verify it is there.
      2. To execute the example code, run python3 vl53l1x_change_i2c_address.py.

      run vl53l1x_change_i2c_address.py
      Execute the vl53l1x_change_i2c_address.py example code. (Click to enlarge)
    3. Follow the prompts of the example code. When selecting, which channel on the Mux to enable, select the channel that the VL53L1X ToF distance sensor is attached to (i.e. channels 0 or 4, from the instructions earilier). If users have successful performed the I2C address change, they should be able to test the sensor on the new I2C address. Once users are finished testing, use Ctrl+C to terminate the script.
      running example code
      Running the I2C address change code. (Click to enlarge)
    4. After the the test is complete, shutdown the Raspberry Pi using the sudo shutdown now command as mentioned in the Software Overview: Part 1 - Raspbian OS section. (*Remember... before unplugging the power or removing the SD card, be sure to verify that the Raspberry Pi has completely shutdown to avoid corrupting the SD card.)
      • Users should shutdown and unplug the Raspberry Pi before swapping the sensors.
      servo test assemblyShutting down the Raspberry Pi. (Click to enlarge)
      Pi Camera AssemblyACT LED indicating the end of the power down sequence, right before the power can be disconnected. (Click to enlarge)

    This completes all the hardware pre-test; please, move on to the Hardware Assembly section below.

    Hardware Assembly

    Note: Before assembling the SparkFun autonomous kit for the Sphero RVR, users should configure their Raspberry Pi and verify the hardware is working. (These steps can be performed with the kit fully assembled; however, avoid any unnecessary troubleshooting or pitfalls, it is recommended that the instructions be followed in the order presented.)

    Now that we have verified that all the hardware is operational, let's assemble the SparkFun autonomous kit! To begin assembling the kit with the Sphero RVR, follow the corresponding guide.

    New!

    Basic Autonomous Kit for Sphero RVR

    December 12, 2019

    Get your Basic Autonomous Kit for Sphero RVR all hooked up with this guide!
    New!

    Advanced Autonomous Kit for Sphero RVR

    December 12, 2019

    Get your Advanced Autonomous Kit for the Sphero RVR built up with this hookup guide!

    Software Overview: Part 3 - Sphero SDK

    Note: Users should use head over to the Sphero's SDK webpage for details on the SDK's functionality. Additionally, Sphero also has a support page in case users get stuck.

    This section will focus on getting started with the Sphero SDK.

    1. To begin using the Sphero SDK, users should change the current working directory to the sphero-sdk-raspberrypi-python folder using the following command:
      • cd ~/sphero-sdk-raspberrypi-python
    2. Once inside the sphero-sdk-raspberrypi-python folder, users will need to spawn a shell in a virtual environment using the pipenv shell command.
      • This will create a virtual environment if one doesn't already exist.
      • This is the most important step to initializing the Sphero SDK; otherwise, users will run into issues executing any of the examples.
    3. After the shell has been activated, users can begin to start using the example code. Navigate around to find a code example.
    4. To run a Python example code, use the following command:
      • python3 <File Name>.py
    5. Exiting:
      • Use Ctrl+C to interrupt the keyboard control script.
      • To exit the virtual environment shell, type exit or Ctrl+D.

    Examples

    Keyboard ⌨️ Control & Camera Web Interface

    This example will focus on getting the Keyboard ⌨️ Control example from the Sphero SDK working while streaming the Raspberry Pi's camera video feed. (*For more details on the Keyboard ⌨️ Control example, check out Sphero's webpage.)

    To begin, users should remotely access the Raspberry Pi through the SSH protocol (see the Remote Access with SSH section).

    Enabling the Camera

    Once users have logged in, change the current working directory to the RPi_Cam_Web_Interface folder using the following command:

    cd RPi_Cam_Web_Interface

    Once inside the RPi_Cam_Web_Interface folder, users can utilize the following two commands to enable/disable the web service for the camera and pan-tilt servo controls.

    • To enable the camera and servo controls, use the ./start.sh command.
    • To disable the camera and servo controls, use the ./stop.sh command.

    After the web service is enabled, users can bring up a live stream of the video feed from the camera using a web browser on the remote computer. The url for the web interface is: <IP Address>/html (users can also use raspberrypi.local/html). If the url doesn't work, try adding the http:// prefix (i.e http://raspberrypi.local/html/).

    screen shot of camera web interface
    Screenshot of camera web interface.

    Users should then return to the home directory using either the cd ~ or cd .. command.

    Keyboard Control

    Note: Don't forget to move the serial switch on the Pi Servo pHat to RVR so that the serial communication passes through the 4-pin UART header for the Sphero RVR.


    Move serial switch to RVR. (Click to enlarge)

    Next, to begin using the Sphero SDK, users should change the current working directory to the sphero-sdk-raspberrypi-python folder using the following command:

    cd sphero-sdk-raspberrypi-python

    Once inside the sphero-sdk-raspberrypi-python folder, users will need to spawn a shell in a virtual environment using the pipenv shell command (this will create a virtual environment if one doesn't already exist). This is the most important step to "initializing" the Sphero SDK; otherwise, users will run into issues executing any of the examples.

    After the shell has been activated, users should move the current working directory to the keyboard_control folder using the following command:

    cd projects/keyboard_control

    Once inside the keyboard_control folder, users will need to start the drive_with_wasd_keys.py Python example code with the following command:

    python3 drive_with_wasd_keys.py

    You may see a few initialization printouts like:

    Checking RVR firmware versions...
    Checking CMS firmware versions...
    Firmware check done.
    

    Wait a minute or two for the script to finish initializing. Once complete, users should be able to use the W, A, S, D, and Space Bar keys to control the Sphero RVR.

    Have fun driving the RVR around, don't forget to play with the servo controls on the web interface.

    Exiting

    Use Ctrl+C to interrupt the keyboard control script. The example code will then display:

    Keyboard Interrupt...
    Press any key to exit.
    

    and prompt user to Press any key to exit.. Pressing another key will exit the script. To exit the virtual environment shell, type exit or Ctrl+D.

    To disable the web interface, change back to the RPi_Cam_Web_Interface directory and use the ./stop.sh command.

    Using Both VL53L1X Sensors

    To use both VL53L1X ToF sensors, users will need to use the Qwiic Mux to access a single sensor and change the I2C address. Then users will need to access both sensors through the Qwiic Mux to retrieve the distance data. The following instructions will get users started on this process with the included example code.

    To begin, users should remotely access the Raspberry Pi through the SSH protocol (see the Remote Access with SSH section).

    Changing the I2C Address

    The VL53L1X ToF distance sensor has a "software" configurable I2C address; however it is "volatile", upon re-powering the device, it will automatically reset to the default I2C address. This is where the Qwiic Mux comes in. It is used to isolate the sensors, initially, so that the I2C address of one of the sensors can be reconfigured on power up.

    Once logged in, change the current working directory to the sparkfun_autonomous_kit folder.

    • Users can use cd sparkfun_autonomous_kit from the home directory.
    • Otherwise, user can also cd ~/sparkfun_autonomous_kit from any other location.

    Inside the sparkfun_autonomous_kit directory is the vl53l1x_change_i2c_address.py example code. Execute the example code.

    1. Use the ls command list the files in the directory and to verify it is there.
    2. To execute the example code, run python3 vl53l1x_change_i2c_address.py.

    Follow the prompts of the example code. When selecting, which channel on the Mux to enable, select the one of the channels that the VL53L1X ToF distance sensor is attached to (i.e. either channels 0 or 4). If users have successful performed the I2C address change, they should be able to test the sensor on the new I2C address. Use Ctrl+C to terminate the script.

    I2C address change
    Running the I2C address change code. (Click to enlarge)

    Running the Example Code

    Now that users have modified the I2C address of one of the sensors, they can use the example code to get readings from both sensor.

    Inside the sparkfun_autonomous_kit directory is the hardware_pre_test folder. Change the current working directory to the hardware_pre_test folder.

    • Use the hardware_pre_test command.

    Inside the hardware_pre_test directory is the VL53L1X folder. Change the current working directory to the VL53L1X folder.

    1. Use the ls command list the files in the directory and to verify it is there.
    2. Use the cd VL53L1X command.

    Inside the VL53L1X directory is the dual_sensors.py example code. Execute the example code.

    1. Use the ls command list the files in the directory and to verify it is there.
    2. To execute the example code, run python3 dual_sensors.py.

    Follow the prompts of the example code. When selecting, which channel on the Mux to enable, select both of the channels that the VL53L1X ToF distance sensors are attached to (i.e. channels 0 and 4). If users have successful performed the I2C address change, they should be able to designate the I2C address of the front and rear sensor. Once users are finished testing, use Ctrl+C to terminate the script.

    dual sensor test
    Reading distances from both VL53L1X ToF sensors. (Click to enlarge)

    Troubleshooting Tips

    Do you think something is broken? Let's try some of these common troubleshooting tips before looking for technical assistance. This section is written in a hierarchical fashion to make it easier for users to follow from top to bottom. If you know what you are looking for an don't see it right away, don't forget to try a "Google" search; often, someone else has already run into the same issue and may have posted a solution.

    First Things First

    If you have never tried to troubleshoot a device before, this is a great beginners guide of common points that novices (and even some experienced users) should check.

    Replacement Parts

    In the event that you loose or break any parts, the components of the kits are linked below. (*Unfortunately, the mounting plate and 3/4" 4-40 standoffs for advanced kit are unavailable at this time.)

    Click the button above to toggle a list of replacement parts that are available from our catalog.
    Main Components:
    SparkFun Distance Sensor Breakout - 4 Meter, VL53L1X (Qwiic)

    SparkFun Distance Sensor Breakout - 4 Meter, VL53L1X (Qwiic)

    SEN-14722
    $21.95
    7
    SparkFun GPS Breakout - XA1110 (Qwiic)

    SparkFun GPS Breakout - XA1110 (Qwiic)

    GPS-14414
    $49.95
    5
    SparkFun Qwiic Cable Kit

    SparkFun Qwiic Cable Kit

    KIT-15081
    $7.95
    1
    microSD Card - 16GB (Class 10)

    microSD Card - 16GB (Class 10)

    COM-15051
    $19.95
    Raspberry Pi Camera Module V2

    Raspberry Pi Camera Module V2

    DEV-14028
    $29.95
    9
    SparkFun Qwiic Mux Breakout - 8 Channel (TCA9548A)

    SparkFun Qwiic Mux Breakout - 8 Channel (TCA9548A)

    BOB-14685
    $11.95
    Pan/Tilt Bracket Kit (Single Attachment)

    Pan/Tilt Bracket Kit (Single Attachment)

    ROB-14391
    $6.95
    4
    SparkFun Servo pHAT for Raspberry Pi

    SparkFun Servo pHAT for Raspberry Pi

    DEV-15316
    $10.95
    1
    Raspberry Pi Zero Camera Cable

    Raspberry Pi Zero Camera Cable

    PRT-14272
    $5.95
    Jumper Wire - 0.1", 4-pin, 6"

    Jumper Wire - 0.1", 4-pin, 6"

    PRT-10369
    $1.50
    Raspberry Pi Zero W (with Headers)

    Raspberry Pi Zero W (with Headers)

    DEV-15470
    $14.00
    1
    Mounting Components:
    Screw - Phillips Head (1/4", 4-40, 10 pack)

    Screw - Phillips Head (1/4", 4-40, 10 pack)

    PRT-10453
    $1.50
    Nut - Metal (4-40, 10 pack)

    Nut - Metal (4-40, 10 pack)

    PRT-10454
    $1.50
    Screw - Phillips Head (1/2", 4-40, 10 pack)

    Screw - Phillips Head (1/2", 4-40, 10 pack)

    PRT-10452
    $1.50
    Angle Bracket - 4-40

    Angle Bracket - 4-40

    PRT-10228
    $0.50

    Sphero RVR and SDK

    For all things related specifically to the Sphero RVR and/or the Sphero SDK, head over to the Sphero SDK website. They have troubleshooting guides for the RVR and SDK software.

    If you can't find the information you need in their troubleshooting guides, their community forum is a great place to find and ask for help.

    Some quick tips...

    • Double check that the UART cable is connected properly and in the correct orientation.
    • The login shell or console must be disabled to use the SDK; double check that it is disabled.
    • Is the serial switch in the correct position? The tab should be sitting overRVR.
      Serial Switch on Pi Servo pHat
      Move serial switch to RVR. (Click to enlarge)
    • Don't forget to spawn a shell in the virtual environment (pipenv shell) to use the example code.
    • To exit the shell, use Ctrl + D or type exit.

    The Pre-Configured Image

    If you have accidentally erased you SD card, it has become corrupted, or you need to start from scratch... the pre-configured image of Raspbian can be downloaded using the button below.

    Remove Overclock

    To undo the overclock configuration, modify the config.txt file using sudo nano boot/config.txt. Scroll down to the bottom and under [pi0w] change:

    over_voltage=4
    force_turbo=1
    

    to:

    over_voltage=6
    force_turbo=0
    

    (*More information on overclocking can be found on the Raspberry Pi Foundation's website.)

    Custom Image

    For users looking to build their own image, here are basic instructions. If you know what you are doing then these should be easy to follow. If you don't know what you are doing, download the pre-configured image. (*Assisting customers with building their own custom Raspbian image is beyond the scope of this tutorial and our technical support team).

    • Follow the instructions on the Sphero SDK to download and setup the SDK software.
    • Download and setup the RPi_Cam_Web_Interface code from the GitHub repository.
    • Install the sparkfun-qwiic Python package using pip3.
    • Download the SparkFun Autonomous Kit example code from the GitHub repository.
    • Move the servo control firmware from the SparkFun Autonomous Kit example code to the RPi_Cam_Web_Interface folder.
    • Modify the start.sh and stop.sh bash scripts to use and terminate the servo control firmware.
    • Configure the SD card to overclock Raspberry Pi Zero Ws:
    • Enable the required interfaces for the Raspberry Pi.

    Testing the Hardware

    Testing the hardware is a great place to start, there is an Initial Hardware Tests section in the guide for testing all the hardware included in these kits.

    If there something you are trying to do with a specific piece of hardware, go back to the Initial Hardware Tests section to verify it is working with the example code. If the device is working with the example code, then there is possibly an issue with the code you have written. Otherwise, if the device isn't responding properly, users double check if any of the "tricks of the trade" (i.e. tips) below apply.

    "Google" It!

    Have you tried searching the internet? Often, with common issues, someone else will have run into the same issue and there will be a few posts on it with solutions, if not workarounds.

    (*Search engines like Google are great resources! At SparkFun, we are a company of ~100 employees with only ~20 of us with technical knowledge. There ~7.7 billion people in the world and ~ 3.5 billion people with internet access. Obviously, not all of them will be technical experts; however, why not leverage these numbers in your favor?)

    Weird Characters/Keyboard Map

    If you are getting weird characters when typing, double check that the keyboard map is configure properly. You can set the localization and keyboard map using sudo raspi-config.

    WiFi

    Double check the WiFi network. As mentioned in the Configure the Raspberry Pi section, the Raspberry Pi Zero W supports 2.4GHz 802.11n wireless LAN and is only compatible with 2.4GHz networks. It will not connect to a 5GHz WiFi network.

    If you are in an office or school setting, you may be on an enterprise network. Check with your IT network administrator, about making sure that you have the necessary permissions and configurations in place to utilize our kit.

    Note: This kit doesn't actually need internet access to work. If you can get approval from your network administrator, you can run the examples from a basic home WiFi router. Just configure the router with an SSID and passphrase, then connect the remote computer to the router directly. You can then configure the Raspberry Pi to use the basic home WiFi router's network instead. (*The Raspberry Pi hosts the camera web interface internally.)

    If you have multiple Raspberry Pi's on a single network. Try powering the rest off and just using the Raspberry Pi you are trying to troubleshoot. This should isolate any bandwith issues that may occur if you have too many devices connected to the network at once.

    Use the WiFi router's network monitoring tools to verify that the Raspberry Pi and the remote computer are on the network.

    Try to ping the Raspberry Pi or ssh in. Try using both the IP address and raspberrypi.local methods.

    1. ping <IP Address>
    2. ssh <IP Address>
    3. ping raspberrypi.local
    4. ssh pi@raspberrypi.local

    Re-enable the serial console/login shell. Using an SD card reader, add console=serial0,115200 back to the cmdline.txt file on the SD card. Then use the Pi Servo pHat for the headless setup.

    • Double check the IP address. Also, try to ping the router, the remote computer, and/or a website to check for any network issues.
      1. ifconfig
      2. hostname -I
      3. ping <IP Address of Remote Computer>
      4. ping <IP Address of Router>
      5. ping google.com
    • Check the wpa_supplicant.conf file. Do you have the correct country code in?
      • sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

    If your Raspberry Pi isn't connecting to the WiFi network, you should re-configure the WiFi. Even if you know you have setup the credentials properly, it was working prviously, or it is on the network... sometimes, it is just as easy are resetting the WiFi configuration. Users should try both the wpa_supplicant.conf file and raspi-config tool methods.

    Camera Focus

    By default the camera lens should be screwed in with the focus set to ∞. Although it is not advisable, the sensor can be refocused.

    • This will void any warranty on the product, and you will NOT be able to return the camera module.
    • You should avoid this as it can damage the sensor and/or possibly loose, break, or scratch the lens.
    • To refocus the lens, carefully twist the lens at the indentations.

    Serial Connection

    If you are having serial connection issues with the Sphero SDK:

    • Double check that the UART cable is connected properly and in the correct orientation.
    • The login shell or console must be disabled to use the SDK; double check that it is disabled.
    • Is the serial switch in the correct position? The tab should be sitting overRVR.
      Serial Switch on Pi Servo pHat
      Move serial switch to RVR. (Click to enlarge)

    Cable Issue?

    Test the serial port on the Raspberry Pi, re-enable the serial console/login shell.

    • Using an SD card reader, add console=serial0,115200 back to the cmdline.txt file on the SD card.
    • Then use the Pi Servo pHat for the headless setup.

    If the serial port on the Pi works, it may be an issue with the UART cable. Try testing for continuity with a multimeter.

    Qwiic Issues

    If none of the Qwiic (I2C) devices are responding or you get an IOError, this may be an I2C issue.

    • Double check that the I2C bus is enabled on the Raspberry Pi using the raspi-config tool.
    • You can also ping the I2C bus using i2cdetect -y 1.
    • Test the hardware:
      • Double check the Qwiic cables are inserted properly.
      • Try testing devices individually following the Initial Hardware Tests section.
        • Time to bust out that dusty multimeter. Are they at least getting power?
      • Try swapping the cable, maybe one of your cables is bad.
        • Use a multimeter to double check the continuity on the I2C lines and power.

    GPS Lock/Accuracy

    The GPS needs a view of the sky; check out our GPS Basics tutorial.

    • If you are indoors, the GPS satellite signals will not reach the modules.
    • If you are near a window, you may get some readings, but they will not be accurate.
    • If you are in an urban/city environment, you may have issues with accuracy near tall objects like trees or buildings. This is due to the signal reflection off these objects.
      • The triangulation calculation requires precision timing, that is why there atomic clocks on each satellite. Any slight deviation, including the reflection of a signal, will throw off the position calculation.)

    If you the PPS LED is blinking, but you are not getting any positional data you may not have a lock from enough satellites. The PPS LED doesn't guarantee a positional lock, based on the datasheet, it usually indicates a NMEA sentence was received at some point.

    The Titan X1110 receiver is only compatible with GPS and GLONASS satellites.

    Servo Inconsistency

    My servo is behaving inconsistently... unfortunately, these are inexpensive servos. (*The Pan/Tilt Bracket Kit costs ~$7. Standard servo costs ~$25-40/each on average.)

    • Things like jiggling and slow movements can be expected. This usually occurs because the manufacturing tolerances are low for the potentiometer and gears, used inside. If your servo is acting "all sorts of crazy" when testing with the example code... ok, then you probably have a bad servo; reach out from the technical assistance page.
    • Stripping the servo gears and damaging the servo can happen when the servo is forced into a position or manually moved (while powered or connected to the Pi Servo pHat).
    • Missing the correct servo horns or screws? This happens from time to time, reach out from the technical assistance page.
    • Users can upgrade their pan-tilt servo assembly if they would like to use a more reliable system. Just make sure the replacements have enough space to move, the camera cable is long enough, and that it is compatible with the mounted servo horn (or mounting holes).

    VL53L1X

    Performance

    The ToF sensor does have performance limitations. For example, the sensor FOV, the target properties (i.e. size, color, reflectivity, etc.), and the ambient light all affect the sensor performance and reliability. Check out these related support articles from Garmin:

    I2C Address

    The VL53L1X does not permanently store any I2C address changes. On each power up cycle, the sensor reverts to the default I2C address. (*There is no work around... we have already asked the manufacturer. That is why the Qwiic Mux was added to the kit.)

    Still Stuck?

    Resources and Going Further

    For more information on the SparkFun Autonomous Kit and the included hardware, check out the resources below:

    Hardware Hookup Guides:

    Setting Up the Pi Zero Wireless Pan-Tilt Camera

    This tutorial will show you how to assemble, program, and access the Raspberry Pi Zero as a headless wireless pan-tilt camera.

    Getting Started with the Raspberry Pi Zero Wireless

    Learn how to setup, configure and use the smallest Raspberry Pi yet, the Raspberry Pi Zero - Wireless.

    SparkFun GPS Breakout - XA1110 (Qwiic) Hookup Guide

    Figure out where in the world you are with the Qwiic SparkFun GPS Breakout - XA1110.

    Qwiic Distance Sensor (VL53L1X) Hookup Guide

    The Qwiic VL53L1X time of flight sensor is capable of several modes, as well as having a range of 4M. Let's hook it up and find out just how far away that thing over there is.

    Qwiic MUX Hookup Guide

    Have a bunch of sensors with the same I2C address? Put them on the Qwiic MUX (TCA9548A) to get them all talking on the same bus!

    Pi Servo pHAT (v2) Hookup Guide

    This hookup guide will get you started with connecting and using the Pi Servo pHAT on a Raspberry Pi.
    New!

    Basic Autonomous Kit for Sphero RVR

    Get your Basic Autonomous Kit for Sphero RVR all hooked up with this guide!
    New!

    Advanced Autonomous Kit for Sphero RVR

    Get your Advanced Autonomous Kit for the Sphero RVR built up with this hookup guide!
    Python Logo

    Interested in other robotics projects? Check out some of our robotics related tutorials below:

    Assembly Guide for RedBot with Shadow Chassis

    Assembly Guide for the RedBot Kit. This tutorial includes extra parts to follow to go along with the RedBot Inventor's Kit tutorial.

    Experiment Guide for RedBot with Shadow Chassis

    This Experiment Guide offers nine experiments to get you started with the SparkFun RedBot. This guide is designed for those who are familiar with our SparkFun Inventor's Kit and want to take their robotics knowledge to the next level.

    SparkFun Line Follower Array Hookup Guide

    Learn how to connect the RedBot Line-Following Sensor Bar to an Arduino-type microcontroller. Use the example sketches to read data from the bar, and try out a simple line-following algorithm.

    Building an Autonomous Vehicle: The Batmobile

    Documenting a six-month project to race autonomous Power Wheels at the SparkFun Autonomous Vehicle Competition (AVC) in 2016.

    Light-Seeking Robot

    We use parts from the SparkFun Inventor's Kit v4.0 to create a light-seeking robot that mimics the behavior of single-celled organisms.

    SparkFun Inventor's Kit Experiment Guide - v4.1

    The SparkFun Inventor's Kit (SIK) Experiment Guide contains all of the information needed to build all five projects, encompassing 16 circuits, in the latest version of the kit, v4.1.

    Assembly Guide for SparkFun JetBot AI Kit

    Assembly Guide for the SparkFun JetBot AI Kit. This tutorial includes photos & comments to assemble the two-layer chassis & additional components unique to the JetBot kit.
    New!

    Advanced Autonomous Kit for Sphero RVR

    Get your Advanced Autonomous Kit for the Sphero RVR built up with this hookup guide!

    learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

    Advanced Autonomous Kit for Sphero RVR Assembly Guide

    $
    0
    0

    Advanced Autonomous Kit for Sphero RVR Assembly Guide a learn.sparkfun.com tutorial

    Available online at: http://sfe.io/t1034

    Introduction

    The SparkFun Advanced Autonomous Kit for Sphero RVR provides all the functionality of the basic kit with the addition of time-of-flight distance sensing in the front and rear. Based around Raspberry Pi’s small yet powerful Zero W model, the kit provides distance sensing, global positioning, and vision to the Sphero RVR. In this tutorial we'll cover assembly of the kit's hardware. Most of the steps are fairly straight forward and just require a little bit of patience.

    SparkFun Advanced Autonomous Kit for Sphero RVR

    SparkFun Advanced Autonomous Kit for Sphero RVR

    KIT-15303
    $164.95

    Required Materials

    To follow along with this tutorial, you will really only need a phillips-head screwdriver. We have quite a few to choose from - but our Pocket Screwdriver Set is a great option.

    Electric Hobby Screwdriver Set

    Electric Hobby Screwdriver Set

    TOL-15548
    $39.95
    Pocket Screwdriver Set

    Pocket Screwdriver Set

    TOL-12891
    $3.95
    5
    Tool Kit - Screwdriver and Bit Set

    Tool Kit - Screwdriver and Bit Set

    TOL-10865
    $9.95
    5
    iFixit Essential Electronics Toolkit

    iFixit Essential Electronics Toolkit

    TOL-15256
    $29.99

    Before We Begin

    If you haven't already, start charging the RVR battery. It takes a while to charge, so now would be a good time to get it going.

    Pan Tilt Mechanism

    Note: Before assembling the pan-tilt mechanism, it is recommended that users follow the instructions for the servo pre-alignment in the getting started guide to avoid issues later.

    You will need to build up the Pan-Tilt mechanism. We have instructions over in the Pan-Tilt Mechanism Section of our basic guide - head on over there now as you'll need to have this assembled in order to move forward with this tutorial!

    New!

    Basic Autonomous Kit for Sphero RVR Assembly Guide

    December 12, 2019

    Get your Basic Autonomous Kit for Sphero RVR all hooked up with this guide!
    Assembling the Pan-Tilt Mechanism Hookup Instructions

    GPS Module and Mux

    The GPS board and Mux board are the only two boards that will mount directly to the cover plate. It’s best to put these boards on first as the additional mounting plate obscures part of the board. We'll do this using two of the 1/4 inch screws and 2 nuts for each board.

    Parts, Boards, and RVR Cover Plate

    The antenna (the beige part on the board) will need to be unobstructed and pointed towards the sky, so we'll mount it off to the side and near the front of the cover plate on the inner set of slide holes. The Qwiic cable that runs from the Servo pHAT to the GPS will use the outer set of holes later. If you have the means, putting the GPS board up higher always helps, but be sure not to obscure the pan-tilt camera rig.

    GPS Board mounted on RVR Cover Plate

    The Mux board will mount to the two screw holes in the middle of the RVR Cover Plate. it's important that the "Main" Connector is facing away from the labeled connector port on the RVR Cover Plate (see photo below).

    Mux board mounted on the RVR Cover Plate along with the GPS board

    Once the Mux board is in place, we'll plug in the 50mm Qwiic cables (these might be 2x 100mm cables and 1 50mm cable in your kit) into the Mux board. We'll want one cable running from rear-facing Qwiic connector on the GPS board to the "Main" Qwiic connector on the Mux board. Then we'll plug one cable into connector 3 and a separate one into connector 4 on the Mux board (where you'll use the 2 100mm cables if you have them). We'll plug these into the Time of Flight sensors later in the tutorial. It's important to use connectors 3 and 4 (3 for the front facing Time of Flight sensor and 4 for the rear) as this corresponds to code in the example. If you want to change which connectors you're using, you'll have to change some parts of the code.

    50mm Qwiic cables plugged into the Mux board

    Raspberry Pi Zero

    For the advanced kit, all four mounting points on the Pi Zero W will be used. Due to the through hole pins soldered to the Pi Zero W, you need to add a set of nuts between the board and the mounting plate. For this we'll use (4) 1/2 inch screws and (8) 4-40 nuts.

    Raspberry Pi Zero with Screws and 4-40 Nuts

    When complete, the Raspberry Pi Zero should look like this:

    Raspberry Pi Zero with 4-40 Standoff Nuts

    Do not mount the Raspberry Pi Zero yet, that will come at a later step.

    Mounting Plate and Time of Flight Sensor Brackets

    If you have not already, peel the protective layer off of the front and back of the acrylic plate.

    peeling the protective layer off the plate

    The metal standoffs attach to the mounting plate with the 4-40 nuts. The threaded end of the standoffs will be facing up. Take extra care in tightening the nuts as you can crack the plate if you over-tighten them.

    The time of flight sensors will need to be facing forward and backwards unobstructed. 4 right-angle mounting brackets have been included so the sensors can be mounted in the proper position on the mounting plate. The sensors can be added later, but it’s best to get these on the board before the pan-tilt rig is mounted. They're fastened to the mounting plate with a 1/4" screws and a 4-40 nut (for each bracket).

    Standoffs and Brackets affixed to mounting plate

    Note that the right-angle brackets have one threaded and one un-threaded hole. The threaded holes are smaller than the un-threaded holes, and if you look closely, you'll see the threads in the smaller holes.

    Right-angle brackets

    It’s important that the threaded holes are perpendicular to the plate, those will be the holes the screws that hold the sensor board in place use.

    Mounting the Servo Horn

    While the pan-tilt will be facing up, the servo horn (which the servo will be affixed to) is mounted on the bottom of the plate.

    Line up the small holes on the plate with the small holes in the servo horn the same. Use the small, self-tapping screws to mount it in place from the top of the mounting plate.

    Fastening servo horn to the mounting plate

    Two of the small self-tapping screws will suffice, but if desired you can use all four.

    Adding the Pan/Tilt Camera and Raspberry Pi Zero

    Once the horn is mounted in place, you can use the larger self-tapping screws to mount the pan-tilt rig. It’s important that the rig is mounted so that the middle of the servo travel faces forward. This will take some trial and error, but you want the servo to be able to move an equal amount in either direction when facing directly forward (it’s okay to move the servo when it isn’t powered, just don’t force it).

    Pan-tilt mechanism mounted to mounting plate

    Add the Pi Zero W (with the spacer nuts installed) to the mounting plate with another 4 of the 4-40 nuts. For the best access to all the connectors on the Pi Zero, make sure the USB and HDMI Connectors are facing the back of the plate and the pins are facing the pan-tilt rig.

    Raspberry Pi Zero mounted to mouting plate

    Attaching the Raspberry Pi Zero Camera Cable

    You'll need to mount the Raspberry Pi Camera to the pan-tilt mechanism using the included square of double sided tape. However, I recommend you plug in the camera to the ribbon cable before securing the camera to the tape square.

    To connect the ribbon cable, you'll need to carefully slide the flexible ribbon cable connector's locking tab out. The locking tab slides out parallel to the board so you'll need to push each side of the tab with your fingernails. The image below highlights where you would need to place your fingernails to slide the tab out.

    Highlighted camera connector tabs

    Once the locking tab is out, you can insert the camera connector into the slot. Face the camera's exposed contacts toward the PCB in order to make a connection with the connector's pins. Then insert the cable until it is firmly into the connector. Care must be taken to ensure that the ribbon cable does not have any sharp bends when installing the camera.

    Inserting the camera connector ribbon into the camera connector slot

    When ready, carefully slide the tab back into the locking position using your fingernails.

    Gently push the locking mechanism back into place

    Now you can mount the Raspberry Pi Camera to the pan-tilt mechanism. Make sure the correct side is facing up. Once mounted, it should look something like what we see here:

    mounting camera to RVR pan tilt mechanism

    You'll also need to connect the camera ribbon cable to the Pi Zero W. The locking mechanism for the cable is exactly the same as you saw above. Make sure the pads point upward as you see here:

    Raspberry Pi Zero camera cable plugged into camera and pi

    Connecting the Servo pHAT and Servos

    The Servo pHAT is the interface for both the pan-tilt rig and the Qwiic sensors. The pHAT plugs in so that it's stacked directly above the Pi Zero.

    Servo pHAT plugged into Raspberry Pi Zero GPIO header

    Click the image for a closer look.

    The servo cables for the pan-tilt rig will run underneath the mounting plate, under the board and pop out on the opposite side. The bottom servo plugs into ROW 0 and the top servo into ROW 1.

    Highlighted Row 0 and Row 1

    The brown wires should be on the pins closest to GPS board. See the image below.

    Servo cables from pan-tilt mechanism plugged in

    Click the image for a closer look.

    The Qwiic cable that connects the GPS Board to the Servo pHAT through the time of flight sensor becomes obscured by the cover plate. It’s best to plug in the 50mm Qwiic cable to the GPS Board Qwiic connector facing the center of the cover plate at this point (don't plug it into the time of flight sensor quite yet).

    Time of Flight Sensors

    Next, we'll mount the time of flight sensors to the mounting plate. The holes from the metal bracket should line up with the holes on the top of the board as to not interfere with the pan-tilt mechanism. It should look like this:

    Time of flight sensor mounted to metal mounting brackets on mounting plate

    Affixing the Mounting Plate to the RVR and Connecting the Remaining Qwiic Cables

    Take four of the remaining 1/4 inch screws and fasten the mounting plate to the cover plate of the RVR. The holes should lineup like this from below the cover plate:

    Bottom of the RVR Cover Plate with the Mounting Plate Affixed

    Again, be mindful with how tight you make the screws so as to not crack the acrylic plates.

    With all the boards in place, we can plug in the remaining boards to the Qwiic bus. The two 50mm Qwiic cables connected to connectors 3 and 4 on the Mux board will plug into the front and rear facing Time of Flights sensors (respectively).

    The remaining unplugged Qwiic connectors sticking out from under the mounting plate

    The 50mm Qwiic Cables plugged into the Time of Flight Sensors

    The rear Time of Flight sensor plugged into connector 4 on the Mux board

    Finally, we'll plug the GPS board into the Servo pHAT. Take the 200mm Qwiic cable and plug it into the Qwiic connector on the Servo pHAT. Then, we'll run the cable through the slot in the mouting plate, then down through the slot directly underneath it in the RVR Cover Plate.

    200mm Qwiic cable plugged into the Servo pHAT and run down through the slots into to below the RVR Cover Plate

    On your build, the camera cable will be plugged in, we removed it for this photo to give you a better view of the Qwiic cable plugged in

    Next, we'll run the cable back up through the outside slot next to the GPS board mentioned in the first steps. Plug the cable into the Qwiic connector on the GPS board facing forward.

    200mm Qwiic Cable plugged into the GPS board

    We'll take any slack from the 200mm cable and pull it gently under the RVR Cover Plate giving the system a cleaner look from the visible side.

    Bottom of the RVR Cover Plate showing the 200mm Qwiic cable running underneath

    Congratulations! You've built the entire system. Now it's time to connect it to the RVR. Gently clip the RVR Cover Plate into place.

    RVR Cover Plate with the system built on top

    Plugging the System into the RVR

    In the final step we'll then connect the 4 pin Ribbon Cable from the four pin connector on the Servo pHAT to the UART Connector on the RVR.

    To keep the UART cable from obscuring the view for the pan-tilt camera, I run it under the mounting plate. Refer to the images below - feel free to click on an image to see it more closely!


    Cable outside the mounting plateCable run under the mounting plate

    Congratulations! You've completed the kit and are ready to start coding!

    Troubleshooting

    Resources and Going Further

    So you've got this amazing looking robot. Now what? Time to program it!

    Head on over to the Getting Started with the Autonomous Kit for the Sphero RVR Tutorial to get coding.

    New!

    Getting Started with the Autonomous Kit for the Sphero RVR

    December 13, 2019

    Want to get started in robotics? Look no further than the SparkFun autonomous kit for the Sphero RVR! Whether you purchased the Basic or Advanced kit, this tutorial will get you rolling...

    Need more information on the components included in this kit? We've got it!

    Need more inspiration? Check out some of these other great SparkFun tutorials!

    Easy Driver Hook-up Guide

    Get started using the SparkFun Easy Driver for those project that need a little motion.

    Building a Safe Cracking Robot

    How to crack an unknown safe in under an hour.

    SparkFun Inventor's Kit Experiment Guide - v4.0

    The SparkFun Inventor's Kit (SIK) Experiment Guide contains all of the information needed to build all five projects, encompassing 16 circuits, in the latest version of the kit, v4.0a.

    Pi Servo pHAT (v2) Hookup Guide

    This hookup guide will get you started with connecting and using the Pi Servo pHAT on a Raspberry Pi.

    learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

    Basic Autonomous Kit for Sphero RVR Assembly Guide

    $
    0
    0

    Basic Autonomous Kit for Sphero RVR Assembly Guide a learn.sparkfun.com tutorial

    Available online at: http://sfe.io/t1033

    Introduction

    The SparkFun Basic Autonomous Kit for Sphero RVR is an expansion set of sensors to the Sphero RVR platform and is a great way to start driving the Sphero RVR, either remotely or autonomously. The pan-tilt camera provides an excellent base for a video streaming interface while the GPS module provides accurate data for navigation. The Raspberry Pi Zero runs your programming and passes the information to the RVR. Setup is fairly simple but there are a few confusing spots. This tutorial will go over how to properly assemble the kit on the mounting plate provided with the RVR. While we feel it's the best way to set this up, it's not necessarily the only way, so feel free to experiment with different configurations.

    SparkFun Basic Autonomous Kit for Sphero RVR

    SparkFun Basic Autonomous Kit for Sphero RVR

    KIT-15302
    $119.95

    Required Materials

    To follow along with this tutorial, you will really only need a phillips-head screwdriver. We have quite a few to choose from - but our Pocket Screwdriver Set is a great option.

    Electric Hobby Screwdriver Set

    Electric Hobby Screwdriver Set

    TOL-15548
    $39.95
    Pocket Screwdriver Set

    Pocket Screwdriver Set

    TOL-12891
    $3.95
    5
    Tool Kit - Screwdriver and Bit Set

    Tool Kit - Screwdriver and Bit Set

    TOL-10865
    $9.95
    5
    iFixit Essential Electronics Toolkit

    iFixit Essential Electronics Toolkit

    TOL-15256
    $29.99

    Before We Begin

    If you haven't already, start charging the RVR battery. It takes a while to charge, so now would be a good time to get it going.

    Pan Tilt Mechanism

    Note: Before assembling the pan-tilt mechanism, it is recommended that users follow the instructions for the servo pre-alignment in the getting started guide to avoid issues later.

    Assembling the pan-tilt rig is by far the most involved part of this tutorial. Take your time and read the instructions carefully. Be mindful of the materials you are working with as well - using too much torque or force when tightening screws or fitting parts together can result in broken parts. On a final note, take extra care to make sure the servos are aligned correctly when mounting them.

    Here are the parts of the pan-tilt rig that come in this kit. You won't be needing the servo horns that come packaged with the servo motors, just the ones that come packaged separately. You will also not need the base plate that comes with the pan-tilt framework package.

    Pan-Tilt mechanism parts

    Click the image for a closer look.

    First, identify the larger self-tapping screws. These will be used for assembling the bottom part of the mechanism or the "Pan" part.

    Self-tapping Screws

    Find the Pan Brackets - these are the two brackets that sandwich together. Place one of the servos in the center and connect the two brackets. Take note of the orientation of the servo in the brackets below as it's important.

    Brackets around Servo

    Here are the brackets together. Try to make sure the servo is centered.

    Brackets fitted together around servo

    Take the larger self-tapping screws and affix the two brackets together like in the image below. Take extra care not to over-torque the screws and damage the plastic.

    Side view of bracket with screw

    You'll now need the single arm servo horn with 5 holes, as shown in the image below. If, for some reason, the single arm servo with 5 holes was not included in the kit, you have two options. You can either contact Customer Service to have them send you a part, or you can modify one of the 6-hole servo horns that were packaged separately. If you are shortening the 6 hole horn, start by clipping off one hole and checking to see if it fits the mold on the tilt bracket. Be careful when clipping and make sure that you do not clip off too much of the horn.

    5 hole single-arm horn on the bracket

    Install the single arm servo horn as shown below. You'll need two of the small self-tapping screws to affix it to the mechanism.

    Installation of single-arm horn

    Next, you'll need the second servo motor and the Tilt Bracket.

    Tilt bracket with servo next to it

    The image below shows the relative orientation of these two pieces:

    Servo installed on tilt bracket

    Now, find the longest machine screws in the bag, as shown below. You may find that there are more of these than you need.

    Machine screws

    Thread these screws through the stand off wings on the servo motor and into the last piece of the mechanism. You can use nuts for these if you like, but I've found it to be unnecessary as they thread into the mechanism quite snugly without the nut.

    Screws affixing servo to tilt bracket

    Now connect the two major pieces of the assembly together. The image below shows the orientation of these two parts. You may need to assemble and disassemble these two parts a couple of times to find the right rotational position of the servo motor so that the tilting portion has its full range of motion. Do this by connecting the two parts and carefully turning the "Tilt" servo back and forth until it's able to get the most unobstructed range while the mid-point of this range falls when the two servos are perpendicular to each other.

    Pan and tilt mechanisms lined up next to each other

    Here's an image of what it should look like with the two mechanisms attached.

    Pan and tilt mechanisms attached

    Sometimes the pan and tilt parts won't line up evenly. if this is the case, add a nut (provided in the bag) between the servo and the plastic part of the tilt mechanism as shown below.

    Standoff screw between the servo and bracket for the tilt mechanism

    Take the final screw that you identified above as a horn attaching screw and use it to secure the horn to the servo motor. You do NOT need much torque here - be very gentle!

    Affixing the pan bracket to the tilt bracket

    Congratulations! You've finished the most difficult part of this build. The rest should be a breeze! Put the pan-tilt mechanism to the side, we'll connect it to the cover plate of the RVR at a later time in the build.

    Standoffs and Mounting for the Pi Zero

    The Pi Zero W mounts to the cover plate with two 4-40 nuts. It uses two of the holes made for the full Raspberry Pi footprint.

    Raspberry Pi Zero and mounting hardware

    This keeps the camera connector within reach of the pan-tilt rig, yet not in a position to tangle itself.

    First, we'll affix the 1/2 inch screws to the Raspberry Pi Zero with two 4-40 nuts. This will provide a small standoff from the RVR cover plate which allows room for the pins on the bottom side of the Raspberry Pi Zero.

    Raspberry Pi Zero with standoff nuts

    From there, we'll affix the Pi Zero to the RVR cover plate with a second set of nuts.

    Raspberry Pi Zero mounted on cover plate for the RVR

    Mounting the GPS Board

    The GPS Qwiic board mounts next to the Pi Zero W. For the Qwiic cable to work, the Qwiic connectors need to be facing front and back in relation to the RVR. We'll use 2 of the 1/4 inch screws and 2 of the 4-40 nuts.

    GPS board mounted to the cover plate along with the Raspberry Pi Zero

    Mounting Pan - Tilt Camera to the Cover Plate

    The pan-tilt rig will mount to the forward-most servo footprint on the cover plate.

    Servo footprint on RVR cover plate

    The horn goes under the cover plate. Use two of the self-tapping screws included with the horn to mount the horn to the plate from the top (see pictures below) using the holes that line up.

    Servo horn positioning

    Mounting the horn to the bottom of the plate using screws

    It’s important that the rig is mounted so that the middle of the servo travel faces forward. This will take some trial and error, but you want the servo to be able to move an equal amount in either direction when facing directly forward (it’s okay to move the servo when it isn’t powered, just don’t force it).

    Fully affixed horn as shown from the bottom of the cover plate

    When mounted, it should look similar to this.

    Pan-tilt rig mounted to RVR cover plate

    Plugging in the pHAT and Cables

    The Servo pHAT is the interface for both the pan-tilt rig and the Qwiic sensors. The pHAT plugs in so it’s stacked directly above the Pi Zero.

    Servo pHAT plugged into the GPIO header of the Raspberry Pi Zero

    The Qwiic cable that connects the GPS Board to the Servo HAT runs underneath the cover plate as shown below. It’s best to plug this in at this step as the pan-tilt cables will impede it later.

    GPS module plugged into the Servo pHAT with a Qwiic cable

    The servo cables for the pan-tilt rig will run underneath the mounting plate, under the board and pop out on the opposite side. The bottom servo plugs into ROW 0 and the top servo into ROW 1.

    Row 0 and Row 1 highlighted

    The brown wires should be on the pins closest to GPS board. See the image below:

    Pan-tilt servos plugged into the Servo pHAT

    Click the image for a closer look.

    You can also run these cables underneath the cover plate but be sure it won't impede the movement of the pan-tilt mechanism.

    Plugging in the Camera

    You'll need to mount the Raspberry Pi Camera to the pan-tilt mechanism using the included square of double sided tape. However, I recommend you plug in the camera to the ribbon cable before securing the camera to the tape square.

    To connect the ribbon cable, you'll need to carefully slide the flexible ribbon cable connector's locking tab out. The locking tab slides out parallel to the board so you'll need to push each side of the tab with your fingernails. The image below highlights where you would need to place your fingernails to slide the tab out.

    Highlighted camera connector tabs

    Once the locking tab is out, you can insert the camera connector into the slot. Face the camera's exposed contacts toward the PCB in order to make a connection with the connector's pins. Then insert the cable until it is firmly into the connector. Care must be taken to ensure that the ribbon cable does not have any sharp bends when installing the camera.

    Inserting the camera connector ribbon into the camera connector slot

    When ready, carefully slide the tab back into the locking position using your fingernails.

    Gently push the locking mechanism back into place

    Now you can mount the Raspberry Pi Camera to the pan-tilt mechanism. Make sure the correct side is facing up. Once mounted, it should look something like what we see here:

    Mounting the Raspberry Pi Camera onto the Pan-tilt mechanism

    You'll also need to connect the camera ribbon cable to the Pi Zero W. The locking mechanism for the cable is exactly the same as the one on the camera breakout. Again, make sure the contacts of the ribbon are faced correctly. This part can be tricky - take your time and make sure there are no sharp bends in the cable.

    Camera cable plugged into the Camera and Raspberry Pi Zero

    Plugging the System into the RVR

    You've built the entire system! Now it's time to connect it to the RVR. Gently clip the RVR Cover Plate into place. We'll then connect the 4 pin Ribbon Cable from the four pin connector on the Servo pHAT to the UART Connector on the RVR.

    4 pin cable plugged into the RVR UART connector and the Servo pHAT

    Congratulations! You've completed the kit and are ready to start coding!

    Troubleshooting

    Resources and Going Further

    So you've got this amazing looking robot. Now what? Time to program it! Head on over to the Getting Started with the Autonomous Kit for the Sphero RVR Tutorial to get coding.

    New!

    Getting Started with the Autonomous Kit for the Sphero RVR

    December 13, 2019

    Want to get started in robotics? Look no further than the SparkFun autonomous kit for the Sphero RVR! Whether you purchased the Basic or Advanced kit, this tutorial will get you rolling...

    Need more information on the components included in this kit? We've got it!

    Need more inspiration? Check out some of these other great SparkFun tutorials!

    Experiment Guide for RedBot with Shadow Chassis

    This Experiment Guide offers nine experiments to get you started with the SparkFun RedBot. This guide is designed for those who are familiar with our SparkFun Inventor's Kit and want to take their robotics knowledge to the next level.

    SparkFun Line Follower Array Hookup Guide

    Learn how to connect the RedBot Line-Following Sensor Bar to an Arduino-type microcontroller. Use the example sketches to read data from the bar, and try out a simple line-following algorithm.

    Wireless Motor Driver Shield Hookup Guide

    Get started with the SparkFun Wireless Motor Driver Shield!

    Assembly Guide for SparkFun JetBot AI Kit

    Assembly Guide for the SparkFun JetBot AI Kit. This tutorial includes photos & comments to assemble the two-layer chassis & additional components unique to the JetBot kit.

    learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

    SparkFun GPS NEO-M9N Hookup Guide

    $
    0
    0

    SparkFun GPS NEO-M9N Hookup Guide a learn.sparkfun.com tutorial

    Available online at: http://sfe.io/t1102

    Introduction

    The SparkFun GPS NEO-M9N is the next iteration of u-blox's GPS offerings! We've developed two flavors of the board: one with a small chip antenna and another with a u.FL connector so that you can select an antenna of your choosing.

    SparkFun GPS Breakout - NEO-M9N, Chip Antenna (Qwiic)

    SparkFun GPS Breakout - NEO-M9N, Chip Antenna (Qwiic)

    GPS-15733
    $69.95
    SparkFun GPS Breakout - NEO-M9N, U.FL (Qwiic)

    SparkFun GPS Breakout - NEO-M9N, U.FL (Qwiic)

    GPS-15712
    $64.95

    Required Materials

    To follow along with this tutorial, you will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary.

    SparkFun RedBoard Qwiic

    SparkFun RedBoard Qwiic

    DEV-15123
    $19.95
    4
    Qwiic Cable - 100mm

    Qwiic Cable - 100mm

    PRT-14427
    $1.50
    USB micro-B Cable - 6 Foot

    USB micro-B Cable - 6 Foot

    CAB-10215
    $4.95
    12

    Additional GPS Antenna Options

    Below are some other GPS Antenna options. Some of the options below have an SMA connector, so make sure to get the u.FL to SMA cable if you decide to use those. Link for that is below in the GPS accessories. If you want to try different chip antennas, then try the GNSS Antenna Evalutation Board listed below and make sure to get the u.FL to u.FL connector in the accessories.

    GPS/GNSS Magnetic Mount Antenna - 3m (SMA)

    GPS/GNSS Magnetic Mount Antenna - 3m (SMA)

    GPS-14986
    $12.95
    1
    GPS/GNSS Embedded Antenna - 1m (SMA)

    GPS/GNSS Embedded Antenna - 1m (SMA)

    GPS-14987
    $59.95
    SparkFun GNSS Chip Antenna Evaluation Board

    SparkFun GNSS Chip Antenna Evaluation Board

    GPS-15247
    $24.95
    1
    GPS Embedded Antenna SMA

    GPS Embedded Antenna SMA

    GPS-00177
    $11.95

    GPS Antenna Accessories

    Interface Cable SMA to U.FL

    Interface Cable SMA to U.FL

    WRL-09145
    $4.95
    3
    GPS Antenna Ground Plate

    GPS Antenna Ground Plate

    GPS-15004
    $4.95
    U.FL to U.FL Mini Coax Cable - 200mm

    U.FL to U.FL Mini Coax Cable - 200mm

    WRL-15114
    $1.95

    Other Qwiic Cable Accessories

    SparkFun Qwiic Cable Kit

    SparkFun Qwiic Cable Kit

    KIT-15081
    $7.95
    1
    Qwiic Cable - 100mm

    Qwiic Cable - 100mm

    PRT-14427
    $1.50
    Qwiic Cable - 200mm

    Qwiic Cable - 200mm

    PRT-14428
    $1.50
    Qwiic Cable - 50mm

    Qwiic Cable - 50mm

    PRT-14426
    $0.95

    Suggested Reading

    If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

    Qwiic Connect System
    Qwiic Connect System

    We would also recommend taking a look at the following tutorials if you aren't familiar with them.

    GPS Basics

    The Global Positioning System (GPS) is an engineering marvel that we all have access to for a relatively low cost and no subscription fee. With the correct hardware and minimal effort, you can determine your position and time almost anywhere on the globe.

    Serial Peripheral Interface (SPI)

    SPI is commonly used to connect microcontrollers to peripherals such as sensors, shift registers, and SD cards.

    I2C

    An introduction to I2C, one of the main embedded communications protocols in use today.

    How to Work with Jumper Pads and PCB Traces

    Handling PCB jumper pads and traces is an essential skill. Learn how to cut a PCB trace, add a solder jumper between pads to reroute connections, and repair a trace with the green wire method if a trace is damaged.

    Getting Started with U-Center for u-blox

    Learn the tips and tricks to use the u-blox software tool to configure your GPS receiver.

    Three Quick Tips About Using U.FL

    Quick tips regarding how to connect, protect, and disconnect U.FL connectors.

    Hardware Overview

    Power

    Power for this board is 3.3V and we have provided multiple power options. This first and most obvious is the USB-C connector. Secondly, are the Qwiic Connectors on the top and bottom of the board. Thirdly, there is a 5V pin on the PTH header along the side of the board that is regulated down to 3.3V. Make sure that power your provide to this pin does not exceed 6 volts. Finally, just below the 5V pin is a 3.3V pin that should only be provided a clean 3.3V power signal.

    Power Pins

    Battery

    The small metal disk in the upper left corner is a small lithium battery. This battery does not provide power to the IC like the 3.3V system does, but to relevant systems inside the IC that allow for a quick reconnection to satellites. The time to first fix will about ~29 seconds, but after it has a lock, that battery will allow for a two second time to first fix. This is known as a hot start and lasts for four hours after the board is powered down. The battery provides over a years worth of power to the backup system and charges slowly when the board is powered. To charge it to full, leave your module plugged in for 48 hours.

    Battery for Hot Start

    LEDs

    There's is a red power LED just to the left of the bottom Qwiic connector and near the board's edge to indicate that the board is powered. There is another LED just above the power LED labeled PPS that is connected to the Pulse Per Second line. When connected to a satellite, this line generates a pulse that is synchronized with a GPS or UTC time grid. By default, you'll see one pulse a second.

    Status LEDs

    Jumpers

    There are four jumpers on the underside of the product, each labeled with its function. At the upper right of the picture is a three way jumper labeled I²C that connects two pull-up resistors to the I2C data lines. If you have many devices on your I2C data lines, then you may consider cutting these. On the left side of the board is a jumper labeled PWR. If you cut this trace it will disconnect the Power LED. Just below is the PPS jumper that when cut disconnects the PPS LED. Finally, there's a jumper labeled SPI which enables the SPI data bus thus disabling the UART functions on those lines. For more information, check out our tutorial on working with jumper pads and PCB traces.

    Jumpers on the Back

    Chip Antenna or U.FL Connector

    The SparkFun GPS NEO-M9N with Chip Antenna has a GNSS antenna near its left Qwiic connector while its cousin has a U.FL connector in which you can connect a patch antenna.

    Power In Top SidePower In Bottom Side
    Chip AntennaU.FL

    Qwiic and I2C

    There are two pins labeled SDA and SCL which indicates the I2C data lines. Similarly, you can use either of the Qwiic connectors to provide power and utilize I2C. The Qwiic ecosystem is made for fast prototyping by removing the need for soldering. All you need to do is plug a Qwiic cable into the Qwiic connector and voila!

    I2C Pins and Qwiic connector

    SPI

    There are four pins on the right most header that are labeled with their corresponding SPI functionality. As mentioned in the jumpers section, you'll need to close the SPI jumper on the underside to enable SPI.

    SPI Pins

    UART

    There are two pins on the right most header labeled for their UART functionality.

    UART Pins

    Broken Out Pins

    There are four other pins broken out: Pulse per second (PPS), Reset (RST), Safeboot (SAFE), and finally the interrupt pin (INT). The first pin PPS, outputs pulse trains synchronized with the GPS or UTC time grid. The signal defaults to once per second but is configurable over a wide range. Read the u-blox Receiver Protocol Specification in the Resources and Going Further tab for more information. The reset pin resets the chip. The next pin, SAFE is used to start up the IC in safe boot mode, this could be useful if you somehow manage to corrupt the module's Flash memory. The final pin INT can be used to wake the chip from power save mode.

    Additional Pins Broken Out

    Board Dimensions

    Overall, the boards are 1.30"x1.60". The location of a majority of the components are the same with the exception of the SMD chip antenna and the u.FL connector.

    Board Dimension for Chip Antenna VersionBoard Dimension for u.FL Version
    Chip Antenna Versionu.FL Version

    Click on image for a closer view.

    GPS Capabilities

    The SparkFun NEO-M9N is able to connect to up to four different GNSS constellations at a time making it very accurate for its size. Below are the listed capabilities of the GPS unit when connecting to multiple GNSS constellations and when connecting to a single constellation.

    ConstellationsGPS+GLO+GAL+BDSGPS+GLONASS+GALGPS+GLOGPS+BDSGPS+GAL
    Horizontal Position Accuracy2m2m2m2m2m
    Max Navigation Update RatePVT25Hz25Hz25Hz25Hz25Hz
    Time-To-First-FixCold Start24s25s26s28s29s
    Hot Start2s2s2s2s2s
    SensitivityTracking and Navigation-167dBm-167dBm-167dBm-1667dBm-166dBm
    Reacquisition-160dBm-160dBm-160dBm-160dBm-160dBm
    Cold Start-148dBm-148dBm-148dBm-148dBm-148dBm
    Hot Start-159dBm-159dBm-159dBm-159dBm-159dBm
    Velocity Accuracy0.05m/s0.05m/s0.05m/s0.05m/s0.05m/s
    Heading Accuracy0.3deg0.3deg0.3deg0.3deg0.3deg


    When using a single GNSS constellation:

    ConstellationGPSGLONASSBEIDOUGalileo
    Horizontal Position Accuracy2m4m3m3m
    Max Navigation Update RatePVT25Hz25Hz25Hz25Hz
    Time-To-First-FixCold Start29s27s32s42s
    Hot Start2s2s2s2s
    SensitivityTracking and Navigation-166dBm-164dBm-160dBm-159dBm
    Reacquisition-160dBm-155dBm-157dBm-154dBm
    Cold Start-148dBm-145dBm-145dBm-140dBm
    Hot Start-159dBm-156dBm-159dBm-154dBm
    Velocity Accuracy0.05m/s0.05m/s0.05m/s0.05m/s
    Heading Accuracy0.3deg0.3deg0.3deg0.3deg

    Hardware Assembly

    For this example, I used a Qwiic capable RedBoard and associated USB cable. connecting the boards with Qwiic cable, the assembly is very simple. Plug a Qwiic cable between the RedBoard and the SparkFun NEO-M9N with chip antenna and that's it! Just as easily I could have used the version with the U.FL connector and plugged in one of our patch antennas to the GPS board. If you need tips on plugging in the U.FL connector, then check out our U.FL tutorial. If you're going to be soldering to the through hole pins for I2C functionality, then just attach lines to power, ground, and the I2C data lines to a microcontroller of your choice.

    GPS wih Antenna Connected to RedBoard Qwiiv

    SparkFun U-Blox Library

    Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

    All of our u-blox based GPS boards share the same library: these two boards, their predeccesors and the higher precisionu-blox cousins. The SparkFun U-blox Arduino library can be downloaded with the Arduino library manager by searching 'SparkFun Ublox' or you can grab the zip here from the GitHub repository:

    There are 13 example sketches provided to get you up and receiving messages from space. We'll go over one of the examples in this tutorial.

    Example Code

    We're just going to look at example two (i.e. "Example2_NMEAParsing.ino") which in my opinion, makes it clear the awesomeness of these GPS receivers. That is to say, talking to satellites and finding out where in the world you are.

    language:c
    #include <Wire.h> //Needed for I2C to GPS
    
    #include "SparkFun_Ublox_Arduino_Library.h" //Click here to get the library: http://librarymanager/All#SparkFun_Ublox_GPS
    SFE_UBLOX_GPS myGPS;
    
    void setup()
    {
      Serial.begin(115200);
      Serial.println("SparkFun Ublox Example");
    
      Wire.begin();
    
      if (myGPS.begin() == false)
      {
        Serial.println(F("Ublox GPS not detected at default I2C address. Please check wiring. Freezing."));
        while (1);
      }
    
      //This will pipe all NMEA sentences to the serial port so we can see them
      myGPS.setNMEAOutputPort(Serial);
    }
    
    void loop()
    {
      myGPS.checkUblox(); //See if new data is available. Process bytes as they come in.
    
      delay(250); //Don't pound too hard on the I2C bus
    }
    

    When you upload this code you'll have to wait ~29s to get a lock onto any satellites. After that first lock, the backup battery on the board will provide power to some internal systems that will allow for a hot start the next time you turn on the board. The hot start only lasts four hours, but allows you to get a lock within one second. After you get a lock the serial terminal will start listing longitude and latitude coordinates, as seen below. Make sure to set the serial monitor to 115200 baud.

    This image shows a screenshot of the Arduino Serial terminal spitting out latitude and longitude data.

    These are the coordinates for SparkFun HQ

    Resources and Going Further

    Now that you've successfully got your GPS receiver up and running, it's time to incorporate it into your own project! For more information, check out the resources below:

    Are you looking for a GPS receiver with an insane 10mm 3D accuracy, then check out the two other u-Blox based GPS boards by SparkFun (ZED-F9P and NEO-M8P-2) on the left below. Need a smaller more compact GPS unit but don't need as high of a refresh rate, check out the ZOE-M8Q and SAM-M8Q on the right.

    SparkFun GPS-RTK2 Board - ZED-F9P (Qwiic)

    SparkFun GPS-RTK2 Board - ZED-F9P (Qwiic)

    GPS-15136
    $219.95
    12
    SparkFun GPS-RTK Board - NEO-M8P-2 (Qwiic)

    SparkFun GPS-RTK Board - NEO-M8P-2 (Qwiic)

    GPS-15005
    $199.95
    5
    SparkFun GPS Breakout - ZOE-M8Q (Qwiic)

    SparkFun GPS Breakout - ZOE-M8Q (Qwiic)

    GPS-15193
    $44.95
    2
    SparkFun GPS Breakout - Chip Antenna, SAM-M8Q (Qwiic)

    SparkFun GPS Breakout - Chip Antenna, SAM-M8Q (Qwiic)

    GPS-15210
    $39.95
    2

    Need some inspiration for your next project? Check out some of these related tutorials:

    Copernicus II Hookup Guide

    A guide for how to get started with the Copernicus II GPS module.

    LS20031 5Hz (66 Channel) GPS Receiver Hookup Guide

    In this tutorial, we will solder headers to the surface mount pads of the LS20031 GPS receiver and read the output using an Arduino!

    HX1 APRS Transmitter Hookup Guide

    The HX1 is a low-power amateur radio transmitter that can be used to send data to the Automatic Packet Reporting System (APRS) network.
    New!

    SparkFun GPS NEO-M9N Hookup Guide

    The u-blox NEO-M9N is a powerful GPS units that comes in two flavors: with and without a chip antenna. We will quickly get you set up using the Qwiic ecosystem and Arduino so that you can start reading the output!

    learn.sparkfun.com | CC BY-SA 3.0 | SparkFun Electronics | Niwot, Colorado

    Viewing all 1123 articles
    Browse latest View live


    <script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>