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

Qwiic LED Stick - APA102C Hookup Guide

$
0
0

Qwiic LED Stick - APA102C Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Qwiic LED Stick - APA102C simplifies adding addressable LED control to any I2C project using the SparkFun Qwiic System. The board includes 10 APA102 addressable LEDs controlled by an ATTiny85 on the board to work in tandem with either the SparkFun Qwiic LED Stick Arduino library or Python package..

SparkFun Qwiic LED Stick - APA102C

SparkFun Qwiic LED Stick - APA102C

COM-18354
$9.95

The Qwiic LED Stick was designed with making large chains of them in mind so with a quick software command, you can change the I2C address of the ATTiny85 so you can control up to 100 LEDs (10 Qwiic LED Sticks) on a single bus! Now, having a hundred LEDs in a circuit significantly increases the required current to drive them and regulators on most development boards are limited to a few hundred mA so we've designed the Qwiic LED Stick to adjust the power input so a dedicated power supply can be used to drive the LED Sticks.

In this tutorial we'll cover the hardware present on the Qwiic LED Stick, how to assemble a basic circuit and to top it off we'll take a close look at the SparkFun Qwiic LED Stick Arduino library and Python package as well as a few of the examples included in them.

Required Materials

In order to follow along with this tutorial you'll need a few items along with the Qwiic LED Stick.

First off, the Qwiic LED Stick needs a controller like an Arduino development board or single-board computer (SBC) like a Raspberry Pi to communicate with the board. Click the button below to toggle to recommended Raspberry Pi and Qwiic Pi products.

Below are a few Arduino development boards SparkFun carries that are Qwiic enabled out of the box:
SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

DEV-15795
$19.95
4
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
8
SparkFun RedBoard Artemis

SparkFun RedBoard Artemis

DEV-15444
$19.95
8
SparkFun Qwiic Micro - SAMD21 Development Board

SparkFun Qwiic Micro - SAMD21 Development Board

DEV-15423
$20.95
5
If your preferred microcontroller does not have a Qwiic connector, you can add one using one of the following products:
SparkFun Qwiic Adapter

SparkFun Qwiic Adapter

DEV-14495
$1.50
1
SparkFun Qwiic Shield for Arduino

SparkFun Qwiic Shield for Arduino

DEV-14352
$6.95
6
SparkFun Qwiic Shield for Thing Plus

SparkFun Qwiic Shield for Thing Plus

DEV-16790
$4.25
SparkFun Qwiic Shield for Arduino Nano

SparkFun Qwiic Shield for Arduino Nano

DEV-16789
$4.25
If you would prefer to use the Qwiic LED Stick with Python, control the breakout with a single-board computer like the Raspberry Pi's listed below:
Raspberry Pi 4 Model B (4 GB)

Raspberry Pi 4 Model B (4 GB)

DEV-15447
$55.00
16
Raspberry Pi Zero W (with Headers)

Raspberry Pi Zero W (with Headers)

DEV-15470
$14.00
6
Raspberry Pi Zero W

Raspberry Pi Zero W

DEV-14277
$10.00
42
SparkFun Raspberry Pi 4 Desktop Kit - 2GB

SparkFun Raspberry Pi 4 Desktop Kit - 2GB

KIT-16385
SparkFun offers several options to add Qwiic connectors to single-board computers using the Raspberry Pi's 2x20 header:
SparkFun Qwiic HAT for Raspberry Pi

SparkFun Qwiic HAT for Raspberry Pi

DEV-14459
$6.50
4
SparkFun Servo pHAT for Raspberry Pi

SparkFun Servo pHAT for Raspberry Pi

DEV-15316
$11.95
3
SparkFun Qwiic SHIM for Raspberry Pi

SparkFun Qwiic SHIM for Raspberry Pi

DEV-15794
$0.95
8
SparkFun Qwiic pHAT v2.0 for Raspberry Pi

SparkFun Qwiic pHAT v2.0 for Raspberry Pi

DEV-15945
$6.95
2

Along with a development board or SBC, you'll need at least one Qwiic cable. SparkFun carries a variety of lengths and types of Qwiic cables as seen here:

SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
12
Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 200mm

Qwiic Cable - 200mm

PRT-14428
$1.50
Flexible Qwiic Cable - 100mm

Flexible Qwiic Cable - 100mm

PRT-17259
$1.50

Recommended Tools

If you plan to use multiple Qwiic LED Sticks in your project, a few other tools and hardware are needed to assemble and drive your circuit. You may already have some of the products and tools suggested below so adjust your selections as needed.

As mentioned above, using many Qwiic LED Sticks draws a significant amount of current that your microcontroller may not be able to provide. We recommend using a dedicated power supply for the APA102 LEDs on the LED Stick. Select your power supply based on the estimated total current draw of the LEDs in your circuit. Below are a few options that can work with the APA102 LEDs:

Power Supply - 5V, 4A

Power Supply - 5V, 4A

TOL-15352
$12.95
SparkFun Breadboard Power Supply 5V/3.3V

SparkFun Breadboard Power Supply 5V/3.3V

PRT-00114
$10.95
16
Power Supply - 12V/5V (2A)

Power Supply - 12V/5V (2A)

TOL-15664
$10.95
3
Mean Well LED Switching Power Supply - 5VDC, 5A

Mean Well LED Switching Power Supply - 5VDC, 5A

TOL-14601
$14.95

Along with a dedicated power supply, you may need some tools to solder with. If you need a soldering iron or soldering supplies, take a look at the tools and supplies below:

Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

TOL-14456
$14.95
13
Solder - 1/4lb Spool (0.020") Special Blend

Solder - 1/4lb Spool (0.020") Special Blend

TOL-10242
$29.95
13
Solder Lead Free - 100-gram Spool

Solder Lead Free - 100-gram Spool

TOL-09325
$8.95
7
Weller WLC100 Soldering Station

Weller WLC100 Soldering Station

TOL-14228
$44.95
2

Recommended Reading

In case you are not familiar with the Qwiic System, we recommend reading here for an overview:

Qwiic Connect System

We also recommend taking a look at the following tutorials if you aren't familiar with the concepts covered in them:

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.

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.

Hardware Overview

The Qwiic LED Stick is a fairly straightforward ATTiny85-based Qwiic board that you may be familiar with already. In this section we'll cover the hardware present on the board in detail.

ATTiny85

The brains of the Qwiic LED Stick is one of our favorite microcontrollers, the ATTiny85. This IC comes pre-programmed with custom firmware designed to interact with the Arduino library and Python package we've written to use with this board. The ATTiny85 accepts I2C reads and writes, interprets them and outputs the appropriate strings to control any APA102 LEDs attached to it.

Highlighting the ATTiny85

The default I2C address of the ATTiny85 is 0x23. Adjust the address either through the ADR jumper or via software. Read on for more information regarding changing the address in both manners.

Just like our other Qwiic breakouts using the ATTiny85, users can update or change the firmware using the 2x3 pin header on the back of the board. The firmware can be found in the Hardware GitHub Repository. For tips and tricks on how to re-program an ATTiny IC, check out this tutorial.

APA102C LEDs

The LED Stick includes 10 APA102C LEDs controlled by the aforementioned ATTiny85. APA102C LEDs operate just like most addressable LEDs over a two-wire interface. The board ties that interface to the ATTiny85 and operates both the IC and LEDs at 3.3V logic. For specific information regarding the LEDs, take a look at the APA102C Datasheet.

Highlighting APA102 LEDs

The board includes a dedicated power PTH pin labeled VIN (along with a spare Ground PTH) to power the LEDs directly for longer chains of Qwiic LED Sticks or circuits with an extra LED strip that require more power than a typical microcontroller can provide. Enable this power input by adjusting the VLED jumper. The APA102C LED accepts a supply voltage between 3.0V and 5.5V.

We've also routed the LED control signals out to a dedicated 0.1"-spaced PTH header on the edge of the board in case you would like to add another APA102 LED strip to the end of the LED stick. This PTH header has signal labels as well as silk labels on the bottom of the board for the coordinating wire colors (Red, Blue, Green and Yellow) to make it easy to match the wires for standard APA102 LED strips.

Qwiic and I2C Interface

As the product name suggests, the LED Stick routes the I2C interface on this board to a pair of Qwiic connectors for easy assembly using the Qwiic system. Those who prefer a a traditional soldered connection for the circuit can use the I2C pins routed to a standard 0.1"-spaced PTH header.

Highlighting the Qwiic & I2C Interface

3.3V and GND are also provided via the Qwiic interface to power both the ATTiny85 as well as the APA102C LEDs in the default configuration.

Solder Jumpers

The Qwiic LED Stick has four solder jumpers labeled I2C, VLED, ADR and LED. Let's take a closer look at them and their functionality. If you've never worked with solder jumpers before or would like a refresher, take a look at our How to Work with Jumper Pads and PCB Traces tutorial.

Highlighting the solder jumpers

The I2C jumper pulls the SDA/SCL lines on the ATTiny85 to 3.3V via a pair of 4.7kΩ resistors. Disable these pull up resistors by severing the trace between the three pads. Recommended practice is to only have a single pair of pull up resistors enabled on an I2C bus to avoid communication errors caused by too strong of a parallel resistance. If you are using multiple Qwiic LED Sticks or other I2C devices in a long chain, we recommend disabling all but one of these resistor pairs.

The VLED jumper controls the input voltage for the APA102C LEDs. By default, this two-way jumper ties the APA102C VCC to 3.3V provided either over the Qwiic connector or the labeled PTH pin. For long chains of Qwiic LED Sticks, switch this jumper to the VCC side by severing the trace between the center and 3.3V pad and adding a blob of solder to connect the center pad with the VCC side. Once this is adjusted, connect a separate voltage between 3.0V and 5.5V to the VIN PTH pin to power the circuit. When in the VIN position, the board connects a 4.7µF decoupling capacitor to help smooth out power supplied to the LEDs.

Note: The VLED jumper isolates the voltage input from the 3.3V used to power the ATTiny85. When using the VIN PTH pin to power the LEDs, make sure to provide power to the ATTiny85 either via the Qwiic interface or over the 3.3V PTH pin.

The ADR jumper sets the I2C address of the ATTiny85 via a hardware adjustment and is OPEN by default. While open, the ATTiny85's address is set to 0x23. Closing this jumper adjusts the address to 0x22.

The LED jumper controls the board's power LED by tying the anode to 3.3V via a 1kΩ resistor. The jumper is CLOSED by default. Sever the trace between the two pads to disable the power LED if needed.

Board Dimensions

The Qwiic LED Stick measures 1.00in x 3.60in (25.4mm x 91.44mm) with four mounting holes that fit a 4-40 screw.

Qwiic LED Stick Dimensional Drawing

Hardware Assembly

Assembling a basic Qwiic LED Stick circuit is easy with the Qwiic system so we'll cover that assembly as well as a few things to be aware of when assembling a larger string of Qwiic LED Sticks or when using other APA102Cs on the end of the stick.

Basic Qwiic/I2C Assembly

For a basic Qwiic LED Stick circuit with a board like the SparkFun RedBoard Qwiic Plus all you need to do is plug the two boards together with a Qwiic cable.

Standard Qwiic LED Stick circuit with the SparkFun RedBoard Qwiic

Multiple Qwiic LED Sticks and APA102C Extensions

Users who wish to use multiple Qwiic LED Sticks chained together or even with an external APA102C LED Strip connected to the LED PTH header on the side of the board will need to do some minor soldering assembly as well as adjusting solder jumpers.

First, take into account the max current draw the LED Stick chain will pull. At full power, each APA102C can draw as much as 40mA when set to white (full Red, Green and Blue) at full brightness so we recommend testing the current draw of your LED chain prior to wiring up long chains of LED Sticks (or adding an extra LED strip) to avoid damaging your controller. In our testing, while running all 10 LEDs at full brightness and White color, the strip only pulled ~65mA@3.3V so you should be safe powering a few of these from your microcontroller but note that most Qwiic development boards use a 3.3V/600mA regulator to power devices connected to the Qwiic connector.

For detailed assembly instructions and tips for building APA102 LED circuits, take a look at our APA102 Addressable LED Hookup Guide:

If using a separate power supply to power the LEDs, adjust the VLED jumper to the VIN side and connect a supply voltage between 3.0 to 5.5 to the VIN and GND pins capable of supplying enough current to power the LED chain. After making your power supply connections, plug the Qwiic LED Stick to the controller using a Qwiic cable or the I2C PTH pins.

Now that our Qwiic LED Stick circuit is assembled, let's take a look at the software packages we use to control them over I2C.

Qwiic LED Stick Arduino Library

Note: This library 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.

The SparkFun Qwiic LED Stick Arduino Library makes controlling the LED stick as easy as sending the command setLEDColor() with three RGB values to set the color along with a host of other functions to control the LED Stick. Install the library by searching for "SparkFun Qwiic LED Stick" in the Arduino Library manager. Users who prefer to manually install it can get the library from the GitHub Repository or download the ZIP by clicking the button below:

Library Functions

The list below outlines all the functions available in the Qwiic LED Stick library along with quick descriptions of what they do.

Class

Construct the LED object in the global scope. The examples use LEDStick as the Qwiic LED Stick object.

  • LED LEDStick;

Device Setup and Settings

  • bool begin(uint8_t address, TwoWire &wirePort); - Initialize the LED Stick at a specified address on a chosen port. If left empty, default address will be used and Wire is used.
  • bool isConnected(); - Check if the LED Stick is connected to the port at the specified address.

LED Control

  • bool setLEDColor(uint8_t number, uint8_t red, uint8_t green, uint8_t blue); - Sets the color of the selected LED using RGB values between 0 and 255. If no LED is selected, all LEDs are set to the specified color. For example, to set the fourth LED to yellow the command would be LEDStick.setLEDColor(4, 0, 255, 255);.
  • bool setLEDBrightness(uint8_t number, uint8_t brightness); - Sets the brightness of the selected LED. If no LED is selected, all LEDs are adjusted. Acceptable values are 0 to 31. Setting an LED to 0 will turn it off but saves the stored color value.
  • bool LEDOff(void); - Sets all LEDs in the Qwiic LED Stick to off.
  • bool changeAddress(uint8_t newAddress); - Change the I2C address of the ATTiny85. Enter a valid address. Note once the address is changed, the LED Stick must be initialized with the new address. For example, initialize a Qwiic LED Stick with the address 0x70 using LEDStick.begin(0x70);.
  • bool changeLength(uint8_t newLengths); - Change the number of LEDs in the chain. Used when adding another Qwiic LED Stick or other addressable LED strip to the circuit. Default value is 10. Max value is 100.

Arduino Examples

The Qwiic LED Stick Arduino Library includes eleven examples to get you started with the basics of the board along with some nifty lighting demos. In this section we'll look at a few of the examples and explore how they work.

Before we get into the examples, let's take a closer look at the setup used for all the examples. The code initializes both the serial and wire ports as well as starts communication with the LED Stick over I2C:

language:c
Wire.begin();
Serial.begin(115200);

if (LEDStick.begin() == false){
    Serial.println("Qwiic LED Stick failed to begin. Please check wiring and try again!);
    while(1);
}

You can open the Arduino serial monitor with the baud set to 115200 to view any serial printouts from the code. If the Qwiic LED Stick fails to initialize on the bus at the default address, the code freezes. The two most common causes of this is a bad connection between the device and controller or the Qwiic LED Stick's I2C address does not match the default value.

Example 1 - Blink

This basic example shows how to initialize the LED Stick along with controlling the LEDs on it all at once. Open the example by navigating to File > Examples > SparkFun Qwiic LED Stick Arduino Library > Example01_Blink. After opening the example, select the correct Board (in our case the SparkFun RedBoard) and Port it enumerated on. Next, click upload and barring any errors, you should see all ten LEDs set to the same color (white) and turn on and off every second.

Try adjusting the values in this line to change the color:

language:c
LEDStick.setLEDColor(50, 50, 50);

Example 3 - Single Pixels2

The third creates three arrays to set the Red, Green and Blue values for each LED. In the global class, the code creates an array for Red, Blue and Green and sets arbitrary values for each pixel.

language:c
//           Pixel#     1    2    3    4    5    6    7    8    9   10
byte redArray[10]   = {214,  78, 183, 198,  59, 134,  15, 209, 219, 186}; //r
byte greenArray[10] = { 59, 216, 170,  21, 114,  63, 226,  92, 155, 175}; //g
byte blueArray[10]  = {214, 147,  25, 124, 153, 163, 188,  33, 175, 221}; //b

After setting up the three arrays and initializing the LED Stick, the code sets the pixels to the color values to the corresponding entry in the array.

language:c
LEDStick.setLEDColor(redArray, greenArray, blueArray, 10);

For example, the fourth LED should match the color (pink/magenta) of the RGB values in the fourth entry in the array.

Example 4 - Set Brightness

The fourth example steps through all the valid brightness settings for the setLEDBrightness(); function with each LED set to a different color rainbow color (plus white) so you can get a quick idea of how each color looks at each brightness level.

Just like Example 3, the code creates three arrays for Red, Blue and Green and assigns values for each LED. After initializing the LED Stick, the main loop steps through each brightness value every second and prints out the brightness value over serial:

language:c
for (byte i = 0; i < 32; i++) {
    LEDStick.setLEDBrightness(i);
    Serial.print("Brightness level: ");
    Serial.println(i);
    delay(1000);
}

These examples round out most of the basics of the Qwiic LED Stick Library. The others include a few demos of cool effects you can do with the Qwiic LED Stick along with changing the I2C address and length of LEDs controlled when using a command not pointed at a specific LED pixel. Take a look at them either in the Arduino IDE or the Library GitHub Repository.

Qwiic LED Stick Python Package

Note: This package and the included examples assume you are using the latest version of Python 3. If this is your first time using Python or I2C hardware on a Raspberry Pi, these tutorial can help you get started:

The Qwiic LED Python package is a port of the Arduino library for users who prefer to use this board with a Raspberry Pi. The Python port includes the same eleven examples as the Arduino library to get you started from simply turning on the LEDs to creating some nifty light displays.

The package is hosted on PyPi to make installation quick and painless using simple commands in the command interface. If you prefer to manually install the package, you can find it on the GitHub repository or click the button below to download the ZIP of it:

(*Please be aware this package depends on the Qwiic I2C Driver. You can also check out the repository documentation page, hosted on Read the Docs.)

Qwiic LED Stick Py Installation

Let's go over both installation methods for the Qwiic LED Stick Python package.

Note: Don't forget to double check that the hardware I2C connection is enabled on your Raspberry Pi or other single board computer. The Raspberry Pi tutorials linked in the note above cover how to enable the Pi's I2C bus.

PyPi Installation

Hosting the package on PyPi makes installation simple on systems that support PyPi installation via pip3 (use pip for Python 2). Open a command interface and enter the following commands:

For all users (The user must have sudo privileges) privileges):

language:bash
sudo pip3 install sparkfun-qwiic-led-stick

For the current user:

language:bash
pip3 install sparkfun-qwiic-led-stick

Local Installation

Follow these instructions for a local installation. Make sure to install the setuptools package prior to installing the Qwiic LED Stick package.

Use this command for direct installation at the command line (use python for Python 2):

language:bash
python3 setup.py install

Build a package for use with pip3:

language:
python setup.py sdist

This command builds and places a subdirectory called "dist". Change to the new subdirectory and install the Qwiic LED Stick package using pip3 with these commands (make sure to fill in the correct version number):

language:bash
cd dist
pip3 install sparkfun_qwiic_led_stick-<version>.targ.gz

Qwiic LED Stick Python Package Operation

A complete overview of all the functions included in the Qwiic LED Stick Py is hosted on the ReadtheDocs. You can also take a look at the source code.

Upgrading the Qwiic LED Stick Python Package

In case the package is updated in the future, you may need to upgrade it. Use these commands to upgrade the package:

For all users (The user must have sudo privileges):

language:bash
sudo pip3 install --upgrade sparkfun-qwiic-led-stick

For the current user:

language:bash
pip3 install --upgrade sparkfun-qwiic-led-stick

Python Examples

The Qwiic LED Stick Python package includes eleven examples ranging from basics to get you started with the board to some some nifty demos. In this section we'll take a closer look at a few of the examples and what they do.

Just like in the Arduino library, each example creates the my_stick object and includes a begin statement that initializes the Qwiic LED Stick on the I2C bus and freezes the code if that fails:

language:python
my_stick = qwiic_led_stick.QwiicLEDStick()

if my_stick.begin() == False:
    print("\nThe Qwiic LED Stick isn't connected to the sytsem. Please check your connection", \
        file=sys.stderr)
    return
print("\nLED Stick ready!")

If your code freezes here, double check the I2C bus is enabled on your Pi and your Qwiic LED Stick is connected properly. Adjusting the address either via the ADR jumper or changing it via Example 10 - Change Address requires entering the new address in the begin statement:

language:python
if my_stick.begin(I2C Address Here) == False:

Example 1 - Blink

The first example demonstrates a standard "Blink" for all ten LEDs. After initializing the LED Stick on the bus, the code sets the brightness to ~50% so we don't burn our retinas looking at super-bright white LEDs.

After that, the code sets the color of the LEDs to all white and blinks them on and off every second:

language:python
my_stick.set_all_LED_color(50, 50, 50)
time.sleep(1)
my_stick.LED_off()
time.sleep(1)

Example 3 - Single Pixel 2

This example creates three lists of ten to set the Red, Green and Blue values for each LED on the stick and then uses the set_all_LED_unique_color() function to set the color of each individual LED.

Try playing around with the values in each list to switch the colors of the LEDs:

language:python
red_list = [214, 78, 183, 198, 59, 134, 15, 209, 219, 186]
green_list = [59, 216, 170, 21, 114, 63, 226, 92, 155, 175]
blue_list = [214, 147, 25, 124, 153, 163, 188, 33, 175, 221]

Example 4 - Set Brightness

The last example we'll cover here demonstrates how to set the brightness of the LED Stick. The first example uses the function in its basic form so you may be familiar with it already. This example sets the LEDs to a rainbow and steps through each valid brightness setting to give you a good idea of what each color looks like at each brightness level to figure out what works best for your project.

language:python
for i in range(0, 32):
    my_stick.set_all_LED_brightness(i)

    print("\nBrightness level: " + str(i))
    time.sleep(1)

The other examples demonstrate some neat lighting displays along with demonstrations of how to change the I2C address, adjust the total number of LEDs controlled to add other LED Sticks or LED strips.

Troubleshooting

In this section we'll outline a few troubleshooting tips for common issues you may run into using the Qwiic LED Stick.

Software Tips

Make sure when using multiple Qwiic LED Sticks to set each board to a unique I2C address. Adjust the address either by opening the ADR jumper or using the Address Examples from the Arduino library or Python package.

Also, update to the new number of LEDs in your chain using the Change Length examples in the Arduino library and Python package. Note, the default firmware limits the maximum number of LEDs to 100.

Power Supply Tips

When using many LEDs (either multiple Qwiic LED Sticks or an additional LED strip), make sure to take into account the total current draw of your LED chain. If the total current draw is outside of the limits of your chosen controller's 3.3V regulator capacity (most SparkFun Qwiic boards have a max out of 600mA@3.3V), adjust the VLED jumper to isolate the LEDs from the rest of the circuit and use a separate voltage input via the VIN PTH pin. Connect 3.3V to 5.5V power supply capable of sourcing enough current to drive the APA102 LEDs in your string.

There is no need to add a decoupling capacitor when using an external power supply connected to VIN as the board includes a 4.7µF capacitor parallel to VIN and Ground when the VLED jumper is adjusted to use that pin to power the LEDs.

General Troubleshooting

If you need technical assistance and more information on the Qwiic LED Stick or another SparkFun product that is not working as you expected, we recommend heading on over to the SparkFun Technical Assistance page for some initial troubleshooting.



If you don't find what you need there, the SparkFun Forums are a great place to find and ask for help. If this is your first visit, you'll need to create a Forum Account to search product forums and post questions.

Resources and Going Further

That wraps up this tutorial for the Qwiic LED Stick. For more information on the board, take a look at the following resources:

For some inspiration on an LED project with the Qwiic LED Stick, take a look at these tutorials:

Das Blinken Top Hat

A top hat decked out with LED strips makes for a heck of a wedding gift.

Interactive LED Music Visualizer

Use an Arduino and the SparkFun Sound Detector to create visualizations on Addressable RGB LED strips.

LED Cloud-Connected Cloud

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

LED Crystal Goddess Crown

Follow this tutorial to make your own Crystal Goddess Crown with LEDs!

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.

LumiDrive Hookup Guide

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.

Or check out some of these blog posts for ideas:


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


Machine Learning @ Home Kit Hookup Guide

$
0
0

Machine Learning @ Home Kit Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Machine learning has taken the technology world by storm.

From smart email categorization to make it easier to sift through your inbox, to ML applications that decipher your handwriting and allow you to deposit checks on your mobile phone, to medical diagnosis like detecting cancer. Machine learning is practically ubiquitous in nearly every facet of our lives at this point.

Machine learning itself is a simple idea - ML algorithms use historical data as input to predict new output values. However, the actual practice of machine learning uses complex math and requires quite a bit of computational power, which can seem overwhelming to implement by oneself. But lucky for us, there's no longer a need to build machine learning models from scratch - there are dozens of APIs that have already built out the complex math to run ML models, and we can just use the libraries with our specific parameters.

That's great, it means we have access to all sorts of machine learning models that we can run on our computers. But that doesn't always feel super tangible, just running models on your laptop. What if you wanted to implement machine learning in the real world, in your everyday life? How do you go from building and training a model to deploying to to solve problems in your physical life?

Welcome to the Machine Learning @ Home Kit - this aims to help you bridge the gap between building and training machine learning models, and deploying them in tangible and meaningful ways.

SparkFun Machine Learning @ Home Kit for NVIDIA Jetson Nano

SparkFun Machine Learning @ Home Kit for NVIDIA Jetson Nano

KIT-18157
$114.95

NVIDIA's Jetson Nano has great GPU capabilities, making it ideal for ML applications. This kit brings machine output and interaction into the picture through a number of different SparkFun Qwiic boards for you to turn machine learning into machine working!

The goals of this particular hookup guide is to extend the content from NVIDIA's Getting Started with AI on Jetson Nano course to implement machine learning in practical ways in your own home. It will be "living", meaning it will be periodically iterated upon and additional projects will be added over time. We will go over how to move away from Jupyter labs and actually deploy applications, as well as how to strategically run applications once deployed. For example, we'll review how to save on power, by starting programs on boot, or using a motion sensor/button rather than having the program run all the time.

Let's jump right in and take a look at what's included in this kit so we can start building!

Kit Overview

The Machine Learning @ Home Kit includes all of the hardware that you need to take your Nvidia Jetson Nano learning experience to a practical level around your home or office. We decided on leveraging the SparkFun Qwiic ecosystem of development boards to keep wiring to a minimum and get you up and running with hardware without a rats nest of wires, soldering or getting things crossed. In this section we will review the different Qwiic boards and components of the kit, but we do want to take a moment and cover what other requirements there are in terms of hardware.

Prerequisite Hardware

The Machine Learning @ Home Kit doesn’t include the Nvidia Jetson Nano or any of the required accessories to get started with it.

SparkFun DLI Kit (without Jetson Nano)

SparkFun DLI Kit (without Jetson Nano)

KIT-16389
$78.95
1

The best first step to get everything you need in one go is to pickup the DLI Course Kit which includes all of the accessories you need including an Nvidia Jetson Nano if you don’t already have one, a power supply and cable (USB for the 2GB or 5V 4A Barrel for the 4GB), microSD card for the OS and a USB webcam. With the DLI Course kit in hand we highly recommend taking the free online course from the Deep Learning Institute to get you acquainted with the Nano itself, get all of the software setup and ready to go and get some experience with Jupyter Labs under your belt.

Kit Contents

Now, back to the Machine Learning @ Home Kit! The kit includes a bunch of hardware that is designed for you to move your machine learning projects out of Jupyter Labs and the feedback off of your monitor and into the physical world as a response. Let’s jump in and take a look at the components!

IoT Relay

Do you want to control a standard wall outlet device with your microcontroller, but don’t want to mess with the high-voltage wiring? The IoT Power Relay is a controllable power relay equipped with four outputs that help you create an Internet of Things project with safe, reliable power control. With the IoT Power Relay you can easily control the power going to a device with an Arduino, Raspberry Pi or other single-board computer or microcontroller. It provides an alternative to the Power Switch Tail.

IoT Power Relay

IoT Power Relay

COM-14236
$29.95
18

The IoT Power Relay is designed to allow you to safely control an outlet device that operates at 3--48VDC or 12--120VAC. Each IoT Power Relay features a single input (from the included C13 power cable) to four outputs: one normally on, one always on, and two normally off. The durable SPDT control relay is rated at 30/40A, for 400,000 operations.

In this kit, we will be using the relay to be able to safely and reliably control larger loads around your house or office without the need to cut wires and deal with high current A/C voltages. The great thing here is that you can also use it to power the project while controlling a device at the same time!

Servo Phat

The SparkFun Servo pHAT allows your Jetson Nano to control up to 16 servo motors in a straightforward and uncomplicated manner via an I2C connection. Thanks to its I2C capabilities, this PWM HAT saves GPIO pins, allowing you to use them for other purposes. The Servo pHAT also adds a serial terminal connection, which will allow you to connect to a number of other devices that are Serial/UART compatible.

SparkFun Servo pHAT for Raspberry Pi

SparkFun Servo pHAT for Raspberry Pi

DEV-15316
$11.95
3

Power to the SparkFun Servo pHAT can be supplied through USB-C connector. This will power either the servo motors only, or power the servo motors as well as the Jetson Nano that is connected to the HAT. We switched to USB-C to allow you to bring more current to your servos than ever before. This USB-C connector can also be used to hook up the Nano via serial port connection to avoid having to use a monitor and keyboard for setting up the Nano. To supply power only to the servo power rail (and not the Pi's 5V power rail), you just need to cut a small trace on the isolation jumper. Doing this allows you to drive heavier loads coming from multiple or larger servos. We've even added power protection circuits to the design, to avoid damage to power sources. Each of this pHAT's 16 servo motor pin headers has been spaced out to the standard 3-pin servo pinout (ground, 5V, signal) to make it easier to attach your servo motors.

Servo

A simple, low-cost, high quality servo for all your mechatronic needs. This servo is very similar in size and specifications to the Hitec HS-55. This little guy is able to take in 6 volts and deliver 20.8 oz-in. of maximum torque at 0.10 sec/60°

Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

ROB-09065
$8.95
12

This small servo comes with a standard 3 pin power and control cable and works perfectly to get your Nvidia Jetson projects to start moving!

Qwiic Button

Buttons are an easy and tactile way to interface with your project, but why would you want to deal with debouncing, polling, and wiring up pull-up resistors? The Qwiic Button with built-in red LED simplifies all of those nasty worries away into an easy to use I2C device! Utilizing our Qwiic Connect System, using the button is as simple as connecting a cable and loading up some pre-written code!

SparkFun Qwiic Button - Red LED

SparkFun Qwiic Button - Red LED

BOB-15932
$4.25
1

If you need multiple buttons for your project, fear not! Each button has a configurable I2C address, so you can daisy-chain multiple buttons over Qwiic and still address each one individually. We've got an example in our Arduino library that provides a super-easy way to configure your Qwiic Button to whatever I2C address you desire. You can download the library through the Arduino library manager by searching 'SparkFun Qwiic Button' or you can get the GitHub repo as a .zip file and install the library from there. In addition to handling blinking and debouncing, the Qwiic Button has configurable interrupts that can be configured to activate upon a button press or click. We've also taken the liberty of implementing a FIFO queue onboard the Qwiic Button where it keeps an internal record of when the button was pressed. This means that code on your microcontroller need not waste valuable processing time checking the status of the button but instead can run a small function whenever the button is pressed or clicked! For more information on interrupts check out our guide here!

Qwiic PIR Motion Sensor

Passive Infrared (PIR) sensors are great for detecting motion in a small area around the sensor. The 170µA SparkFun EKMC4607112K Qwiic PIR uses an EKM-series PIR sensor from Panasonic® paired with an ATTiny84 to interact with it using I2C with the Qwiic system. The EKM-series PIR sensors are optimized for small movements to offer motion-sensing options for continuously powered applications. A great way to enable a webcam or run a machine learning program when there is actually something in front of the project detected!

SparkFun Qwiic PIR - 170uA (EKMC4607112K)

SparkFun Qwiic PIR - 170uA (EKMC4607112K)

SEN-17374
$20.95
1

PIR sensors do not return specific distance data but instead monitor for IR light coming from objects in their field of view and will activate their signal when motion is detected in their sensing area, making them perfect for applications such as turning devices on automatically when motion is detected. Applications include home and building automation for energy saving, automated on/off lighting control, security, appliances, and IoT. Panasonic's low-profile PIR motion sensors (10.9mm versus standard 14.4mm height offer space savings for constrained designs) consist of a lens to create various detection zones, an optical filter to block non-infrared light, pyroelectric sensing elements, electromagnetic shielding to all circuitry, and an impedance converter to get an electrical signal. This PIR sensor offers digital output across 32 zones at 5m detection distance with 90° x 90° detection area.

Qwiic SerLCD Display

The SparkFun SerLCD is an AVR-based, serial enabled LCD that provides a simple and cost effective solution for adding a 16x2 Black on RGB Liquid Crystal Display into your machine learning project.

SparkFun 16x2 SerLCD - RGB Backlight (Qwiic)

SparkFun 16x2 SerLCD - RGB Backlight (Qwiic)

LCD-16396
$19.95

We've seriously overhauled the PCB design on the back of the screen by including an ATmega328P that handles all of the screen control, meaning a backpack is no longer needed! This display can now communicate in three different ways: serial, I2C, and SPI. This version comes equipped with a Qwiic connector, bringing serial LCDs into the Qwiic ecosystem. This simplifies the number of wires needed and allows your project to display all kinds of text and numbers.

Qwiic SparkFun Environmental Combo Sensor

The SparkFun CCS811/BME280 Environmental Combo Breakout takes care of all your atmospheric-quality sensing needs with the popular CCS811 and BME280 ICs. This unique breakout provides a variety of environmental data, including barometric pressure, humidity, temperature, TVOCs and equivalent CO2 (or eCO2) levels. To make it even easier to use this breakout, all communication is enacted exclusively via I2C, utilizing our handy Qwiic system. However, we still have broken out 0.1" spaced pins in case you prefer to use a breadboard.

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SEN-14348
$35.95
20

The CCS811 is an exceedingly popular sensor, providing readings for equivalent CO2 (or eCO2) in the parts per million (PPM) and total volatile organic compounds in the parts per billion (PPB). The CCS811 also has a feature that allows it to fine-tune its readings if it has access to the current humidity and temperature. Luckily for us, the BME280 provides humidity, temperature and barometric pressure! This allows the sensors to work together to give us more accurate readings than they’d be able to provide on their own. We also made it easy to interface with them via I2C.

Software Overview and Setup

This section is going to walk you through getting up and starting from a software perspective. With the advent of the Nvidia Jetson 2GB also came the use of Docker and its Containers as a way to manage different OS images rather than having to burn different OS images to microSD cards and swap them out as needed.

For those unfamiliar with Docker Containers, they are portable units of software that combine an application and all of its dependencies (code, runtime, system tools, system libraries, etc.) into a single package that is agnostic to the host OS. In other words, regardless of its environment the application will always run the same. This removes the need to build complex environments from scratch repetitively and simplifies the process of deploying applications.

For a quick start, we can just burn the basic OS to a microSD card, download whatever containers we need for what content we are working with, and then open those containers. The process is a little different and new for those who are used to managing SD cards for the Raspberry Pi or other single board computers, but it is an improvement and much more efficient in terms of time.

NVIDIA Jetson Nano OS Image

With all of the container talk, we still need a base operating system. You can find the most up-to-date image from Nvidia for the Jetson Nano here.

Once you download it, you can write the image to your microSD card by following Nvidia's instructions according to your computer’s operating system: Windows, macOS, or Linux.

Mac Setup

Download and Install the DLI Course Container

Once you have your Jetson Nano up and running and the basic configuration complete including connecting it to your personal network, either through WiFi or Ethernet). If you are using a 2GB, connection through the WiFi dongle included should be straightforward using the GUI and selecting your network during setup. If you are using a different dongle or the one we carry, you can find the hookup guide for the Edimax adapter we carry here.

Once connected to the internet, open a command prompt and type the following command to download the DLI Course container that we will use as our starting point and then add to it as we go!

[command line]

The container will take some time to download. It is a good time to grab some coffee, watch some YouTube videos or take a nap! Launch the DLI Course Container

When the container image has completely downloaded you will again gain control of the command prompt. Once you do you can launch the container by typing the following command into the prompt.

[command]

If you have run the DLI Course container before, you may notice that this command has been slightly changed from the previous version you find in the course materials. We add a device flag addition for /dev/i2c-1. This option give the container access to the i2c-1 bus that all of your SparkFun Qwiic Boards will connect through. Without this flag you would get a bunch of errors when you start trying to work with the different boards in your kit.

Starting the Container on Boot

The command that we just used to open the DLI Course container image normally needs to be run each time you power on / boot up your Jetson Nano. Which is fine if you are new to the Jetson Nano or are managing a number of different containers for different things. But, if you are looking to use this container as a foundation to build a project or two like we are; we want to make sure it launches every time into this container.

To launch this container on boot from the base command line (Not the command prompt inside of the container) type the following commands:

[commands]

[MAKE SURE THIS IS CORRECT}

You can now either reboot you Jetson Nano to test and make sure the container launches correctly, or repeat the command above to launch the container again.

Jupyter Notebooks

When the container successfully launches you will notice that the command prompt will inform you that Jupyter Labs is running on a given IP address.

[screen shot]

On a separate computer on the same network as your Jetson Nano you can point your web browser to that IP address and you should be greeted with a Jupyter Labs login.

[screen shot]

Again, if you haven’t gone through the DLI Course or used Jupter labs before we highly recommend it for familiarizing yourself with the interface. Since we are using the DLI course as our starting point, the password for JupterLabs is “dlinano”. If you want to explore using JupyterLabs a little more before moving forward we highly recommend our tutorial on using it with your Nano and the SparkFun Qwiic Ecosystem.

[tutorial]

Nvidia Jetson I/O Libraries

SparkFun Qwiic Python Libraries


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

STM32 Thing Plus Hookup Guide

$
0
0

STM32 Thing Plus Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

What incorporates a high-performance Arm® Cortex®-M4 32-bit RISC core, a full set of DSP instructions, memory protection unit (MPU), high-speed embedded memories, up to 4 Kbytes of backup SRAM, and an extensive range of enhanced I/Os and peripherals? The new SparkFun STM32 Thing Plus has all this and more in the popular, Feather-compatible Thing Plus form factor.

Let's have a look at the details!

SparkFun Thing Plus - STM32

SparkFun Thing Plus - STM32

DEV-17712
$29.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.

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.

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.

ARM Programming

How to program SAMD21 or SAMD51 boards (or other ARM processors).

Hardware Overview

STM32F405

The STM32 Thing Plus exploits the vast capabilities of STMicroElectronics' STM32F405 series. This family of ICs uses the ARM 32-bit Cortex M4 CPU to provide high performance, floating point single precision, a full set of DSP instructions, and a memory protection unit that enhances application security. For more information, refer to the Datasheet.

Features

  • Core: ARM® 32-bit Cortex®-M4 CPU with FPU
  • Adaptive real-time accelerator (ART Accelerator™) allowing 0-wait state execution from Flash memory
  • Frequency up to 168 MHz
  • Memory protection unit
  • 210 DMIPS/1.25 DMIPS/MHz (Dhrystone 2.1)
  • DSP instructions

STM32 Arm Cortex is highlighted

Power

Power to the STM32 Thing Plus can be supplied either by a single-cell LiPo battery or by USB-C. The STM32 Thing Plus has an onboard 3.3V regulator, as well as a LiPo battery charging circuit.

USBC connector and LiPo battery connector highlighted

Qwiic Connector

Our Qwiic Ecosystem makes sensors pretty much plug and play. The Qwiic connector provides power and I2C connectivity simultaneously. In addition, the Thing Plus form factor breaks out the I2C functionality to PTH.

Qwiic connector is highlighted

Boot and Reset Buttons

In order to upload code to the STM32 Thing Plus, you'll need these two buttons to put the board into Boot mode. To enter Boot mode, hold the Boot button down, press the Reset button (while still holding the Boot button), and then release the Boot button.

Boot and Reset Buttons are highlighted

MicroSD

Want extra storage space? Add a MicroSD card using the slot on the back of the board.

MicroSD slot is highlighted

Flash

In addition to the STM32's internal Flash memory, we've provided an additional (128M-bit) Serial Flash memory.

Flash chip is highlighted

Board Dimensions

Board Outline and Measurements

Assembly Tips

Headers

The STM32 Thing Plus ships without anything soldered into the header pins -- ensuring that you can mold the board to best fit your project. To use the chip's pins you'll need to solder something to the I/O and power rail vias broken out to either side of the board.

New to soldering? Check out our Through-Hole Soldering Tutorial for a quick introduction!

What you solder to the STM32 Thing Plus's I/O pins is completely up to you. The header rows are breadboard-compatible, so you may want to solder male headers in.

STM32 Thing with male headers soldered

STM32 Thing Plus with soldered male headers.

Then plug it into the breadboard, hanging the USB and LiPo connectors off the end, and start wiring!

Alternatively, female headers (you may need two separate strips to solder all the pins), right-angle headers, or stranded wire are all good options, depending on your project's needs.

Software Setup and Programming

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.

Arduino Board Definition

Installation for the STM32 Thing Plus is relatively straight-forward. You will want to install the board definitions via the Arduino Boards manager. Search for SparkFun STM32 and you should see the option for the STM32 Thing Plus show up.

Boards Manager with SparkFun STM32 boards

For more information on installing boards via the Arduino Board Manager, check out the add-ons section of our Installing Arduino IDE tutorial.

Installing Arduino IDE

March 26, 2013

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

Install STM32Cube Programmer Software

In order to work with the STM32 Thing Plus, you'll need to install the STM32Cube Programmer. This is an all-in-one multi-OS software tool for programming STM32 products. It primarily provides the driver we need, but you can also program your board using this GUI.

DFU Bootloader

As of this writing, SparkFun is using the DFU bootloader to upload code to the STM32 Thing Plus. In order to do so, you need to do the following:

  • Press and hold down the Boot button
  • Press and release the Reset button while continuing to press the Boot button
  • Keep pressing the Boot button until the code is uploaded

Example - Blinky

With the STM32 Arduino core installed, you're ready to begin programming. If you haven't already, plug the STM32 Thing Plus into your computer using a USB-C cable.

Once the board is plugged in, it should be assigned a unique port identifier. On Windows machines, this will be something like COM#, and on Macs or Linux computers it will come in the form of /dev/tty.usbserial-XXXXXX.

Select the Board and Port

You'll notice that there are quite a few options. Make sure you have the Generic STM32F4 Series board and SparkFun Thing Plus STM32F405 board part number selected under your Tools menus.

The other options are more variable. For this example, you'll want to set your selections as you see below.

Tools Menu with options selected

Loading Blink

To make sure your toolchain and board are properly set up, we'll upload the simplest of sketches -- Blink! The builtin LED is perfect for this test. Copy and paste the example sketch below into a fresh Arduino sketch:

language:c

void setup()
{
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.begin(115200);
}

void loop()
{
    Serial.println("Hello, world!");
    digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(1000);                       // wait for a second
    digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
    delay(1000);                       // wait for a second
}

With everything setup correctly, hit the upload button.

IMPORTANT In order to upload code via the DFU Bootloader, you will need to press and hold the Boot Button, then press the Reset Button, then release the Reset Button, then release the Boot Button.

Once the code finishes transferring, open the serial monitor and set the baud rate to 115200. You should see Hello, world!'s begin to fly by.

Note: If the blue LED remains dimly lit, it's probably still sitting in the bootloader. After uploading a sketch, you may need to tap the RST button to get your STM32 Thing Plus to begin running the sketch.

Example serial port output

You may also notice that when the STM32 boots up it prints out a long sequence of debug messages. These are emitted every time the chip resets -- always at 115200 baud.

STM32 Thing Plus with blinking LED!

Example - I2C Scanner

The Qwiic Connect Ecosystem makes attaching sensors a breeze. That said, sometimes it's nice to be able to scan your I2C connections to find out the address of your sensor. That's what we'll do here!

Grab your STM32 Thing Plus and attach a Qwiic Sensor to the Qwiic port on the Thing Plus like so:

Image of STM32 TP and Qwiic sensor attached

Copy and paste the code below into a new Arduino sketch.

language:c
// --------------------------------------
// I2C Scanner example using Wire1
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

TwoWire Wire1(SDA1,SCL1); //Intialize Wire1 class

void setup()
{
  Wire1.begin();

  Serial.begin(115200);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}


void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire1.beginTransmission(address);
    error = Wire1.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }    
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

Make sure your options are all set up correctly in the Tools menu, and make sure you put the Carrier Board into Boot Mode in order to upload the code.

  • Press and hold down the Boot button
  • Press and release the Reset button while continuing to press the Boot button
  • Release the Boot button and press the Upload button in your Arduino IDE

After uploading, open the Serial Monitor and set the baud to 115200. You should see something similar to the printout below.

GIF of screen monitor showing that the qwiic sensor has been found and address 0x48

Example - Serial UART

Let's have a quick look at an example using UART. If you're unfamiliar with Serial Output, go ahead and have a look at our Serial Basic Tutorial.

Grab your MicroMod STM32 Thing Plus board and attach the Serial Basic Rx and Tx pins like so:

Hookup image showing Rx connected to Tx and Tx connected to Rx

Click on the image for a closer view

Note that the RX pin functionality is D0 and the TX pin functionality is D1.

Copy and paste the code below into a new Arduino sketch.

language:c
// --------------------------------------
// UART example using Serial1
//
//
// This sketch prints "Hello World!" every second
// using the secondary UART pins D0 and D1.
//



HardwareSerial Serial1(D0, D1); //Attach Serial1 to D0 and D1

void setup() {
  Serial1.begin(115200);
  while (!Serial1) {
    ; // wait for serial port to connect. Needed for Native USB only
  }
  Serial1.println("Goodnight moon!");

}

void loop() {
  Serial1.println("Hello World!");
  delay(1000);
}

Make sure your options are all set up correctly in the Tools menu, and make sure you put your board into Boot Mode in order to upload the code.

  • Press and hold down the Boot button
  • Press and release the Reset button while continuing to press the Boot button
  • Release the Boot button and press the Upload button in your Arduino IDE

Once your code is uploaded, open up the Serial Monitor attached to your Serial Basic with the baud set to 115200 to see your output!

Gif of the serial output printing "Hello World" every second

Troubleshooting

Resources and Going Further

This should get you started with the STM32 Thing Plus. Need more information? Check out some of the links below:

Check out these other great Thing Plus tutorials from SparkFun:

XBee3 Thing Plus Hookup Guide

Get started with SparkFun's XBee3 Thing Plus - both the u.FL as well as the PCB antenna versions.

ESP32 Thing Plus Hookup Guide

Hookup guide for the ESP32 Thing Plus using the ESP32 WROOM's WiFi/Bluetooth system-on-chip in Arduino.

RP2040 Thing Plus Hookup Guide

Want to take a stab at advancing your programming skills? Check out the Thing Plus - RP2040, with the first microcontroller from the Raspberry Pi Foundation. This guide will get you started working with the RP2040 and programming in MicroPython and C/C++.

ESP32-S2 Thing Plus Hookup Guide

Looking to use the more secure ESP32-S2? Follow this hookup guide to get started.

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

QuickLogic Thing Plus (EOS S3) Hookup Guide

$
0
0

QuickLogic Thing Plus (EOS S3) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

This guide provides users with functional descriptions, configuration options for the QuickLogic Thing Plus EOS S3. It also serves as a “Getting Started” and “How To” guide.

SparkFun QuickLogic Thing Plus - EOS S3

SparkFun QuickLogic Thing Plus - EOS S3

DEV-17273
$45.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.

Reversible USB A to Reversible Micro-B Cable - 0.8m

Reversible USB A to Reversible Micro-B Cable - 0.8m

CAB-15428
$3.95
SparkFun QuickLogic Thing Plus - EOS S3

SparkFun QuickLogic Thing Plus - EOS S3

DEV-17273
$45.95

You Will Also Need

You will also need a computer with a terminal program or any UART console application. For the scope of this tutorial, we will use PuTTY.

  • Computer with Windows 10 OS or Linux OS
    • Serial Terminal

Suggested Reading

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 also recommend checking out a few of these tutorials before continuing.

Serial Peripheral Interface (SPI)

SPI is commonly used to connect microcontrollers to peripherals such as sensors, shift registers, and SD cards.

Logic Levels

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

Accelerometer Basics

A quick introduction to accelerometers, how they work, and why they're used.

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.

Hardware Overview

The QuickLogic Thing Plus EOS S3 is a small form factor system ideal for enabling the next generation of low-power Machine Learning (ML) capable Internet of Things (IoT) devices. Unlike other development boards which are based on proprietary hardware and software tools, the QuickLogic Things Plus is based on 100% open source hardware, compatible with the Feather form factor, and is built around 100% open source software (including the Symbiflow FPGA Tools).

The QuickLogic is powered by QuickLogic’s EOS™ S3, the first eFPGA-enabled Arm Cortex©-M4F MCU to be fully supported with Zephyr RTOS and FreeRTOS.

Other functionality includes:

  • QuickLogic EOS S3 MCU Platform
  • ST micro LIS2DH12TR accelerometer
  • Vesper VM3011 Adaptive ZeroPower Listening™ Digital Piezoelectric MEMS PDM Microphone
  • SparkFun’s Qwiic connector to enable easy connection to large number of Qwiic modules
  • 16Mbit of on-board flash memory
  • User button and RGB LED
  • Powered from USB or a single Li-Po battery
  • Integrated battery charger
  • USB data signals tied to programmable logic
  • IO signals routed into general purpose pinheads
  • Compatible with standard 0.1" breadboards

Benefits

  • QuickLogic Thing Plus EOS S3 is small, Feather compatible, inexpensive, and is 100% supported by open source tools.
  • With a Cortex M4F MCU and integrated eFPGA, the EOS S3 lets you innovate with 100% open source hardware and software.

Applications

  • Tiny ML applications (such as with SensiML’s AI Software Platform and Google’s TensorFlow Lite)
  • General purpose MCU applications

Board Layout

  • QuickLogic EOS S3 MCU Platform
  • ST micro LIS2DH12TR accelerometer
  • SparkFun’s Qwiic connector
  • Vesper’s VM3011 MEMS PDM microphone
  • 16Mbit of on-board flash memory
  • User button and RGB LED
  • Hardware Reset button
  • Powered from USB or a single Li-Po battery
  • Integrated battery charger
  • USB data signals tied to programmable logic
  • IO signals break-routed into general purpose pinheads

alt text

IO Expansion Connectors EOS S3 MCU IO Map to QuickLogic Thing Plus

QuickLogic Thing Plus Graphical Datasheet

Click image for a closer view.
EOS S3 MCU IO QuickLogic Thing Plus Function Additional Function Expansion
IO_0I2C0 SCLJ9.11
IO_1I2C0 SDAJ9.12
IO_2IOJ6.7
IO_3Accelerometer LIS2DH12TR InterruptJ9.10
IO_4IOJ8.8
IO_5IOJ8.9
IO_6User Button InputJ8.10
IO_7IOJ8.11
IO_8IOJ8.12
IO_10IOJ8.13
IO_11IOJ8.6
IO_12IOJ8.7
IO_13IOJ6.8
IO_14Serial Wire Debug CLKJ6.4
IO_15Serial Wire Debug DATAJ6.2
IO_16IOSPI Peripheral CLKJ9.8
IO_17IOSPI Peripheral CIPO (input)J9.7
IO_18Blue LEDN/A
IO_19IOSPI Peripheral COPIJ9.6
IO_20IOSPI Peripheral CSnJ9.5
IO_21Green LEDN/A
IO_22Red LEDN/A
IO_23IOI2S Peripheral WCLK (Frame)J8.3
IO_24IOI2S Peripheral DATA (dout)J8.4
IO_25IOJ6.9
IO_27IOSPI Controller CS2J9.2
IO_28PDM Data; to isolate, remove R28J8.1
IO_29PDM CKOJ8.2
IO_30IOJ6.10
IO_31IOI2S Peripheral CLK (input)J8.5
IO_32IOJ9.3
IO_33IOJ9.4
IO_34SPI Controller CLKJ6.6
IO_36SPI Controller CIPOJ6.4
IO_38SPI Controller COPI (flash)J6.5
IO_40ION/A
IO_43IOInterrupt Output to HostJ9.9
IO_44IOUART TXJ6.2
IO_45IOUART RXJ6.3

Connector J9

J2 EOS S3 MCU IO BGA Pin# Function
1VBAT
23.3V Circuit Enable
3VBUS
4IO_27HSIO; SPI Controller CSn2
5IO_20G8SPI Peripheral SSn input; EOS S3 boot-strap
6IO_19H8SPi Peripheral COPI input; EOS S3 boot-strap
7IO_17D7SPI Peripheral CIPO output
8 IO_16E7SPI Peripheral CLK input
9IO_43D1EOS S3 Interrupt Output
10IO_3A2Accel Interrupt input
11IO_0B1I2C0 SCL
12IO_1C1I2C0 SDA

Connector J6

J6 EOS S3 MCU IO BGA Pin# Function
1Ground
2IO_44E1S3 UART TX
3IO_45G1S3 UART RX
4IO_36H3SPI Controller CIPO input
5IO_38E2SPI Controller COPI output
6IO_34F3SPI Controller CLK output
7IO_2A1IO
8IO_13D6IO
9IO_25F7IO
10IO_30F4IO
11ADC1C7ADC1 input
12No Connect
13Ground
14No Connect
15+3.3V
16SYS_RSTnF8EOS S3 HW reset input

Connector J8

J8 EOS S3 MCU IO BGA Pin# Function
1IO_28G5PDM microphone Data
2IO_29F5PDM microphone CLK
3IO_23H6I2S Peripheral WCLK Input
4IO_24G6I2S Peripheral DATA output
5IO_31G4I2S Peripheral CLK input
6IO_11C5IO
7IO_12B5IO
8IO_4B2IO
9IO_5C3IO
10IO_6B3User button input
11IO_7A3IO
12IO_8C4IO
13IO_10A4IO
14IO_35F2IO
15+3.3V
16Ground
17+3.3V
18Ground

Development Connector

EOS S3 MCU SWD Connector

J7 EOS S3 MCU IO Function
1+3.3V
2IO_15SWD_IO
3Ground
4IO_14SWD_CLK
5Ground
6No Connect
7No Connect
8No Connect
9Ground
10SYS_RSTnHardware Reset

Boot-strap IO_19 & IO_20

  • Install both shunts to use SWD Debugger for development
  • Remove both shunts for boot-from-flash

Bootstrap J2 and J3

Power

There are two ways to provide power to the QuickLogic Thing Plus: USB connector (J5) or Battery connector (J4). When both ports are connected at the same time, the USB power activates the battery charging circuit that provide charging current to the battery.

When using a rechargeable battery, the minimum input voltage will determine the maximum currents that the system needs to support. This is important when connecting additional peripherals to the QuickLogic Thing Plus that also requires connection to +3.3V for supplies.

alt text

The MCP73831 LiPo charger is set to ~212.76mA for the default charge rate. Before you plug a battery into the charger, you should be aware of your battery's capacity and the charge current supplied by the charger. To be safe*, you should keep the charge current at or below 1C of your battery. That means you should connect a LiPo battery that has a capacity of ~212.75mAh or higher to charge safely. For more information on the charge LED's status, check out the LiPo USB Charger breakout board for the MCP73831.

Connecting Additional Peripherals to the QuickLogic Thing Plus

QuickLogic Thing Plus supports direct connection to FeatherWing module (providing that the FeatherWing module has Stack Headers installed) via expansion connector J2 and J3. Refer to AdaFruit's web site for additional information on available FeatherWing modules.

Sensor with I2C Port

QuickLogic Thing Plus board supports connecting to sensor module with I2C peripheral interface via expansion connectors J2. QuickLogic Thing Plus I2C supports I2C Standard mode (100KHz) and Fast mode (400KHz). There is one I2C bus available; additional I2C IP can be implemented in EOS S3 FPGA.

  • I2C0 bus: J2 pin 12 (SDA) and J2 pin 11 (SCL); the signals (SCL and SDA) are connected to 4.7KΩ pull-up resistor. This bus is shared with onboard I2Csensor, LIS2DH12TR (b0011000x).

Steps to connect external I2C sensors to QuickLogic Thing Plus board:

  • Ground connection
  • Power connection (+3.3V supplies); check supply voltage level meeting connecting module requirement
  • Connect SCL and SDA signals; check IO level (> +3.0V IO only)
  • Keep connecting wires as short as possible
  • Configure the I2Caddress to avoid LIS2DH12TR assigned address (b0011000x)
  • Check SCL and SDA rise time (< 1000 ns for Standard mode and < 300 ns for Fast mode)

Note: may need to use oscilloscope to validate the rise time for SCL and SDA to stay within rise time specification



Sensor with SPI Peripheral port

QuickLogic Thing Plus board supports connecting to sensor module with SPI peripheral interface via expansion connectors J6 and J9: SPI CONTROLLER CLK (J6 pin 6), SPI CONTROLLER CIPO (J6 pin 4), SPI CONTROLLER COPI (J6 pin 5) and SPI CONTROLLER CS2 (J9 pin 4). The maximum supported SPI clock frequency is 10MHz.

Steps to connect external SPI sensor to QuickLogic Thing Plus board:

  • Ground connection
  • Power connection (+3.3V supplies check supply voltage level meeting connecting module requirement
  • Connect SPI CONTROLLER signals; check IO level (> +3.0V IO only)
  • Keep connecting wires as short as possible
  • Check signal quality using scope



PDM Microphones

Single PDM Microphone

The on-board PDM microphone (Vesper VM3011) is configured as left channel output (driving active data on falling edge of PDM CLK). QuickLogic Thing Plus supports external PDM microphone connection via expansion connector J8: PDM CLK (J8 pin 2) and PDM DATA (J8 pin 1).

Steps to connect one external PDM microphone to QuickLogic Thing Plus board:

  • Ground connection
  • Power connection (+3.3V supplies check supply voltage level meeting connecting module requirement
  • Remove R28 (100Ω resistor)
  • Connect PDM CLK and PDM DATA signals; check IO level (> +3.0V IO only)
  • Keep connecting wires as short as possible
  • PDM microphone is configured as right channel microphone; the L/R signal or Channel signal is connected to VDD
  • Check signal quality using scope



Double PDM Microphone

To support two external PDM microphones configuration, it is required to disable the connection of the on-board PDM microphone.

QuickLogic Thing Plus supports external PDM microphone connection via expansion connector J8: PDM CLK (J8 pin 2) and PDM DATA (J8 pin 1).

Steps to connect two external PDM microphones to QuickLogic Thing Plus board:

  • Ground connection
  • Power connection (+3.3V supplies check supply voltage level meeting connecting module requirement
  • Remove R28 (100Ω resistor)
  • Connect PDM CLK and PDM DATA signals; check IO level (> +3.0V IO only)
  • Keep connecting wires as short as possible; avoid star connection scheme (see figure below)
  • Configure one PDM microphone as left channel and one PDM microphone as right channel
  • Check signal quality using scope

alt text

Board Dimensions

The board is 2.75"x2.10". While the board uses the Thing Plus footprint, length of the board is slightly longer than other Thing Plus designs.

alt text

Hardware Assembly

To power, you will need to insert a USB cable to the board.

alt text

Getting Started

Running Pre-Loaded Program from Flash

The purpose of the pre-loaded program is to make it very fast and straightforward for a new user to verify the board is functioning correctly. While we do production testing on every QuickLogic Thing Plus before we ship, sometimes things happen during shipping or storage. Running this test takes less than a minute to do, requires no knowledge of the QuickLogic Thing Plus, and will give you peace of mind the QuickLogic Thing Plus is ready for you to start innovating freely.

  1. Make sure there is no shunt installed at J2 and J3; if there are shunts installed, remove the shunts; save the shunts for future firmware development
  2. Provide power to the QuickLogic Thing Plus using the Type-C USB cable; the power source can be either a PC or wall adapter. When there is power applied to the board, the LED flashes “white” for a short duration
  3. Press the “reset” button
  4. The LED flashes blue color for 5 seconds and then turns off
  5. Wait for 5 seconds
  6. On Windows 10 machine, open Device Manager to check for the assign COM port

Checking COM Port with Device Manager
  1. Launch PuTTY application and configure for Serial access and select “Open”.

PuTTY Configuration


8. Perform the followings in the PuTTY terminal:

    a) Type: “diag” to bring up QuickLogic Thing Plus diagnostic menu

    b) Type: “help” to bring up the menu of commands

    c.) Type: “red”; the command shows red color for LED

    d.) Type: “red”; the LED turns off the LED

    e.) Try “green” and “blue” command

Hello World Application Menu

Diagnostic Menu

QuickLogic Thing Plus supports loading and testing stand-alone eFPGA design or eFPGA + M4 MCU design, using SWD standard tool such as Segger’s Jlink SWD or OCD. Below are the instructions for system with Windows 10 OS with Segger Jlink pod.

What you need

  • Laptop or PC with Windows 10
  • Segger Jlink pod and PC connecting USB cable
  • Segger Jlink adapter to 10-pin connector and cable
  • QuickLogic Thing Plus board and micro USB cable

J-Link to QuickLogic Thing Plus Connection

Download stand-alone FPGA binaries instructions

  • Disconnect QuickLogic Thing Plus power; if USB-to-Serial cable connected to the board, remove the connection from PC
  • Install shunts at QuickLogic Thing Plus J2 and J3
  • Connect micro USB cable from QuickLogic Thing Plus to PC
  • Connect 10-pin cable to QuickLogic Thing Plus connector J6; check connector key for correct alignment
  • Press reset button
  • Open CMD console
  • Type: “Jlink.exe -device cortex-m4 -If SWD -speed 4000 -commandFile "Jlink script"

Note: * Jlink.exe: Link commander – include reference to the location of executable * Jlink script: output file symbiflow for EOS S3 FPGA binaries * Refer to Jlink Commander for more additional information

Download FPGA binaries + M4 MCU binaries instructions

  • Disconnect QuickLogic Thing Plus power; if USB-to-Serial cable connected to the board, remove the connection from PC
  • Install shunts at QuickLogic Thing Plus J2 and J3
  • Connect micro USB cable from QuickLogic Thing Plus to PC
  • Connect 10-pin cable to QuickLogic Thing Plus connector J7; check connector key for correct alignment
  • Press reset button
  • Open CMD console (#1)
  • Launch Jlink commander (i.e. type “Jlink.exe”) and follow the on-screen instructions to connect to QuickLogic Thing Plus M4 target
  • Execute the followings in Link Commander console
    • Type: “r” to reset the EOS S3
    • Type: “loadbin qt_helloworldsw.bin 0x0”
    • Type: “r”
  • Open another CMD console (#2)
  • Type: “Jlink.exe -device cortex-m4 -If SWD -speed 4000 -commandFile "Jlink script"

Note: * Jlink.exe: Link commander – include reference to the location of executable * Jlink script: Symbiflow’s output for EOS S3 FPGA binaries * Refer to Jlink Commander for more additional information * Return to console #1; type: “g”; the M4 binaries in M4 SRAM will start to run and the eFPGA is configured

Resources and Going Further

Now that you've successfully got your QuickLogic EOS S3 Thing Plus 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:

Programming an FPGA

Come look at the basics of working with Field Programmable Gate Arrays.

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

Qwiic EEPROM Hookup Guide

$
0
0

Qwiic EEPROM Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Qwiic EEPROM is a simple and cost effective option to add some extra storage space to any project. With 512 kilo-bits (or 64 kilo-bytes) of storage, this product is great for any microcontroller that doesn't have any EEPROM storage space, like the SAMD21.

SparkFun Qwiic EEPROM Breakout - 512Kbit

SparkFun Qwiic EEPROM Breakout - 512Kbit

COM-18355
$3.95

Maybe your project needs to store data, like a public-key, in non-volatile memory? Maybe you want to use multiple boards as configuration keys with different default settings for your project? Whatever your project needs might be, this guide will help users familiarize themselves with the Qwiic EEPROM and its operation.

Required Materials

The Qwiic EEPROM does need a few additional items for you to get started. The RedBoard Qwiic will be used for the Arduino examples. A single board computer and the Qwiic pHAT are required for the Python examples (see note below). You may already have a few of these items, including the required Qwiic cable, so feel free to modify your cart based on your needs. Additionally, there are also options that are available as well (click button below to toggle options).

SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
12
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
8
USB micro-B Cable - 6 Foot

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
13
SparkFun Qwiic pHAT v2.0 for Raspberry Pi

SparkFun Qwiic pHAT v2.0 for Raspberry Pi

DEV-15945
$6.95
2
Qwiic Compatible Microcontrollers:
SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

DEV-15795
$19.95
4
SparkFun Thing Plus - ESP32 WROOM

SparkFun Thing Plus - ESP32 WROOM

WRL-15663
$20.95
7
SparkFun Thing Plus - SAMD51

SparkFun Thing Plus - SAMD51

DEV-14713
$19.95
1
SparkFun RedBoard Artemis

SparkFun RedBoard Artemis

DEV-15444
$19.95
8
In addition we also offer, Qwiic compatible stackable shields for microcontrollers and pHATs for single board computers (like the Raspberry Pi boards) that don't include a Qwiic connector.
SparkFun Qwiic Adapter

SparkFun Qwiic Adapter

DEV-14495
$1.50
1
SparkFun Qwiic Shield for Thing Plus

SparkFun Qwiic Shield for Thing Plus

DEV-16790
$4.25
SparkFun Qwiic Shield for Arduino Nano

SparkFun Qwiic Shield for Arduino Nano

DEV-16789
$4.25
SparkFun Qwiic Shield for Teensy

SparkFun Qwiic Shield for Teensy

DEV-17119
$4.25
1
SparkFun Qwiic HAT for Raspberry Pi

SparkFun Qwiic HAT for Raspberry Pi

DEV-14459
$6.50
4
SparkFun Servo pHAT for Raspberry Pi

SparkFun Servo pHAT for Raspberry Pi

DEV-15316
$11.95
3
SparkFun Auto pHAT for Raspberry Pi

SparkFun Auto pHAT for Raspberry Pi

ROB-16328
$29.95
1
SparkFun Qwiic SHIM for Raspberry Pi

SparkFun Qwiic SHIM for Raspberry Pi

DEV-15794
$0.95
8
SparkFun Qwiic pHAT v2.0 for Raspberry Pi

SparkFun Qwiic pHAT v2.0 for Raspberry Pi

DEV-15945
$6.95
2
SparkFun Top pHAT for Raspberry Pi

SparkFun Top pHAT for Raspberry Pi

DEV-16301
$49.95
You will also need a Qwiic cable to connect to your Qwiic device, choose a length that suits your needs.
Flexible Qwiic Cable - 500mm

Flexible Qwiic Cable - 500mm

PRT-17257
$1.95
Flexible Qwiic Cable - 200mm

Flexible Qwiic Cable - 200mm

PRT-17258
$1.50
Flexible Qwiic Cable - 100mm

Flexible Qwiic Cable - 100mm

PRT-17259
$1.50
Flexible Qwiic Cable - 50mm

Flexible Qwiic Cable - 50mm

PRT-17260
$0.95

Python Example: If you don't already have them, you will need an SBC (single board computer) such as a Raspberry Pi and standard peripherals or Jetson Nano and standard peripherals. An example setup is listed below.
NVIDIA Jetson Nano Developer Kit (V3)

NVIDIA Jetson Nano Developer Kit (V3)

DEV-16271
$99.00
10
SparkFun Raspberry Pi 4 Basic Kit - 8GB

SparkFun Raspberry Pi 4 Basic Kit - 8GB

KIT-17980
$114.95
SparkFun DLI Kit (without Jetson Nano)

SparkFun DLI Kit (without Jetson Nano)

KIT-16389
$78.95
1
NVIDIA Jetson Nano 2GB Developer Kit

NVIDIA Jetson Nano 2GB Developer Kit

DEV-17244
$59.00
1
SparkFun DLI Kit for Jetson Nano 2GB

SparkFun DLI Kit for Jetson Nano 2GB

KIT-17245
$139.95
Multimedia Wireless Keyboard

Multimedia Wireless Keyboard

WIG-14271
$29.95
4
pi-topCEED (Green)

pi-topCEED (Green)

KIT-14035
$114.95
4

Suggested Reading

If you're unfamiliar with serial terminals, jumper pads, or I2C be sure to checkout some of these foundational 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.

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.

Serial Terminal Basics

This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.

Reading and Writing Serial EEPROMs

EEPROM is a great way to add extra memory to your microcontroller project. Wait 'til you see how easy it is to use!

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.

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.

Arduino Shields v2

An update to our classic Arduino Shields Tutorial! All things Arduino shields. What they are and how to assemble them.

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.

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.

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.

Working with Qwiic on a Jetson Nano through Jupyter Notebooks

We created a few Jupyter Notebooks to make using our Qwiic boards with your Jetson Nano even easier!

Qwiic Connect System

The Qwiic EEPROM utilizes the Qwiic connect system. We recommend familiarizing yourself with the Logic Levels and I2C tutorials (above) before using it. Click on the banner above to learn more about our Qwiic products.

Note: First time Raspberry Pi users should also head over to the Raspberry Pi Foundation website and check out their quickstart guides:

We have also listed a few additional resources for users to familiarize themselves with the Raspberry Pi:

Hardware Overview

Board Dimensions

The Qwiic EEPROM Breakout is laid out on the standardized 1" x 1" (2.54 x 2.54 cm) Qwiic breakout board and includes the standard four 0.13" mounting holes, which are compatible with 4-40 screws.

board dimensions
Board dimensions. (Click to enlarge)

Power

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

power
Power LED and power breakout pins. (Click to enlarge)

CAT24C512 EEPROM

The CAT24C512 IC is a 512-Kb (kilobit) EEPROM flash memory is organized as 65,536 words of 8 bits each with a 128-byte page write buffer. An on board ECC (Error Correction Code) makes this EEPROM suitable for high reliability applications. The IC also offers write protection, which inhibits write operations by pulling the WP pin High (protects the entire memory). The external address pins make it possible to connect up to eight CAT24C512 EEPROM chips on the same I2C bus.

EEPROM IC
EEPROM chip. (Click to enlarge)

For more details on how the serial EEPROM works, check out our guide below:

Reading and Writing Serial EEPROMs

August 11, 2017

EEPROM is a great way to add extra memory to your microcontroller project. Wait 'til you see how easy it is to use!

Sensor Characteristics

Below, is a table of the characteristics of the EEPROM chip. For more details, please refer to the [datasheet](

CharacteristicDescription
Power Supply Voltage: 1.8 to 5.5V
Supply Current:
  • Read Current: 1mA
  • Write Current: 1.8mA - 2.5mA
Reliability Endurance: 1,000,000 Program/Erase Cycles
Data Retention: 100 Years
Page Write Buffer128 bytes
Write ProtectionEntire Memory
I2C Address (7-bit) 1010[E2][E1][E0]
0x50 (Default), 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57

Qwiic and I2C

I2C Address

The Qwiic EEPROM’s I2C address, 0x50 (7-bit), is factory set. An alternate I2C address can be configured to 1010[E2][E1][E0] by modifying the address jumpersE0, E1, E2(see Jumpers section below).

Qwiic Connectors

The simplest way to use the Qwiic EEPROM is through the Qwiic connect system. The connectors are polarized for the I2C connection and power. (*They are tied to the corresponding power and I2C breakout pins.)

Qwiic connectors
Qwiic connectors. (Click to enlarge)

Breakout Pins

The board also provides five labeled breakout pins.

Breakout pins
Breakout pins. (Click to enlarge)

I2C

You can connect these lines to the I2C bus of your microcontroller and power pins (3.3V and GND), for a more permanent connection.

I2C Pins
I2C Connections- The pins are tied to the Qwiic connectors.

Write Protection Pin

Pulling the WP pin high, will disable all write operations to the entire memory space.

Interrupt pins
Interrupt breakout pins. (Click to enlarge)

Jumpers

There are five jumpers on the board. Not sure how to cut or modify a jumper? Read here!

Power LED Jumper

Cutting the LED jumper will remove the 1kΩ resistors and PWR LED from the 3.3V power. This is useful for low power applications.

power LED jumper
Power LED jumper. (Click to enlarge)

Write Protection

Bridging the WP jumper will pull the pin high (to the 3.3V power) and disable any write operations.

WP jumper
Write protection jumper. (Click to enlarge)

I2C Pull-Up

Cutting the I2C jumper will remove the 2.2kΩ pull-up resistors from the I2C bus. If you have many devices on your I2C bus you may want to remove these jumpers.

I2C pullup jumper
I2C pull-up resistor jumper. (Click to enlarge)

Address Jumpers

Modifying the address jumpers (E0, E1, E2) allows users to configure the I2C address. This can be used to configure the default I2C address of the device to 1010[E2][E1][E0] (7-bit).

address jumpers
Address jumpers. (Click to enlarge)

Hardware Hookup

Arduino Examples

With the Qwiic connector system, assembling the hardware is simple. All you need to do is connect your SparkFun Qwiic EEPROM Breakout - 512Kbit to the RedBoard Qwiic with a Qwiic cable. Otherwise, you can use the I2C pins of your microcontroller; just be aware of logic levels.

Hardware assembly with RedBoard Qwiic
RedBoard Qwiic connected the Qwiic EEPROM with a Qwiic cable.

Note: This tutorial assumes users are familiar with Arduino products and are using the latest stable version of the Arduino IDE on your desktop. If this is your first time using the Arduino IDE, please review our tutorial on installing the Arduino IDE.

Python Examples

With the Qwiic connector system, assembling the hardware is simple. In addition to the SparkFun Qwiic EEPROM Breakout - 512Kbit, you will need: a Qwiic cable, a SparkFun Qwiic pHAT for Raspberry Pi, single board computer, monitor, and standard peripherals. (*If you are unfamiliar with the Qwiic pHAT, you can find the Hookup Guide here.)

There are two single board computer (SBC) options that we have tested on:

Hardware assembly with Raspberry Pi 4 with Qwiic pHAT
Raspberry Pi 4 (with Qwiic pHAT) connected the Qwiic EEPROM.
Hardware assembly with Jetson with Qwiic pHAT
Jetson connected to the Qwiic EEPROM.

Note: Don't forget to connect any necessary peripherals, such as a monitor, keyboard and mouse, and power supply to the single board computer.

Note: This tutorial assumes users are familiar with using a Raspberry Pi and have the latest version of Raspbian OS (full... with recommended software) your Raspberry Pi. You can download the latest version of the Raspbian OS from the Raspberry Pi Foundation website.

If this is your first time using a Raspberry Pi, please head over to the Raspberry Pi Foundation website to use their quickstart guides. We have listed a few of them here:

  1. Setting up your Raspberry Pi
  2. Using your Raspberry Pi
  3. Documentation:
  4. Setup Documentation
    Installation Documentation
    Raspbian Documentation
    SD card Documentation

Note: This tutorial assumes users are familiar with using a Jetson Nano and you have the latest version of L4T OS your Jetson Nano. You can download the latest version of the L4T OS from the Jetson Download Center on Nvidia's website.

If this is your first time using a Jetson Nano, please head over to the Nvidia website to use their quickstart guides. We have listed a few of them here:

  1. Getting Started With Jetson Nano Developer Kit
  2. Jetson Nano Developer Kit User Guide
  3. Documentation:
  4. Jetson Nano Getting Started Guide
    Jetson Download Center
    Wiki: Jetson Nano
    Jetpack Software Documentation
    Nvidia Jetson Tutorials

Arduino Library and Examples

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.

We've written a library to easily get setup and read/write data on the SparkFun Qwiic EEPROM Breakout - 512Kbit. However, before we jump into using this board, 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 External EEPROM Arduino Library 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:

For more details on this Arduino library and its use, please refer to the Serial EEPROM hookup guide:

Reading and Writing Serial EEPROMs

August 11, 2017

EEPROM is a great way to add extra memory to your microcontroller project. Wait 'til you see how easy it is to use!

Python Package

Note: This tutorial assumes you are using the latest version of Python 3. If this is your first time using Python or I2C hardware on a Raspberry Pi, please checkout our tutorial on Python Programming with the Raspberry Pi and the Raspberry Pi SPI and I2C Tutorial. Jetson Nano users can check out this tutorial on Working with Qwiic on a Jetson Nano through Jupyter Notebooks.

We've written a Python package to easily get setup and read/write data on the SparkFun Qwiic EEPROM Breakout - 512Kbit. There are two methods for installing the Python package for the Qwiic EEPROM.

  1. Install the all inclusive SparkFun Qwiic Python package.
  2. Independently install the Python package for SparkFun Qwiic EEPROM.

The all inclusive SparkFun Qwiic Python package, is recommended as is also installs the required I2C driver as well.

Note: Don't forget to double check that the hardware I2C connection is enabled on your single board computer.

SparkFun Qwiic Package

This repository is hosted on PyPi as the sparkfun-qwiic package. On systems that support PyPi installation via pip3 (use pip for Python 2) is simple, using the following commands:

For all users (note: the user must have sudo privileges):

language:bash
sudo pip3 install sparkfun-qwiic

For the current user:

language:bash
pip3 install sparkfun-qwiic

Independent Installation

You can install the sparkfun-qwiic-eeprom Python package independently, which is hosted by PyPi. However, if you prefer to manually download and install the package from the GitHub repository, you can grab them here (*Please be aware of any package dependencies. You can also check out the repository documentation page, hosted on ReadtheDocs.):

PyPi Installation

This repository is hosted on PyPi as the sparkfun-qwiic-eeprom package. On systems that support PyPi installation via pip3 (use pip for Python 2) is simple, using the following commands:

For all users (note: the user must have sudo privileges):

language:bash
sudo pip3 install sparkfun-qwiic-eeprom

For the current user:

language:bash
pip3 install sparkfun-qwiic-eeprom

Local Installation

To install, make sure the setuptools package is installed on the system.

Direct installation at the command line (use python for Python 2):

language:bash
python3 setup.py install

To build a package for use with pip3:

language:bash
python3 setup.py sdist

A package file is built and placed in a subdirectory called dist. This package file can be installed using pip3.

language:bash
cd dist
pip3 install sparkfun_qwic_eeprom-<version>.tar.gz

Python Package Operation

Before we jump into getting readings, let's take a closer look at the available functions in the Python package. Below, is a description of the basic functionality of the Python package. This includes the package organization, built-in methods, and their inputs and/or outputs. For more details on how the Python package works, check out the source code and package documentation.

Dependencies

This Python package has a very few dependencies in the code, listed below:

language:python
import math
import time
import qwiic_i2c
import smbus2
import struct

Default Variables

The default variables, in the code, for this Python package are listed below:

language:python
# qwiic_eeprom GLOBAL VARIABLES
#----------------------------------------------------------------------------------------------------
# Define the device name and I2C addresses. These are set in the class defintion 
# as class variables, making them avilable without having to create a class instance.
# This allows higher level logic to rapidly create a index of qwiic devices at 
# runtine

# The name of this device 
_DEFAULT_NAME = "Qwiic EEPROM"

# Some devices have multiple availabele addresses - this is a list of these addresses.
# NOTE: The first address in this list is considered the default I2C address for the 
# device.
_AVAILABLE_I2C_ADDRESS = [0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57]
Note: This package is different from previous packages as the local variables are declared in the object class.
language:python
# QwiicEEPROM CLASS VARIABLES
#----------------------------------------------------------------------------------------------------
memory_size_bytes = 512000 / 8
page_size_bytes = 64
page_write_time_ms = 5
poll_for_write_complete = True

I2C_BUFFER_LENGTH = 32

Class

QwiicEEPROM() or QwiicEEPROM(address)
This Python package operates as a class object, allowing new instances of that type to be made. An __init__() constructor is used that creates a connection to an I2C device over the I2C bus using the default or specified I2C address.

The Constructor

A constructor is a special kind of method used to initialize (assign values to) the data members needed by the object when it is created.

__init__(address=None, i2c_driver=None):

Input: value
The value of the device address. If not defined, the Python package will use the default I2C address (0x50) stored under _AVAILABLE_I2C_ADDRESS variable.
Input: i2c_driver
Loads the specified I2C driver; by default the Qwiic I2C driver is used: qwiic_i2c.getI2CDriver(). Users should use the default I2C driver and leave this field blank.

Functions

A function is an attribute of the class, which defines a method for instances of that class. In simple terms, they are objects for the operations (or methods) of the class. A list of all the available functions are detailed on the API Reference page of ReadtheDocs for the Qwiic_EEPROM_Py Python package.

Upgrading the Python Package

In the future, changes to the Python package might be made. Updating the installed packages has to be done individually for each package (i.e. sub-modules and dependencies won't update automatically and must be updated manually). For the sparkfun-qwiic-eeprom Python package, use the following command (use pip for Python 2):

For all users (note: the user must have sudo privileges):

language:bash
sudo pip3 install --upgrade sparkfun-qwiic-eeprom

For the current user:

language:bash
pip3 install --upgrade sparkfun-qwiic-eeprom

Python Examples

There are several examples written for the Qwiic_EEPROM_Py Python package. They can be found in the Examples folder of the GitHub repository or view on the repository documentation page, hosted on ReadtheDocs. Users can also grab them here, using the link below. (*Please be aware of any package dependencies.):

Example 1 - Basic Read and Write

This example is hosted on ReadtheDocs: Example 1.

write and read data
Write data on and read data from the EEPROM. (Click to enlarge)

In this example, various data types are written to and read from the EEPROM at different memory locations.

Note: When writting data, users need to keep in mind the size of the data and memory available at the specified location. Otherwise, users can accidentally overwrite data already stored in the memory.

More Examples

Users can also check out the more advanced examples below:

Troubleshooting

Below, we have also included some troubleshooting tips for issues that you may come across.

  1. One of our employees compiled a great list of troubleshooting tips based on the most common customer issues. This is the perfect place to start.
  2. For any Arduino IDE specific issues, we recommend starting with their troubleshooting guide.

If neither of the troubleshooting guides above were able to help, here are some resources you might have missed. (Most of this material is summarized from the tutorial.)

Raspberry Pi

For comprehensive information or troubleshooting issues, on the Raspberry Pi, users should check out the Raspberry Pi Foundation website and their forum.

As a general guideline, users should use the following resources when looking for technical information or assistance that is specifically related to the Raspberry Pi itself:

  1. Raspberry Pi FAQ
  2. Raspberry Pi Beginner's Subforum
  3. Raspberry Pi Documentation and Help Guides
  4. Raspberry Pi Forum

Nvidia Jetson Nano

For comprehensive information or troubleshooting issues, on the Nvidia Jetson, users should check out the Nvidia website and their forum.

As a general guideline, users should use the following resources when looking for technical information or assistance that is specifically related to the Jetson Nano itself:

  1. Jetson Support Resources
  2. Jetson Nano Getting Started Guide
  3. Developer Kit User Manual
  4. Jetson Nano Wiki
  5. Nvidia FAQ
  6. Jetson Forum
  7. Jetpack Documentation

For users looking for technical assistance, click on the link. There you will find, basic troubleshooting tips and instructions to get started with posting a topic in our forum. Our technical support team will do their best to assist you.

Resources and Going Further

For more information on the SparkFun Qwiic EEPROM Breakout, check out the links below:

For more sensor action, check out these other great SparkFun tutorials.

Build a Qwiic Jukebox that is Toddler Approved!

Follow this tutorial to build your own custom jukebox. Note, this is designed simple and tough for use primarily with toddlers. It's also a great introduction to SparkFun's Qwiic products!

Qwiic 12-Bit ADC Hookup Guide

Need to add more analog inputs for your project? Check out the Qwiic 12-bit ADC.

Qwiic Atmospheric Sensor (BME280) Hookup Guide

Measure temperature, humidity, barometric pressure with the SparkFun Atmospheric Sensor Breakout BME280 (Qwiic).

SparkFun Humidity Sensor Breakout - SHTC3 (Qwiic) Hookup Guide

A Hookup Guide to get started using the SHTC3 breakout.

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

Buck Regulator Hookup Guide

$
0
0

Buck Regulator Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Who doesn't occasionally need power regulation? We certainly do, so we've designed the SparkFun Buck Regulator Breakout and the SparkFun BabyBuck Regulator Breakout to help us with just such a task.

Starring the AP63203 from Diodes Inc, both breakout boards take advantage of the 2A synchronous buck converter that has a wide input voltage range of 3.8V to 32V and fully integrated 125mΩ high-side power MOSFET/68mΩ lowside power MOSFET to provide high-efficiency step-down DC/DC conversion. All of this snuggled up in a a low-profile, TSOT26 package that's integrated into either a 1x1" or 0.4x0.5" board. For a wide variety of power management needs - grab yourself a Buck Regulator or Baby Buck Regulator and let's dive in!

SparkFun Buck Regulator Breakout - 3.3V (AP63203)

SparkFun Buck Regulator Breakout - 3.3V (AP63203)

COM-18356
$4.95
SparkFun BabyBuck Regulator Breakout - 3.3V (AP63203)

SparkFun BabyBuck Regulator Breakout - 3.3V (AP63203)

COM-18357
$3.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.

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
13
Solder Lead Free - 15-gram Tube

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
3

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.

Logic Levels

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

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!

Hardware Overview

AP63203

The AP63203 is a 2A, synchronous buck converter from Diodes Inc that has a wide input voltage range (3.8V to 32V) and provides high-efficiency step-down DC/DC conversion to 3.3V. Frequency Spread Spectrum (FSS) reduces EMI and a proprietary gate driver scheme resists switching node ringing without sacrificing MOSFET turn-on and turn-off times, which further erases high-frequency radiated EMI noise. Full details can be found in the datasheet.

Features:

  • VIN 3.8V to 32V
  • Up to 2A Continuous Output Current
  • 0.8V ± 1% Reference Voltage
  • 22µA Ultralow Quiescent Current
  • Switching Frequency - 1.1MHz
  • Supports Pulse Frequency Modulation (PFM)
    • Up to 80% Efficiency at 1mA Light Load
    • Up to 88% Efficiency at 5mA Light Load
  • Fixed Output Voltage - 3.3V
  • Proprietary Gate Driver Design for Best EMI Reduction
  • Frequency Spread Spectrum (FSS) to Reduce EMI
  • Precision Enable Threshold to Adjust UVLO
  • Protection Circuitry
    • Overvoltage Protection
    • Cycle-by-Cycle Peak Current Limit
    • Thermal Shutdown

AP63203 on the Buck RegulatorAP63203 on the Baby Buck Regulator

Power

For the Buck Regulator, input power can be supplied in a number of ways. There are screw terminals on the right side of the board, solder pads for a barrel jack, which can be mounted on the top or bottom side of the board, and the plated through holes on the left side of the board can all be used as input. Output can be obtained via the screw terminals or the plated through holes.

Power options for the Buck Regulator

The Baby Buck sacrifices flexibility for space. Use the plated through holes for input and output power.

Plated through holes on the baby buck used for input and output

Both the Buck Regulator as well as the Baby Buck Regulator ratchet the output voltage down to 3.3V. Be mindful that thermal properties change as Vin increases.

Thermal Characteristics

One of the benefits of a buck converter over a linear regulator is their superior efficiency at stepping down the voltage. Unfortunately though, heat can still be a problem, particularly as the difference between the input and output voltage increases.

One of the trade-offs of the small size of the BabyBuck is because there is less copper to pull heat away from switching IC, the maximum output current available is reduced due to the thermal protections. Refer to the graphs below to see the how hot you can expect the AP63203 to get at various loads and supply voltages.

Baby Buck regulator thermal characteristics

Buck regulator thermal characteristics

To dissipate some of the excess heat, we've added a copper pad for a heat sink on the back of the 1" x 1" Buck Regulator Board. Use one of our small heatsinks and attach it with some thermal tape.

Heatsink Pad

Power LED and Jumper

On the 1" x 1" Buck Regulator, there is a power LED available for use.

Power LED is on the front of the Buck Regulator, below the AP63203

To disable this LED, cut the Jumper on the back of the board:

LED Jumper is to the left of the heatsink pad on the back of the Buck Regulator board

Board Outline

Buck Board Outline:

Outline and measurements of the SparkFun Buck Regulator Board

Baby Buck Board Outline:

Outline and measurements of the SparkFun Baby Buck Regulator Board

Hardware Hookup

There are three options when using the 1" x 1" Buck Regulator.

Screw terminals

To use the screw terminals, simply insert the correct wires into the screw terminal opening and gently tighten the screw for that port. Your board should look similar to the following:

Screw terminals on the right side of the Buck Regulator Board with wires inserted and screws tightened

Barrel Jack

To use a barrel jack for input, grab one of our PTH Mount Barrel Jack Connectors and solder that sucker on. It should look something like what you see here:

Barrel Jack fits to the board faceing out

PTH Pins

To use the plated through holes on either the Buck Regulator or the Baby Buck Regulator, you'll need to solder either straight headers or angle headers to the board.

Headers soldered to the PTH pins on both the Buck Regulator and the Baby Buck Regulator

Troubleshooting

Resources and Going Further

For more information, check out the resources below:

Buck Regulator:

Baby Buck Regulator:

Need some inspiration for your next project? Check out some of these related tutorials:

Battery Technologies

The basics behind the batteries used in portable electronic devices: LiPo, NiMH, coin cells, and alkaline.

Photon Battery Shield Hookup Guide

The Photon Battery Shield has everything your Photon needs to run off, charge, and monitor a LiPo battery. Read through this hookup guide to get started using it.

Hookup Guide for the SparkFun RedBoard Artemis Nano

Get started with the powerful RedBoard Artemis Nano

Fuse Breakout Board Hookup Guide

Protect your project by adding a fuse in your circuit to save it from molten destruction.


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

RedHat Instrument Kit Hookup Guide

$
0
0

RedHat Instrument Kit Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

How can open source help us find new ways to express ourselves? In the RedHat Instrument Kit, you'll learn how conductivity works and use that understanding to create an interactive musical instrument. Conductive paint and ink will allow you to explore how physical design affects the way a tool is used. This experiment empowers participants to bring their own creative thinking to the world of sound and instruments. This activity is best suited for people between the ages of 10-13 and does not require any prior knowledge of circuits or skill in wiring or electronics. Given that some of the components are small and making connections requires a level of dexterity, younger students may need some adult assistance.

Required Materials

To follow along with this tutorial, you will need the RedHat Instrument Kit.

Red Hat Co.Lab Instrument Kit

Red Hat Co.Lab Instrument Kit

CUST-18432
$24.95

If you wish to purchase the individual parts for this as refill or expansion, here is a list:

You Will Also Need

You will need materials that didn’t come with your kit (paper and a pair of scissors).

Suggested Reading

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

What is a Circuit?

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

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.

Hardware Overview

It’s always helpful to know the parts you’ll be using before diving into the build. Go ahead and lay the parts out in front of you on a piece of paper. As you lay them out, pick them up and explore each one. How many pins does it have? What colors are on it? Is each leg of the component the same length? Can you guess what it does, based on how it looks or what it's called? You should write these observations down next to each part. That will help you organize the pieces as we begin to explore and build. This is what you should have:

Labelled overview of parts in the kit

Having a hard time seeing everything? Click the image for a closer look.

Breadboard

Let’s start by taking a look at the breadboard in your kit. First, notice there are two long columns of holes running down each side of the board, one with a red line beside it, and one with a black line. These are the power rails, and all the holes in a single power rail are connected to each other. If power is connected to one hole in the column, it's connected to all the other holes in the column.

Second, all the holes in a numbered row are connected to each other, but this connection is broken at the small trench or indent that runs down the center of the board. Each side COULD be its own separate circuit. Our project will jump over the trench using jumper wires and send power back and forth.

Basically, you can view a breadboard as a series of columns (labeled A-E and F-J) and rows (labeled 1-30.) And remember, the trench in the middle means A5 isn’t connected to F5. When we get to actually creating the circuit, we’ll use this row-and-column system to mark where connections should be made (A6, E3, H23, etc.).

Image of the breadboard

For more information on how to Use a Breadboard, feel free to head on over to our tutorial here, or click on the breadboard image below.

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.

555 timer

A 555 circuit’s use is so open-ended that contests are held to see who can conceive of the most useful, complex, and/or artistic use of the thing. Every sound we hear from an instrument is made of a waveform. The pitch (how high or low a note sounds to our ears) changes with the number of times a wave occurs in a second. With the 555 at the heart of our circuit, (and a handful of choice resistors and capacitors) we can create waveforms that oscillate at frequencies from thousandths to hundreds of thousandths of a second. That’s a lot of waves per second!

Product image for the 555 timer

Capacitor

A capacitor is a two-terminal, electrical component. Along with resistors and inductors, they are one of the most fundamental passive components we use. You would have to look very hard to find a circuit which didn't have a capacitor in it. What makes capacitors special is their ability to store energy; they're like a fully charged electric battery. Caps, as we usually refer to them, have all sorts of critical applications in circuits. Common applications include local energy storage, voltage spike suppression, and complex signal filtering.

Product image for the Capacitor Ceramic

For more information on capacitors and their uses, feel free to head on over to our tutorial here, or click on the Capacitor image below.

Capacitors

Learn about all things capacitors. How they're made. How they work. How they look. Types of capacitors. Series/parallel capacitors. Capacitor applications.

Speaker

This little guy is similar to what you'd find in one of those singing greeting cards. Thin and flat, and able to make just enough noise for our project.

Image of the speaker

Resistors

Resistors are electronic components which have a specific, never-changing electrical resistance. The resistor's resistance limits the flow of electrons through a circuit. For a basic description, this is good enough, but if you would like to delve into the world of resistors and Ohm's law.

Product image for the Resistor 1K Ohm

Consider checking out this tutorial or click on the image below:

Resistors

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.

Jumper Wires

Jumper wires help a circuit "jump" from one location to another. Hence the name "jumper wire". Pretty nifty eh? The end ports can be male or female - in this tutorial you'll be using Male to Male jumpers, meaning both ends have plugs on them.

Product photo of jumper wires

Alligator Clip Jumper Wires

These guys are just like Jumper Wires, except that they are pre-terminated with an alligator clip on one end and a hookup pigtail on the other. Like so:

Product photo for Alligator Clips

Electric Paint

Bare Conductive's Electric Paint is just like any other water-based paint... except that it's electrically conductive. This means that you can actually paint wires onto things like models, clothes, furniture, walls, almost anything you can think of. In this case, we'll be using it to draw our instrument. Check out the video below for more information on our conductive paint...

If that nifty little video didn't sate your need for information, see the datasheet for more in-depth info.

There are other parts in this kit, but this is the bulk of what you'll need to know for this tutorial. Let's get to building!

Part 1: Drawing your Instrument

What is an instrument? This is kind of a weird question, right? Really, a musical instrument is anything you can use to produce sound. Guitars, gourds, seashells, pianos ― used the right way, they can all be instruments.

For the purposes of this kit, a musical instrument is a device that lets us make sounds and control their pitch ― how high or low they are. Using your conductive paint/ink, make a long line on your piece of paper. Be sure to draw at least one solid block of ink near the edge of the paper. You’ll be able to redesign your instrument later and be really creative in how it takes shape, but for now just make a thin line.

Image of a thin line drawn with bare conductive electric paint

Image courtesy of RedHat

Part 2: Breadboarding, 555 timer, and potentiometer

What is a circuit? A circuit is a closed loop that electricity can travel around. At its most basic, a circuit consists of three parts:

  • A voltage source: The power for the circuit
  • A load: The thing that is being powered, like a motor, buzzer, or light
  • The circuit path: The continuous path that the current follows as it travels around the circuit

An example of a simple circuit would be a power source (like a battery), a load (like an LED), and the circuit path (the wires that connect them).

The power/voltage source

Your kit comes with a 9V battery and 9V snap connector to be used as a power/voltage source. You'll notice that the snap connector has a plastic connector ― the small, white, rectangular box at the end of the red and black wires. This makes it easy to connect to many types of electronics; however, we won’t be using it for our project today. We’ll actually connect the power to the breadboard with jumper wires. The jumper wires in your kit have small metal pins on either side.

The colors of the jumper wires don’t correspond to anything in your kit. Use any two colors that you prefer. That said, make sure you keep track of which jumper is positive and which jumper is negative. By convention, the red jumpers are positive, and the black jumpers are negative/ground.

There are two holes in the plastic molding at the end of the wires coming from the battery pack. Insert a jumper wire into each of these holes like so:

Battery and snap connector with jumper wires inserted into the
Image courtesy of RedHat

Now insert the other ends into the (+) power rail and the (-) power rail - again making sure that your positive jumper goes to the (+) side of the power rail and the negative jumper goes to the (-) side of the power rail:

Battery and jumpers hooked into the breadboard

Image courtesy of RedHat

The load

For this circuit, we'll use a 555 circuit attached to a speaker triggered by a potentiometer. Potentiometers can take multiple shapes. Sometimes, we might see them as knobs that we turn, like volume knobs on radios. Other times, they look like faders that slide up and down; think of some dimmable light switches. They can give us control over things like speed, voltage, or frequency in our circuit kits. As we make adjustments to our knob or fader, we are changing the amount of resistance that a circuit is passing.

For our circuit, we’ll draw our potentiometer using conductive paint or ink. Since we know that circuits are continuous devices, we’ll have to make sure that, whatever instrument we draw, all the lines connect somehow. The ink we used to draw our line above will serve as our potentiometer.

Our circuit culminates in the speaker. If you’ve used headphones or earbuds, or watched TV, you have a pretty good idea what speakers are capable of. For our purposes, the speaker converts the electrical audio signal (in the form of sound waves) from our 555 timer into sound. This is the same basic principle that a guitar amplifier or movie theater sound system uses.

Outline of breadboard hooked to the circuit including the speaker

Image courtesy of RedHat

The circuit path

For a circuit to work, the path of the power can’t be interrupted — every piece must connect with another piece. Luckily, we have a breadboard, which is a helpful tool we can use to quickly plug in items and keep them connected. It also lets us create, fix small mistakes, and practice with our components.

Fritzing like image of the circuit

Image courtesy of RedHat

We're going to replicate this circuit (the steps are below). We’re using quite a few jumper wires, so be extra careful to place them into the appropriate coordinate points on your breadboard. We’ll save the special alligator clip connections for last. We’ll use both sides of our breadboard, so remember that each side has a positive (+) and negative (-) power rail, as well as its own unique set of column connections. The left hand columns are labeled A-E, and the right hand columns are F-J.

Create your circuit:

  • Place the 555 timer circuit so that one set of pins aligns with E9-E12 and the other set aligns with F9-F12. This will mean that the 555 timer bridges the center trench/gap. Gently press into place.
  • Connect a jumper wire from positive power (+) rail 2 on the left side to positive power (+) rail 2 on the right side
  • Connect a jumper wire from negative power (-) rail 2 on the left side to the negative power (-) rail 2 on the right side
  • On the left side, connect a jumper wire from negative power (-) rail 9 to A9
  • On the right side, connect a jumper wire from positive power rail (+) 9 to i9
  • Connect a jumper wire from D10 to G11
  • On the left side, connect a jumper wire from positive power rail (+) 11 to A12
  • On the right side, place the resistor so that it bridges between H10 and positive power rail (+) 10
  • On the left side, place a capacitor so that it bridges between C11 and B16
  • On the right side, place a capacitor so that it bridges between i11 and the negative power rail (-) 13
  • On the left side, connect the pin end of an alligator clip jumper wire to A16 and clip the other end to the positive wire (+) of the speaker
  • On the left side, connect the pin end of an alligator clip jumper wire to negative power rail (-) 15 and clip the other end to the negative wire (-) of the speaker
  • On the right side, connect the pin end of an alligator clip jumper wire to H11 and clip the other end to the ink block on the edge of your drawing paper
  • On the right side, connect the pin end of an alligator clip jumper wire to G10

Testing

Once you complete the steps above and place the battery into the pack, you can play the ink like an instrument! To test your build, simply take the loose end of the final alligator clip jumper wire and tap it against any part of the conductive ink/paint line.

gif showing the alligator clip touching different parts of the conductive ink line

Image courtesy of RedHat

Redesign your instrument

Now that you see how the system works, take some time to redesign your instrument any way you want. Just remember that it’s best to have a small block of conductive ink on the edge of your piece of paper to anchor the clip to. After you redesign your instrument, all you have to do is reclip the alligator wire that was previously on the edge of your paper with the straight line to the edge of the paper with the new instrument. Tap away!

image of whole system put together

Image courtesy of RedHat

Troubleshooting

Here are some things to look for if your project isn't working. Also, ScienceBuddies.org has a great exploration of common mistakes people make with breadboards.

If your LED won’t light up

  • Check your connections
    • Be sure to double-check the coordinates in the instructions to make sure the pins are completely inserted into the matching holes on the breadboard
    • Make sure components are fully seated in the breadboard. A component should go into the breadboard at least 4-5 mm (or a little less than the thickness of a pencil) when it's fully inserted.
    • Check for short circuits. When components get connected accidentally, it can cause a short.
    • Check the polarity of the capacitors and make sure they match the instructions
  • Check your power
    • Make sure your batteries are fully inserted
    • Make sure your batteries work

Replacement Parts

Sometimes, things break or get lost ― it's part of making and tinkering. If you need to replace a part, refer to the wishlist in the introduction of this guide to purchase any individual components that make up the Red Hat Co.Lab Instrument kit that you might need.

Resources and Going Further

After you’ve built your instrument, check out the Red Hat Open Source Stories film, Art of Exchange. This film shows the role open source plays in the shaping and sharing of new ideas.

Want more? Check out additional Co.Lab kits at red.ht/colab-kits.


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

Red Hat Instrument Kit Hookup Guide

$
0
0

Red Hat Instrument Kit Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

How can open source help us find new ways to express ourselves? In the Red Hat Instrument Kit, you'll learn how conductivity works and use that understanding to create an interactive musical instrument. Conductive paint and ink will allow you to explore how physical design affects the way a tool is used. This experiment empowers participants to bring their own creative thinking to the world of sound and instruments. This activity is best suited for people between the ages of 10-13 and does not require any prior knowledge of circuits or skill in wiring or electronics. Given that some of the components are small and making connections requires a level of dexterity, younger students may need some adult assistance.

Required Materials

To follow along with this tutorial, you will need the Red Hat Instrument Kit.

Red Hat Co.Lab Instrument Kit

Red Hat Co.Lab Instrument Kit

CUST-18432
$24.95

If you wish to purchase the individual parts for this as refill or expansion, here is a list:

You Will Also Need

You will need materials that didn’t come with your kit (paper and a pair of scissors).

Suggested Reading

If you are not familiar with the following concepts, we recommend checking out these tutorials before continuing.

What is a Circuit?

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

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.

Hardware Overview

It’s always helpful to know the parts you will be using before diving into the build. Go ahead and lay the parts out in front of you on a piece of paper. As you lay them out, pick them up and explore each one. How many pins does it have? What colors are on it? Is each leg of the component the same length? Can you guess what it does, based on how it looks or what it's called? You should write these observations down next to each part. That will help you organize the pieces as we begin to explore and build. This is what you should have:

Labelled overview of parts in the kit

Having a hard time seeing everything? Click the image for a closer look.

Breadboard

Let’s start by taking a look at the breadboard in your kit. First, notice there are two long columns of holes running down each side of the board, one with a red line beside it, and one with a black line. These are the power rails, and all the holes in a single power rail are connected to each other. If power is connected to one hole in the column, it is connected to all the other holes in the column.

Second, all the holes in a numbered row are connected to each other, but this connection is broken at the small trench or indent that runs down the center of the board. Each side COULD be its own separate circuit. Our project will jump over the trench using jumper wires and send power back and forth.

Basically, you can view a breadboard as a series of columns (labeled A-E and F-J) and rows (labeled 1-30.) And remember, the trench in the middle means A5 isn’t connected to F5. When we get to actually creating the circuit, we’ll use this row-and-column system to mark where connections should be made (A6, E3, H23, etc.).

Image of the breadboard

For more information on how to Use a Breadboard, feel free to head on over to our tutorial here, or click on the breadboard image below.

How to Use a Breadboard

May 14, 2013

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.

555 timer

A 555 circuit’s use is so open-ended that contests are held to see who can conceive of the most useful, complex, and/or artistic use of the thing. Every sound we hear from an instrument is made of a waveform. The pitch (how high or low a note sounds to our ears) changes with the number of times a wave occurs in a second. With the 555 at the heart of our circuit, (and a handful of choice resistors and capacitors) we can create waveforms that oscillate at frequencies from thousandths to hundreds of thousandths of a second. That’s a lot of waves per second!

Product image for the 555 timer

Capacitor

A capacitor is a two-terminal, electrical component. Along with resistors and inductors, they are one of the most fundamental passive components we use. You would have to look very hard to find a circuit which did not have a capacitor in it. What makes capacitors special is their ability to store energy; they are like a fully charged electric battery. Caps, as we usually refer to them, have all sorts of critical applications in circuits. Common applications include local energy storage, voltage spike suppression, and complex signal filtering.

Product image for the Capacitor Ceramic

For more information on capacitors and their uses, feel free to head on over to our tutorial here, or click on the Capacitor image below.

Capacitors

June 19, 2013

Learn about all things capacitors. How they're made. How they work. How they look. Types of capacitors. Series/parallel capacitors. Capacitor applications.

Speaker

This little guy is similar to what you'd find in one of those singing greeting cards. Thin and flat, and able to make just enough noise for our project.

Image of the speaker

Resistors

Resistors are electronic components which have a specific, never-changing electrical resistance. The resistor's resistance limits the flow of electrons through a circuit.

Product image for the Resistor 1K Ohm

For a basic description, this is good enough, but if you would like to delve into the world of resistors and Ohm's law, consider checking out this tutorial or click on the image below:

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.

Jumper Wires

Jumper wires help a circuit "jump" from one location to another. Hence the name "jumper wire". Pretty nifty eh? The end ports can be male or female - in this tutorial you'll be using Male to Male jumpers, meaning both ends have plugs on them.

Product photo of jumper wires

Alligator Clip Jumper Wires

These guys are just like Jumper Wires, except that they are pre-terminated with an alligator clip on one end and a hookup pigtail on the other. Like so:

Product photo for Alligator Clips

Electric Paint

Bare Conductive's Electric Paint is just like any other water-based paint... except that it's electrically conductive. This means that you can actually paint wires onto things like models, clothes, furniture, walls, almost anything you can think of. In this case, we will be using it to draw our instrument. Check out the video below for more information on our conductive paint...

If that nifty little video didn't sate your need for information, see the datasheet for more in-depth info.

There are other parts in this kit, but this is the bulk of what you'll need to know for this tutorial. Let's get to building!

Part 1: Drawing your Instrument

What is an instrument? This is kind of a weird question, right? Really, a musical instrument is anything you can use to produce sound. Guitars, gourds, seashells, pianos ― used the right way, they can all be instruments.

For the purposes of this kit, a musical instrument is a device that lets us make sounds and control their pitch ― how high or low they are. Using your conductive paint/ink, make a long line on your piece of paper. Be sure to draw at least one solid block of ink near the edge of the paper. You’ll be able to redesign your instrument later and be really creative in how it takes shape, but for now just make a thin line.

Image of a thin line drawn with bare conductive electric paint

Image courtesy of Red Hat

Part 2: Breadboarding, 555 timer, and potentiometer

What is a circuit? A circuit is a closed loop that electricity can travel around. At its most basic, a circuit consists of three parts:

  • A voltage source: The power for the circuit
  • A load: The thing that is being powered, like a motor, buzzer, or light
  • The circuit path: The continuous path that the current follows as it travels around the circuit

An example of a simple circuit would be a power source (like a battery), a load (like an LED), and the circuit path (the wires that connect them).

The power/voltage source

Your kit comes with a 9V battery and 9V snap connector to be used as a power/voltage source. You'll notice that the snap connector has a plastic connector ― the small, white, rectangular box at the end of the red and black wires. This makes it easy to connect to many types of electronics; however, we won’t be using it for our project today. We’ll actually connect the power to the breadboard with jumper wires. The jumper wires in your kit have small metal pins on either side.

The colors of the jumper wires don’t correspond to anything in your kit. Use any two colors that you prefer. That said, make sure you keep track of which jumper is positive and which jumper is negative. By convention, the red jumpers are positive, and the black jumpers are negative/ground.

There are two holes in the plastic molding at the end of the wires coming from the battery pack. Insert a jumper wire into each of these holes like so:

Battery and snap connector with jumper wires inserted into the
Image courtesy of Red Hat

Now insert the other ends into the (+) power rail and the (-) power rail - again making sure that your positive jumper goes to the (+) side of the power rail and the negative jumper goes to the (-) side of the power rail:

Battery and jumpers hooked into the breadboard

Image courtesy of Red Hat

The load

For this circuit, we will use a 555 circuit attached to a speaker triggered by a potentiometer. Potentiometers can take multiple shapes. Sometimes, we might see them as knobs that we turn, like volume knobs on radios. Other times, they look like faders that slide up and down; think of some dimmable light switches. They can give us control over things like speed, voltage, or frequency in our circuit kits. As we make adjustments to our knob or fader, we are changing the amount of resistance that a circuit is passing.

For our circuit, we’ll draw our potentiometer using conductive paint or ink. Since we know that circuits are continuous devices, we’ll have to make sure that, whatever instrument we draw, all the lines connect somehow. The ink we used to draw our line above will serve as our potentiometer.

Our circuit culminates in the speaker. If you’ve used headphones or earbuds, or watched TV, you have a pretty good idea what speakers are capable of. For our purposes, the speaker converts the electrical audio signal (in the form of sound waves) from our 555 timer into sound. This is the same basic principle that a guitar amplifier or movie theater sound system uses.

Outline of breadboard hooked to the circuit including the speaker

Image courtesy of Red Hat

The circuit path

For a circuit to work, the path of the power can’t be interrupted — every piece must connect with another piece. Luckily, we have a breadboard, which is a helpful tool we can use to quickly plug in items and keep them connected. It also lets us create, fix small mistakes, and practice with our components.

Fritzing like image of the circuit

Image courtesy of Red Hat

We are going to replicate this circuit (the steps are below). We’re using quite a few jumper wires, so be extra careful to place them into the appropriate coordinate points on your breadboard. We’ll save the special alligator clip connections for last. We’ll use both sides of our breadboard, so remember that each side has a positive (+) and negative (-) power rail, as well as its own unique set of column connections. The left hand columns are labeled A-E, and the right hand columns are F-J.

Create your circuit:

  • Place the 555 timer circuit so that one set of pins aligns with E9-E12 and the other set aligns with F9-F12. This will mean that the 555 timer bridges the center trench/gap. Gently press into place.
  • Connect a jumper wire from positive power (+) rail 2 on the left side to positive power (+) rail 2 on the right side
  • Connect a jumper wire from negative power (-) rail 2 on the left side to the negative power (-) rail 2 on the right side
  • On the left side, connect a jumper wire from negative power (-) rail 9 to A9
  • On the right side, connect a jumper wire from positive power rail (+) 9 to i9
  • Connect a jumper wire from D10 to G11
  • On the left side, connect a jumper wire from positive power rail (+) 11 to A12
  • On the right side, place the resistor so that it bridges between H10 and positive power rail (+) 10
  • On the left side, place a capacitor so that it bridges between C11 and B16
  • On the right side, place a capacitor so that it bridges between i11 and the negative power rail (-) 13

Connecting the Alligator Clip Jumper Wires

  • On the left side, connect the pin end of an alligator clip jumper wire to A16 and clip the other end to the positive wire (+) of the speaker
  • On the left side, connect the pin end of an alligator clip jumper wire to negative power rail (-) 15 and clip the other end to the negative wire (-) of the speaker
  • On the right side, connect the pin end of an alligator clip jumper wire to H11 and clip the other end to the ink block on the edge of your drawing paper
  • On the right side, connect the pin end of an alligator clip jumper wire to G10

Testing

Once you complete the steps above and place the battery into the pack, you can play the ink like an instrument! To test your build, simply take the loose end of the final alligator clip jumper wire and tap it against any part of the conductive ink/paint line.

gif showing the alligator clip touching different parts of the conductive ink line

Image courtesy of Red Hat

Redesign your instrument

Now that you see how the system works, take some time to redesign your instrument any way you want. Just remember that it’s best to have a small block of conductive ink on the edge of your piece of paper to anchor the clip to. After you redesign your instrument, all you have to do is reclip the alligator wire that was previously on the edge of your paper with the straight line to the edge of the paper with the new instrument. Tap away!

image of whole system put together

Image courtesy of Red Hat

Troubleshooting

Here are some things to look for if your project isn't working. Also, ScienceBuddies.org has a great exploration of common mistakes people make with breadboards.

Check your connections

  • Be sure to double-check the coordinates in the instructions to make sure the pins are completely inserted into the matching holes on the breadboard
  • Make sure components are fully seated in the breadboard. A component should go into the breadboard at least 4-5 mm (or a little less than the thickness of a pencil) when it's fully inserted.
  • Check for short circuits. When components get connected accidentally, it can cause a short.
  • Check the polarity of the capacitors and make sure they match the instructions

Check your power

  • Make sure your batteries are fully inserted
  • Make sure your batteries work

Replacement Parts

Sometimes, things break or get lost ― it's part of making and tinkering. If you need to replace a part, refer to the wishlist in the introduction of this guide to purchase any individual components that make up the Red Hat Co.Lab Instrument kit that you might need.

Resources and Going Further

After you’ve built your instrument, check out the Red Hat Open Source Stories film, Art of Exchange. This film shows the role open source plays in the shaping and sharing of new ideas.

Want more? Check out additional Red Hat Co.Lab kits at red.ht/colab-kits.


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


Tsunami Super WAV Trigger Hookup Guide

$
0
0

Tsunami Super WAV Trigger Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

NOTE: This guide is for the Tsunami Super WAV Trigger (Qwiic). For the previous version of this board, the Tsunami Super WAV Trigger (without a Qwiic connector), please refer to the original Tsunami hookup guide.

NOTE: This can be a relatively complex and overwhelming product for novice users, due to the numerous configuration options that make it so versatile. Novice users, may want to consider the WAV Trigger or MP3 Trigger first.


WAV Trigger

WAV Trigger

WIG-13660
$55.95
34
MP3 Trigger

MP3 Trigger

WIG-13720
$49.95
16

The Tsunami Super WAV Trigger (Qwiic) is a polyphonic WAV file player that was developed in collaboration with Robertsonics(a portion of each sale goes back to them for product support and development). The Tsunami Super WAV Trigger (Qwiic) is an improved version of the Tsunami Super WAV Trigger (the bigger brother of the WAV Trigger), which can now, be controlled through the Qwiic connect system.

Tsunami Super WAV Trigger (Qwiic)

Tsunami Super WAV Trigger (Qwiic)

WIG-18159
$79.95

Users familiar with the original Tsunami, will notice a few improvements to the Qwiic Tsunami:

  • Input Voltage: 5 - 10V
    • USB-C Connector
  • RGB Status LED
  • I2C Control
    • Qwiic Connector
  • New Audio Codec
  • Digital Filters

Comparison Table

Tsunami WAV Trigger (Qwiic)Tsunami WAV TriggerWAV Trigger
Power
  • Range:
  • Inputs:

5 - 10V
USB-C and PTH

5 - 15V
micro-B USB and PTH

6 - 15V
DC Barrel Jack
Tracks
  • Number:
  • Layer Mixing:
Up to:
4096 uncompressed files
  • 18 stereo WAV files
  • 32 mono WAV files
Up to:
4096 uncompressed files
  • 18 stereo WAV files
  • 32 mono WAV files
Up to:
2048 uncompressed files
14 stereo WAV files
Audio Outputs 8-channel (Mono)
4-channel (Stereo)
8-channel (Mono)
4-channel (Stereo)
3.5mm TRRS Audio Jack
Speaker connector (PTH)
  • Mono amplifier
Audio InputLine-level stereoLine-level stereoNone
Control
  • Triggers:
  • Serial:
  • Qwiic (I2C):

16 (3.3V)
Yes (3.3V)
Yes (3.3V)

16 (3.3V)
Yes (3.3V)
N/A

16 (5V or 3.3V)
Yes (5V or 3.3V)
N/A
Status LEDRGBBlueRed
Hot Swap SD CardYes (with RESET button)Yes (with RESET button)No
Firmware Updatesvia SD cardvia SD cardvia serial port
MIDIDedicated I/O pinsDedicated I/O pinsPossible via serial port

Required Materials

The Qwiic Tsunami does need a few additional items, including a pair of(chorded)headphones, for users to get started with this tutorial. You may already have a few of these items, including the required USB-C cable, so feel free to modify your cart based on your needs.

Note: For the best results, we recommend Class 10 SD cards with a FAT16 or FAT32 file system format and a 32kB file allocation size. We recommend avoiding:
  • The 1GB SparkX SD Card, from our catalog, since it isn't a Class 10 card and can lead to reliability issues.
  • SD Cards with a capacity larger than 32GB, since it can be difficult to convert them to the FAT16 or FAT32 file system format with a 32kB file allocation size.
For more information on compatible SD cards, please check out the Robertsonics website.
Tsunami Super WAV Trigger (Qwiic)

Tsunami Super WAV Trigger (Qwiic)

WIG-18159
$79.95
microSD Card - 16GB (Class 10)

microSD Card - 16GB (Class 10)

COM-15051
$19.95
USB 3.1 Cable A to C - 3 Foot

USB 3.1 Cable A to C - 3 Foot

CAB-14743
$4.95
3
microSD USB Reader

microSD USB Reader

COM-13004
$4.95
10
SparkFun TRRS 3.5mm Jack Breakout

SparkFun TRRS 3.5mm Jack Breakout

BOB-11570
$3.95
6
IC Hook Test Leads

IC Hook Test Leads

CAB-00501
$8.95
3

There are other available from our catalog (click the button below to display).

SD Card Option
microSD Card with Adapter - 32GB (Class 10)

microSD Card with Adapter - 32GB (Class 10)

COM-14832
$24.95
Audio Component Options

Note: For the best results, we recommend connecting the audio output channels from the Qwiic Tsunami to an active amplifier when speakers are used. Otherwise, when speakers are connected directly to the Qwiic Tsunami, without boosting the signal power, users will notice a significant decrease in sound quality of the audio playback.

*Users can connect the audio output channels from any Tsunami board directly to headphones.

Depending on how user want to configure their audio system, some of these audio components might be of interest:
Audio Cable TRRS - 18" (pigtail)

Audio Cable TRRS - 18" (pigtail)

CAB-11580
$1.50
TRRS Audio Plug - 3.5mm (Metal)

TRRS Audio Plug - 3.5mm (Metal)

COM-15337
$0.95
Audio Plug - 3.5mm

Audio Plug - 3.5mm

COM-11143
$0.50
TRS Audio Plug - 3.5mm (Metal)

TRS Audio Plug - 3.5mm (Metal)

COM-15438
$0.95
Hamburger Mini Speaker

Hamburger Mini Speaker

COM-14023
$4.95
2
SparkFun Mono Audio Amp Breakout - TPA2005D1

SparkFun Mono Audio Amp Breakout - TPA2005D1

BOB-11044
$8.50
16
SparkFun Audio Amplifier Kit - STA540

SparkFun Audio Amplifier Kit - STA540

KIT-09612
17
SparkFun Noisy Cricket Stereo Amplifier - 1.5W

SparkFun Noisy Cricket Stereo Amplifier - 1.5W

DEV-14475
$11.50
1
SparkFun TRRS 3.5mm Jack Breakout

SparkFun TRRS 3.5mm Jack Breakout

BOB-11570
$3.95
6
Audio Jack 3.5mm

Audio Jack 3.5mm

PRT-08032
$1.50
4
MIDI Connector - Female Right Angle

MIDI Connector - Female Right Angle

PRT-09536
$1.95
1
Audio Jack - 1/4" Stereo (right angle)

Audio Jack - 1/4" Stereo (right angle)

COM-11144
$0.95
1
SparkFun Audio Jack Breakout

SparkFun Audio Jack Breakout

PRT-10588
$0.95
1
SparkFun TRS Jack Breakout - 1/4" Stereo

SparkFun TRS Jack Breakout - 1/4" Stereo

BOB-13005
1Retired
Trigger Component Options
Depending on how users intend to trigger or control the audio playback, users may want to check out the switches and buttons categories from our catalog. Additionally, users can also trigger/control the Qwiic Tsunami through serial and I2C communication.
SparkFun Qwiic Twist - RGB Rotary Encoder Breakout

SparkFun Qwiic Twist - RGB Rotary Encoder Breakout

DEV-15083
$22.95
1
SparkFun Serial Basic Breakout - CH340C and USB-C

SparkFun Serial Basic Breakout - CH340C and USB-C

DEV-15096
$8.95
7
Toggle Switch and Cover - Illuminated (Red)

Toggle Switch and Cover - Illuminated (Red)

COM-11310
$2.95
7
Magnetic Door Switch Set

Magnetic Door Switch Set

COM-13247
$3.50
Rocker Switch - SPST (round)

Rocker Switch - SPST (round)

COM-11138
$0.50
3
Metal Pushbutton - Momentary (16mm, White)

Metal Pushbutton - Momentary (16mm, White)

COM-11970
$5.95
SparkFun Qwiic Button - Green LED

SparkFun Qwiic Button - Green LED

BOB-16842
$3.95
1
Big Dome Pushbutton - Blue

Big Dome Pushbutton - Blue

COM-11274
$11.95
4
Concave Button - Black

Concave Button - Black

COM-09339
$2.50
3
Reed Switch - Insulated

Reed Switch - Insulated

COM-10601
$1.95
Momentary Button - Panel Mount (Yellow)

Momentary Button - Panel Mount (Yellow)

COM-11995
$0.95$0.50
1
Right Angle Tactile Button

Right Angle Tactile Button

COM-10791
$0.50
Soldering Equipment Options
For a more permanent installation, users might want to consider some soldering equipment and accessories:
Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
Hook-Up Wire - Assortment (Stranded, 22 AWG)

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

PRT-11375
$20.95
18
SparkFun Beginner Tool Kit

SparkFun Beginner Tool Kit

TOL-14681
$57.95
Header - 8-pin Female (PTH, 0.1")

Header - 8-pin Female (PTH, 0.1")

PRT-11895
$0.50

Below is a sample selection of our other headers and soldering tools in our catalog. For a full selection of our available Headers, Hook-Up Wire, or Soldering Tools, click on the associated link.

Weller WE1010 Soldering Station

Weller WE1010 Soldering Station

TOL-14734
$129.00
4
Insulated Silicone Soldering Mat

Insulated Silicone Soldering Mat

TOL-14672
$9.95
9
Solder Lead Free - 100-gram Spool

Solder Lead Free - 100-gram Spool

TOL-09325
$8.95
7
Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

TOL-14456
$14.95
13
Hook-Up Wire - Assortment (Solid Core, 22 AWG)

Hook-Up Wire - Assortment (Solid Core, 22 AWG)

PRT-11367
$19.95
35
Arduino Stackable Header - 8 Pin

Arduino Stackable Header - 8 Pin

PRT-09279
$0.50
Break Away Male Headers - Right Angle

Break Away Male Headers - Right Angle

PRT-00553
$1.95
5
Hook-up Stranded Wire - Black (22 AWG)

Hook-up Stranded Wire - Black (22 AWG)

PRT-08867
$2.95
Hook-up Stranded Wire - Red (22 AWG)

Hook-up Stranded Wire - Red (22 AWG)

PRT-08865
$2.95

Arduino Example

For the Arduino example, a RedBoard Qwiic Plus and Qwiic cable are required. There are also options for this example as well (click button below to toggle options).

SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
12
SparkFun RedBoard Plus

SparkFun RedBoard Plus

DEV-18158
$19.95
USB 3.1 Cable A to C - 3 Foot

USB 3.1 Cable A to C - 3 Foot

CAB-14743
$4.95
3
Qwiic Compatible Microcontrollers:
SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

DEV-15795
$19.95
4
SparkFun Thing Plus - ESP32 WROOM

SparkFun Thing Plus - ESP32 WROOM

WRL-15663
$20.95
7
SparkFun Thing Plus - SAMD51

SparkFun Thing Plus - SAMD51

DEV-14713
$19.95
2
SparkFun RedBoard Artemis

SparkFun RedBoard Artemis

DEV-15444
$19.95
8
In addition we also offer, Qwiic compatible stackable shields for microcontrollers and pHATs for single board computers (like the Raspberry Pi boards) that don't include a Qwiic connector.
SparkFun Qwiic Adapter

SparkFun Qwiic Adapter

DEV-14495
$1.50
1
SparkFun Qwiic Shield for Thing Plus

SparkFun Qwiic Shield for Thing Plus

DEV-16790
$4.25
SparkFun Qwiic Shield for Arduino Nano

SparkFun Qwiic Shield for Arduino Nano

DEV-16789
$4.25
SparkFun Qwiic Shield for Teensy

SparkFun Qwiic Shield for Teensy

DEV-17119
$4.25
1
You will also need a Qwiic cable to connect to your Qwiic device, choose a length that suits your needs.
Flexible Qwiic Cable - 500mm

Flexible Qwiic Cable - 500mm

PRT-17257
$1.95
Flexible Qwiic Cable - 200mm

Flexible Qwiic Cable - 200mm

PRT-17258
$1.50
Flexible Qwiic Cable - 100mm

Flexible Qwiic Cable - 100mm

PRT-17259
$1.50
Flexible Qwiic Cable - 50mm

Flexible Qwiic Cable - 50mm

PRT-17260
$0.95

Suggested Reading

Note: Robertsonics has a more detailed about this product on their Tsunami product page. Robertsonics also provides a cross-platform utility for generating Tsunami configuration files and updating the firmware. All of which, can be downloaded from the Robertsonics' Tsunami downloads page.

If you're unfamiliar with serial terminals, jumper pads, or I2C be sure to checkout some of these foundational tutorials.

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.

Analog vs. Digital

This tutorial covers the concept of analog and digital signals, as they relate to electronics.

Serial Terminal Basics

This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.

How to Solder: Through-Hole Soldering

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

SD Cards and Writing Images

How to upload images to an SD card for Raspberry Pi, PCDuino, or your favorite SBC.

MIDI Tutorial

Understanding the Musical Instrument Digital Interface.

Tsunami Hookup Guide

Hit the ground running with Tsunami, the Super Wav Trigger.

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.

Installing Arduino IDE

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

SparkFun Serial Basic CH340C Hookup Guide

SparkFun Serial Basic Breakout takes advantage of USB-C and is an easy-to-use USB-to-Serial adapter based on the CH340C IC from WCH. With USB-C you can get up to three times the power delivery over the previous USB generation and has the convenient feature of being reversable.

RedBoard Plus Hookup Guide

This tutorial covers the basic functionality of the RedBoard Plus. This tutorial also covers how to get started blinking an LED and using the Qwiic system.

Qwiic Connect System

The Tsunami Super WAV Trigger also utilizes the Qwiic connect system. We recommend familiarizing yourself with the Logic Levels and I2C tutorials (above) before using it. Click on the banner above to learn more about our Qwiic products.

Hardware Overview

Note: For more details on the Tsunami Super WAV Trigger (Qwiic) check out these resources from the Robertsonics website:

Board Dimensions

The dimensions for the Qwiic Tsunami are essentially the same as the original Tsunami. The overall board size is 2.95" x 2.925" (approx. 7.5cm x 7.4cm) and includes four 0.13" mounting holes, which are compatible with standard 4-40 screws.

board dimensions
The dimensions for the Qwiic Tsunami. (Click to enlarge)

Power

WARNING: The input voltage on the Qwiic Tsunami is limited to 5 - 10V; while the original Tsunami had a voltage range up to 15V. Users swapping or replacing boards should be aware of this change; exceeding the input voltage range will damage the board permanently.

There is a status LED to help make sure that the Qwiic Tsunami is getting power. On the Qwiic Tsunami, users can power the board through either the USB-C connector or the power breakout pins (VIN and GND). We recommend users power the board through the USB-C connector.

power connections
The power connections on the Qwiic Tsunami. (Click to enlarge)

The input voltage range for the power pins is 5V - 10V, but we recommend providing a 5V supply. The current draw from the Qwiic Tsunami is approximately 220mA (at 5V) at idle with an SD card inserted. When playing audio files, the current draw increases. (When testing, playing a single .wav file to a mono (single) channel output, the current draw spiked just past 240mA.)

By default, the board's power is isolated from the polarizedQwiic connector system. Although it isn't recommended, users can modify the 3V3_Qwiic jumper to draw power from the Qwiic connector (see jumper section below). The Qwiic system is meant to run on 3.3V, be sure that another voltage is NOT used with the Qwiic system.

Polyphonic Engine

The operation of the polyphonic engine on the Tsunami is proprietary to Robertsonics. While we can't go into exact details on how the board works, here are some highlights of the board:

primary components
The primary polyphonic engine components of the Qwiic Tsunami. (Click to enlarge)
  • Supports up to 4096 uncompressed 16-bit, 44.1kHz mono or stereo WAV files – CD quality
  • Polyphonic – Play and mix 32 mono or 18 stereo tracks independently and simultaneously
  • Dynamic routing to 8 mono or 4 stereo outputs
  • Seamless looping over arbitrary track length
  • Independent real-time volume and playback rate control per output
  • Pause and resume individual or groups of tracks
  • Minimal trigger-to-sound delay: 8 msecs typ, 12 msecs max
  • Trigger inputs can be individually inverted and set to be edge, latched, or level sensitive
  • Dedicated MIDI I/O
    • Assign individual MIDI notes to specific outputs, with individual looping control
    • Outputs provide independent real-time playback rate control and MIDI Pitch Bend
    • MIDI Velocity-sensitive triggering of up to 4096 tracks, adjustable attack and release times
  • Line-level stereo audio input
  • Output volumes adjustable from +10dB to -70dB
  • Firmware track fades (attacks & decays)
  • Extensive serial and I2C control (Default I2C address: 0x13)
  • Reset button allows changing SD cards without power-cycle
  • Firmware updates from microSD card. No additional hardware required

For more details, users can checkout the Tsunami product page on the Robertsonics website.

µSD Card Slot

Note: For the best results, we recommend Class 10 SD cards with a FAT16 or FAT32 file system format and a 32kB file allocation size. We recommend avoiding:
  • The 1GB SparkX SD Card, from our catalog, since it isn't a Class 10 card and can lead to reliability issues.
  • SD Cards with a capacity larger than 32GB, since it can be difficult to convert them to the FAT16 or FAT32 file system format with a 32kB file allocation size.
For more information on compatible SD cards, please check out the Robertsonics website.

A µSD card is used store the audio *.wav files and initialization tsunami.ini file (optional) for the Qwiic Tsunami. The µSD card slot contains a spring-loaded locking mechanism:

  • Insert the card and press in to lock the card into the slot.
  • Press in to unlock and remove the card from the slot.

SD card slot
The µSD card slot on the Qwiic Tsunami. (Click to enlarge)

Buttons

There are two buttons available on the Qwiic Tsunami.

  • RESET: Used to reset (reinitialize) the board after an SD card has been inserted.
  • USER: Used to update the firmware from the SD card.
    1. Hold the USER button down
    2. Insert SD card with new firmware tsunamix.hex file (can have normal operation *.wav and *.ini files)
    3. Press RESET button
    4. Wait for successful firmware update status indicator before releasing the USER button

buttons
The RESET and USER buttons on the Qwiic Tsunami. (Click to enlarge)

Status LED

New on the Qwiic Tsunami is the RGB status indication LED.

RGB LED
The RGB status LED on the Qwiic Tsunami. (Click to enlarge)

Along with this improvement is a whole list of status indicators for users:

  • After SD card is inserted and Tsunami is reset:
    • MicroSD card found and formatted correctly: 3 short green blinks, then idle state
    • Error Codes:
      • No microSD card: One long blue, then idle state
      • MicroSD card format error (card installed but can't read FAT): One long red, one short, then idle state
      • Audio hardware initialization error: One short red, repeats forever (continuous fast blinking red)
  • During normal operation:
    • System idle state: 1 very short blue (flash) every 3 seconds.
    • Audio playing: Solid green.
    • Error Codes:
      • Stereo wave file is triggered with the mono firmware, or a mono wave file is triggered with the stereo firmware: 1 long red
  • Bootloader operation (Updating firmware):
    • Firmware successfully updated: Solid green
    • Error Codes: (All bootloader blink codes, except success, repeat forever)
      • No microSD card: One long blue, repeats (slow blinking blue.)
      • MicroSD card format error (card installed but can't read FAT): One long red, one short red, repeats
      • No firmware hex file found, or incorrect file contents: One long red, two short reds, repeats
      • Flash write error (hardware error): One short red, repeats (fast blinking red.)
      • Firmware successfully updated: Solid green.

Breakout Pins

Note: All the trigger, serial control, and button pins operate with 3.3V logic. Do not provide 5V to any of these pins; it will permanently damage the board. The exception to this are the MIDI pins, which are opto-isolated.

There are a lot of breakout pins on the Qwiic Tsunami. While we won't cover them all, we'll discuss the pins with major functionality that users would normally interface with.

breakout pins
The breakout pins on the Qwiic Tsunami. (Click to enlarge)

Power Input

While we normally recommend that users power the Qwiic Tsunami through the USB-C connector, there are four power input pins on the bottom of the board for users, who wish to permanently attach an external power source. The input voltage range is 5 - 10V, but we recommend providing a 5V supply.

power input pins
The power input pins on the Qwiic Tsunami. (Click to enlarge)

Audio Pins

The audio pins support up to 7.1 channel surround sound (or 8 mono channels) output and stereo (or 2 mono channels) line-level input.

Output Channels
Note:

For impedance matching the audio output channels, the impedance of the speakers or amplifiers should be above 3.8k&ohm;.

There is significant frequency roll off at the ends of the high and low range of the audio output channels. Extended use in these ranges can potentially damage the audio codec chip.

The audio output channels can be configured as stereo or mono outputs. By default, the factory programmed firmware on the Qwiic Tsunami only supports mono .wav file playback and audio output channels will act independently as eight mono outputs. For the best results, users should be hooking up the audio outputs to an amplifier or active speakers, which include an internal amplifier.

audio output
The audio output pins on the Qwiic Tsunami. (Click to enlarge)
Input Channels

There are two line-level inputs on the Qwiic Tsunami. The inputs have capacitors to negate any DC offsets and are compatible with 1.1VPP signals.

audio input
The audio input pins on the Qwiic Tsunami. (Click to enlarge)

Trigger Pins

Note: Any inputs to the Qwiic Tsunami must use 3.3V logic-levels; otherwise, users risk permanently damaging their board.

The trigger pins are the primary inputs for the Qwiic Tsunami. They can be configured to trigger various actions on the Qwiic Tsunami. By default, the 16 trigger pins are active-high and are triggered by pulling the pins low.

trigger pins
The trigger pins on the Qwiic Tsunami. (Click to enlarge)

Serial Control

Note: Any inputs to the Qwiic Tsunami must use 3.3V logic-levels; otherwise, users risk permanently damaging their board.

Users have the option of controlling the Qwiic Tsunami through the serial pins. Users can directly connect a USB-to-serial UART bridge like the Serial Basic Breakout or they can connect a microcontroller like the RedBoard Qwiic Plus.

serial pins
The serial control pins on the Qwiic Tsunami. (Click to enlarge)

MIDI Pins

Note: The MIDI pins are the only exception to the 3.3V logic-level input voltage, as the pins are opto-isolated. Therefore, the pins can directly interface with the 5V logic levels of the MIDI standard.

The Qwiic Tsunami can be connected with MIDI controllers and instruments; users only need to solder the pins to a 5-pin DIN connector. For more details, users can checkout the Tsunami User Guide and tutorial on the Robertsonics website.

MIDI interface
The MIDI interface pins on the Qwiic Tsunami. (Click to enlarge)

Buttons

There are two PTH breakouts for the two user buttons. These allow users to solder on their own right-angle buttons for a panel mounted operation.

reset breakout pins
The reset breakout pins on the Qwiic Tsunami. (Click to enlarge)
user breakout pins
The user breakout pins on the Qwiic Tsunami. (Click to enlarge)

Qwiic Connector

Note: By default, the board's power is isolated from the Qwiic connector system. Although it isn't recommended, users can modify the 3V3 Qwiic jumper to draw power from the Qwiic connector. The Qwiic system is meant to run on 3.3V, be sure that another voltage is NOT used with the Qwiic system.

New for the Qwiic Tsunami, users can now control the board through the an I2C protocol. The polarized Qwiic connector allows users to easily interface with the Qwiic connect system. The Qwiic Tsunami’s default I2C address is 0x13 (7-bit).

Qwiicconnector
The Qwiic connector on the Qwiic Tsunami. (Click to enlarge)

I2C Jumpers

There are two jumpers on the Qwiic Tsunami:

  • I2C
  • 3V3_Qwiic

Cutting the I2C jumper will remove the 2.2kΩ pull-up resistors from the I2C bus. If you have many devices on your I2C bus you may want to remove these jumpers.

I2C jumper
The I2C pull-up resistor jumper on the Qwiic Tsunami. (Click to enlarge)

By default, the board's power is isolated from the Qwiic connector system. Bridging the 3V3_Qwiic jumper allows users to connect the board's power to the 3.3V input voltage of the Qwiic connect system.

3.3V power jumper
The 3.3V power jumper on the Qwiic Tsunami. (Click to enlarge)

Prepare the &micro;SD Card

Format the µSD Card

Note: For the best results, we recommend Class 10 SD cards with a FAT16 or FAT32 file system format and a 32kB file allocation size. We recommend avoiding:
  • The 1GB SparkX SD Card, from our catalog, since it isn't a Class 10 card and can lead to reliability issues.
  • SD Cards with a capacity larger than 32GB, since it can be difficult to convert them to the FAT16 or FAT32 file system format with a 32kB file allocation size.
For more information on compatible SD cards, please check out the Robertsonics website.

The µSD card is an integral part of the Qwiic Tsunami's operation. In order for the µSD card to be compatible with the Qwiic Tsunami:

  • A FAT16 or FAT32 file system must be used
  • The file allocation size must be 32 kilobytes

For a brand new card, formatting may not be necessary. However, if users experience the Qwiic Tsunami missing commands, making occasional strange buzzing sounds, or sometimes crashing, then the file allocation size may be incorrect. The Quick Format option in the Windows operating system is the usually the simplest method to properly format the µSD card.

Formatting an SD card with a Window OS
The format settings for a µSD card with a Windows operating system. (Click to enlarge)

µSD Card Contents

The contents of the microSD card are the key to how the Qwiic Tsunami operates. There are two types of files that the firmware on the Qwiic Tsunami will utilize: audio *.wav files and a tsunami.ini initialization file. The firmware on the Qwiic Tsunami, by default, is configured to operate in the following manner:

  1. Default firmware operation (filenames matching the trigger inputs, will output on the first audio output channel 1L).
  2. If there is a tsunami.ini file on the µSD card on reset, the Qwiic Tsunami will operate on its configuration content.
  3. Any additional changes via I2C or serial commands then take precedence over the initialization file.

Audio Files

The Qwiic Tsunami is designed to playback *.wav audio files from the &microSD card. However, the *wav files must be compatible with the firmware on the Qwiic Tsunami.

  • The audio format of *.wav files must be compatible with the firmware on the Qwiic Tsunami.
    • By default, the Qwiic Tsunami is factory programmed with the mono audio firmware and will only work with *.wav files in mono audio format.
  • The filenames if the *wav files must follow the naming convention utilized by the firmware for the Qwiic Tsunami to trigger the audio playback.
Audio File Format

The Qwiic Tsunami plays *.wav files recorded at 16-bit resolution, with a 44.1kHz sampling rate. Different firmware images allow for the playback of stereo or mono files. The Qwiic Tsunami also requires that the files not contain any additional header information. Some audio recording programs, such as Pro Tools, write additional information at the start of the file. An easy way to remove the unnecessary header information is to utilize Audacity. Users can use this software to export a file as WAV (Microsoft) signed 16-bit PCM and clear out the metadata containing the header infromation (i.e. title, artist, genre, etc.).

The following video gives a brief demonstration of the Audacity export process.

Exporting from Audacity to Tsunami. (Click to enlarge)
Note: For users curious about the header contents, Rail John Rogut has written the Header Investigator application, which can display Pro Tools region information and BWF time stamps. This extra data might be meaningful to DAW applications, but Tsunami doesn't use the information.
Naming Convention

The filenames contain the trigger input mapping for the Qwiic Tsunami. Each file should start with a three-digit number, which will assign it to a corresponding trigger input.

example trigger map

Example of a filename trigger mapping. (Click to enlarge)

In the example above, the firmware on the Qwiic Tsunami will correspond the filenames of the 16 files numbered 001 to 016 to each of the trigger inputs by default. The triggered *.wav files would be output on the first audio channel (1L).

Initialization File

Note: When creating an intialization *.ini file with the configuration tool, users should make sure to select the proper settings for the firmware on the Qwiic Tsunami. By default, the Qwiic Tsunami factory programmed firmware is configured for the mono setting and the configuration tool settings should match the image below:

example settings
. (Click to enlarge)

Below is a comparison of the configuration tool appearance between the mono and stereo settings. Users will notice that some of the audio channel output options are greyed-out in the stereo setting.

stereo setting
The stereo setting option for the configuration tool. (Click to enlarge)
mono setting
The mono setting option for the configuration tool. (Click to enlarge)

There is also an initialization file, tsunami.ini. The Qwiic Tsunami reads this file when it starts, to gather more details about how it should configure the trigger inputs. The *.ini files can be generated and edited using the Tsunami Configurator application. The files contain readable ASCII text, which can be created or edited with a text editor.

configuration tool

Tsunami configuration tool. (Click to enlarge)

More information about the configuration tool can be found in the Tsunami user guide.

Firmware

The firmware on the Qwiic Tsunami, by default, is configured to operate in the following manner:

  1. Default firmware operation (filenames matching the trigger inputs, will output on the first audio output channel 1L).
  2. If there is a tsunami.ini file on the µSD card on reset, the Qwiic Tsunami will operate on its configuration content.
  3. Any additional changes via I2C or serial commands then take precedence over the initialization file.

Updating the Firmware

When necessary, users can easily update the firmware by saving the file to the µSD card. The latest firmware for the Qwiic Tsunami can be found on Robertsonics website. The file name needs to be changed to tsunami.hex for the bootloader to upload the new firmware. Once the files is saved onto the µSD card, users need to follow the following procedures to update the firmware on the board:

  1. Hold the USER button down
  2. Insert SD card with new firmware tsunamix.hex file (can have normal operation *.wav and *.ini files)
  3. Press RESET button
  4. Wait for successful firmware update status indicator before releasing the USER button
    • When the status LED is a solid green, the firmware update is complete.

Example Files

For the examples in the following section, users will need to prepare their card with the demonstration files we provide.

  1. Download the example files using the link below.
    button needs text, url
  2. Unzip the folder and put the files on the root directory of the card.
  3. Verify the files on the &microSD card.
    Files on the card
    Files on the card

Hardware Assembly

Basic Operation

The basic operation of the Qwiic Tsunami only requires the use of the trigger pins to interact with the board. For the example in the next section, users must insert their configured µSD card with *.wav files and connect their headphones to the Qwiic Tsunami.

Inserting the µSD Card

Inserting the µSD card, prepared from the previous section, is straight forward. The µSD card slot contains a spring-loaded locking mechanism:

  • Insert the card and press in to lock the card into the slot.
  • Press in to unlock and remove the card from the slot.

inserting an SD card
The inserting an µSD card into the Qwiic Tsunami.

Connecting the Headphone Jack

Note: If users experience problems with the audio output to their headphones, there are different headphone connector standards that might be the issue. If that is the case, users only need to swap the connection from SLEEVE pin on TRRS 3.5mm breakout board to the RING2 pin.

different headphone jack standards
Two of the more common variations of the headphone jack connection standards. (Click to enlarge)
Source: quora.com

This part of the guide will demonstrate how to temporarily connect a pair of headphones to the audio output channels of the Qwiic Tsunami with the IC hook cables. Connect the TRRS 3.5mm jack breakout board to the Qwiic Tsunami, as illustrated below:

  • Connect three of the IC hook cables to the TIP, RING1, and SLEEVE pins on the TRRS headphone jack breakout board.
    attaching IC hooks to audio jack
    Attaching the IC hooks to the TRRS headphone jack breakout board. (Click to enlarge)
    closeup of IC hook connection
    A close up of the IC hooks connected to the pins of the breakout board. (Click to enlarge)
  • Connect the other end of the cables to the 1L, 1R, and GND audio output pins of the Qwiic Tsunami.
    attaching IC hooks to the audio output
    Attaching the IC hooks to the audio output channels of the Qwiic Tsunami. (Click to enlarge)

Below, is a table summarizing the cable connections between the Qwiic Tsunami's pins and the TRRS 3.5mm jack breakout board's pins:

Qwiic TsunamiTRRS Breakout Board
Cable 11LTIP
Cable 21RRING1
Cable 3AGNDSLEEVE

Finally, users will need to connect their headphones to the TRRS 3.5mm jack breakout board. The overall hardware assembly should resemble the image below:

completed assembly
Completed assembly with headphones attached and the Qwiic Tsunami powered through a USB cable. (Click to enlarge)

For a more permanent solution, users can solder the boards together with hook-up wire.

Assembly for Arduino (Qwiic) Example

The assembly for the example in the Arduino library section is similar to the previous assembly. Users only need to connect their RedBoard Plus to the Qwiic Tsunami with a Qwiic cable. The RedBoard Plus should also be connected to their computer with a USB cable.

Assembly for Arduino library example
The assembly for the Arduino library example, with the Redboard Plus connected to the Qwiic Tsunami. (Click to eleagre)

MIDI

Users interested in connecting the Qwiic Tsunami to other MIDI devices will need to solder the MIDI pins to a 5-pin DIN connector. For more information, users can check out the original Tsunami hookup guide, our MIDI tutorial, and the Tsunami user guide.

MIDI connection
Attaching a MIDI connector to the Qwiic Tsunami. (Click to enlarge)
close up of MIDI connector pins
A close up of the MIDI connector pins. (Click to enlarge)

Basic Operation Example

Note: The default firmware is for mono channel operation; therefore, users should only expect audio ouput on one side of their headphone. Users can use the configuration tool to create an initialization file to modify the default operation.

If users experience problems with the audio output to their headphones, there are different headphone connector standards that might be the issue. If that is the case, users only need to swap the connection from SLEEVE pin on TRRS 3.5mm breakout board to the RING2 pin.

different headphone jack standards
Two of the more common variations of the headphone jack connection standards. (Click to enlarge)
Source: quora.com

The simplest way to utilize the Qwiic Tsunami is with the trigger pins. The trigger pins are active-high by default; therefore, the pins need to be shorted to ground for the board to react. As a simple demonstration, use one of the IC hook cables to bridge a trigger input to the corresponding ground pads:

basic demonstration

Triggering the Qwiic Tsunami to play a *.wav file. (Click to enlarge)

Once the wire makes contact, users should hear a sound on the output on one side of the headphone. The provided demonstration *.wav files are recordings of someone reciting the number of the trigger input. Users should also see the status LED illuminate green while a file is playing.

In a more permanent installation users could connect momentary switches, like this large push button.

Arduino Libraries and Example

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.

Arduino Libraries

The Qwiic Tsunami is a unique product, in that two different Arduino libraries are available to control the board. For more information on how to install an Arduino library in the Arduino IDE, check out our tutorial below.

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.

Serial Control

As with the original Tsunami, the Qwiic Tsunami can also be controlled from the serial connection with the Tsunami Arduino serial library. For more details on how to utilize this library, please refer to the Tsunami user guide and tutorial, which are available on the Robertsonics website.

I2C (Qwiic) Control

Unlike the original Tsunami, the Qwiic Tsunami now has a Qwiic connector; and therefore, the board can be controlled with I2C, through the Qwiic connect system, using the SparkFun Tsunami Qwiic Arduino library.

SparkFun Tsunami Qwiic Arduino Library in library manager
The SparkFun Tsunami Qwiic Arduino Library in the Arduino library manager. Click to enlarge)

Users can install this library through the Arduino Library Manager. Search for SparkFun Tsunami Qwiic Arduino Library and you should be able to install the latest version. Users who prefer manually downloading the libraries from the GitHub repository, can download it here:

The utilization of this library mimics the serial control version to allow users to easily transition between the two. For more details on how to use this library, users can check out the documentation from the serial control library and the Tsunami user guide.

Tsunami Qwiic Arduino Library Example

Note: If users experience problems with the audio output to their headphones, there are different headphone connector standards that might be the issue. If that is the case, users only need to swap the connection from SLEEVE pin on TRRS 3.5mm breakout board to the RING2 pin.

different headphone jack standards
Two of the more common variations of the headphone jack connection standards. (Click to enlarge)
Source: quora.com

Once you've got the Qwiic version of the library installed, open the Example 01 PlayFile sketch. You can find it under

File > Examples > SparkFun Tsunami Super WAV Trigger Qwiic > Examples

Then load it onto your RedBoard Plus or Uno. Open your favorite Serial Terminal to see the debug output and trigger the board to reset.

  • Users should hear the "track 1"*.wav file play on one side of the headphones.
  • Users should also see the status LED illuminate green while a file is playing.

debug output from example
Running the Arduino library example. (Click to enlarge)

Feel free to try other examples as well to get a better understanding of the library operation.

Troubleshooting Tips

Below, we have also included some troubleshooting tips for issues that you may come across.

  1. One of our employees compiled a great list of troubleshooting tips based on the most common customer issues. This is the perfect place to start.
  2. For any Arduino IDE specific issues, we recommend starting with their troubleshooting guide.

The latest information on the Qwiic Tsunami can be found on the Robertsonics website; including instructions for serial control and MIDI implementation. Other useful resources include:

For users looking for technical assistance, click on the link. There you will find, basic troubleshooting tips and instructions to get started with posting a topic in our forum. Our technical support team will do their best to assist you.

Resources and Going Further

For more information on the Tsunami Super WAV Trigger (Qwiic), check out the links below:

For more inspiration, check out theses other audio related tutorials:

MP3 Player Shield Music Box

Music Box Project based on the Dr. Who TARDIS.

Getting Started with the LilyPad MP3 Player

The LilyPad MP3 Player is an amazing little board that contains almost everything you need to play audio files. You can use it to create all kinds of noisy projects, from MP3 hoodies to talking teddy bears. Your imagination is the only limit! This tutorial will help you get started.

Dot/Bar Display Driver Hookup Guide

How to hook up the LM3914 or LM3916 to drive a 10-LED display with a lone analog signal.

Touch Potentiometer Hookup Guide

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

SparkPunk Sequencer Theory and Applications Guide

Examine the inner workings of the SparkPunk Sequencer, then explore some modifications and alternate applications.

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.

Qwiic MP3 Trigger Hookup Guide

Playing MP3s has never been easier.

MicroMod Artemis Processor Board Hookup Guide

Get started with the Artemis MicroMod Processor Board in this tutorial!

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

Getting Started with the micro:bit

$
0
0

Getting Started with the micro:bit a learn.sparkfun.com tutorial

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

Introduction

So you bought this thing called a micro:bit...or even better, you've purchased the updated version, the micro:bit v2. But what is it?

micro:bit Board

micro:bit Board

DEV-14208
10Retired
micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$15.95
5

The BBC micro:bit is a pocket-sized computer that lets you get creative with digital technology. You can code, customize, and control your micro:bit from anywhere! You can use your micro:bit for all sorts of unique creations, from robots to musical instruments and more.

The micro:bit is a project by the BBC in an effort to bring computer science education and STEM topics to every student in the United Kingdom. It is an open development board that works in sync with other onboard hardware components to get you started down the path of programming hardware.

At half the size of a credit card, you will be surprised at the amount of hardware each board is equipped with, including 25 red LED lights that can flash messages. There are two programmable buttons that can be used to control games or pause and skip songs on a playlist. The micro:bit can even detect motion and tell you which direction you’re heading. It can also use Bluetooth Low Energy (BLE) to interact with other devices and the Internet.

The micro:bit features an embedded compass, accelerometer, mobile, and web-based programming capabilities. The micro:bit v2 adds an onboard speaker and MEMS microphone, as well as a touch-sensitive logo. Both boards are compatible with a number of online code editors across a number of different languages. This guide will focus on MakeCode, a block or JavaScript-based environment that was developed by Microsoft.

Required Materials

To follow along with this tutorial, you will only need a micro:bit, and a micro USB cable. Pretty simple!

USB micro-B Cable - 6 Foot

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
13
USB Micro-B Cable - 6"

USB Micro-B Cable - 6"

CAB-13244
$1.95
3
SparkFun Traveler microB Cable - 1m

SparkFun Traveler microB Cable - 1m

CAB-14741

Hardware Overview

There are two versions of the BBC micro:bit and both have a lot to offer when it comes to onboard inputs and outputs. In fact, there are so many things packed onto these little boards that you would be hard pressed to really need anything else if you were looking at just exploring the basics of programming and hardware.

Front

On the front of the board there are a number of components that are pretty visible right off the bat!

LED Array

The micro:bit has a 5x5 LED array that you can use as a tiny screen to draw on and display words, numbers and other information.


LED Array on micro:bitLED Array on micro:bit V2

A/B Buttons

Two buttons in all of their clicky glory: A is on the left, B is on the right, and both are prime for controlling a game of your design.


A/B Buttons on micro:bitA/B Buttons on micro:bit V2

Edge "Pins"

The gold tabs at the bottom of the board are for hooking up external components. The tabs with larger holes can be easily used with alligator clips to prototype things quickly! To access all the pins, you will need a board with an edge connector. For breadboard prototyping, you'll want the micro:bit breakout with headers.


Edge Pins on micro:bitEdge Pins on micro:bit V2

Light Sensor

A bit of a hidden gem. The LED array doubles as a light sensor!


Light Sensor on micro:bitLight Sensor on micro:bit V2

V2 Only - Microphone Input and LED Indicator

Microphone input and LED indicator is on the right side of the touch sensitive logo at the top of the board

V2 Only - Touch Sensitive Logo

The gold logo is a capacitive touch sensor that works a bit like a touch screen on a mobile phone, measuring tiny changes in electricity.

Touch sensitive logo is at the top center of the board

Back

The back is where a lot of the magic happens. Check it out...

Microcontroller

The brains of the outfit.

The micro:bit is powered by a 16MHz ARM Cortex-M0 microcontroller with 256KB Flash and 16KB RAM.

The micro:bit v2 is powered by Nordic Semiconductor's nRF52833 chip - a 64MHz ARM Cortex-M4 microcontroller with FPU, 512KB Flash, and 128KB RAM.


nRF51822 Processor on micro:bitnRF52833 Processor on micro:bit V2

Accelerometer/Compass

The micro:bit has an onboard accelerometer that measures gravitational force, as well as a compass (a.k.a. a magnetometer) that can detect its orientation using Earth's magnetic field.

Accelerometer and Magnetometer on micro:bitAccelerometer and Magnetometer on micro:bit v2

Bluetooth/Radio

Communication is huge with the micro:bit. You can communicate with your phone or tablet using Bluetooth Low Energy (BLE) or between two or more micro:bits using the standard "radio".

Bluetooth / Radio Antenna on micro:bitBluetooth / Radio Antenna on micro:bit v2

Temperature Sensor

No, the drawing is not highlighted incorrectly! The microcontroller doubles as a temperature sensor!

Microcontroller as Temperature Sensor on micro:bitMicrocontroller as Temperature Sensor on micro:bit v2

USB Port

Used to upload code to your micro:bit or power from your computer or laptop.

USB Port on micro:bitUSB Port on micro:bit v2

Reset Button

A button to reset your micro:bit and start your code over from the beginning.

Reset Button on micro:bitReset Button on micro:bit v2

JST Battery Connector

A connector to hook up an external battery pack to your micro:bit.

Reset Button on micro:bitReset Button on micro:bit v2

V2 Only - Microphone

V2 of the micro:bit contains a MEMS microphone to allow sound-sensing without the need to attach another device.

The microphone is on the back of the board, just below and left of the USB port

V2 Only - Speaker

Speaker is smack center on the back of the board

Phew! That is a lot of bells and whistles...a true Swiss army knife!

Hooking It Up

The micro:bit uses a microUSB cable to hook up to your computer or Chromebook. It is as simple as plugging the cable into your micro:bit and the other end into an open USB port.

USB Between MicroBit and Computer

Once you plug your board in, you should see the small yellow LED on the back of your micro:bit light up and possibly blink a few times. Then whatever existing program that was put on the micro:bit will start running. If this is your first time plugging your micro:bit in, go ahead and play around with it a bit --- push buttons, shake it, and you will get a bit of an Easter egg.

Once your micro:bit boots up, check out your Finder if you are on a Mac, or your My Computer Drives if you are on a PC. The micro:bit should show up as an external storage device with two files stored in it.

MicroBit Showing up as External Storage Device

If you are on a Chromebook, when you plug your micro:bit in you will be greeted with a dialog box to open the drive. Feel free to do so to make sure it works!

Let's get programming!

Using MakeCode

This guide and most of SparkFun's content around the micro:bit will use MakeCode by Microsoft for programming.

What Is MakeCode?

MakeCode is an open programming environment built by Microsoft for the micro:bit, as well as other boards. You can navigate to MakeCode for the micro:bit by following this link:

Once you have launched MakeCode, you will be greeted by its basic layout with a simulator on the left and a block-based environment on the right when your browser's window is maximized, as shown here.

MakeCode Highlighted

Click on the image above for a larger view.

Let's take a quick tour and check out what is available to us!

  1. Projects --- A cloud storage system connected to your computer with no account setup required.
  2. Share --- Allows you to share your project code in a number of different ways with your friends!
  3. Blocks/JavaScript --- Choose your own adventure by programming in blocks (default) or in JavaScript.
  4. Program Space --- This is where the magic happens and where you build your program...where you "make code."
  5. Zoom/Undo-Redo --- Sometimes you need to undo things, or zoom out and look around; these are the buttons for that.
  6. Name & Save --- Name your program and save it (download it) to your computer.
  7. Download --- Similar to Save, download your program as a .hex file and drag it into your micro:bit.
  8. Simulator Hide/Show --- You can hide/show the simulator if you would like.
  9. Block Library --- All of the options in terms of program building blocks, which are color-coded by function.
  10. Simulator --- You don't need hardware! MakeCode has a real-time simulator! As you change your program, you can see what it will do on this virtual micro:bit!

Phew! Now you have a choice - blocks or text-based programming?

Blocks or Text

For this guide and the majority of the content that you will find on SparkFun for the micro:bit, we will be using block-based programming examples.

Toggle Switch for Drag and Drop Programming or JavaScript

But, if you so choose there is a JavaScript option to use as well. The choice is yours, and the good news is that you can switch back and forth from one to the other in the same program; one will populate the other, which is really nice if you are new to programming!

Simulator

MakeCode includes a simulator for the micro:bit, meaning if you don't have your micro:bit in hand you can still write code for it. Or if you want to try out an idea before you upload it to your micro:bit, you can do that too!

MakeCode Simulator

The simulator will update as you build your code, and if you want to run it from the beginning you can click the stop and run buttons to start it over again!

Speaking of code, let's write a quick program and get it onto your micro:bit!

Hello, World!

Now comes the good stuff --- writing your first program for your micro:bit in the MakeCode programming environment!

"Hello World" is the term we use to define that first program you write in a programming language or on a new piece of hardware. Essentially it is a simple piece of code that gives you a quick win (fingers crossed) and a first step in learning. It also gives you a chance to make sure everything is up and running and A-OK.

For your first "Hello World" we are going to create a simple animation on the LED array that repeats forever. If you just want the complete program, you can see it here. To see a step-by-step explanation of how we built the program, continue reading!

Note: You may need to disable your ad/pop blocker to interact with the MakeCode programming environment and simulated circuit!

Building 'Hello World'

A "Hello World" on the micro:bit is a little different than on a normal run-of-the-mill microcontroller. The micro:bit has no single LED to blink on its own, as you would find on the Arduino or similar boards. What the micro:bit does have is an LED array! So, the "Hello World" for the micro:bit is to draw something using the LED array!

When you open MakeCode you are greeted with two blocks: the On Start block and the forever block. The On Start block is all of your code that will execute at the very beginning of your program and only run once. The forever block is code that will loop over and over again...forever.

We are going to use the forever block for building this "Hello World." We now need to start adding blocks to forever.

forever code block

First, click on the Basics category. These blocks are, well, the basic building blocks of a BuildCode program. It will expand into a number of options. Click and drag the show leds block over and place it inside of your forever block. Notice that the block is keyed to fit inside of the forever block, and if you have the volume up on your computer you will hear a satisfying 'click' noise when you let go of the block.

Basic Code Blocks

The show leds block has an array of squares that symbolize the LED array. If you click on a square, it will turn red, which means that it is 'on'. Draw a simple pixel art shape by turning different LEDs on or off; you should be able to see the outcome in your simulator on the lefthand side of your window.

LED Array Code Block with Smiley Face

To turn this static image into an animation we need another show leds block to place just under the first block. You can then make a second drawing with this set of rectangles. In your simulator you will see the images switching really, really fast. We need to slow this down!

To slow your animation down you will use the pause block, which is under the basic block set. The pause block is just what it says; it tells the micro:bit to pause and wait for a certain amount of time. Place two pause blocks in the program as shown.

LED Array Code Blocks with Delay Between Animations

The reason we are using two 'pause' blocks and placing one at the end is that this program is a loop. Without the block at the end, the image in your animation will change really, really fast.

We have built up an example in the next section where you can download the file and try it out on your own micro:bit, or use the simulator. If you want to play around with the code and make some changes, go ahead and click the Edit button in the widget, and it will open a MakeCode editor for you to start hacking "Hello World." Enjoy!

Getting Your Program Onto Your micro:bit

You've built your first program in MakeCode, and it works in your simulator. Now, how do you get it onto your micro:bit?

Download Your Program

Once you are happy with your program, you can click the Download button in MakeCode.

MakeCode Download Button

This will download your program file to your standard download location, probably the Downloads folder on your computer, or whatever location you have set in your download preference.

Window After Downloading

You then simply click and drag your program file from its download location to your micro:bit drive, which shows up as an external device.

That's it!

Your micro:bit will flash for a few seconds, and then your program will start automatically. Yes! Win!

Note: You may need to disable your ad/pop blocker to see the simulated circuit!

MakeCode Extension

Heads up! Previously, these libraries were referred to as MakeCode packages. They are now referred to as MakeCode extensions.

If you have used Arduino before, you probably know about a thing called a library; which is a collection of code that extends the functionality of the core programming language. MakeCode extensions work the same way.

There are some amazing differences between Arduino libraries and MakeCode extensions. One of them is that MakeCode extensions include JavaScript functions, which you can use when programming in text, as well as all of the blocks you need to program using the block method. This makes learning and using new extensions straightforward and shortens the time to awesome when setting out to build the project of your dreams.

There are several MakeCode extensions that are available. The following instructions takes advantage of the Controller:bit's MakeCode extension but you can follow along to add other extensions as well.

Installing a MakeCode Extension

To install or add a new extension to your MakeCode toolbox (the list of different block groups), click on "Advanced" and then on "Add Extension."

MakeCode Extensions

From here you can search for "SparkFun" or "SparkFun gamer-bit," and it should show up as a public extension in the list. Go ahead and click on it.

SparkFun Extensions

This will add all of the blocks to your toolbox. In general, this is a bit tricky as, depending on how the extension was written, it may either have its own toolbox or just add blocks to the existing ones. Take a look at your toolbox; for the gamer:bit you should see...

Screenshot gamer:bit installed

Great! You have now installed the gamer:bit extension! If you bought the micro:arcade kit, you are ready to use the board as well as the components that came in the kit. As a side note, for every new MakeCode project that you make, you will have to load extensions over again. Not a big deal, but noteworthy!

Updating Extensions

Published example codes and *.hex files that are saved use archived versions of extensions. Occasionally, there are updates to either MakeCode editor or the extensions. If you need to update an extension to the latest due to a compile error or new features, there are two methods of updating your extensions. One method is to remove all instances of the blocks provided by the extension and reinstalling the extension as outlined above. This can be tedious if there are several blocks sandwiched together and the length of your code. The second method is to update the version number in the Javascript View. The benefit is that users do not have to manually remove blocks that are sandwiched together.

Below is a published example where a previous gamer:bit extension was able to compile. An update to the MakeCode editor caused an error due to a bug in the gamer:bit extension that was ignored in previous versions of the MakeCode editor. A patch was eventually applied to the gamer:bit extension so we want to update the example to pull in the latest version to fix the error.

Error in MakeCode Example from gamer:bit extension

Toggle the JavaScript button at the top to switch to the JavaScript view. On the left hand side, you will notice the Explorer Menu. Click on the arrow to expand the menu.

Switch to Javascript View

Scroll down to the MakeCode extension's version number. Here you can delete or update the extension version. We'll want to update the version number since the code relies on the gamer:bit extension. Click the button with the refresh symbol and version number.

Check out the Explorer Menu

At this point, give it a few seconds to pull in the latest version number from the cloud. Then re-open the Explorer menu. If there was an update, this will refresh the extension and use the latest version. In this case, there was an update so it pulled in version v0.0.8! You'll notice that the red box with the number (which indicates the number of issues with the code) went away as well.

Hit the Refresh/Version Button

Just to make sure everything is going smoothly. Head back to the Blocks view, the error indicated by a triangle went away. Sweet! We have successfully updated the MakeCode extension so that we can get back to coding!

Head Back to Blocks View

Powering the micro:bit

You have your program running on your micro:bit, but it is still tethered to your computer. There are a number of ways to solve this problem... batteries, batteries and more batteries!

USB Battery Pack

USB battery packs are becoming pretty commonplace out there. You can use one to run your micro:bit project for quite a long time.

micro:bit powered with USB Power via the USB Connector

It is handy to have a shorter USB cable to keep from dragging a super-long wire around.

2xAA Battery Pack

The 2xAA battery holder with JST-PH connector is a great solution if you are looking to power a whole lot of micro:bits for a good amount of time, such as in a classroom setting.

micro:bit powered with 2xAA batteries via the JST connector

These batteries can be purchased in bulk for pretty cheap.

2xAAA Battery Pack

Looking for a smaller battery holder? Try looking at the 2xAAA battery holder with JST-PH connector. There is one that is included in the micro:bit Go bundle!

micro:bit v2 Go Bundle

micro:bit v2 Go Bundle

DEV-17288
$18.50

Or even check out the 2xAAA battery holder with JST-PH connector and power switch! The added switch makes it easy to turn on and off your micro:bit project without the need to wiggle the JST-PH connector off of your micro:bit.

micro:bit Battery Holder - 2xAAA (JST-PH)

micro:bit Battery Holder - 2xAAA (JST-PH)

PRT-15101
$1.95

Resources and Going Further

Now that you are familiar with the basics of the micro:bit, check out these additional resources for more inspiration!

Looking for additional project ideas using just the micro:bit? Check out micro:climate kit's reading light levels experiment:

micro:climate Experiment 2 - Reading Light Level

For additional SparkFun tutorials, check out some of these related micro:bit tutorials:

micro:climate Kit Experiment Guide

A weather station kit that is built on top of the inexpensive, easy-to-use micro:bit and Microsoft MakeCode.

micro:bot Kit Experiment Guide

Get started with the moto:bit, a carrier board for the micro:bit that allows you to control motors, and create your own robot using this experiment guide for the micro:bot kit.

Gator:starter ProtoSnap Hookup Guide

Get started clipping sensors and lights to the micro:bit with the gator:starter gator:board from SparkFun!

Check out Shawn's 4-part video series with the micro:bit. The projects have examples that use the accelerometer, combines the servo and temperature example, and sends a bluetooth message between two micro:bits. There are two additional videos using micro:bit with MicroPython. Or try exploring micro:bit with cardboard circuits!


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

Digital Temperature Sensor Breakout - AS6212 (Qwiic) Hookup Guide

$
0
0

Digital Temperature Sensor Breakout - AS6212 (Qwiic) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Digital Temperature Sensor Breakout - AS6212 (Qwiic) provides a combination of high temperature accuracy with excellent low power consumption using the AS6212 digital temperature sensor from ams AG. The AS6212 measures temperature with ±0.2°C accuracy between -10°C to 65°C (full measurement range is -40°C to 125°C), consumes an average of 6µA (0.1µA in standby) and communicates over I2C so naturally we put it on a Qwiic breakout to add to our ever expanding Qwiic system. All of this in a tiny IC package measuring 1.5mm x 1mm.

SparkFun Digital Temperature Sensor Breakout - AS6212 (Qwiic)

SparkFun Digital Temperature Sensor Breakout - AS6212 (Qwiic)

SEN-18521
$8.95

Required Materials

In order to follow along with this tutorial you'll need a few items along with the AS6212 breakout.

First off, the Digital Temperature Sensor Breakout - AS6212 (Qwiic) needs a controller like an Arduino development board or single-board computer (SBC) like a Raspberry Pi to communicate with the board. Click the button below to toggle to recommended Raspberry Pi and Qwiic Pi products.

Below are a few Arduino development boards SparkFun carries that are Qwiic enabled out of the box:
SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

DEV-15795
$19.95
4
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
SparkFun RedBoard Artemis

SparkFun RedBoard Artemis

DEV-15444
$19.95
8
SparkFun Qwiic Micro - SAMD21 Development Board

SparkFun Qwiic Micro - SAMD21 Development Board

DEV-15423
$20.95
5
If your preferred microcontroller does not have a Qwiic connector, you can add one using one of the following products:
SparkFun Qwiic Adapter

SparkFun Qwiic Adapter

DEV-14495
$1.50
1
SparkFun Qwiic Shield for Arduino

SparkFun Qwiic Shield for Arduino

DEV-14352
$6.95
6
SparkFun Qwiic Shield for Thing Plus

SparkFun Qwiic Shield for Thing Plus

DEV-16790
$4.25
SparkFun Qwiic Shield for Arduino Nano

SparkFun Qwiic Shield for Arduino Nano

DEV-16789
$4.25
If you would prefer to use the Digital Temperature Sensor Breakout - AS6212 (Qwiic) with Python, control the breakout with a single-board computer like the Raspberry Pi's listed below:
Raspberry Pi 4 Model B (4 GB)

Raspberry Pi 4 Model B (4 GB)

DEV-15447
$55.00
16
Raspberry Pi Zero W (with Headers)

Raspberry Pi Zero W (with Headers)

DEV-15470
$14.00
6
Raspberry Pi Zero W

Raspberry Pi Zero W

DEV-14277
$10.00
43
SparkFun Raspberry Pi 4 Desktop Kit - 2GB

SparkFun Raspberry Pi 4 Desktop Kit - 2GB

KIT-16385
SparkFun offers several options to add Qwiic connectors to single-board computers using the Raspberry Pi's 2x20 header:
SparkFun Qwiic HAT for Raspberry Pi

SparkFun Qwiic HAT for Raspberry Pi

DEV-14459
$6.50
4
SparkFun Qwiic pHAT v2.0 for Raspberry Pi

SparkFun Qwiic pHAT v2.0 for Raspberry Pi

DEV-15945
$6.95
2
SparkFun Servo pHAT for Raspberry Pi

SparkFun Servo pHAT for Raspberry Pi

DEV-15316
$11.95
3
SparkFun Qwiic SHIM for Raspberry Pi

SparkFun Qwiic SHIM for Raspberry Pi

DEV-15794
$0.95
10

Along with a development board or SBC, you'll need at least one Qwiic cable. SparkFun carries a variety of lengths and types of Qwiic cables as seen here:

SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
12
Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Flexible Qwiic Cable - 100mm

Flexible Qwiic Cable - 100mm

PRT-17259
$1.50
Qwiic Cable - 200mm

Qwiic Cable - 200mm

PRT-14428
$1.50

Recommended Reading

In case you are not familiar with the Qwiic System, we recommend reading here for an overview:

Qwiic Connect System

We also recommend taking a look at the following tutorials if you aren't familiar with the concepts covered in them:

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.

Serial Terminal Basics

This tutorial will show you how to communicate with your serial devices using a variety of terminal emulator applications.

Hardware Overview

Let's take a closer look at the AS6212 temperature sensor and other hardware present on this Qwiic breakout.

AS6212 Digital Temperature Sensor

The AS6212 is a highly accurate and power efficient digital temperature sensor with a wide temperature sensing range (-40°C to 125°C) from ams AG. The AS6212 boasts a host of features including a configurable alert pin that can trigger when temperature data exceeds user-defined temperature thresholds. Read more on configuring the alert pin and temperature thresholds in the Arduino and Python sections of this guide as well as in the AS6212 Datasheet. The AS6212 also features a sleep/low power mode that works in tandem with a Single Shot measurement mode to wake the device, retrieve stored temperature data and return it to sleep mode.

Photo highlighting AS6212

The AS6212 accepts a supply voltage between 1.7V and 3.6 and typically consumes 6µA during normal temperature conversions and 0.1µA on standby. The AS6212 normally runs at 3.3V and receives power either through the Qwiic connectors or the dedicated 3.3V and GND PTH pins.

The breakout design isolates the AS6212 from the rest of the PCB as much as possible to minimize ambient heat from interfering with temperature data. The table below outlines the temperature data accuracy across the AS6212's temperature measurement range:

Temperature RangeTemperature Accuracy
−10°C to 65°C±0.2°C
−40°C to −10°C and 65°C to 85°C±0.3°C
85°C to 125°C±0.5°C

I2C and Qwiic Interface

As the name of this breakout suggests, the board routes the AS6212's I2C pins to a pair of Qwiic connectors as well as a 0.1"-spaced PTH header for users who prefer a soldered connection. The AS6212 supports both fast (max 400kHz) and high-speed (max 3.4MHz) clock frequencies and has eight configurable I2C addresses (default is 0x48). Select the address by adjusting the labeled jumpers covered in the next section.

Photo highlighting Qwiic connectors and PTH header.

The Alert/AD1 and AD0 pins are also broken out to the same PTH header as the I2C pins to interact with. The Alert pin can be enabled to act as an external hardware interrupt for an attached microcontroller.

Solder Jumpers

Never worked with solder jumpers or PCB traces before or would like a refresher? Take a look at our How to Work with Jumper Pads and PCB Traces tutorial.

The Digital Temperature Sensor Breakout - AS6212 (Qwiic) has four solder jumpers labeled LED, I2C, AD0 and AD1. The LED jumper connects the Power LED anode to 3.3V via a 1k&ohm; resistor. The jumper is CLOSED by default. Open the jumper to disable the Power LED and reduce the total current draw of the board. The I2C jumper ties the SDA and SCL lines to 3.3V via a pair of 2.2k&ohm; resistors and is CLOSED by default. Open the jumper to disable the pull-up resistors.

Note: Recommended practice suggests to only have a single pair of pull-up resistors on an I2C bus to avoid creating too strong of a parallel resistance on the bus. If you disable the pull-ups on this breakout to use a separate pair, make sure the entire bus is operating at the appropriate logic level (in this case, 3.3V) or the lines are properly shifted to avoid damaging this or other devices on the bus.

Photo highlighting solder jumpers.

The AD0 and AD1 jumpers control the I2C address as well as enabling/disabling the Alert pin. By default, these two-way jumpers connect the AD0 pin to Ground and the Alert/AD1 pin to 3.3V to enable the Alert pin and set the I2C address to 0x48. Adjust these jumpers to change the address and/or disable the Alert pin. The table below outlines the various settings these jumpers can be set to:

ALERT/AD1 Jumper NetAD0 Jumper NetAlert Pin FunctionalityI2C Address
VCC (PU)GNDEnabled0x48 (Default)
VCC (PU)VCCEnabled0x49
VCC (PU)SDAEnabled0x4A
VCC (PU)SCLEnabled0x4B
SCLGNDDisabled0x44
SCLVCCDisabled0x45
SCLSDADisabled0x46
SCLSCLDisabled0x47
GNDGNDDisabled0x48
GNDVCCDisabled0x49
GNDSDADisabled0x4A
GNDSCLDisabled0x4B

Board Dimensions

The Digital Temperature Sensor Breakout - AS6212 (Qwiic) matches the 1" x 1" (25.4mm x 25.4mm) standard form-factor for most of SparkFun's Qwiic breakouts and has four mounting holes that fit 4-40 screws.

Board dimensions screenshot

Hardware Assembly

Assembling your temperature sensing circuit with the Qwiic system is simple. Just connect your SparkFun Digital Temperature Sensor Breakout - AS6212 (Qwiic) to your chosen development board or single-board computer with a Qwiic cable or adapter cable.

Photo showing completed Qwiic circuit.

Users who prefer a traditional through-hole connection can solder the PTH pins broken out on the board. Reminder, the Alert/AD1 Pin is not connected to the Qwiic connector so it requires a separate connection to the Alert PTH pin for use. Alternatively, if you want a temporary connection for prototyping, these IC Hooks are a great option to make that connection. If you are not familiar with through-hole soldering take a look at this tutorial:

How to Solder: Through-Hole Soldering

September 19, 2013

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

With the AS6212 connected to your microcontroller it's time to get some code uploaded and start taking temperature measurements!

Qwiic AS6212 Arduino Library

Note: This library assumes the latest version of the Arduino IDE is used. If this is your first time using Arduino, please review our tutorials on Installing the Arduino IDE and Installing an Arduino Library.

The SparkFun AS6212 Arduino Library helps users configure and pull temperature data from the AS6212. Install the library through the Arduino Library Installer by searching for "SparkFun AS6212". Users who prefer to manually install the library can find it on the GitHub Repository or can download a .ZIP of the repo by clicking the button below:

Library Functions

The list below outlines the functions included in the AS6212 Arduino Library along with short descriptions of what they do.

Class

Construct the AS6212 object in the global class. The examples use sensor as the AS6212 breakout object.

  • AS6212 sensor;

Device Setup and Settings

  • bool begin(uint8_t sensorAddress, TwoWire &wirePort); - Initialize the AS6212 Qwiic breakout at a specified address on a selected port. If left empty, default values are used for the address (0x48) and Wire port.
  • bool setDefaultSettings(); - Set the AS6212 CONFIG register to default/factory settings. This helps quickly return the sensor to default settings if anything in the CONFIG register has been changed as adjustments to the CONFIG register remain through power cycles.
  • uint8_t getAddress(); - Returns the device's I2C address.
  • bool getAlertStatus(); - Returns the status of the Alert bit.
  • void setConsecutiveFaults(int faults); - Sets the number of consecutive faults (temperature above THigh) to occur before the Alert pin state adjusts. Acceptable values are 1,2,3 and 4.
  • uint8_t getConsecutiveFaults(); - Returns the value set for setConsecutiveFaults();.
  • void setInterruptMode(bool mode); - Set the AS6212 Alert pin to operate in Interrupt mode.
  • bool getInterruptMode(); - Read whether the Alert pin is set to operate in Interrupt mode.
  • void setConversionCycleTime(uint8_t cycleTime = AS6212_CONVERSION_CYCLE_TIME_250MS); - Sets the time between temperature conversions in milliseconds. Acceptable entries are: 125MS, 250MS, 1000MS or 4000MS.
  • uint16_t getConversionCycleTime(); - Returns the value set for Conversion Cycle Time in milliseconds.
  • void setAlertPolarity(bool polarity); - Set the polarity of the Alert pin output to go either HIGH or LOW when triggered. Default is LOW/0.
  • bool getAlertPolarity(); - Returns the value set for the Alert polarity bit. 0 for active LOW or 1 for active HIGH.
  • void sleepModeOn(); - Put the AS6212 into Sleep Mode. The device must be in Sleep Mode for Single Shot measurements to be made.
  • void sleepModeOff(); - Clears the Sleep Mode bit in the config register and after reseting the SM bit to 0 the device returns to continuous conversion mode.
  • bool getSleepMode(); - Returns the Sleep Mode bit status as a boolean.
  • void triggerSingleShotConversion(); - Tell the AS6212 to perform a Single Shot temperature conversion.
  • bool getSingleShotStatus(); - Returns the Single Shot mode bit status as a boolean. 0 for no conversion ongoing/conversion finished. 1 for start Single Shot conversion/conversion ongoing.
  • void setConfig(uint16_t targetState); - Legacy function for users who wish to interact directly with the CONFIG register. Refer to section 6.2 in the AS6212 Datasheet for a detailed description of this regsiter and the adjustable bits in it.
  • uint16_t readConfig(); - Returns the settings in the CONFIG register as an unsigned integer.

Temperature Data

  • float readTempC(); - Returns the recorded temperature in degrees Celsius.
  • float getTLowC(); - Returns the temperature value set for setTLowC.
  • bool setTLowC(int16_t lowLimit); - Sets the temperature in °C for low temperature threshold. Used for the alert pin temperature limits.
  • float getTHighC(); - Returns the temperature value set for setTHighC.
  • bool setTHighC(int16_t highLimit); - Sets the temperature in °C for the high temperature threshold. Used for the alert pin temperature limits.
  • float readTempF(); - Returns the recorded temperature in degrees Fahrenheit.
  • float getTLowF(); - Returns the temperature value set for setTLowF.
  • bool setTLowF(int16_t lowLimit); - Sets the temperature in °F for low temperature threshold. Used for the alert pin temperature limits.
  • float getTHighF(); - Returns the temperature value set for setTHighF.
  • bool setTHighF(int16_t highLimit); - ets the temperature in °F for high temperature threshold. Used for the alert pin temperature limits.

Arduino Examples

The SparkFun AS6212 Arduino Library includes ten examples to showcase the various capabilities and settings of the AS6212. In this section we'll take an in-depth look at most of those examples and highlight pertinent bits of code where necessary. The examples build on each other so it may help to go through them in sequential order.

Prior to uploading the examples, let's take a quick look at the setup function used in all examples:

language:c
if (sensor.begin() == false)
{
    Serial.println("AS6212 Qwiic failed to respond. Please check wiring and possibly the I2C address. Freezing...");
    while (1);      
};

After uploading any of the examples, open the Arduino serial monitor with the baud set to 115200. If the AS6212 fails to initialize on the bus, the code freezes and prints out "AS6212 Qwiic failed to respond. Please check wiring and possibly the I2C address. Freezing...".

If you see this message, check the connection between the breakout and controller and make sure the AS6212 is either set to the default address or the sensor.begin(); function is adjusted to the correct address. Refer to Example 2 - Different I2C Address for a quick demonstration of initializing the AS6212 on an alternate address.

Each example also includes a quick call of the setDefaultSettings(); function to return the AS6212 to default settings as adjustments to the CONFIG register (e.g. conversion cycle time, interrupt mode, alert pin polarity) remain through power cycles.

Example 1 - Basic Readings

The first example in the library demonstrates how to initialize the AS6212 on the I2C bus and retrieve temperature data from the sensor in both °C and °F. Open the example by navigating to File > Examples > SparkFun AS6212 Arduino Library > Example_01_BasicReadings. Select the appropriate Board and Port and click upload. Assuming the upload was successful, open the serial monitor with the baud set to 115200.

Screenshot of serial monitor for Example 1

After initializing, the code prints out temperature data recorded by the AS6212 in both °C and °F every second. Try breathing on the sensor or gently press your finger to it and watch the temperature data change.

Example 3 - Sleep

Example 3 demonstrates how to put the AS6212 in and out of Sleep Mode with default settings. Note, this example keeps the default settings so the AS6212 measures in continuous mode when awake. Take a look at the next example for use of the Single Shot readings for maximum power efficiency.

The main loop creates a wake/sleep loop with a 150ms delay after waking to ensure temperature current and accurate temperature data. Without this delay the first values read will be from the last time the AS6212 was awake. Once woken up, the code returns temperature data for both Celsius and Fahrenheit and then puts the AS6212 back into Sleep Mode for five seconds.

Example 4 - Single Shot Readings

Example 4 builds on the previous example to combine Sleep Mode with Single Shot readings to maximize power efficiency. The example starts similarly to Example 3 but includes an extra two lines in the setup to start with the AS6212 in Sleep Mode to enable Single Shot readings.

language:c
sensor.sleepModeOn();
delay(150);

With the sensor in Sleep Mode, the code triggers a Single Shot reading. Note, this automatically returns the AS6212 to sleep mode once complete.:

language:c
sensor.triggerSingleShotConversion();

The code also includes a serial print to let the user know when a Single Shot conversion is ongoing and prints out the temperature data in both Celsius and Fahrenheit for each reading.

Example 5 - Alert

Example 5 shows how to set upper and lower temperature thresholds and how to enable/disable the Alert pin when the recorded temperature crosses those values. The code starts by checking to make sure the AS6212 is awake in case it was left in Sleep Mode from a previous example in this library. After checking that (and waking the sensor up if it was asleep), the code sets values for THighF(); and TLowF(); to 80°F and 77°F, respectively.

language:c
if (sensor.getSleepMode() == true)
{
    Serial.println("Sensor was asleep, waking up now");
    sensor.sleepModeOff();
    delay(150);
}

sensor.setTHighF(80);
sensor.setTLowF(77);
Note: The registers for setting the THigh and TLow thresholds have a specific resolution so you may notice that the code prints out a value slightly off of what was set for the threshold. Refer to section 6.2.9 in the AS6212 Datasheet for more specific information on the High and Low Limit Registers.

The code sets these values close together specifically to easily test the threshold settings by breathing on the sensor lightly to raise the temperature above the threshold. The main loop prints the temperature data and watches the alert status. When the temperature crosses the THigh threshold, the Alert pin goes LOW and remains LOW until the temperature drops below the TLow threshold. The code also prints out the status of the Alert pin.

language:c
void loop() {
    tempF = sensor.readTempF();
    Serial.print("Temperature (°F): ");
    Serial.print(tempF, 6);              //Reads out 6 characters of the temperature float

    alertStatus = sensor.getAlertStatus();

    Serial.print("\talertStatus: ");
    Serial.print(alertStatus);

    if (alertStatus == false) // be default alertStatus is active low
    {
        Serial.print("\tAlert ACTIVE LOW!");
    }

    Serial.println();
    delay(1000);
}

Screenshot of serial monitor display for Example 5

Example 6 - Conversion Cycle Time

Now that we've used the high and low temperature thresholds to toggle the Alert pin, Example 6 shows how to adjust the conversion cycle time for Single Shot measurements to alter how long the temperature must stay above/below the set temperature thresholds to trigger the Alert pin. The example sets the conversion cycle time to once every four seconds while reading the alert status every second. With this setting, the temperature data must cross the threshold and stay there through the conversion before the Alert pin will fire.

language:c
sensor.setConversionCycleTime(AS6212_CONVERSION_CYCLE_TIME_4000MS);

Other options for this setting are 125MS (8 times/sec), 250MS (4 times/sec) and 1000MS (1 time/sec). The main loop performs the same alertStatus check as the previous example and if the temperature crosses the THigh threshold and stays there during the conversion cycle time, the alert pin will go LOW until the temperature drops below the TLow threshold and stays there through a conversion cycle.

Example 7 - Consecutive Faults

Further building on the alert examples, Example 7 demonstrates how to integrate the setConsecutiveFaults function into monitoring temperature data to trigger the Alert pin. Adding a consecutive fault check on top of the conversion cycle time setting allows you to really configure how long temperature must remain above/below the THigh and TLow thresholds to trigger the Alert pin. This example sets both the setConsecutiveFaults and setConversionCycleTime to their max values so the temperature must remain above the THigh threshold for 16 seconds for the Alert pin to go LOW. Note, this also means the Alert pin will remain LOW until the temperature data is below the TLow threshold for 16 seconds as well.

language:c
sensor.setConsecutiveFaults(4);

Allowable values for the setConsecutiveFaults function are 1,2,3 or 4. The main loop is the same as the previous two examples; temperature data prints and alertStatus is checked every second. If the temperature crosses the THigh threshold and stays there for four conversion cycles (16 seconds), the code prints "Alert ACTIVE LOW!" until the temperature drops below the TLow threshold for the same duration.

Example 8 - Interrupt Mode

Example 8 shows how to use the setInterruptMode function to switch between Comparator and Interrupt. The previous examples all use the default mode, Comparator, where the Alert pin changes state when temperature data crosses the THigh threshold and stays in the new state until the temperature drops below the TLow threshold. This example sets the Alert pin to operate in Interrupt mode:

language:c
sensor.setInterruptMode(AS6212_MODE_INTERRUPT);`

In Interrupt mode, the Alert pin changes state quickly when the temperature crosses the THigh threshold and again when the temperature drops below the TLow threshold. This change is extremely quick so it works best when connected to a hardware interrupt pin on a microcontroller (see Example 10 for that use case). This example sets the Conversion Cycle time and Consecutive Faults to their lowest values to reduce any delays in reading temperature since the Alert state changes so quickly.

language:c
sensor.setConversionCycleTime(AS6212_CONVERSION_CYCLE_TIME_250MS);
sensor.setConsecutiveFaults(1);

The code prints out the Alert status and temperature when the Alert pin is fired and also includes an extra function to blink the LED to show the code is alive and working. This function exists outside of the main loop to eliminate any delays.

Note: When operating in Interrupt mode, the Alert pin only changes state once temperature data crosses the THigh threshold and again when the temperature data crosses the TLow threshold. This means even if the temperature data crosses the THigh threshold multiple times, the Alert pin changes state only once until the temperature data crosses below the TLow threshold. For more information, refer to section 6.2.5 and Figure 19 in the AS6212 Datasheet.

Example 10 - Hardware Interrupt

To round out the Alert pin examples (and this section), Example 10 shows how to use the Alert pin as an external hardware interrupt to your RedBoard/Arduino. Example 10 performs nearly identically to Example 9 where the Alert pin operates in Interrupt mode. The primary difference here is the code attaches an external interrupt to D2 on the RedBoard/Arduino:

language:c
attachInterrupt(digitalPinToInterrupt(2), ISR_alert, FALLING);

The example does not run any routines or actions when the interrupt pin triggers so it's left to the user to include the necessary code to run an action on interrupt. Use the interrupt to trigger an external component like a fan to cool down a temperature-sensitive device or an LED to indicate a temperature fault.

Qwiic AS6212 Python Package

Note: This package and the included examples assume you are using the latest version of Python 3. If this is your first time using Python or I2C hardware on a Raspberry Pi, these tutorial can help you get started:

The Qwiic AS6212 Python package

The module is hosted on PyPi to make installation quick and painless with simple commands in the command interface. Users who prefer to manually install the package can find it on the GitHub Repository or download the ZIP of the repository by clicking the button below:

(*Please be aware this package depends on the Qwiic I2C Driver. You can also view the repository documentation page hosted on Read the Docs.)

Qwiic AS6212 Py Installation

Now we'll cover the two installation methods for the Qwiic AS6212 Python package.

Note: Don't forget to double check the hardware I2C connection is enabled on your Rasbperry Pi or other single board computer. The Raspberry Pi tutorials linked in the note above cover how to enable the I2C bus.

PyPi Installation

Since the package is hosted on PyPi, installation on systems that support PyPi installation via pip3 (use pip for Python 2) is easy using a command interface and the following commands:

For all users (The user must have sudo privileges):

language:bash
sudo pip3 install sparkfun-qwiic-as6212

For the current user:

language:bash
pip3 install sparkfun-qwiic-as6212

Local Installation

The following instructions cover how to perform a local installation of the Qwiic AS6212 Python package. Make sure to install the setuptools package prior to installing the Qwiic AS6212 Python package.

Use this command for direct installation at the command line (use python for Python 2):

language:bash
python3 setup.py install

Build a package for use with pip3:

language:bash
python setup.py sdist

This command builds and places a subdirectory called "dist". Change to the new subdirectory and install the Qwiic AS6212 package using pip3 with these commands (make sure to fill in the correct version number):

language:bash
pip3 install sparkfun_qwiic_as6212-<version>.targ.gz

Qwiic AS6212 Python Package Operation

For a complete overview of all functions included in Qwiic AS6212 Py, visit ReadtheDocs. You can also review the package's source code.

Upgrading the Qwiic AS6212 Python Package

In case the package is updated in the future, you may need to upgrade it. Use the following commands to upgrade it:

For all users (The user must have sudo privileges):

language:bash
sudo pip3 install --upgrade sparkfun-qwiic-as6212

For the current user:

language:bash
pip3 install --upgrade sparkfun-qwiic-as6212

Python Examples

The Qwiic AS6212 Python package includes two quick examples to get you started. Let's take a quick look at both of them. Just like the Arduino library, the examples start by creating the temperature sensor object and checking the Digital Temperature Sensor Breakout - AS6212 (Qwiic) is connected to the bus at the default address:

language:python
myTempSensor = qwiic_as6212.QwiicAs6212Sensor()

if myTempSensor.is_connected == False:
    print("The Qwiic AS6212 Sensor device isn't connected to the system. Please check your connection", \
        file=sys.stderr

return

If you see this printout, the most common causes are the AS6212 is set to an alternate I2C address and the code has not been adjusted properly or the device is not making a good connection with the I2C pins. If the AS6212 is set to an alternate address, make sure to add the address to this line:

language:python
myTempSensor = qwiic_as6212.QwiicAs6212Sensor(NEW ADDRESS HERE)

Example 1 - Basic Readings

Don't be fooled by the name of Example 1, think of it more as a kitchen sink demo of getting temperature data, setting high and low temperature thresholds, the alert behavior, alert polarity, consecutive fault count and conversion cycle time. After initializing the sensor on the bus, the code sets all of the values listed above:

language:python
# set the number of consecutive faults before triggering alarm.
# valid options: 1,2,3 or 4
myTempSensor.set_consecutive_faults(1)

# set the polarity of the Alert. (0:Active LOW, 1:Active HIGH).
myTempSensor.set_alert_polarity(myTempSensor.AS6212_ALERT_ACTIVE_LOW)

# set the sensor in Comparator Mode (0) or Interrupt Mode (1).
myTempSensor.set_interrupt_mode(myTempSensor.AS6212_MODE_COMPARATOR)

# set the Conversion Cycle Time (how quickly the sensor gets a new reading)
myTempSensor.set_conversion_cycletime(myTempSensor.AS6212_CONVERSION_CYCLE_TIME_250MS)

# set T_HIGH, the upper limit to trigger the alert on
myTempSensor.set_high_temp_f(78.0)  # set T_HIGH in F
# myTempSensor.set_high_temp_c(25.56) # set T_HIGH in C

# set T_LOW, the lower limit to shut turn off the alert
myTempSensor.set_low_temp_f(75.0)   # set T_LOW in F
# myTempSensor.set_low_temp_c(23.89)    # set T_LOW in C

The main loop puts the AS6212 in and out of sleep mode. When awake, the code retrieves temperature data in °F and then puts it back into sleep mode. Each second the code prints out the recorded temperature data and the Alert Register state.

language:python
while True:
    myTempSensor.set_sleep_mode(0) # turn sleep  mode off (0)
    time.sleep(0.250) # allow time to wake up and complete first conversion

    temperature = myTempSensor.read_temp_f()

    # Check for alert
    alertRegisterState = myTempSensor.get_alert_status()        # read the Alert from register

    # Place sensor in sleep mode to save power.
    # Current consumption typically ~0.1uA.
    myTempSensor.set_sleep_mode(1) # turn sleep  mode on (1)

    print("Temperature: ", temperature, "\tAlert Register: ", alertRegisterState)
    time.sleep(1)

This method works fine for standard applications but using the AS6212's single shot readings is even better to conserve power as we can call for temperature data on demand. The next example covers using single shot.

Example 2 - Single Shot

The second example shows how to set up and use single shot readings on the AS6212. The example sets up similarly to the previous example but does not set any of the alert or threshold settings. Instead, the code initializes the AS6212 and then puts the device into sleep mode:

lanugage:python
myTempSensor.set_sleep_mode(1)
print("Sleep mode ON")
time.sleep(1)

The AS6212 must be in sleep mode for single shot measurements to work. After the device has been initialized and put in sleep mode, the main loop triggers single shot conversions and prints out the reported temp data every second:

language:python
while True:
    myTempSensor.trigger_single_shot_conversion() # trigger SS

    #wait for conversion to complete (~51ms)
    conversionTime = 0
    while myTempSensor.get_single_shot_status() == 1:
        conversionTime += 1
        time.sleep(0.001) # 1ms

    tempF = myTempSensor.read_temp_f()

    print("Temperature: %.2fF \t Conversion time: %ims" % (tempF, conversionTime))
    time.sleep(1)

Troubleshooting

Device Not Initializing

The examples from both the Arduino library and Python module print out:

"AS6212 Qwiic failed to respond. Please check wiring and possibly the I2C address. Freezing..."

If you see this, double-check the connections to the breakout and make sure if the I2C address has been changed to adjust the appropriate line to start communication with the AS6212 at the correct address as demonstrated below:

Arduino
language:c
sensor.begin(NEW ADDRESS HERE)
Python
language:python
myTempSensor = qwiic_as6212.QwiicAs6212Sensor(NEW ADDRESS HERE)

THigh and TLow Temperature Resolution

As mentioned in the Arduino Examples section, some users may notice the value printed for the THigh and TLow by the code do not exactly match the value set in the setTHighF/C or setTLowF/C functions. This is due to the resolution of the registers controlling those thresholds so the code sets it to the closest "step" on that resolution. For more information on these registers, refer to section 6.2.9 in the AS6212 Datasheet.

CONFIG Register Settings

Reminder, any changes to the CONFIG register such as changing the alert pin from Comparator mode to Interrupt mode, conversion cycle time, consecutive faults, etc. remain through power cycles. Users need to either manually set these to their desired settings or, in the case of the Arduino library, use the setDefaultSettings(); function to return the settings back to default.

General Troubleshooting and Technical Assistance

Resources and Going Further

That's a wrap for this tutorial. Check out the resources below for more information about the Digital Temperature Sensor Breakout - AS6212 (Qwiic).

Not sure what to do for your temperature sensing project? The following Weather-related tutorials might offer some inspiration:

Creating a Humidor Control Box

Because some of our boards need to be re-humidified after reflow, we decided to make our own humidor. This tutorial will focus on how to model a project in 3D and then fabricate it using a CNC routing machine.

SparkFun gator:environment Hookup Guide

The gator:environment combines two I2C sensors for temperature, humidity, pressure, eCO2, and eTVOC values. This tutorial will get you started using the gator:environment with the micro:bit platform.

SparkFun gator:soil Hookup Guide

The gator:soil is analog soil moisture sensor. This tutorial will get you started using the gator:soil with the micro:bit platform.

Qwiic TMP117 High Precision Digital Temperature Sensor Hookup Guide

Add a high precision, digital temperature sensor to your projects using the TMP117 over the I2C!

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

Tinker Kit Circuit Guide

$
0
0

Tinker Kit Circuit Guide a learn.sparkfun.com tutorial

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

Introduction

Important! This tutorial is for the SparkFun Tinker Kit (KIT-18577). If you are using one of the previous versions of the Tinker Kit: KIT-14556 or KIT-13930, you'll want to refer to their respective guides:

The SparkFun Tinker Kit is your starter tool kit for beginning with embedded electronics, robotics and citizen science using the SparkFun RedBoard Qwiic without breaking the bank. This guide contains all the information you will need to explore the 11 circuits of the Tinker Kit. At the center of this guide is one core philosophy -- that anyone can (and should) play around with cutting-edge electronics in a fun and playful way.

SparkFun Tinker Kit

SparkFun Tinker Kit

KIT-18577
$49.95

When you're done with this guide, you'll have the know-how to start creating your own projects and experiments. From building robots and game controllers to data logging, the world will be your oyster. Now enough talking -- let's start tinkering!

Open Source!

At SparkFun, our engineers and educators have been improving this kit and coming up with new experiments for a long time now. We would like to give attribution to Oomlout, since we originally started working off their Arduino Kit material many years ago. The Oomlut version is licensed under the Creative Commons Attribution Share-Alike 3.0 Unported License.

The SparkFun Tinker Kit is licensed under the Creative Commons Attribution Share-Alike 4.0 International License.

The SparkFun RedBoard Qwiic

The SparkFun RedBoard Qwiic is your development platform. At its roots, the RedBoard is essentially a small, portable computer also known as a microcontroller. You can program it to accept inputs such as the push of a button or a reading from a light sensor and interpret that information to control various outputs like blinking a light like an LED or spinning an electric motor. That’s where the term “physical computing” comes in; this board can take the world of electronics and relate it to the physical world in a real and tangible way.

The SparkFun RedBoard Qwiic is one of a multitude of development boards based on the ATmega328 microprocessor. It has 14 digital input/output pins (six of which can be pulse-width modulation outputs; also referred to as PWM), six analog inputs, a 16MHz crystal oscillator, a USB connection, a power jack, a reset button and a Qwiic connector for connecting other Qwiic devices. You’ll learn more about each of these features as you progress through this guide.

Check out the guide below to learn more about the SparkFun RedBoard Qwiic.

RedBoard Qwiic Hookup Guide

January 10, 2019

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.

If you'd like to learn more about the Qwiic System, we recommend reading here for an overview:

Qwiic Connect System

Understanding Breadboards

A breadboard is a circuit building platform that allows you to connect multiple components without using a soldering iron.

All experiments in this guide use the included breadboard so if you have never seen or used a breadboard before, we highly recommended you read the guide below that explains the breadboard's anatomy and how to use one.

How to Use a Breadboard

May 14, 2013

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.

Installing the Arduino IDE

The following steps provide a quick overview of getting started with the Arduino IDE and the RedBoard Qwiic USB drivers. For more detailed, step-by-step instructions on installing and using the Arduino IDE on your computer, please read through the tutorial below:

Installing Arduino IDE

March 26, 2013

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

Download the Arduino IDE

In order to get your microcontroller up and running, you'll need to download the newest version of the Arduino IDE first (it's free and open source!).

This software, known as the Arduino IDE, allows you to program the board to do exactly what you want. It’s like a word processor for writing code. If you have not already, go ahead and open Arduino.

Optional: Download the Tinker Kit Code Examples

If you're looking to plan ahead for the circuits in this guide or just prefer to not copy and paste them into Arduino while following along, find them in the GitHub repository or click the button below to download a ZIP the Arduino examples:

Unzip the download and either keep the Tinker Kit Code folder in your Downloads folder to open them as you go or you can move them to your Arduino sketchbook folder to open them in the Arduino IDE. If you're not sure where the sketchbook folder is, go to File > Preferences and look for the filepath titled "Sketchbook location". You can also use this option to change the sketchbook location if you prefer.

Screenshot showing Arduino sketchbook location.
Having trouble seeing the detail in this screenshot? Click on it for a larger view.

Install the CH340 USB Drivers

If you are using the RedBoard Qwiic, you will need to install drivers for the CH340.

RedBoard Qwiic with CH340 Highlighted

The drivers for the CH340C may be pre-installed on Windows, Mac, and Linux or may automatically install when the RedBoard Qwiic is connected to your computer. However, there are a wide range of operating systems and versions out there so we recommend installing the drivers to ensure that they work properly. Please go to How to Install CH340 Drivers for specific instructions on how to install the CH340C drivers with your RedBoard Qwiic.

How to Install CH340 Drivers

August 6, 2019

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

Connect the RedBoard to Your Computer

Connect the RedBoard Qwiic to one of your computer's USB inputs using the included micro-USB cable.

Select Your Board: Arduino Uno

Before we can start jumping into the experiments, there are a couple adjustments we need to make. This step is required to tell the Arduino IDE which of the many Arduino boards we have. Go up to the Tools menu then hover over Board and select Arduino Uno.

Arduino IDE board selection
Note: In case you were wondering, your SparkFun RedBoard Qwiic and the Arduino Uno are interchangeable in the Arduino IDE but you won’t find the RedBoard Qwiic listed in Arduino by default.

Select a Serial Port

Next up we need to tell the Arduino IDE which of our computer's serial ports the microcontroller is connected to. For this, again go up to the Tools menu, then hover over Port and select your RedBoard's serial port. If you're not sure about which port is correct, open the Port menu without the RedBoard connected, take note of the ports available, connect the RedBoard and see which port appears. That new port is your RedBoard's port.

Arduino IDE port selection

With that, you're ready to build your first circuit!

Light-Emitting Diodes, or LEDs (pronounced el-ee-dees), are small, powerful lights that are used in many different applications. You can find LEDs in just about any source of light nowadays, from the bulbs lighting your home to the tiny status lights flashing on your home electronics. Blinking an LED is the classic starting point for learning how to program embedded electronics. It's the "Hello, World!" of microcontrollers.

In this circuit, you'll write code that makes an LED flash on and off. This will teach you how to build a circuit, write a short program and upload that program to your RedBoard.

Tinker Kit Circuit 1

Parts Needed

This circuit requires the following parts:

  • 1x Breadboard
  • 1x SparkFun RedBoard Qwiic
  • 1x Red LED
  • 1x 330Ω Resistor
  • 2x Jumper Wires

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
LED - Assorted (20 pack)

LED - Assorted (20 pack)

COM-12062
$3.30
8
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20
Resistor 330 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 330 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14490
$0.95
New Components and Concepts: Each circuit introduces new components or parts used in the circuit as well as a few new concepts that help you understand what your circuit and code does and why.

New Components

LED (Light Emitting Diode)

Light-Emitting Diodes (LEDs) are small lights made from a silicon diode. They come in different colors, brightnesses and sizes. LEDs have a positive (+) leg and a negative (-) leg, and they only let electricity flow through them in one direction. LEDs can also burn out if too much electricity flows through them, so you should always use a resistor to limit the current when you wire an LED into a circuit.

LED

Resistors

Resistors create a resistance to limit the flow of electricity in a circuit. You can use them to protect sensitive components like LEDs. The strength of a resistor (measured in ohms) is marked on the body of the resistor using small colored bands. Each color stands for a number, which you can look up using a resistor chart.

Resistors

New Concepts

Polarity

Many electronics components have polarity, meaning electricity only flows through them in one direction. Components like resistors do not have polarity; electricity flows through them in either direction. LEDs are polarized and only work when electricity flows through them in one direction.

Ohm's Law

Ohm's law describes the relationship between the three fundamental elements of electricity: voltage, resistance and current. The following equation represents their relationship:

Ohm's Law

Where

  • V = Voltage in volts
  • I = Current in amps
  • R = Resistance in ohms (&ohm;)

Use this equation to calculate which resistor values are suitable to sufficiently limit the current flowing to the LED so that it does not get too hot and burn out.

Digital Output

When working with microcontrollers such as the RedBoard Qwiic, each has a variety of pins you can connect to electronic components. Knowing which pins perform which functions is important when building your circuit. This circuit uses what is known as a digital output. The RedBoard Qwiic has 14 pins that work as digital outputs. Digital pins only have two states: ON or OFF. These two states can also be thought of as HIGH/LOW or TRUE/FALSE, respectively. When an LED is connected to one of these pins, the pin can only perform two jobs: turning the LED on and turning the LED off. We'll explore the other pins and their functions in later circuits.

RedBoard digital pins

The 14 digital pins highlighted.

Hardware Hookup

Take some time familiarizing yourself with each of the components used in each circuit before assembling the parts.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Pay close attention to the LED. It is polarized. The negative side of the LED is the short leg, marked with a flat edge.

LED drawing

Components like resistors need their legs bent into 90° angles in order to correctly fit the breadboard sockets.

Bent resistor

Ready to start hooking everything up? Check out the circuit diagram and hookup table below to see how everything connects.

Circuit Diagram

Circuit Diagrams: SparkFun uses a program called Fritzing to draw the circuit diagrams you see throughout this guide. Fritzing allows us to create diagrams that make it easier for you to see how your circuit should be built.

Circuit 1 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

Hookup Tables: Many electronics beginners find it helps to have a coordinate system when building their circuits. For each circuit, you'll find a hookup table that lists the coordinates of each component and where it connects to the RedBoard, the breadboard, or both. The breadboard has a letter/number coordinate system, just like the game Battleship.
ComponentRedBoard QwiicBreadboardBreadboard
LED A1 LED ( - )A2 LED ( + )
330Ω Resistor
(orange, orange, brown)
E2F2
Jumper WireGNDE1
Jumper WireDigital Pin 13J2

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open Your First Sketch

Open the Arduino IDE software on your computer if it's not already open. If you previously downloaded and moved the Tinker Kit Code into your Arduino sketchbook folder, open the Circuit 1 example by navigating to File > Sketchbook > SparkFun Tinker Kit Code > Circuit 1 Blink.

Opening Circuit 1 in Arduino Sketchbook.

Alternatively, you can copy and paste the following code into a blank sketch in Arduino. Hit upload, and watch what happens!

language:cpp
/*
SparkFun Tinker Kit
Circuit 1: Blink an LED

Turns an LED connected to pin 13 on and off. Repeats forever.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit/
Download code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code
*/

void setup() {

pinMode(13, OUTPUT);      // Set pin 13 to output

}


void loop() {

digitalWrite(13, HIGH);   // Turn on the LED

delay(2000);              // Wait for two seconds

digitalWrite(13, LOW);    // Turn off the LED

delay(2000);              // Wait for two seconds

}

What You Should See

The LED will turn on for two seconds then off for two seconds repeatedly. If it doesn't, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the Troubleshooting tips at the end of this section.

Tinker Kit Circuit 1 Demo

Program Overview

  1. Turn the LED on by sending power to Pin 13.
  2. Wait 2 seconds (2000 milliseconds).
  3. Turn the LED off by cutting power to Pin 13.
  4. Wait 2 seconds (2000 milliseconds).
  5. Repeat.

One of the best ways to understand the code you just uploaded is to change something and see how it affects the behavior of your circuit. For this first circuit, try changing the number found in these lines of code:

language:c
`delay(2000);` 

What happens if you change both to 100? What happens if you change both to 5000? What happens if you change just one delay and not the other?

Onboard LED PIN 13: You may have noticed a second, smaller LED blinking in unison with the LED in your breadboard circuit. This is known as the onboard LED, and you can find one on almost any Arduino or Arduino-compatible board including the RedBoard. In most cases, this LED is connected to digital pin 13 (D13), which is the same pin used in this circuit. This LED is useful for troubleshooting, as you can always upload the Blink sketch to see if that LED lights up. If so, you know your board is functioning properly. If you do not want this LED to blink with other LEDs in your circuits, simply use any of the other 12 digital pins (D0-D12).

Code to Note

Code to Note: The sketches that accompany each circuit introduce new programming techniques and concepts as you progress through the guide. The Code to Note section highlights specific lines of code from the sketch and explains them in further detail.
CodeDescription
Setup and Loop:
void setup(){code to run once}&void loop(){code to run forever}
Every Arduino program needs these two functions. Code that goes in between the curly brackets of setup() runs once, then the code in between the loop() curly brackets runs over and over until the RedBoard is reset or powered off.
Input or Output?:
pinMode(13, OUTPUT);
Before you can use one of the digital pins, you need to tell the RedBoard whether it is an INPUT or OUTPUT. We use a built-in "function" called pinMode() to make pin 13 a digital output. You'll learn more about digital inputs in the digital trumpet circuit.
Digital Output:
digitalWrite(13, HIGH);
When you're using a pin as an OUTPUT, you can command it to be HIGH (output 5 volts) or LOW (output 0 volts).
Delay:
delay(time in milliseconds);
Causes the program to wait on this line of code for the amount of time in between the brackets. After the time has passed, the program will continue to the next line of code.
Comments:
//This is a comment
Comments are a great way to leave notes in your code explaining why you wrote it the way you did. You'll find many comments in the examples that further explain what the code is doing and why. Comments can be single line using //, or they can be multi-line using /* */.

Coding Challenges

Coding Challenges: The Coding Challenges section is where you can find suggestions for changes to the circuit or code that will make the circuit more challenging. If you feel underwhelmed by the tasks in each circuit, visit the Coding Challenges section to push yourself to the next level.
ChallengeDescription
Persistence of VisionComputer screens, movies and the lights in your house all flicker so quickly that they appear to be on all of the time but are actually blinking faster than the human eye can detect. See how much you can decrease the delay time in your program before the light appears to be on all the time but is still blinking.
Morse CodeTry changing the delays and adding more digitalWrite() commands to make your program blink a message in Morse code.

Troubleshooting

Troubleshooting: Last, each circuit has a Troubleshooting section with helpful tips and tricks to aid you in any problems you encounter along the way.
ProblemSolution
I get an error when uploading my codeThe most likely cause is that you have the wrong board selected in the Arduino IDE. Make sure you have selected Tools > Board > Arduino Uno.
I still get an error when uploading my codeIf you're sure you have the correct Board selected but you still can't upload, check that you have selected the correct Serial Port. You can change this in Tools > Serial Port >your_serial_port.
Which Serial Port is the right one?Depending on how many devices you have plugged into your computer, you may have several active Serial Ports. Make sure you are selecting the correct one. A simple way to determine this is to look at your list of Serial Ports. Unplug your RedBoard from your computer. Look at the list again. Whichever Serial Port has disappeared from the list is the one you want to select once you plug your board back in to your computer.
My code uploads, but my LED won’t turn onLEDs will only work in one direction. Try taking it out of your breadboard, turning it 180 degrees, and reinserting it.
Still not working?Jumper wires unfortunately can go "bad" from getting bent too much. The copper wire inside can break, leaving an open connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working.

Circuit 2: Potentiometer

Potentiometers (also known as “pots” or “knobs”) are one of the more basic inputs for electronics devices. By tracking the position of the knob with your RedBoard, you can make volume controls, speed controls, angle sensors and a ton of other useful inputs for your projects. In this circuit, you'll use a potentiometer as an input device to control the speed at which your LED blinks.

Tinker Kit Circuit 2

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x SparkFun RedBoard
  • 1x Red LED
  • 1x 330Ω Resistor
  • 7x Jumper Wires
  • 1x Potentiometer

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
Trimpot 10K Ohm with Knob

Trimpot 10K Ohm with Knob

COM-09806
$0.95
6
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20
Resistor 330 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 330 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14490
$0.95
LED - Basic Red 5mm

LED - Basic Red 5mm

COM-09590
$0.35

New Components

Potentiometer

A potentiometer (trimpot for short) is a variable resistor. When powered with 5V, the middle pin outputs a voltage between 0V and 5V, depending on the position of the knob on the potentiometer. Internal to the trimpot is a single resistor and a wiper, which cuts the resistor in two and moves to adjust the ratio between both halves. Externally, there are usually three pins: two pins connect to each end of the resistor, while the third connects to the pot's wiper.

potentiometer

New Concepts

Analog vs. Digital

Understanding the difference between analog and digital is a fundamental concept in electronics.

We live in an analog world. There is an infinite number of colors to paint an object (even if the difference is indiscernible to our eye), an infinite number of tones we can hear, and an infinite number of smells we can smell. The common theme among all of these analog signals is their infinite possibilities.

Digital signals deal in the realm of the discrete or finite, meaning there is a limited set of values they can be. The LED from the previous circuit had only two states it could exist in, ON or OFF, when connected to a Digital Output.

Analog Inputs

So far, we've only dealt with outputs. The RedBoard also has inputs. Both inputs and outputs can be analog or digital. Based on our definition of analog and digital above, that means an analog input can sense a wide range of values versus a digital input, which can only sense two states.

You may have noticed some pins labeled Digital and some labeled Analog In on your RedBoard. There are only six pins that function as analog inputs labeled A0--A5.

RedBoard analog pins highlighted

The six analog pins highlighted.

Voltage Divider

A voltage divider is a simple circuit that turns some voltage into a smaller voltage using two resistors. The following is a schematic of the voltage divider circuit. Schematics are a universally agreed upon set of symbols that engineers use to represent electric circuits.

voltage divider

A potentiometer is a variable resistor that can be used to create an adjustable voltage divider.

Schematic symbol for a potentiometer

A potentiometer schematic symbol where pins 1 and 3 are the resistor ends, and pin 2 connects to the wiper

If the outside pins connect to a voltage source (one to ground, the other to Vin), the output (Vout) at the middle pin will mimic a voltage divider. Turn the trimpot all the way in one direction, and the voltage may be zero; turned to the other side, the output voltage approaches the input. A wiper in the middle position means the output voltage will be half of the input.

Voltage dividers will be covered in more detail in the next circuit.

Hardware Hookup

The potentiometer has three legs. Pay close attention into which pins you're inserting it on the breadboard, as they will be hard to see once inserted.

Potentiometers are not polarized. You can attach either of the outside pins to 5V and the opposite to GND. However, the values you get out of the trimpot will change based on which pin is 5V and which is GND.

potentiometer_pinout

Ready to start hooking everything up? Check out the circuit diagram and hookup table below to see how everything is connected.

Circuit Diagram

Circuit 2 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
LED A1 LED ( - )A2 LED ( + )
330Ω Resistor
(orange, orange, brown)
E2F2
Jumper WireE1GND Rail ( - )
Jumper WireDigital Pin 13J2
PotentiometerB25B26B27
Jumper WireAnalog Pin 0 (A0)E26
Jumper WireE255V Rail ( + )
Jumper WireE27GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

Open the sketch from your Arduino sketchbook or copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:c
/*
SparkFun Tinker Kit
Circuit 2: Potentiometer

Changes how fast an LED connected to pin 13 blinks, based on a potentiometer connected to pin A0

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit/
Download code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code
*/

int potPosition;       //this variable will hold a value based on the position of the potentiometer

void setup()
{
  Serial.begin(9600);       //start a serial connection with the computer

  pinMode(13, OUTPUT);      //set pin 13 as an output that can be set to HIGH or LOW
}

void loop()
{
  //read the position of the pot
  potPosition = analogRead(A0);    //set potPosition to a number between 0 and 1023 based on how far the knob is turned
  Serial.println(potPosition);     //print the value of potPosition in the serial monitor on the computer

  //change the LED blink speed based on the trimpot value
  digitalWrite(13, HIGH);           // Turn on the LED
  delay(potPosition);              // delay for as many miliseconds as potPosition (0-1023)

  digitalWrite(13, LOW);            // Turn off the LED
  delay(potPosition);              // delay for as many miliseconds as potPosition (0-1023)
}

What You Should See

Try adjusting the potentiometer's position and you should see the LED blink faster or slower in accordance with it. The delay between each flash will change based on the position of the knob. If it isn't working, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the Troubleshooting section.

Tinker Kit Circuit 2 demo

Program Overview

  1. Read the position of the potentiometer (from 0 to 1023) and store it in the variable potPosition.
  2. Turn the LED on.
  3. Wait from 0 to 1023 milliseconds, based on the position of the knob and the value of potPosition.
  4. Turn the LED off.
  5. Wait from 0 to 1023 milliseconds, based on the position of the knob and the value of potPosition.
  6. Repeat.
The Serial Monitor: The Serial Monitor is one of the Arduino IDE's many great built-in tools. It can help you understand the values that your program is trying to work with, and it can be a powerful debugging tool when you run into issues where your code is not behaving the way you expected it to. This circuit introduces you to the Serial Monitor by showing you how to print the values from your potentiometer to it. To see these values, click the Serial Monitor button, found in the upper-right corner of the IDE in most recent versions. You can also select Tools > Serial Monitor from the menu.

You should then see numeric values print out on the monitor. Turn the potentiometer, and you should see the values change as well as the delay between each print.



If you are having trouble seeing the values, ensure that you have selected 9600 baud in the dropdown menu and have auto scroll checked.

Code to Note

CodeDescription
Integer Variables:
int potPosition;
A variable is a placeholder for values that may change in your code. You must introduce, or "declare" variables before you use them. Here we're declaring a variable called potPosition of type int (integer). We will cover more types of variables in later circuits. Don't forget that variable names are case-sensitive!
Serial Begin:
Serial.begin(9600);
Serial commands can be used to send and receive data from your computer. This line of code tells the RedBoard that we want to "begin" that communication with the computer, the same way we would say "Hi" to initiate a conversation. Notice that the baud rate, 9600, is the same as the one we selected in the monitor. This is the speed at which the two devices communicate, and it must match on both sides.
Analog Input:
potPosition = analogRead(A0);
We use the analogRead() function to read the value on an analog pin. analogRead() takes one parameter, the analog pin you want to use, A0 in this case, and returns a number between 0 (0 volts) and 1023 (5 volts), which is then assigned to the variable potPosition.
Serial Print:
Serial.println(potPosition);
This is the line that actually prints the trimpot value to the monitor. It takes the variable potPosition and prints whatever value it equals at that moment in the loop(). The ln at the end of print tells the monitor to print a new line at the end of each value; otherwise the values would all run together on one line. Try removing the ln to see what happens.

Coding Challenges

ChallengeDescription
Changing the RangeTry multiplying, dividing or adding to your sensor reading so that you can change the range of the delay in your code. For example, can you multiply the sensor reading so that the delay goes from 0–2046 instead of 0–1023?
Adding More LEDsAdd more LEDs to your circuit. Don't forget the current limiting resistor for each one. Try making multiple LEDs blink at different rates by changing the range of each using multiplication or division.

Troubleshooting

ProblemSolution
The potentiometer always reads as 0 or 1023Make sure that your 5V, A0 and GND pins are properly connected to the three pins on your potentiometer. It is easy to misalign a wire with the actual trimpot pin.
No values in Serial MonitorMake sure that you have selected the correct baud rate, 9600. Also ensure that you are on the correct Serial Port. The same Serial Port you use when uploading code to your board is the same Serial Port you use to print values to the Serial Monitor.

Circuit 3: Photoresistor

In the previous circuit, you got to use a potentiometer, which varies resistance based on the twisting of a knob. In this circuit you’ll be using a photoresistor, which changes resistance based on how much light the sensor receives. This circuit creates a simple night-light using the photoresistor that turns on when the room gets dark and turns off when it is bright.

Tinker Kit Circuit 3

Parts Needed

Gather the following parts required for this circuit:

  • 1x Breadboard
  • 1x SparkFun RedBoard Qwiic
  • 7x Jumper Wires
  • 1x Red LED
  • 1x 330Ω Resistor
  • 1x Photoresistor
  • 1x 10kΩ Resistor

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
LED - Assorted (20 pack)

LED - Assorted (20 pack)

COM-12062
$3.30
8
Mini Photocell

Mini Photocell

SEN-09088
$1.50
7
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20
Resistor 10K Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 10K Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14491
$1.20
Resistor 330 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 330 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14490
$0.95

New Components

Photoresistor

Photoresistors, or photocells, are light-sensitive, variable resistors. As more light shines on the sensor’s head, the resistance between its two terminals decreases and vice versa. They’re an easy-to-use component in projects that require ambient-light sensing.

Photoresistor

New Concepts

Analog to Digital Conversion

We covered the difference between analog and digital signals in the last experiment but you may be wondering how a digital thing like the RedBoard Qwiic can interpret analog signals. The answer to that is an Analog to Digital Converter (or ADC). The six analog inputs (A0--A5) we highlighted in the last circuit all use an ADC. These pins "sample" the analog signal and create a digital signal for the microcontroller to interpret. The "resolution" of this signal is based on the resolution of the ADC. In the case of the RedBoard, that resolution is 10-bit. With a 10-bit ADC, we get 2 ^ 10 = 1024 possible values, which is why the analog signal varies between 0 and 1023.

Voltage Divider Continued

Since the RedBoard can’t directly interpret resistance (rather, it reads voltage), we need to use a voltage divider to use our photoresistor, a part that doesn't output voltage. The resistance of the photoresistor changes as it gets darker or lighter which changes the amount of voltage that is read on the analog pin and "divides" the voltage, 5V in this case. That divided voltage is then read on the analog to digital converter.

Left: A regular voltage divider circuit. Vout will be a constant voltage. Right: A variable voltage divider circuit. Vout will fluctuate as the resistance of the photoresistor changes.

The voltage divider equation assumes that you know three values of the above circuit: the input voltage (Vin), and both resistor values (R1 and R2). Given those values, we can use this equation to find the output voltage (Vout):

Vout = Vin * (R2 / (R1 + R2))

If R1 is a constant value (the resistor) and R2 fluctuates (the photoresistor), the amount of voltage measured on the Vout pin changes.

Hardware Hookup

The photoresistor is not polarized. It can be inserted in either direction.

Ready to start hooking everything up? Check out the circuit diagram and hookup table below to see how everything is connected.

Circuit Diagram

Circuit 3 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
LED A1 LED ( - )A2 LED ( + )
330Ω Resistor
(orange, orange, brown)
E2F2
Jumper WireE1GND Rail ( - )
Jumper WireDigital Pin 13J2
PhotoresistorA26B25
10kΩ Resistor
(brown, black, orange)
C26D27
Jumper WireAnalog Pin 0 (A0)E26
Jumper WireE255V Rail ( + )
Jumper WireE27GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

Open the example code from your Arduino sketchbook or copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Tinker Kit
Circuit 3: Photoresistor

Use a photoresistor to monitor how bright a room is, and turn an LED on when it gets dark.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit/
Download drawings and code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code
*/

int photoresistor = 0;              //this variable will hold a value based on the position of the knob
int threshold = 750;                //if the photoresistor reading is below this value the light will turn on

void setup()
{
  Serial.begin(9600);               //start a serial connection with the computer

  pinMode(13, OUTPUT);              //set pin 13 as an output that can be set to HIGH or LOW
}

void loop()
{
  //read the position of the knob
  photoresistor = analogRead(A0);   //set photoresistor to a number between 0 and 1023 based on how far the knob is turned
  Serial.println(photoresistor);    //print the value of photoresistor in the serial monitor on the computer

  //if the photoresistor value is below the threshold turn the light on, otherwise turn it off
  if (photoresistor < threshold){
    digitalWrite(13, HIGH);         // Turn on the LED  
  } else{
    digitalWrite(13, LOW);          // Turn off the LED
  }

  delay(100);                       //short delay to make the printout easier to read
}

What You Should See

The program stores the light level in a variable, photoresistor. Then, using an if/else statement, the program checks to see what it should do with the LED. If the variable is above the threshold (it’s bright), turn the LED off. If the variable is below the threshold (it’s dark), turn the LED on. You now have just built your own night-light!

Tinker Kit Circuit 3 Photoresistor

Open the Serial Monitor in Arduino. The value of the photoresistor should be printed every so often. When the photoresistor value drops below the threshold value set in the code, the LED should turn on (you can cover the photoresistor with your finger to make the value drop).

Note: If the room you are in is very bright or dark, you may have to change the value of the “threshold” variable in the code to make your night-light turn on and off. See the Troubleshooting section for instructions.

Program Overview

  1. Store the light level in the variable photoresistor.
  2. If the value of photoresistor is above the threshold (it’s bright), turn the LED off.
  3. If the value of photoresistor is below the threshold (it’s dark), turn the LED on.

Code to Note

CodeDescription
If/else Statements:
if(logic statement) {
code to be run if the logic statement is true}
else {
code to be run if the logic statement is false }
The if/else statement lets your code react to the world by running one set of code when the logic statement in the round brackets is true and another set of code when the logic statement is false. For example, this sketch uses an if statement to turn the LED on when it is dark, and turn the LED off when it is light.
Logical Operators:
(photoresistor < threshold)
Programmers use logic statements to translate things that happen in the real world into code. Logic statements use logical operators such as 'equal to' (==), 'greater than' (>), and 'less than' (<), to make comparisons. When the comparison is true (e.g., 4 < 5) then the logic statement is true. When the comparison is false (e.g., 5 < 4) then the logic statement is false. This example is asking whether the variable photoresistor is less than the variable threshold.

Coding Challenges

ChallengeDescription
Response PatternRight now your if statement turns the LED on when it gets dark, but you can also use the light sensor like a no-touch button. Try using digitalWrite() and delay() to make the LED blink a pattern when the light level drops, then calibrate the threshold variable in the code so that the blink pattern triggers when you wave your hand over the sensor.
Replace 10K&ohm; Resistor with LEDAlter the circuit be replacing the 10K&ohm; resistor with an LED (the negative leg should connect to GND). Now what happens when you place your finger over the photoresistor? This is a great way to see Ohm's law in action by visualizing the change in resistance's affect on the current flowing through the LED.

Troubleshooting

ProblemSolution
The light never turns on or always stays onStart the Serial Monitor in Arduino. Look at the value that the photoresistor is reading in a bright room (e.g., 915). Cover the photoresistor, or turn the lights off. Then look at the new value that the photoresistor is reading (e.g., 550). Set the threshold in between these two numbers (e.g., 700) so that the reading is above the threshold when the lights are on and below the threshold when the lights are off.
Nothing is printing in the Serial MonitorTry unplugging your USB cable and plugging it back in. In the Arduino IDE, go to Tools > Port, and make sure that you select the right port.

Circuit 4: RGB Night-Light

In this circuit, you'll take the night-light concept to the next level by adding an RGB LED, which is three differently colored Light-Emitting Diodes (LEDs) built into one component. RGB stands for Red, Green and Blue, and these three colors can be combined to create any color of the rainbow!

Tinker Kit Circuit 4

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x SparkFun RedBoard
  • 12x Jumper Wires
  • 1x LED - RGB Diffused Common Cathode
  • 3x 330Ω Resistor
  • 1x 10K Potentiometer
  • 1x Photoresistor
  • 1x 10kΩ Resistor

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
Trimpot 10K Ohm with Knob

Trimpot 10K Ohm with Knob

COM-09806
$0.95
6
Mini Photocell

Mini Photocell

SEN-09088
$1.50
7
LED - RGB Diffused Common Cathode

LED - RGB Diffused Common Cathode

COM-09264
$2.05
2
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20
Resistor 10K Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 10K Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14491
$1.20
Resistor 330 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 330 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14490
$0.95

New Components

RGB LED

An RGB LED is actually three small LEDs --- one red, one green and one blue --- inside a normal LED housing. The RGB LED included in this kit has all the internal LEDs share the same ground wire, so there are four legs in total. To turn one color on, ensure ground is connected, then power one of the legs just as you would a regular LED. If you turn on more than one color at a time, you will see the colors start to blend together to form a new color.

RGB LED

New Concepts

Analog Output (Pulse-width Modulation)

You can use the digitalWrite() command to turn pins on the RedBoard on (5V) or off (0V), but what if you want to output 2.5V? The RedBoard doesn't have an Analog Output, but it is really good at switching some digital pins on and off fast enough to simulate an analog output. analogWrite() can output 2.5 volts by quickly switching a pin on and off so that the pin is only on 50 percent of the time (50% of 5V is 2.5V). By changing the percent of time that a pin is on, from 0 percent (always off) to 100 percent (always on), analogWrite() can output any voltage between 0 and 5V. This is known as pulse-width modulation (or PWM). By using PWM, you can create many different colors with the RGB LED.

Digital (PWM~): Only a few of the pins on the RedBoard have the circuitry needed to turn on and off fast enough for PWM. These are pins 3, 5, 6, 9, 10 and 11. Each PWM pin is marked with a ~ on the board. Remember, analogWrite() can only used on these pins.

Creating Your Own Simple Functions

When programmers want to use a piece of code over and over again, they write a function. The simplest functions are just chunks of code that you give a name to. When you want to run that code, you can “call” the function by typing its name, instead of writing out all of the code. More complicated functions take and return pieces of information from the program (we call these pieces of information parameters). In this circuit, you'll write functions to turn the RGB LED different colors by just typing that color's name.

Hardware Hookup

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Just like a regular LED, an RGB LED is polarized and only allows electricity to flow in one direction. Pay close attention to the flat edge and to the different length leads. Both are indicators to help orient the LED correctly.

RGB LED Pins

Ready to start hooking everything up? Check out the circuit diagram and hookup table below to see how everything is connected.

Circuit Diagram

Circuit 4 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboardBreadboard
RGB LED A5 (RED)A4 (GND)A3 (GREEN)A2 (BLUE)
330Ω Resistor
(orange, orange, brown)
E2F2
330Ω Resistor
(orange, orange, brown)
E3F3
330Ω Resistor
(orange, orange, brown)
E5F5
Jumper WireE4GND Rail ( - )
Jumper WireDigital Pin 9J5
Jumper WireDigital Pin 10J3
Jumper WireDigital Pin 11J2
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
PotentiometerB15B16B17
Jumper WireAnalog Pin 1 (A1)E16
Jumper WireE155V Rail ( + )
Jumper WireE17GND Rail ( - )
PhotoresistorA26B25
10kΩ Resistor
(brown, black, orange)
C26D27
Jumper WireAnalog Pin 0 (A0)E26
Jumper WireE255V Rail ( + )
Jumper WireE27GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

Open the example code from your Arduino sketchbook or copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Tinker Kit
Circuit 4: RGB Night-Light

Turns an RGB LED on or off based on the light level read by a photoresistor.
Change colors by turning the potentiometer.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit/
Download drawings and code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code
 */

int photoresistor;          //variable for storing the photoresistor value
int potentiometer;          //variable for storing the photoresistor value
int threshold = 700;            //if the photoresistor reading is lower than this value the light wil turn on

//LEDs are connected to these pins
int RedPin = 9;
int GreenPin = 10;
int BluePin = 11;

void setup() {
  Serial.begin(9600);           //start a serial connection with the computer

  //set the LED pins to output
  pinMode(RedPin,OUTPUT);
  pinMode(GreenPin,OUTPUT);
  pinMode(BluePin,OUTPUT);
}

void loop() {

  photoresistor = analogRead(A0);         //read the value of the photoresistor
  potentiometer = analogRead(A1);

  Serial.print("Photoresistor value:");
  Serial.print(photoresistor);          //print the photoresistor value to the serial monitor
  Serial.print("  Potentiometer value:");
  Serial.println(potentiometer);          //print the photoresistor value to the serial monitor

  if(photoresistor < threshold){          //if it's dark (the photoresistor value is below the threshold) turn the LED on
    //These nested if staments check for a variety of ranges and 
    //call different functions based on the current potentiometer value.
    //Those functions are found at the bottom of the sketch. 
    if(potentiometer > 0 && potentiometer <= 150)
      red();
    if(potentiometer > 150 && potentiometer <= 300)
      orange();
    if(potentiometer > 300 && potentiometer <= 450)
      yellow(); 
    if(potentiometer > 450 && potentiometer <= 600)
      green();
    if(potentiometer > 600 && potentiometer <= 750)
      cyan();
    if(potentiometer > 750 && potentiometer <= 900)
      blue(); 
    if(potentiometer > 900)
      magenta();  
  } 
  else {                                //if it isn't dark turn the LED off

    turnOff();                            //call the turn off function

  }  

  delay(100);                             //short delay so that the printout is easier to read
}

void red (){

    //set the LED pins to values that make red    
    analogWrite(RedPin, 100);
    analogWrite(GreenPin, 0);
    analogWrite(BluePin, 0);
}
void orange (){

    //set the LED pins to values that make orange
    analogWrite(RedPin, 100);
    analogWrite(GreenPin, 50);
    analogWrite(BluePin, 0);
}
void yellow (){

    //set the LED pins to values that make yellow
    analogWrite(RedPin, 100);
    analogWrite(GreenPin, 100);
    analogWrite(BluePin, 0);
}
void green (){

    //set the LED pins to values that make green    
    analogWrite(RedPin, 0);
    analogWrite(GreenPin, 100);
    analogWrite(BluePin, 0);
}
void cyan (){

    //set the LED pins to values that make cyan    
    analogWrite(RedPin, 0);
    analogWrite(GreenPin, 100);
    analogWrite(BluePin, 100);
}
void blue (){

    //set the LED pins to values that make blue
    analogWrite(RedPin, 0);
    analogWrite(GreenPin, 0);
    analogWrite(BluePin, 100);
}
void magenta (){

    //set the LED pins to values that make magenta   
    analogWrite(RedPin, 100);
    analogWrite(GreenPin, 0);
    analogWrite(BluePin, 100);
}
void turnOff (){

    //set all three LED pins to 0 or OFF
    analogWrite(RedPin, 0);
    analogWrite(GreenPin, 0);
    analogWrite(BluePin, 0);
}

What You Should See

This sketch is not dissimilar from the last. It reads the value from the photoresistor, compares it to a threshold value, and turns the RGB LED on or off accordingly. This time, however, we've added a potentiometer back into the circuit. When you twist the pot, you should see the color of the RGB LED change based on the pot's value.

Circuit 4 demo photo

Open the Serial Monitor. The value being read by the light sensor should be printed several times a second. When you turn out the lights or cover the sensor, the LED will shine whatever color your programmed in your color function. Next to the light value, you'll see the potentiometer value print out as well.

Note: If the room you are in is very bright or dark, you may have to change the value of the “threshold” variable in the code to make your night-light turn on and off. See the Troubleshooting section for instructions.

Program Overview

  1. Store the light level from pin A0 in the variable photoresistor.
  2. Store the potentiometer value from pin A1 in the variable potentiometer.
  3. If the light level variable is above the threshold, call the function that turns the RGB LED off.
  4. If the light level variable is below the threshold, call one of the color functions to turn the RGB LED on.
  5. If potentiometer is between 0 and 150, turn the RGB LED on red.
  6. If potentiometer is between 151 and 300, turn the RGB LED on orange.
  7. If potentiometer is between 301 and 450, turn the RGB LED on yellow.
  8. If potentiometer is between 451 and 600, turn the RGB LED on green.
  9. If potentiometer is between 601 and 750, turn the RGB LED on cyan.
  10. If potentiometer is between 751 and 900, turn the RGB LED on blue.
  11. If potentiometer is greater than 900, turn the RGB LED on magenta.

Code to Note

CodeDescription
Analog Output (PWM):
analogWrite(RedPin, 100);
The analogWrite() function outputs a voltage between 0 and 5V on a pin. The function breaks the range between 0 and 5V into 255 little steps. Note that we are not turning the LED on to full brightness (255) in this code so that the night-light is not too bright. Feel free to change these values and see what happens.
Nested if Statements:
if(logic statement) {
if(logic statement) {
code to be run if the logic statement is true}
if(logic statement) {
code to be run if the logic statement is true}
}
A nested if statement is one or more if statements "nested" inside of another if statement. If the parent if statement is true, then the code looks at each of the nested if statements and executes any that are true. If the parent if statement is false, then none of the nested statements will execute.
More Logical Operators:
if(potentiometer > 0 && potentiometer <= 150)
These if statements are checking for two conditions by using the AND (&&) operator. In this line, the if statement will only be true if the value of the variable potentiometer is greater than 0 AND if the value is less than or equal to 150. By using &&, the program allows the LED to have many color states.
Defining a Function:
void function_name () {
code to run inside function }
This simple version of a function executes the code inside the curly brackets whenever the name is written in the main program.
Calling a Function:
function_name();
Calls a function that you have created. In a later circuit, you will learn how to make more complicated functions that take data from the main program (these pieces of data are called parameters).

Coding Challenges

ChallengeDescription
Add more colorsYou can create many more colors with the RGB LED. Use the analogWrite() function to blend different values of red, green and blue together to make even more colors. You can divide the potentiometer value up more and make more nested if statements so that you can have more colors as you twist the knob.
Multi color blinkTry using delays and multiple color functions to have your RGB LED change between multiple colors.
Change the thresholdTry setting your threshold variable by reading the value of a potentiometer with analogRead(). By turning the potentiometer, you can then change the threshold level and adjust your night-light for different rooms.
Fading the LEDTry using a loop with the analogWrite() to get your LED to pulse gently or smoothly transition between colors.

Troubleshooting

ProblemSolution
The LED never turns on or offOpen the Serial Monitor in Arduino and make sure that your photoresistor is returning values between 0 and 1023. Try covering the photoresistor; the values should change. If they do not change, check the wiring of the photoresistor.
If your photoresistor is working correctly, make sure that your threshold variable sits in between the value that the photoresistor reads when it is bright and the value that the photoresistor reads when it is dark (e.g., bright = 850, dark = 600, threshold = 700).
My LED doesn’t show the colors that I expectMake sure that all three of the pins driving your RGB LED are set to OUTPUT, using the pinMode() command in the setup section of the code. Then make sure that each LED is wired properly.
Nothing is printing in the Serial MonitorTry unplugging your USB cable and plugging it back in. In the Arduino IDE, go to Tools > Port, and make sure that you select the right port.

Circuit 5: Buzzer

In this circuit, you'll use the RedBoard and a small buzzer to make music, and you'll learn how to program your own songs using arrays.

Tinker Kit Circuit 5

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x SparkFun RedBoard
  • 4x Jumper Wires
  • 1x 10K Potentiometer
  • 1x Buzzer

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
Trimpot 10K Ohm with Knob

Trimpot 10K Ohm with Knob

COM-09806
$0.95
6
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20
Mini Speaker - PC Mount 12mm 2.048kHz

Mini Speaker - PC Mount 12mm 2.048kHz

COM-07950
$1.95
5

New Components

Buzzer

The buzzer uses a small magnetic coil to vibrate a metal disc inside a plastic housing. By pulsing electricity through the coil at different rates, different frequencies (pitches) of sound can be produced. Attaching a potentiometer to the output allows you to limit the amount of current moving through the buzzer and lower its volume.

buzzer

New Concepts

Reset Button

The RedBoard has a built-in reset button. This button will reset the board and start the code over from the beginning, running what is in setup() and then loop().

reset button

Tone Function

The tone function controls the pitch of the buzzer. This function is similar to PWM in that it generates a wave of a certain frequency on the specified pin. The frequency and duration can both be passed to the tone() function when calling it. To turn the tone off, you need to call noTone() or pass a duration of time for it to play and then stop. Unlike PWM, tone() can be used on any digital pin.

Arrays

Arrays operate like variables but they can store multiple values. The simplest array is just a list. Imagine that you want to store the frequency for each note of the C major scale. We could make seven variables and assign a frequency to each one, or we could use an array and store all seven in the same array, as shown below. To refer to a specific value in the array, an index number is used. Arrays are indexed from 0. For example, to call the first element in the array, use array_name[0];; to call the second element, use array_name[1]; and so on.

Musical NoteFrequency (Hz)Using VariablesUsing an Array
A220aFrequencyfrequency[0]
B247bFrequencyfrequency[1]
C261cFrequencyfrequency[2]
D294dFrequencyfrequency[3]
E330eFrequencyfrequency[4]
F349fFrequencyfrequency[5]
G392gFrequencyfrequency[6]

Hardware Hookup

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

The buzzer is polarized. To see which leg is positive and which is negative, flip the buzzer over and look at the markings underneath. Keep track of which pin is where, as they will be hard to see once inserted into the breadboard. There is also text on the positive side of the buzzer, along with a tiny (+) symbol.

Volume Knob

All of the circuits with the buzzer make use of a potentiometer as a rudimentary volume knob. Notice that only two of the potentiometer's legs are used in these circuits. In these instances, the potentiometer is acting as a variable resistor, limiting the amount of current flowing to the speaker and thus affecting the volume as you turn the knob. This is similar to the current-limiting resistor used to limit current to the LED in circuit 1 --- only this time the resistance is variable.

Ready to start hooking everything up? Check out the circuit diagram and hookup table below to see how everything is connected.

Circuit Diagram

Circuit 5 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
BuzzerJ1 (Buzzer + )J3 (Buzzer - )
PotentiometerB1B2B3
Jumper WireGNDGND Rail ( - )
Jumper WireDigital Pin 10F1
Jumper WireE2GND Rail ( - )
Jumper WireE1F3

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

Open the example code from your Arduino sketchbook or copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Tinker Kit
Circuit 5: Buzzer

Play notes using a buzzer connected to pin 10

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit/
Download drawings and code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code/
*/


int speakerPin = 10;               //the pin that buzzer is connected to

void setup()
{
  pinMode(speakerPin, OUTPUT);    //set the output pin for the speaker
}

void loop()
{

  play('g', 2);       //ha
  play('g', 1);       //ppy
  play('a', 4);       //birth
  play('g', 4);       //day
  play('C', 4);       //to
  play('b', 4);       //you

  play(' ', 2);       //pause for 2 beats

  play('g', 2);       //ha     
  play('g', 1);       //ppy
  play('a', 4);       //birth
  play('g', 4);       //day
  play('D', 4);       //to
  play('C', 4);       //you

  play(' ', 2);       //pause for 2 beats

  play('g', 2);       //ha
  play('g', 1);       //ppy
  play('G', 4);       //birth
  play('E', 4);       //day
  play('C', 4);       //dear
  play('b', 4);       //your
  play('a', 6);       //name

  play(' ', 2);       //pause for 2 beats

  play('F', 2);       //ha
  play('F', 1);       //ppy
  play('E', 4);       //birth
  play('C', 4);       //day
  play('D', 4);       //to
  play('C', 6);       //you

  while(true){}       //get stuck in this loop forever so that the song only plays once
}


void play( char note, int beats)
{
  int numNotes = 14;  // number of notes in our note and frequency array (there are 15 values, but arrays start at 0)

  //Note: these notes are C major (there are no sharps or flats)

  //this array is used to look up the notes
  char notes[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G', 'A', 'B', ' '};
  //this array matches frequencies with each letter (e.g. the 4th note is 'f', the 4th frequency is 175)
  int frequencies[] = {131, 147, 165, 175, 196, 220, 247, 262, 294, 330, 349, 392, 440, 494, 0};

  int currentFrequency = 0;    //the frequency that we find when we look up a frequency in the arrays
  int beatLength = 150;   //the length of one beat (changing this will speed up or slow down the tempo of the song)

  //look up the frequency that corresponds to the note
  for (int i = 0; i < numNotes; i++)  // check each value in notes from 0 to 14
  {
    if (notes[i] == note)             // does the letter passed to the play function match the letter in the array?
    {
      currentFrequency = frequencies[i];   // Yes! Set the current frequency to match that note
    }
  }

  //play the frequency that matched our letter for the number of beats passed to the play function
  tone(speakerPin, currentFrequency, beats * beatLength);   
  delay(beats* beatLength);   //wait for the length of the tone so that it has time to play
  delay(50);                  //a little delay between the notes makes the song sound more natural

}

/* CHART OF FREQUENCIES FOR NOTES IN C MAJOR
Note      Frequency (Hz)
c        131
d        147
e        165
f        175
g        196
a        220
b        247
C        262
D        294
E        330
F        349
G        392
A        440
B        494
*/

What You Should See

When the program begins, a song will play from the buzzer once. To replay the song, press the reset button on the RedBoard. Use the potentiometer to adjust the volume.

Tinker Kit Circuit 5

Program Overview

Inside the main loop:

  1. Play the first note for x number of beats using the play function.
    1. (Inside the play function:) Take the note passed to the play function and compare it to each letter in the notes array. When you find a note that matches, remember the index position of that note (e.g., 6th entry in the notes array).
    2. Get a frequency from the frequency array that has the same index as the note that matched (e.g., the 6th frequency).
    3. Play that frequency for the number of beats passed to the play function.
  2. Play the second note using the play function
    ...and so on.

Code to Note

CodeDescription
Character Variables:
void play( char note, int beats)
The char, or character, variable to store character values. For example, in this sketch, the play() function gets passed two variables, a character variable that represents the mucial note we want to play and an integer variable that represents how long to play that note. A second array takes the character variable and associates a frequency value to it. This makes programming a song easier as you can just reference the character and not the exact frequency.
Tone Function:
tone(pin, frequency, duration);
The tone() function will pulse power to a pin at a specific frequency. The duration controls how long the sound will play. Tone can be used on any digital pin.
Declaring an Array:
arrray_name[array_size]; or arrray_name[] = {array elements};
To declare an array, you must give it a name, then either tell Arduino how many positions the array will have or assign a list of values to the array.
Calling an Array:
array_name[index #];
To call one of the values in an array, simply type the name of the array and the index of the value. You can use a variable instead of a number in between the square brackets. Don't forget the index starts at 0, not 1, so to call the first element, use array_name[0];.

Coding Challenges

ChallengeDescription
Change the tempo of the songExperiment with the beatLength; variable to change the tempo of the song.
Make your own songTry changing the notes to make a different song. Spaces "" can be used for rests in the song.

Troubleshooting

ProblemSolution
The song is too quiet or too loudTurn the potentiometer to adjust the volume.
No sound is playingTry pressing the reset button on the RedBoard. If that doesn’t work, check your wiring of the buzzer. It's easy to misalign a pin with a jumper wire.

Circuit 6: Digital Trumpet

Learn about digital inputs and buttons as you build your own digital trumpet!

Tinker Kit Circuit 6

Parts Needed

Gather the following parts to build the circuit:

  • 1x Breadboard
  • 1x SparkFun RedBoard
  • 10x Jumper Wires
  • 1x 10K Potentiometer
  • 1x Buzzer
  • 1x Green Push Button
  • 1x Yellow Push Button
  • 1x Red Push Button

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
Trimpot 10K Ohm with Knob

Trimpot 10K Ohm with Knob

COM-09806
$0.95
6
Multicolor Buttons - 4-pack

Multicolor Buttons - 4-pack

PRT-14460
$1.60
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20
Mini Speaker - PC Mount 12mm 2.048kHz

Mini Speaker - PC Mount 12mm 2.048kHz

COM-07950
$1.95
5

New Components

Buttons

Buttons, also known as momentary switches, are switches that only remain in their on state as long as they’re being actuated, or pressed. Most often momentary switches are best used for intermittent user-input cases: reset button and keypad buttons. These switches have a nice, tactile, “clicky” feedback when you press them.

multicolored buttons

Note that the different colors are just aesthetic. All of the buttons included behave the same no matter their color.

New Concepts

Binary Number System

Number systems are the methods we use to represent numbers. We’ve all been mostly operating within the comfy confines of a base-10 number system, but there are many others. The base-2 system, otherwise known as binary, is common when dealing with computers and electronics. There are really only two ways to represent the state of anything: ON or OFF, HIGH or LOW, 1 or 0. And so, almost all electronics rely on a base-2 number system to store and manipulate numbers. The heavy reliance electronics places on binary numbers means it’s important to know how the base-2 number system works.

Digital Input

In circuit 1, you worked with digital outputs. This circuit focuses on digital inputs. Digital inputs only care if something is in one of two states: TRUE or FALSE, HIGH or LOW, ON or OFF. Digital inputs are great for determining if a button has been pressed or if a switch has been flipped.

Pull-up Resistors

A pull-up resistor is a small circuit that holds the voltage HIGH (5V) on a pin until a button is pressed, pulling the voltage LOW (0V). The most common place you will see a pull-up resistor is when working with buttons. A pull-up resistor keeps the button in one state until it is pressed. The RedBoard has built-in pull-up resistors, but they can also be added to a circuit externally. This circuit uses the internal pull-up resistors, covered in more detail in the Code to Note section.

Hardware Hookup

Buttons are not polarized. However, they do merit a closer look. Buttons make momentary contact from one connection to another, so why are there four legs on each button? The answer is to provide more stability and support to the buttons in your breadboard circuit. Each row of legs is connected internally. When the button is pressed, one row connects to the other, making a connection between all four pins.

button pins explained

If the button's legs don't line up with the slots on the breadboard, rotate it 90 degrees.

Ready to start hooking everything up? Check out the circuit diagram and hookup table below to see how everything is connected.

Circuit Diagram

Circuit 6 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
BuzzerJ1 (Buzzer + )J3 (Buzzer - )
PotentiometerB1B2B3
Jumper WireGNDGND Rail ( - )
Jumper WireDigital Pin 10F1
Jumper WireE2GND Rail ( - )
Jumper WireE1F3
Push ButtonD16/D18G16/G18
Push ButtonD22/D24G22/G24
Push ButtonD28/D30G28/G30
Jumper WireDigital Pin 4J18
Jumper WireDigital Pin 3J24
Jumper WireDigital Pin 2J30
Jumper WireJ16GND Rail ( - )
Jumper WireJ22GND Rail ( - )
Jumper WireJ28GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

Open the example code from your Arduino sketchbook or copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Tinker Kit
Circuit 6: Digital Trumpet

Use 3 buttons plugged to play musical notes on a buzzer.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit/
Download drawings and code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code/
*/

//set the pins for the button and buzzer
int firstKeyPin = 2;
int secondKeyPin = 3;
int thirdKeyPin = 4;

int buzzerPin = 10;


void setup() {
  //set the button pins as inputs
  pinMode(firstKeyPin, INPUT_PULLUP);
  pinMode(secondKeyPin, INPUT_PULLUP);
  pinMode(thirdKeyPin, INPUT_PULLUP);

  //set the buzzer pin as an output
  pinMode(buzzerPin, OUTPUT);
}

void loop() {

  if(digitalRead(firstKeyPin) == LOW){        //if the first key is pressed
    tone(buzzerPin, 262);                     //play the frequency for c
  }
  else if(digitalRead(secondKeyPin) == LOW){  //if the second key is pressed
    tone(buzzerPin, 330);                     //play the frequency for e
  }
  else if(digitalRead(thirdKeyPin) == LOW){   //if the third key is pressed
    tone(buzzerPin, 392);                     //play the frequency for g
  }
  else{
    noTone(buzzerPin);                        //if no key is pressed turn the buzzer off
  }
}

  /*
  note  frequency
  c     262 Hz
  d     294 Hz
  e     330 Hz
  f     349 Hz
  g     392 Hz
  a     440 Hz
  b     494 Hz
  C     523 Hz
  */

What You Should See

Different tones will play when you press different keys. Turning the potentiometer will adjust the volume.

Tinker Kit Circuit 6 demo

Program Overview

  1. Check to see if the first button is pressed. a. If it is, play the frequency for c. b. If it isn’t, skip to the next else if statement.
  2. Check to see if the second button is pressed. a. If it is, play the frequency for e. b. If it isn’t, skip to the next else if statement.
  3. Check to see if the second button is pressed. a. If it is, play the frequency for g. b. If it isn’t, skip to the next else if statement.
  4. If none of the if statements are true a. Turn the buzzer off.

Code to Note

CodeDescription
Internal Pull-Up Resistor:
pinMode(firstKeyPin, INPUT_PULLUP);
To declare a standard input, use the line pinMode(pin_name, INPUT). If you would like to use one of the RedBoard's built-in pull-up 20k&ohm; resistors, it would look like this: pinMode(firstKeyPin, INPUT_PULLUP);. The advantage of external pull-ups is being able to choose a more exact value for the resistor.
Digital Input:
digitalRead(pin);
Check to see if an input pin is reading HIGH (5V) or LOW (0V). Returns TRUE (1) or FALSE (0) depending on the reading.
Is Equal to:
if(digitalRead(firstKeyPin) == LOW)
This is another logical operator. The 'is equal to' symbol (==) can be confusing. Two equals signs are equivalent to asking, "Are these two values equal to one another?" On the other hand, one equals sign in code is assigning a particular variable to a value. Don't forget to add the second equals sign if you are comparing two values.

Coding Challenges

ChallengeDescription
Change the key of each buttonUse the frequency table in the comment section at the end of the code to change the notes that each button plays.
Play more than three notes with if statementsBy using combinations of buttons, you can play up to seven notes of the scale. You can do this in a few ways. To get more practice with if statements, try adding seven if statements and using the Boolean AND (&&) operator to represent all of the combinations of keys.
Play more than three notes with binary mathYou can use a clever math equation to play more than three notes with your three keys. By multiplying each key by a different number, then adding up all of these numbers, you can make a math equation that produces a different number for each combination of keys.

Troubleshooting

ProblemSolution
The buzzer is too loud or too quietTurn the potentiometer to adjust the volume.
The RedBoard thinks one key is always pressedCheck your wiring. You may have ground and 5V backward if one or more buttons behave as though they're pressed all the time.
The buttons are not workingFirst, make sure that the wiring is correct. It is easy to misalign a wire with a button leg. Second, make sure that you have declared your buttons as inputs and have enabled the internal pull-up resistors with INPUT_PULLUP.

Circuit 7: Simon Says Game

The Simon Says game uses LEDs to flash a pattern, which the player must remember and repeat using four buttons. The classic [Simon](https://en.wikipedia.org/wiki/Simon_(game)) game has been a hit since the 1980s. Now you can build your own!

Tinker Kit Circuit 7

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x SparkFun RedBoard
  • 16x Jumper Wires
  • 4x 330Ω Resistor
  • 1x 10K Potentiometer
  • 1x Buzzer
  • 1x Blue LED
  • 1x Blue Push Button
  • 1x Green LED
  • 1x Green Push Button
  • 1x Yellow LED
  • 1x Yellow Push Button
  • 1x Red LED
  • 1x Red Push Button

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
Trimpot 10K Ohm with Knob

Trimpot 10K Ohm with Knob

COM-09806
$0.95
6
LED - Assorted (20 pack)

LED - Assorted (20 pack)

COM-12062
$3.30
8
Multicolor Buttons - 4-pack

Multicolor Buttons - 4-pack

PRT-14460
$1.60
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20
Mini Speaker - PC Mount 12mm 2.048kHz

Mini Speaker - PC Mount 12mm 2.048kHz

COM-07950
$1.95
5
Resistor 330 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 330 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14490
$0.95

New Concepts

For Loops

For loops repeat a section of code a set number of times. The loop works by using a counter (usually programmers use the letter “i” for this variable) that increases each loop until it reaches a stop value. Here’s an example of a simple for loop:

language:c
for (int i = 0; i < 5; i++){
    Serial.print(i);
}

The for loop takes three parameters in the brackets, separated by semicolons. The first parameter is the start value. In this case, integer i starts at 0. The second value is the stop condition. In this case, we stop the loop when i is no longer less than 5 (i < 5 is no longer true). The final parameter is an increment value. i++ is shorthand for increase i by 1 each time, but you could also increase i by different amounts. This loop would repeat five times. Each time it would run the code in between the brackets, which prints the value of i to the serial monitor.

Measuring Durations of Time With millis()

The RedBoard has a built-in clock that keeps accurate time. You can use the millis() command to see how many milliseconds have passed since the RedBoard was last powered. By storing the time when an event happens and then subtracting the current time, you can measure the number of milliseconds (and thus seconds) that have passed. This sketch uses this function to set a time limit for repeating the pattern.

Custom Functions

This sketch uses several user-defined functions. These functions perform operations that are needed many times in the program (for example, reading which button is currently pressed or turning all of the LEDs off). Functions are essential to make more complex programs readable and compact.

Hardware Hookup

Ready to start hooking everything up? Check out the circuit diagram and hookup table below to see how everything is connected.

Circuit Diagram

Circuit 7 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
BuzzerJ1 (Buzzer + )J3 (Buzzer - )
PotentiometerB1B2B3
Jumper WireGNDGND Rail ( - )
Jumper WireDigital Pin 10F1
Jumper WireE2GND Rail ( - )
Jumper WireE1F3
Push ButtonD10/D12G10/G12
Push ButtonD16/D18G16/G18
Push ButtonD22/D24G22/G24
Push ButtonD28/D30G28/G30
Jumper WireDigital Pin 8J12
Jumper WireDigital Pin 6J18
Jumper WireDigital Pin 4J24
Jumper WireDigital Pin 2J30
Jumper WireJ10GND Rail ( - )
Jumper WireJ16GND Rail ( - )
Jumper WireJ22GND Rail ( - )
Jumper WireJ28GND Rail ( - )
Blue LED H7 LED ( + )H8 LED ( - )
Green LED H13 LED ( + )H14 LED ( - )
Yellow LED H19 LED ( + )H20 LED ( - )
Red LED H25 LED ( + )H26 LED ( - )
Jumper WireDigital Pin 9J7
Jumper WireDigital Pin 7J13
Jumper WireDigital Pin 5J19
Jumper WireDigital Pin 3J25
330Ω Resistor
(orange, orange, brown)
J8GND Rail ( - )
330Ω Resistor
(orange, orange, brown)
J14GND Rail ( - )
330Ω Resistor
(orange, orange, brown)
j20GND Rail ( - )
330Ω Resistor
(orange, orange, brown)
J26GND Rail ( - )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

Open the example code from your Arduino sketchbook or copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Tinker Kit
Circuit 7: Simon Says Game

The Simon Says game flashes a pattern using LED lights, then the player must repeat the pattern.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit/
Download drawings and code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code/
*/

//set the pins where the butons, LEDs and buzzer connect
int button[] = {2,4,6,8};     //red is button[0], yellow is button[1], green is button[2], blue is button[3]
int led[] = {3,5,7,9};        //red is led[0], yellow is led[1], green is led[2], blue is led[3]
int tones[] = {262, 330, 392, 494};   //tones to play with each button (c, e, g, b)

int roundsToWin = 10;         //number of rounds the player has to play before they win the game (the array can only hold up to 16 rounds)
int buttonSequence[16];       //make an array of numbers that will be the sequence that the player needs to remember

int buzzerPin = 10;           //pin that the buzzer is connected to

int pressedButton = 4;        //a variable to remember which button is being pressed. 4 is the value if no button is being pressed.
int roundCounter = 1;         //keeps track of what round the player is on


long startTime = 0;           //timer variable for time limit on button press
long timeLimit = 2000;        //time limit to hit a button

boolean gameStarted = false;      //variable to tell the game whether or not to play the start sequence

void setup(){

  //set all of the button pins to input_pullup (use the builtin pullup resistors)
  pinMode(button[0], INPUT_PULLUP);
  pinMode(button[1], INPUT_PULLUP);
  pinMode(button[2], INPUT_PULLUP);
  pinMode(button[3], INPUT_PULLUP);

  //set all of the LED pins to output
  pinMode(led[0], OUTPUT);
  pinMode(led[1], OUTPUT);
  pinMode(led[2], OUTPUT);
  pinMode(led[3], OUTPUT);

  pinMode(buzzerPin, OUTPUT);   //set the buzzer pin to output
}

void loop(){

if (gameStarted == false){    //if the game hasn't started yet
  startSequence();            //flash the start sequence
  roundCounter = 0;           //reset the round counter
  delay(1500);                //wait a second and a half
  gameStarted = true;         //set gameStarted to true so that this sequence doesn't start again
}

//each round, start by flashing out the sequence to be repeated
for(int i=0; i <= roundCounter; i++){   //go through the array up to the current round number
  flashLED(buttonSequence[i]);          //turn on the LED for that array position and play the sound
  delay(200);                           //wait
  allLEDoff();                          //turn all of the LEDs off
  delay(200);
}

//then start going through the sequence one at a time and see if the user presses the correct button
for(int i=0; i <= roundCounter; i++){   //for each button to be pressed in the sequence

  startTime = millis();                 //record the start time

  while(true){  //loop until the player presses a button or the time limit is up (the time limit check is in an if statement)

    pressedButton = buttonCheck();      //every loop check to see which button is pressed

    if (pressedButton < 4){             //if a button is pressed... (4 means that no button is pressed)

      flashLED(pressedButton);          //flash the LED for the button that was pressed

      if(pressedButton == buttonSequence[i]){   //if the button matches the button in the sequence
          delay(250);                   //leave the LED light on for a moment
          allLEDoff();                  //then turn off all of the lights and
          break;                        //end the while loop (this will go to the next number in the for loop)

      } else{                           //if the button doesn't match the button in the sequence
          loseSequence();               //play the lose sequence (the loose sequence stops the program)
          break;                        //when the program gets back from the lose sequence, break the while loop so that the game can start over
      }

    } else {                            //if no button is pressed
      allLEDoff();                      //turn all the LEDs off
    }

    //check to see if the time limit is up
    if(millis() - startTime > timeLimit){   //if the time limit is up
      loseSequence();                       //play the lose sequence
      break;                                //when the program gets back from the lose sequence, break the while loop so that the game can start over
    }
  }    
}

  roundCounter = roundCounter + 1;      //increase the round number by 1

  if (roundCounter >= roundsToWin){               //if the player has gotten to the 16th round
    winSequence();                      //play the winning song
  }

  delay(500);                           //wait for half a second between rounds


}

//----------FUNCTIONS------------

//FLASH LED
void flashLED (int ledNumber){
  digitalWrite(led[ledNumber], HIGH);
  tone(buzzerPin, tones[ledNumber]);
}

//TURN ALL LEDS OFF
void allLEDoff (){
  //turn all the LEDs off
  digitalWrite(led[0],LOW);
  digitalWrite(led[1],LOW);
  digitalWrite(led[2],LOW);
  digitalWrite(led[3],LOW);
  //turn the buzzer off
  noTone(buzzerPin);
}

//CHECK WHICH BUTTON IS PRESSED
int buttonCheck(){
  //check if any buttons are being pressed
  if(digitalRead(button[0]) == LOW){
    return 0;
  }else if(digitalRead(button[1]) == LOW){
    return 1;
  }else if(digitalRead(button[2]) == LOW){
    return 2;
  }else if(digitalRead(button[3]) == LOW){
    return 3;
  }else{
    return 4; //this will be the value for no button being pressed
  }
}

//START SEQUENCE
void startSequence(){

  randomSeed(analogRead(A0));   //make sure the random numbers are really random

  //populate the buttonSequence array with random numbers from 0 to 3
  for (int i=0;i<=roundsToWin;i++){
    buttonSequence[i] = round(random(0,4));
  }

  //flash all of the LEDs when the game starts
  for(int i=0; i<=3; i++){

    tone(buzzerPin, tones[i], 200); //play one of the 4 tones

    //turn all of the leds on
    digitalWrite(led[0],HIGH);
    digitalWrite(led[1],HIGH);
    digitalWrite(led[2],HIGH);
    digitalWrite(led[3],HIGH);

    delay(100);         //wait for a moment

    //turn all of the leds off
    digitalWrite(led[0],LOW);
    digitalWrite(led[1],LOW);
    digitalWrite(led[2],LOW);
    digitalWrite(led[3],LOW);

    delay(100);   //wait for a moment

  } //this will repeat 4 times
}

//WIN SEQUENCE
void winSequence(){

  //turn all the LEDs on
  for(int j=0; j<=3; j++){
    digitalWrite(led[j], HIGH);
  }

  //play the 1Up noise
  tone(buzzerPin, 1318, 150);   //E6
  delay(175);
  tone(buzzerPin, 1567, 150);   //G6
  delay(175);
  tone(buzzerPin, 2637, 150);   //E7
  delay(175);
  tone(buzzerPin, 2093, 150);   //C7
  delay(175);
  tone(buzzerPin, 2349, 150);   //D7
  delay(175);
  tone(buzzerPin, 3135, 500);   //G7
  delay(500);  

  //wait until a button is pressed
  do {         
    pressedButton = buttonCheck();
  } while(pressedButton > 3);
  delay(100);

  gameStarted = false;   //reset the game so that the start sequence will play again.

}

//LOSE SEQUENCE
void loseSequence(){

  //turn all the LEDs on
  for(int j=0; j<=3; j++){
    digitalWrite(led[j], HIGH);
  }

  //play the 1Up noise
  tone(buzzerPin, 130, 250);   //E6
  delay(275);
  tone(buzzerPin, 73, 250);   //G6
  delay(275);
  tone(buzzerPin, 65, 150);   //E7
  delay(175);
  tone(buzzerPin, 98, 500);   //C7
  delay(500);

  //wait until a button is pressed
  do {         
    pressedButton = buttonCheck();
  } while(pressedButton > 3);
  delay(200);

  gameStarted = false;   //reset the game so that the start sequence will play again.
}

What You Should See

The circuit will flash all of the LEDs and play a melody. After a few seconds, it will flash the first light in the pattern. If you repeat the pattern correctly by pressing the corresponding colored button, then the game will move to the next round and add another color to the pattern sequence. If you make a mistake, the loss melody will play. If you get to round 10, the win melody will play. Press any button to start a new game.

Tinker Kit Circuit 7 demo

Program Overview

  1. Check if a new game is starting. If it is, play the start sequence. Reset the counter that keeps track of rounds, and randomly generate a sequence of numbers from 0 to 3 that control which LEDs the user will have to remember.
  2. The game works in rounds that progress from 0 to 10. Each round the game will flash LEDs in a pattern, then the player has to recreate the pattern by pressing the button(s) that match the LED(s). In the first round, one LED will flash, and the player will have to press one button. In the eighth round, eight LEDs will flash, and the player will have to press eight buttons.
  3. Use a loop to flash LEDs from the sequence until you have flashed the number of LEDs that matches the round number (1 for round 1, 2 for round 2, etc).
  4. Start a timer, and wait for the player to press a button. The player has 1.5 seconds to press the correct button. a. If the time limit runs out before a button is pressed, the player loses. b. If the player presses the wrong button, the player loses. c. If the player presses the right button, move on to the next number in the sequence. d. Repeat this process until the player has lost or correctly repeated the sequence for this round.
  5. If the player repeats the entire sequence for that round. Increase the round number by one (this will add one extra item to the end of the pattern). Then go back to step 3.
  6. Keep incrementing the round until the player loses or the player finishes 10 rounds. If the player finishes 10 rounds, play the winning sequence.

Code to Note

CodeDescription
Elapsed Time:
millis();
The millis function returns the number of milliseconds that have passed since the RedBoard was last turned on.
Boolean Variables:
boolean variable_name;
The name for these variables comes from Boolean logic. The Boolean variable type only has two values: 1 or 0, HIGH or LOW, TRUE or FALSE. Using Boolean variables helps save memory on your microcontroller if you only need to know if something is true or false. Space in your microcontroller's memory is reserved when a variable is declared. How much memory is reserved depends on the type of variable.
Storing pin numbers in Arrays:
int led[] = {3,5,7,9};
Sometimes you will want to cycle through all of the LEDs or buttons connected to a project. You can do this by storing a sequence of pin numbers in an array. The advantage of having pins in an array instead of a sequence of variables is that you can use a loop to easily cycle through each pin.
User Functions Description
flashLED(# for LED to flash);This turns one of the four LEDs on and plays the tone associated with it.
0 = Red, 1 = Yellow, 2 = Green, 3 = Blue.
allLEDoff();Turns all four LEDs off.
buttonCheck();Uses digitalRead() to check which button is pressed. Returns 0, 1, 2 or 3 if one of the buttons is pressed. Returns 4 if no button is pressed.
startSequence();Flashes the LEDs and plays tones in a sequence. Resets the round counter and generates a new random sequence for the user to remember.
winSequence();Plays a sequence of tones, turns all of the LEDs on, then waits for the player to press a button. If a button is pressed, restarts the game.
loseSequence();Plays a sequence of tones, turns all of the LEDs on, then waits for the player to press a button. If a button is pressed, restarts the game.

Coding Challenges

ChallengeDescription
Change the difficulty of the gameChange the difficulty of the game by changing how fast the player has to press each button or by increasing or decreasing the number of rounds needed to win. Note that if you increase the number of rounds to be larger than 16, you will need to change the size of the “buttonSequence” array (it is set at the top of the code in a line that looks like this: int buttonSequence[16];.
Change the sound effectsTry changing the sequence of notes that play when you start, win or lose the game.
2-Player modeReady for a real coding challenge? Try changing the code so that two players can play head-to-head.

Troubleshooting

ProblemSolution
One of the LEDs isn’t lighting upMake sure your LED is flipped around in the right direction. If the LED still doesn’t work, try wiggling the resistor and the wires that connect to the LED.
The buzzer is too loud or too quietTurn the potentiometer to adjust the volume
One of the buttons isn’t workingCarefully check your wiring for each button. One leg of the button should connect to a pin on the RedBoard; the other leg should connect to the ground rail on the breadboard.
None of the buttons or LEDs is workingMake sure you don't have 5V and GND mixed up. Double check that you have a GND connection from the RedBoard to the GND rail on the breadboard.
Still not working?Jumper wires unfortunately can go "bad" from getting bent too much. The copper wire inside can break, leaving an open connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded, but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working.

Circuit 8: Servo Motors

In this circuit, you will learn how to wire a servo and control it with code. Servo motors can be told to move to a specific position and stay there. Low-cost servo motors were originally used to steer remote-controlled airplanes and cars, but they have become popular for any project where precise movement is needed.

Tinker Kit Circuit 8

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x SparkFun RedBoard
  • 8x Jumper Wires
  • 1x 10K Potentiometer
  • 1x Servo

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

ROB-09065
$8.95
12
Trimpot 10K Ohm with Knob

Trimpot 10K Ohm with Knob

COM-09806
$0.95
6
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20

New Components

Servo Motors

Regular DC motors have two wires. When you hook the wires up to power, the motor spins around and around. Servo motors, on the other hand, have three wires: one for power, one for ground and one for signal. When you send the right signal through the signal wire, the servo will move to a specific angle and stay there. Common servos rotate over a range of 0° to 180°. The signal that is sent is a PWM signal, the same used to control the RGB LED.

servo motor

New Concepts

Duty Cycle

The Pulse Width Modulation (PWM) hardware available on a microcontroller is a great way to generate servo control signals. When talking about how long a PWM signal is on, this is referred to as duty cycle. Duty cycle is measured in percentage. The percentage of duty cycle specifically describes the percentage of time a digital signal is on over an interval or period of time. The variation in the duty cycle tells the servo which position to go to in its rotation.

Duty Cycle Percentage reflects percentage of 'on' time per interval

50%, 75% and 25% duty cycle examples

Arduino Libraries

Writing code that sends precise PWM signals to the servo would be time consuming and would require a lot more knowledge about the servo. Luckily, the Arduino IDE has hundreds of built-in and user-submitted containers of code that are called libraries. One of the built-in libraries, the Servo Library, allows us to control a servo with just a few lines of code!

To use one of the built-in Arduino libraries, all you have to do is "include" a link to its header file. A header file is a smaller code file that contains definitions for all the functions used in that library. By adding a link to the header file in your code, you are enabling your code to use all of those library functions. To use the Servo Library, you would add the following line to the top of your sketch.

language:cpp
#include <Servo.h>

Objects and Methods

To use the Servo Library, you will have to start by creating a servo object, like this:

language:cpp
Servo myServo;

Objects look a lot like variables, but they can do much more. Objects can store values, and they can have their own functions, which are called methods.

The most used method that a servo object has is .write().

language:cpp
myServo.write(90);

The write method takes one parameter, a number from 0 to 180, and moves the servo arm to the specified position (in this case, degree 90).

Why would we want to go to the trouble of making an object and a method instead of just sending a servo control signal directly over a pin? First, the servo object does the work of translating our desired position into a signal that the servo can read. Second, using objects makes it easy for us to add and control more than one servo.

Hardware Hookup

Polarized Components
Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Servo motor connectors are polarized, but there is no place to attach them directly. Instead, connect three jumper wires to the female 3-pin header on the servo. This will make it so you can connect the servo to the breadboard.

Servo Jumpers

The servo wires are color coded to make hookup simple. The pin-out is as follows:

PinDescription
WhiteSignal - PWM In
RedPower (5V)
BlackGround (GND)

Included with your servo motor you will find a variety of motor mounts that connect to the shaft of your servo. You may choose to attach any mount you wish for this circuit. It will serve as a visual aid, making it easier to see the servo spin.

motor mounts

The various motor mounts included with your servo motor

Ready to start hooking everything up? Check out the Fritzing diagram below to see how everything is connected.

Circuit Diagram

Circuit 8 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboardServo
PotentiometerB1B2B3
Jumper WireAnalog Pin 0E2
Jumper WireE15V Rail ( + )
Jumper WireE3GND Rail ( - )
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
Jumper WireDigital Pin 9White Servo Pin
Jumper Wire5V Rail ( + )Red Servo Pin
Jumper WireGND Rail ( - )Black Servo Pin

In the table, polarized components are shown with a warning triangle and the whole column highlighted yellow.

Open the Sketch

Open the example code from your Arduino sketchbook or copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Tinker Kit
Circuit 8: Servo Motors

Move a servo attached to pin 9 so that it's angle matches a potentitometer attached to A0.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit/
Download drawings and code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code/
 */

#include <Servo.h>          //include the servo library

int potPosition;           //this variable will store the position of the potentiometer
int servoPosition;         //the servo will move to this position

Servo myservo;              //create a servo object

void setup() {

  myservo.attach(9);        //tell the servo object that its servo is plugged into pin 9

}

void loop() {



  potPosition = analogRead(A0);                     //use analog read to measure the position of the potentiometer (0-1023)

  servoPosition = map(potPosition, 0,1023,20,160);  //convert the potentiometer number to a servo position from 20-160
                                                    //Note: its best to avoid driving the little SIK servos all the 
                                                    //way to 0 or 180 degrees it can cause the motor to jitter, which is bad for the servo.

  myservo.write(servoPosition);                      //move the servo to the 10 degree position
}

What You Should See

Turning the potentiometer will cause the servo to turn.

Tinker Kit Circuit 8 demo gif

Program Overview

  1. Read the value of the potentiometer.
  2. Convert the potentiometer value (0--1023) to an angle (20--160).
  3. Tell the servo to go to this angle.

Code to Note

CodeDescription
Including Libraries:
#include <Servo.h>
The #include command adds a library to your Arduino program. After you include a library, you can use the commands in the library in your program. This line adds the Servo library.
Creating Servo Objects:
Servo myServo;
The Servo command creates a new servo object and assigns a name to it, myServo in this case. If you make more than one servo object, you will need to give them different names.
Servo Attach:
myServo.attach(9);
The .attach() method tells the servo object to which pin the signal wire of its servo is attached. It will send position signals to this pin. In this sketch, pin 9 is used. Remember to only use digital pins that are capable of PWM.
Range Mapping:
map(potPosition, 0,1023,20,160);
As shown in previous circuits, the analog pin values on your microcontroller vary from 0-1023. However, what if we want those values to control a servo motor that only accepts a value from 0-180? The answer is to use the map function. The map() function takes a range of values and outputs a different range of values that can contain more or less values than the original. In this case, we are taking the range 0-1023 and mapping it to the range 20-160.
Servo Write:
myServo.write(90);
The .write() method moves the servo to a specified angle. In this example, the servo is being told to go to angle 90.

Coding Challenges

ChallengeDescription
Reverse the directionTry making the servo move in the opposite direction to the potentiometer.
Change the rangeTry altering the map function so that moving the potentiometer a lot only moves the servo a little.
Swap in a different sensorTry swapping a light sensor in for the potentiometer. You have just made a dial that reads how much light is present!

Troubleshooting

ProblemSolution
The servo doesn’t moveCheck the wiring on your servo. Make sure that the red wire on the servo cord is connected to 5V, the black wire is connected to GND and the white signal wire is connected to pin 9.
The servo is twitchingAlthough these servos are supposed to move from 0 to 180 degrees, sometimes sending them to the extremes of their range causes them to twitch (the servo is trying to move farther than it can). Make sure that you aren’t telling the servo to move outside of the 20-160 degree range.

Circuit 9: Temperature Sensor

Want to create a DIY environmental monitor or weather station? You can use a small, low-cost sensor like the TMP36 to make devices that track and respond to temperature. In this activity, you will read the raw 0--1023 value from the temperature sensor, calculate the actual temperature, and then print it out over the serial monitor.

Tinker Kit Circuit 9

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x SparkFun RedBoard
  • 3x Jumper Wires
  • 1x TMP36 Temperature Sensor

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20
Temperature Sensor - TMP36

Temperature Sensor - TMP36

SEN-10988
$1.50
17

New Components

TMP36 Temperature Sensor

This temperature sensor has three legs. One connects to 5V, one to ground, and the voltage output from the third leg varies proportionally to changes in temperature. By doing some simple math with this voltage we can measure temperature in degrees Celsius or Fahrenheit.

TMP36 Temperature sensor

New Concepts

Algorithms

An algorithm is a process used in order to achieve a desired result. Often, the information needed to create an algorithm lives in the part's datasheet. This sketch uses a few formulas to turn a voltage value into a temperature value, making them all part of the larger temperature-retrieving algorithm. The first formula takes the voltage read on analog pin 0 and multiplies it to get a voltage value from 0V--5V:

language:c
voltage = analogRead(A0) * 0.004882814;

The number we are multiplying by comes from dividing 5V by the number of samples the analog pin can read (1024), so we get: 5 / 1024 = 0.004882814.

The second formula takes that 0--5V value and calculates degrees Centigrade:

language:c
degreesC = (voltage - 0.5) * 100.0;

The reason 0.5V is subtracted from the calculated voltage is because there is a 0.5V offset, mentioned on page 8 of the TMP36 datasheet. It's then multiplied by 100 to get a value that matches temperature.

The last formula takes the Centigrade temperature and converts it to a Fahrenheit temperature using the standard conversion formula:

language:c
degreesF = degreesC * (9.0/5.0) + 32.0;

Together, these three formulas make up the algorithm that converts voltage to degrees Fahrenheit.

Hardware Hookup

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

The temperature sensor is polarized and can only be inserted in one direction. See below for the pin outs of the temperature sensor. Pay very close attention to the markings on each side as you insert it into your circuit.

Temperature Sensor
Heads up! Double check the polarity of the TMP36 temperature sensor before powering the RedBoard. It can become very hot if it is inserted backward!

Ready to start hooking everything up? Check out the circuit diagram and hookup table below to see how everything is connected.

Circuit Diagram

Circuit 9 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
TMP36 Temperature SensorF6 (GND)F7 (Signal)F8 (V+)
Jumper WireJ6GND( - )
Jumper WireAnalog Pin 0 (A0)J7
Jumper WireJ85V ( + )

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

Open the example code from your Arduino sketchbook or copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Tinker Kit
Circuit 9: Temperature Sensor

Use the "serial monitor" window to read a temperature sensor.

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit/
Download drawings and code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code/

*/

//analog input pin constant
const int tempPin = 0;

//raw reading variable
int tempVal;

//voltage variable
float volts;

//final temperature variables
float tempC;
float tempF;

void setup()
{
  // start the serial port at 9600 baud
  Serial.begin(9600);
}


void loop()
{
 //read the temp sensor and store it in tempVal
 tempVal = analogRead(tempPin);

 //print out the 10 value from analogRead
 Serial.print("TempVal = ");
 Serial.print(tempVal);

 //print a spacer  
 Serial.print(" **** ");

 //converting that reading to voltage by multiplying the reading by 5V (voltage of       //the RedBoard)
 volts = tempVal * 5;
 volts /= 1023.0;

 //print out the raw voltage over the serial port
 Serial.print("volts: ");
 Serial.print(volts, 3);

 //print out divider
 Serial.print(" **** ");

 //calculate temperature celsius from voltage
 //equation found on the sensor spec.
 tempC = (volts - 0.5) * 100 ;

// print the celcius temperature over the serial port
Serial.print(" degrees C: ");
Serial.print(tempC);

//print spacer
 Serial.print(" **** ");

// Convert from celcius to fahrenheit
tempF = (tempC * 9.0 / 5.0) + 32.0;

//print the fahrenheit temperature over the serial port
Serial.print(" degrees F: ");
Serial.println(tempF);

//wait a bit before taking another reading
delay(1000);
}

What You Should See

The Arduino serial monitor will show the temperature in Celsius and Fahrenheit. The temperature readings will update every second. An easy way to see the temperature change is to press your finger to the sensor.

Tinker Kit Circuit 9 Demo

Here's an example of what you should see in the Arduino IDE’s serial monitor:

TempVal = 223 **** volts: 0.719 ****  degrees C: 21.94 ****  degrees F: 71.48
TempVal = 224 **** volts: 0.723 ****  degrees C: 22.26 ****  degrees F: 72.06
TempVal = 224 **** volts: 0.723 ****  degrees C: 22.26 ****  degrees F: 72.06
TempVal = 224 **** volts: 0.723 ****  degrees C: 22.26 ****  degrees F: 72.06
TempVal = 224 **** volts: 0.723 ****  degrees C: 22.26 ****  degrees F: 72.06
TempVal = 224 **** volts: 0.723 ****  degrees C: 22.26 ****  degrees F: 72.06
TempVal = 223 **** volts: 0.719 ****  degrees C: 21.94 ****  degrees F: 71.48
TempVal = 223 **** volts: 0.719 ****  degrees C: 21.94 ****  degrees F: 71.48

Program Overview

  1. Get the analog value from the TMP36.
  2. Print the raw temperature value to the serial monitor.
  3. Convert it back to a voltage between 0 and 5V.
  4. Print the voltage value.
  5. Calculate the degrees Celsius from this voltage.
  6. Print the Degrees C.
  7. Calculate the degrees Fahrenheit from same voltage.
  8. Print the Degrees F.
  9. Wait for a second before taking the next reading.

Code to Note

CodeDescription
Voltage Conversion AlgorithmsMany of the sensors that you will use with your microcontroller work by changing a voltage in some predictable way in response to a property of the world (like temperature, light or magnetic fields). Often, you will need to build an algorithm that converts these voltages to the desired value and units. The temperature sensor is a great example of this code. We use three equations to convert a voltage value into degrees in C and F.

voltage = analogRead(A0) * 0.004882814;
degreesC = (voltage - 0.5) * 100.0;
degreesF = degreesC * (9.0/5.0) + 32.0;

Coding Challenges

ChallengeDescription
Display the temperature in degrees KelvinTry adding an equation so that the temperature is displayed in degrees Kelvin (you will have to look up the formula for converting from degrees Celsius or Fahrenheit to Kelvin).
Display a LED bar graphTry changing the code so you can display the temperature visually as a LED bar graph.
Display values from another sensorYou can swap out the TMP36 for a potentiometer, photoresistor or other sensor and display the new set of values.
Add an RGB LEDAdd an RGB LED that changes color based on the temperature.

Troubleshooting

ProblemSolution
Sensor is warm or hot to the touchMake sure that you wired the temperature sensor correctly. The temperature sensor can get warm to the touch if it is wired incorrectly. Disconnect your microcontroller, rewire the circuit, and connect it back to your computer.
Temperature value is unchangingTry pinching the sensor with your fingers to heat it up or pressing a bag of ice against it to cool it down. Also, make sure that the wires are connected properly to the temperature sensor.
Values not printing to serial monitorIf you see text but no temperature values, there could be an error in your code. If you see no text at all, make sure that you are on the correct serial port using a baud rate of 9600.

Circuit 10: Motor Basics

In this circuit you will learn the basic concepts behind motor control. Motors require a lot of current, so you can’t drive them directly from a digital pin on the RedBoard. Instead, you’ll use what is known as a motor controller or motor driver board to power and spin the motor accordingly.

Tinker Kit Circuit 10

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x SparkFun RedBoard
  • 16x Jumper Wires
  • 1x TB6612FNG Motor Driver (w/ Headers)
  • 1x Hobby Gearmotor

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
Hobby Gearmotor - 140 RPM (Pair)

Hobby Gearmotor - 140 RPM (Pair)

ROB-13302
$4.95$4.11
2
SparkFun Motor Driver - Dual TB6612FNG (with Headers)

SparkFun Motor Driver - Dual TB6612FNG (with Headers)

ROB-14450
$5.45
12
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20

New Components

DC Gearmotors

The motors in your Tinker Kit have two main parts: a small DC motor that spins quickly and a plastic gearbox that gears down that output from the hobby motor so that it is slower but stronger, allowing it to move your robot. The motors have a clever design so that you can attach things that you want to spin fast (like a small fan or flag) to the hobby motor, and things that you want to be strong (like a wheel) to the plastic axle sticking out the side of the motor.

DC Hobby Gear Motor

Inside the hobby motor are coils of wire that generate magnetic fields when electricity flows through them. When power is supplied to these electromagnets, they spin the drive shaft of the motor.

TB6612FNG Motor Driver

If you switch the direction of current through a motor by swapping the positive and negative leads, the motor will spin in the opposite direction. Motor controllers contain a set of switches (called an H-bridge) that let you easily control the direction of one or more motors. The TB6612FNG Motor Driver takes commands for each motor over three wires (two wires control direction, and one controls speed), then uses these signals to control the current through two wires attached to your motor.

MotorDriver

New Concepts

Voltage In (VIN)

This circuit utilizes the VIN pin found with the other power pins. The VIN pin outputs a voltage that varies based on whatever voltage the RedBoard is powered with. If the RedBoard is powered through the USB port, then the voltage on VIN will be about 4.6--5V. However, if you power the RedBoard through the barrel jack (highlighted in the picture below), the VIN pin will reflect that voltage. For example, if you were to power the barrel jack with 9V, the voltage out on VIN would also be 9V.

VIN Pin

Integrated Circuits (ICs) and Breakout Boards

An Integrated Circuit (IC) is a collection of electronic components --- resistors, transistors, capacitors, etc. --- all stuffed into a tiny chip and connected together to achieve a common goal. They come in all sorts of flavors, shapes and sizes. The chip that powers the RedBoard, the ATMega328, is an IC. The chip on the motor driver, the TB6612FNG, is another IC, one designed to control motors, referred to as an H-bridge.

Internal view of an IC

The guts of an integrated circuit, visible after removing the top.

Integrated circuits are often too small to work with by hand. To make working with ICs easier and to make them breadboard-compatible, they are often added to a breakout board, which is a printed circuit board that connects all the IC's tiny legs to larger ones that fit in a breadboard. The motor driver board in your kit is an example of a breakout board.

Hardware Hookup

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Most ICs have polarity and usually have a polarity marking in one of the corners. The motor driver is no exception. Be sure to insert the motor driver as indicated in the circuit diagrams. The motor driver pins are shown in the image below.

MotorDriver

Each pin and its function is covered in the table below.

Pin LabelFunctionPower/Input/Output
Notes
VMMotor VoltagePowerThis is where you provide power for the motors (2.2V to 13.5V)
VCCLogic VoltagePowerThis is the voltage to power the chip and talk to the microcontroller (2.7V to 5.5V)
GNDGroundPowerCommon Ground for both motor voltage and logic voltage (all GND pins are connected)
STBYStandbyInputAllows the H-bridges to work when high (has a pulldown resistor so it must actively be pulled high)
AIN1/BIN1Input 1 for channels A/BInputOne of the two inputs that determines the direction
AIN2/BIN2Input 2 for channels A/BInputOne of the two inputs that determines the direction
PWMA/PWMBPWM input for channels A/BInputPWM input that controls the speed
A01/B01Output 1 for channels A/BOutputOne of the two outputs to connect the motor
A02/B02Output 2 for channels A/BOutputOne of the two outputs to connect the motor

When you're finished with the circuit, removing the motor driver from the breadboard can be difficult due to its numerous legs. To make this easier, use the a screwdriver as a lever to gently pry it out. Be careful not to bend the legs as you remove it by slowly lifting the motor driver off the breadboard from each side.

alt text

The motors are also polarized. However, motors are unique in that they will still work when the two connections are reversed. They will just spin in the opposite direction when hooked up backward. To keep things simple, always think of the red wire as positive ( + ) and the black wire as negative ( - ).

motor Polarity

Last, the switch is not polarized. It works the same no matter its orientation.

Ready to start hooking everything up? Check out the circuit diagram and hookup table below to see how everything is connected.

Circuit Diagram

Circuit 10 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
Jumper Wire5V Rail ( + )5V Rail ( + )
Jumper WireGND Rail ( - )GND Rail ( - )
Jumper WireVINA1
Motor Driver C1-C8 (VM on C1)G1-G8 (PWMA on G1)
Jumper WireA25V Rail ( + )
Jumper WireA3GND Rail ( - )
Jumper WireDigital Pin 8J5
Jumper WireDigital Pin 9J6
Jumper WireDigital Pin 10J7
Jumper WireJ45V Rail ( + )
Jumper WireDigital Pin 11J1
Jumper WireDigital Pin 12J2
Jumper WireDigital Pin 13J3
MotorA4 (Red +)A5 (Black -)

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

Open the example code from your Arduino sketchbook or copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Tinker Kit
Circuit 10: Motor Basics

Learn how to control one motor with the motor driver. 

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit/circuit-10-motor-basics
Download drawings and code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code/
*/

//PIN VARIABLES
//the motor will be controlled by the motor A pins on the motor driver
const int AIN1 = 13;           //control pin 1 on the motor driver for the right motor
const int AIN2 = 12;            //control pin 2 on the motor driver for the right motor
const int PWMA = 11;            //speed control pin on the motor driver for the right motor

//VARIABLES
int motorSpeed = 0;       //starting speed for the motor

void setup() {
  //set the motor contro pins as outputs
  pinMode(AIN1, OUTPUT);
  pinMode(AIN2, OUTPUT);
  pinMode(PWMA, OUTPUT);
}

void loop() {
    //drive motor forward (positive speed)
    digitalWrite(AIN1, HIGH);                         //set pin 1 to high
    digitalWrite(AIN2, LOW);                          //set pin 2 to low
    analogWrite(PWMA, 255);               //now that the motor direction is set, drive it at max speed
    delay(3000);

    //drive motor backward (negative speed)
    digitalWrite(AIN1, LOW);                          //set pin 1 to low
    digitalWrite(AIN2, HIGH);                         //set pin 2 to high
    analogWrite(PWMA, 255);               //now that the motor direction is set, drive it at max speed
    delay(3000);

    //stop motor
    digitalWrite(AIN1, LOW);                          //set pin 1 to low
    digitalWrite(AIN2, LOW);                          //set pin 2 to low
    analogWrite(PWMA, 0);               //now that the motor direction is set, stop motor
    delay(3000);
}

What You Should See

After uploading, the motor will spin in one direction at the maximum speed available (255) for three seconds. Then the motor will spin the other direction at the maximum speed available (255) for another three seconds. Finally the motor will stop for three seconds. Adding a piece of tape to the motor shaft makes it easier to see it spinning.

Tinker Kit Circuit 10 Demo
We slowed the motor speed down a bit to show it better here. Your motor should spin much faster.

Program Overview

  1. Spin motor in one direction at maximum speed for 3 seconds.
  2. Spin motor in the opposite direction at maximum speed for 3 seconds.
  3. Stop spinning the motor for 3 seconds
  4. Repeat.

Code to Note

CodeDescription
Direction:
digitalWrite(AIN1, HIGH);
digitalWrite(AIN2, LOW);
digitalWrite() on pins AIN1 and AIN2 sets the direction for the motor to spin on motor connected to channel A. When one pin is HIGH and the other is LOW, the motor will spin in one direction. The motor will spin the other direction when the logic is reversed. Setting both pins to LOW will stop the motor.
Speed: analogWrite(PWMA, 255);analogWrite() on the PWMA pin will tell the motor to move at a certain speed. The value must be a value between 0 and 255.

Coding Challenges

ChallengeDescription
Change speedChange the code so that the motor speed can spin at a slower rate.
Add another motorTry wiring the second motor and making both motors spin.
Build a robotAttach the circuit and mount the motors to a box. Then add wheels to the motors to build a robot. Once the robot is built, try changing the code so that the motors move forward, backward, or spin.

Troubleshooting

ProblemSolution
Motor not spinningCheck the wiring to the motor driver. There are a lot of connections, and it’s easy to mix one of them up with another. If it is still not working, you can test the B channel by moving you motor. (Black wire to A6, Red wire to A7). You’ll need to change the code as well.
Still not working?Jumper wires unfortunately can go "bad" from getting bent too much. The copper wire inside can break, leaving an open connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working.

Circuit 11: Driving a Motor w/ Inputs

It’s remote control time! In this circuit, you’ll use a motor driver to control the speed and direction of two motors. You will also learn how to read multiple pieces of information from one serial command so that you can use the Serial Monitor to tell the robot what direction to move in and how far to move.

Tinker Kit Circuit 11

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x SparkFun RedBoard
  • 18x Jumper Wires
  • 1x TB6612FNG Motor Driver (w/ Headers)
  • 1x Hobby Gearmotor
  • 1x Switch

Didn't Get the Tinker Kit?

If you are conducting this experiment and didn't get the Tinker Kit, we suggest using these parts:

Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
42
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
Hobby Gearmotor - 140 RPM (Pair)

Hobby Gearmotor - 140 RPM (Pair)

ROB-13302
$4.95$4.11
2
SparkFun Motor Driver - Dual TB6612FNG (with Headers)

SparkFun Motor Driver - Dual TB6612FNG (with Headers)

ROB-14450
$5.45
12
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.25
20
Mini Power Switch - SPDT

Mini Power Switch - SPDT

COM-00102
$1.50

New Concepts

Switch

A switch is a component that controls the open-ness or closed-ness of an electric circuit. Just like the momentary buttons used in earlier circuits, a switch can only exist in one of two states: open or closed. However, a switch is different in that it will stay in the position it was last in until it is switched again.

Switch

Hardware Hookup

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Ready to start hooking everything up? Check out the circuit diagram and hookup table below to see how everything is connected.

Circuit Diagram

Circuit 11 Fritzing diagram

Having a hard time seeing the circuit? Click on the image for a closer look.

Hookup Table

ComponentRedBoardBreadboardBreadboardBreadboard
Jumper Wire5V5V Rail ( + )
Jumper WireGNDGND Rail ( - )
Jumper Wire5V Rail ( + )5V Rail ( + )
Jumper WireGND Rail ( - )GND Rail ( - )
Jumper WireVINA1
Motor Driver C1-C8 (VM on C1)G1-G8 (PWMA on G1)
Jumper WireA25V Rail ( + )
Jumper WireA3GND Rail ( - )
Jumper WireDigital Pin 8J5
Jumper WireDigital Pin 9J6
Jumper WireDigital Pin 10J7
Jumper WireJ45V Rail ( + )
Jumper WireDigital Pin 11J1
Jumper WireDigital Pin 12J2
Jumper WireDigital Pin 13J3
MotorA4 (Red +)A5 (Black -)
SwitchF25F26F27
Jumper WireI26GND Rail ( - )
Jumper WireDigital Pin 7I27

In the table, polarized components are shown with a warning triangle and the whole row highlighted yellow.

Open the Sketch

Open the example code from your Arduino sketchbook or copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

language:cpp
/*
SparkFun Tinker Kit
Circuit 11: Driving a Motor w/ Inputs

Learn how to control one motor with the motor driver with a switch and input from a serial monitor. 

This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.

View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/activity-guide-for-sparkfun-tinker-kit
Download drawings and code at: https://github.com/sparkfun/SparkFun_Tinker_Kit_Code/
*/

//PIN VARIABLES
//the motor will be controlled by the motor A pins on the motor driver
const int AIN1 = 13;           //control pin 1 on the motor driver for the right motor
const int AIN2 = 12;            //control pin 2 on the motor driver for the right motor
const int PWMA = 11;            //speed control pin on the motor driver for the right motor

int switchPin = 7;             //switch to turn the robot on and off

//VARIABLES
int motorSpeed = 0;       //starting speed for the motor

void setup() {
  pinMode(switchPin, INPUT_PULLUP);   //set this as a pullup to sense whether the switch is flipped

  //set the motor contro pins as outputs
  pinMode(AIN1, OUTPUT);
  pinMode(AIN2, OUTPUT);
  pinMode(PWMA, OUTPUT);

  Serial.begin(9600);                       //begin serial communication with the computer

  Serial.println("Enter motor speed (0-255)... ");    //Prompt to get input in the serial monitor.
}

void loop() {

  if (Serial.available() > 0){          //if the user has entered something in the serial monitor
    motorSpeed = Serial.parseInt();     //set the motor speed equal to the number in the serial message

    Serial.print("Motor Speed: ");      //print the speed that the motor is set to run at
    Serial.println(motorSpeed);
  }

  if(digitalRead(7) == LOW){            //if the switch is on...
      spinMotor(motorSpeed);
  } else{                               //if the switch is off...
      spinMotor(0);                   //turn the motor off
  }


}

/********************************************************************************/
void spinMotor(int motorSpeed)                       //function for driving the right motor
{
  if (motorSpeed > 0)                                 //if the motor should drive forward (positive speed)
  {
    digitalWrite(AIN1, HIGH);                         //set pin 1 to high
    digitalWrite(AIN2, LOW);                          //set pin 2 to low
  }
  else if (motorSpeed < 0)                            //if the motor should drive backwar (negative speed)
  {
    digitalWrite(AIN1, LOW);                          //set pin 1 to low
    digitalWrite(AIN2, HIGH);                         //set pin 2 to high
  }
  else                                                //if the motor should stop
  {
    digitalWrite(AIN1, LOW);                          //set pin 1 to low
    digitalWrite(AIN2, LOW);                          //set pin 2 to low
  }
  analogWrite(PWMA, abs(motorSpeed));                 //now that the motor direction is set, drive it at the entered speed
}

What You Should See

When you flip the switch, the motor will turn on and spin at the speed set by the motor speed variable (default is 0). By opening the serial monitor and sending numbers, you can change the speed of the motor. Any number from about 130 to 255 or -130 to -255 will work, though changes in the speed will be hard to notice. Send the number 0 to stop the motor. Adding a piece of tape to the motor shaft makes it easier to see it spinning.

Tinker Kit Circuit 11 demo gif

Program Overview

  1. Check to see if a command has been sent through the Serial Monitor. If a command has been sent, then set the motor speed to the number that was sent over the Serial Monitor.
  2. Check to see if the switch is ON or OFF. a. If the switch is ON, drive the motor at the motor speed. b. If the switch is OFF, stop the motor.

Code to Note

CodeDescription
Parsing Integers:
Serial.parseInt();
parseInt() receives integer numbers from the serial monitor. It returns the value of the number that it receives, so you can use it like a variable.
Serial Available:
Serial.available();
Serial.available() checks how many bytes of data are being sent to the RedBoard. If it is greater than 0, then a message has been sent. It can be used in an if statement to run code only when a command has been received.

Coding Challenges

ChallengeDescription
Make the switch change directionsChange the code so that the position of the switch changes the direction of the motor instead of turning it on and off.
Replace the switch with a buttonTry wiring a button into the circuit instead of the sliding switch. Now the motor only turns on when you push the button.
Replace the switch with a sensorTry changing the code so that the motor is activated by another sensor, like the photoresistor.

Troubleshooting

ProblemSolution
Motor not spinningCheck the wiring to the motor driver. There are a lot of connections, and it’s easy to mix one of them up with another. If it is still not working, you can test the B channel by moving you motor. (Black wire to A6, Red wire to A7). You’ll need to change the code as well.
Motor spins but then stopsIn the Serial Monitor, make sure you have No line ending selected in the drop down menu next to the Baud Rate drop down menu.
Switch not workingMake sure that you are hooked up to the middle pin and one side pin on the switch.
Still not working?Jumper wires unfortunately can go "bad" from getting bent too much. The copper wire inside can break, leaving an open connection in your circuit. If you are certain that your circuit is wired correctly and that your code is error-free and uploaded but you are still encountering issues, try replacing one or more of the jumper wires for the component that is not working.

Resources and Going Further

For more information about the Tinker Kit, check out the resources below:

Now that you've successfully got your Tinker Kit up and running, it's time to incorporate it into your own project! There are tons of sensors and shields you can hookup to an Arduino that will help take your projects to the next level. Here's some further reading that may help you along in learning more about the world of electronics.


For more inspiration and ideas for working, check out the following tutorials. You may require additional parts to get these circuits functioning.

SIK Keyboard Instrument

We can use the parts and concepts in the SparkFun Invetor's Kit to make a primitive keyboard instrument.

Measuring Internal Resistance of Batteries

Classroom STEM activity that has students build a battery from a lemon, measure the open and closed circuit voltages, and determine the battery's internal resistance.

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.

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.

Endless Runner Game

We make a simple side-scrolling endless runner game using parts from the SparkFun Inventor's Kit v4.0.

For more information on Arduino, check out these tutorials:


For more electrical engineering and hardware related tutorials, give these a read:


Interested in using the SparkFun Qwiic System to add other inputs and outputs to your project? Get started here:

Qwiic Connect System

We also have additional kits available that cover different microcontrollers, development environments, and robotics.

SparkFun JetBot AI Kit v3.0 Powered by Jetson Nano

SparkFun JetBot AI Kit v3.0 Powered by Jetson Nano

KIT-18486
$249.95
Raspberry Pi 3 B+ Starter Kit

Raspberry Pi 3 B+ Starter Kit

KIT-15361
$92.95
SparkFun Inventor's Kit for RedBot

SparkFun Inventor's Kit for RedBot

ROB-12649
$129.95
24
SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-15228
$49.95
2
SparkFun Inventor's Kit for Photon

SparkFun Inventor's Kit for Photon

KIT-14684
SparkFun Advanced Autonomous Kit for Sphero RVR

SparkFun Advanced Autonomous Kit for Sphero RVR

KIT-15303
$164.95
2
Johnny-Five Inventor's Kit

Johnny-Five Inventor's Kit

KIT-14604
4
SparkFun mbed Starter Kit

SparkFun mbed Starter Kit

KIT-14458

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

Air Velocity Sensor Breakout - FS3000 Hookup Guide

$
0
0

Air Velocity Sensor Breakout - FS3000 Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Need to keep track of the airflow in your data center or around your servers? How about making sure your HVAC and air control systems are functioning at full capacity? Or, if you're more fun, what about figuring out how fast your RC airplane is going? Well, the new SparkFun Air Velocity Sensor Breakout - FS3000 can help you with all that and more! It's super easy, super Qwiic to hookup, and super fun to play with. Let's have a look!

SparkFun Air Velocity Sensor Breakout - FS3000 (Qwiic)

SparkFun Air Velocity Sensor Breakout - FS3000 (Qwiic)

SEN-18377
$49.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.

Suggested Reading

If you aren't familiar with the Qwiic system, take a look here for an overview.

Qwiic Connect System

We also recommend taking a look at the following tutorials if you aren't familiar with the concepts covered in them.

What is an Arduino?

What is this 'Arduino' thing anyway? This tutorials dives into what an Arduino is and along with Arduino projects and widgets.

Installing Arduino IDE

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

Logic Levels

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

Hardware Overview

FS3000

The FS3000 is a surface-mount type air velocity module utilizing a MEMS thermopile-based sensor. It features a digital output with 12-bit resolution and comprises a “solid” thermal isolation technology and silicon carbide coating to protect it from abrasive wear and water condensation. For more in depth information on this chip, please refer to the datasheet.

FS3000 Sensor is highlighted

Qwiic Connectors

Our Qwiic Ecosystem makes sensors pretty much plug and play. There are two Qwiic connectors on either side of the Qwiic Air Velocity Sensor board to provide power and I2C connectivity simultaneously.

The I2C address of the board is 0x28.

Qwiic connectors on either side of the board

Pins

Power

Ideally, power will be supplied via the Qwiic connectors on either side of the board. Alternatively, power can be supplied through the header along the bottom side of the board labeled 3V3 and GND. The input voltage range should be between 2.7-3.3V. The usual current draw is around 10mA.

Power pins are the two pins on the far right of the six pins at the bottom of the board

I2C

The I2C pins break out the functionality of the Qwiic connectors. Depending on your application, you can connect to these pins via the plated through holes for SDA and SCL.

I2C Pins are the two pins in the middle of the six pins at the bottom of the board

VCM and ADCR

VCM is an output from the sensor that provides a common bias voltage. With a power supply voltage at 3.3V (usual for Qwiic), the VCM pin will output 1.25V. The current datasheet does not provide any more information about this pin, however, it is most likely a bias voltage used with some sort of analog gain stage internal to the sensor (prior to it's internal ADC). This can be useful for unique more advanced projects that may benefit from having a known bias voltage tied to another analog system.

ADCR stands for ADC Reference. This is an input to the FS3000 which allows you to provide a reference voltage for the sensor's internal ADC. Note, you must first cut the "ADC-REF" jumper (on the bottom side of the board) before providing a custom voltage to this pin. By default, it is connected to VDD.

VCM and ADCR pins are the two pins on the far right of the six pins at the bottom of the board

Jumpers

LED

If power consumption is an issue, cutting this jumper will disable the Power LED on the front of the board.

LED Jumper is located on the right side of the board

ADC-REF

Cut the ADC-REF jumper to provide your own custom ADC reference voltage on the ADCR header pin. By default (jumper closed), it is connected to VDD.

ADC Ref Jumper is at the top of the board

I2C

The Sparkfun Air Velocity Sensor has pull up resistors attached to the I2C bus; if multiple sensors are connected to the bus with the pull-up resistors enabled, the parallel equivalent resistance will create too strong of a pull-up for the bus to operate correctly. As a general rule of thumb, disable all but one pair of pull-up resistors if multiple devices are connected to the bus. If you need to disconnect the pull up resistors they can be removed by cutting the traces on the corresponding jumpers highlighted below.

I2C Jumper is on the left side of the board

Board Outline

The board measures 1" x 1"

Hardware Hookup

Using the Qwiic system, assembling the hardware is simple. All you need to do is connect your Air Velocity Sensor Breakout to your chosen development board with a Qwiic cable or adapter cable. Otherwise, you can use the I2C pins broken out if you do not have a Qwiic connector on your development board or if you do not want to use a Qwiic connection. If you are not using a Qwiic-enabled board, make sure your input voltage and logic are either running at 3.3V or you are shifting the logic level from whatever logic your controller runs at to 3.3V.

Plug the qwiic connector to the sensor and the redboard - voila!

Software Setup and Programming

Note: 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.

SparkFun has written a library to work with the Qwiic Air Velocity Sensor. You can obtain this library through the Arduino Library Manager by searching for "FS3000". Find the one written by SparkFun Electronics and install the latest version. If you prefer downloading libraries manually, you can grab them from the GitHub Repository or by clicking on the button below.

Readings

The FS3000 has a response time of 125ms. In the provided example, we are only taking readings from the sensor once per second, so this is well above the response time. If you wish to take a higher frequency of readings, make sure to add in at least a 125ms delay in between each read.

To calculate or understand airflow and how it relates to diameter, you can use this tool.

Functions

Below is a list of the functions that can be used with the Air Velocity Sensor, along with a description of what each function does and how to use it.

  • FS3000() - Base constructor
  • begin() -- Initialize the sensor. Returns false if sensor is not detected.
  • isConnected() -- Returns true if I2C device ack's
  • readRaw() -- Read from sensor, checksum, return raw data (409-3686)
  • readMetersPerSecond() -- Read from sensor, checksum, return m/s (0-7.23)
  • readMilesPerHour() -- Read from sensor, checksum, return mph (0-33ish)
Note: If you are using a board with an Apollo core, please note that 100KHz on the Apollo 2.1.1 doesn't currently work. You will need to use 400KHz, or jump back to Apollo 2.1.0.

Example Code

Once you've installed the FS3000 library, you should see File>Examples>SparkFun_FS3000_Arduino_Library>Example01_BasicReadings to open the example sketch.

Finding the example


Alternatively, you can copy and paste the code below into a fresh Arduino sketch.

language:c
/******************************************************************************
  Example_01_BasicReadings.ino

  Read values of air velocity from the FS3000 sensor, print them to terminal.
  Prints raw data, m/s and mph.
  Note, the response time on the sensor is 125ms.

  SparkFun FS3000 Arduino Library
  Pete Lewis @ SparkFun Electronics
  Original Creation Date: August 5th, 2021
  https://github.com/sparkfun/SparkFun_FS3000_Arduino_Library

  Development environment specifics:

  IDE: Arduino 1.8.15
  Hardware Platform: SparkFun Redboard Qwiic
  SparkFun Air Velocity Sensor Breakout - FS3000 (Qwicc) Version: 1.0

  Artemis Redboard @ 400KHz (Core v2.1.0) 
  (note, v2.1.1 has a known issue with clock stretching at 100KHz)  

  Do you like this library? Help support SparkFun. Buy a board!

    SparkFun Air Velocity Sensor Breakout - FS3000 (Qwicc)
    https://www.sparkfun.com/products/18377

  Hardware Connections:
  Use a qwiic cable to connect from the Redboard Qwiic to the FS3000 breakout (QWIIC).
  You can also choose to wire up the connections using the header pins like so:

  ARDUINO --> FS3000
  SDA (A4) --> SDA
  SCL (A5) --> SCL
  3.3V --> 3.3V
  GND --> GND

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/

#include <Wire.h>
#include <SparkFun_FS3000_Arduino_Library.h> //Click here to get the library: http://librarymanager/All#SparkFun_FS3000

FS3000 fs;

void setup()
{
  Serial.begin(115200);
  Serial.println("Example 1 - Reading values from the FS3000");

  Wire.begin();

  if (fs.begin() == false) //Begin communication over I2C
  {
    Serial.println("The sensor did not respond. Please check wiring.");
    while(1); //Freeze
  }
  Serial.println("Sensor is connected properly.");
}

void loop()
{
    Serial.print("FS3000 Readings \tRaw: ");
    Serial.print(fs.readRaw()); // note, this returns an int from 0-3686

    Serial.print("\tm/s: ");
    Serial.print(fs.readMetersPerSecond()); // note, this returns a float from 0-7.23

    Serial.print("\tmph: ");
    Serial.println(fs.readMilesPerHour()); // note, this returns a float from 0-16.17

    delay(1000); // note, repsone time on the sensor is 125ms
}

Set your Board and Serial Port, and then upload the sketch to your Arduino. Then open the serial monitor. Make sure your baud rate is set to 115200. You'll begin to see output, including raw data and translated miles per second and miles per hour.

Serial Monitor Output

Note that peak in the middle of the readings? That's where I pointed the sensor at the fan!

Troubleshooting

Resources and Going Further

For more on the Air Velocity Sensor Breakout, check out some of the links below:

Need some inspiration for your next project? Check out some of these related tutorials:

RedBoard Edge Hookup Guide

The RedBoard Edge is a RedBoard that's been rebuilt around the idea that projects are eventually put into an enclosure to help clean up their look.

SparkFun Qwiic Button Hookup Guide

A Hookup Guide for the SparkFun Qwiic Button (Red) and SparkFun Qwiic Button Breakout. Goes over connecting the Qwiic Button to an Arduino microcontroller and using it with the Qwiic Button Arduino library.

SparkFun Clock Generator 5P49V60 (Qwiic) Hookup Guide

The SparkFun Clock Generator 5P49V60 (Qwiic) breakout board offers a wide range of customizable frequencies in a wide range of different signal types using a single reference clock. This hookup guide will go over all of the many available functions and gives the hardware rundown on what exactly is on this board.

Qwiic LED Stick - APA102C Hookup Guide

Add some I2C RGB to your project with the SparkFun Qwiic LED Stick - APA102C

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

Machine Learning @ Home Kit Hookup Guide

$
0
0

Machine Learning @ Home Kit Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Machine learning has taken the technology world by storm.

From smart email categorization to make it easier to sift through your inbox, to ML applications that decipher your handwriting and allow you to deposit checks on your mobile phone, to medical diagnosis like detecting cancer. Machine learning is practically ubiquitous in nearly every facet of our lives at this point.

Machine learning itself is a simple idea - ML algorithms use historical data as input to predict new output values. However, the actual practice of machine learning uses complex math and requires quite a bit of computational power, which can seem overwhelming to implement by oneself. But lucky for us, there's no longer a need to build machine learning models from scratch - there are dozens of APIs that have already built out the complex math to run ML models, and we can just use the libraries with our specific parameters.

That's great, it means we have access to all sorts of machine learning models that we can run on our computers. But that doesn't always feel super tangible, just running models on your laptop. What if you wanted to implement machine learning in the real world, in your everyday life? How do you go from building and training a model to deploying to to solve problems in your physical life?

Welcome to the Machine Learning @ Home Kit - this aims to help you bridge the gap between building and training machine learning models, and deploying them in tangible and meaningful ways.

SparkFun Machine Learning @ Home Kit for NVIDIA Jetson Nano

SparkFun Machine Learning @ Home Kit for NVIDIA Jetson Nano

KIT-18157
$114.95

NVIDIA's Jetson Nano has great GPU capabilities, making it ideal for ML applications. This kit brings machine output and interaction into the picture through a number of different SparkFun Qwiic boards for you to turn machine learning into machine working!

The goals of this particular hookup guide is to extend the content from NVIDIA's Getting Started with AI on Jetson Nano course to implement machine learning in practical ways in your own home. It will be "living", meaning it will be periodically iterated upon and additional projects will be added over time. We will go over how to move away from Jupyter labs and actually deploy applications, as well as how to strategically run applications once deployed. For example, we'll review how to save on power, by starting programs on boot, or using a motion sensor/button rather than having the program run all the time.

Let's jump right in and take a look at what's included in this kit so we can start building!

Kit Overview

The Machine Learning @ Home Kit includes all of the hardware that you need to take your Nvidia Jetson Nano learning experience to a practical level around your home or office. We decided on leveraging the SparkFun Qwiic ecosystem of development boards to keep wiring to a minimum and get you up and running with hardware without a rats nest of wires, soldering or getting things crossed. In this section we will review the different Qwiic boards and components of the kit, but we do want to take a moment and cover what other requirements there are in terms of hardware.

Prerequisite Hardware

The Machine Learning @ Home Kit doesn’t include the Nvidia Jetson Nano or any of the required accessories to get started with it.

SparkFun DLI Kit (without Jetson Nano)

SparkFun DLI Kit (without Jetson Nano)

KIT-16389
$78.95
1

The best first step to get everything you need in one go is to pickup the DLI Course Kit which includes all of the accessories you need including an Nvidia Jetson Nano if you don’t already have one, a power supply and cable (USB for the 2GB or 5V 4A Barrel for the 4GB), microSD card for the OS and a USB webcam. With the DLI Course kit in hand we highly recommend taking the free online course from the Deep Learning Institute to get you acquainted with the Nano itself, get all of the software setup and ready to go and get some experience with Jupyter Labs under your belt.

Kit Contents

Now, back to the Machine Learning @ Home Kit! The kit includes a bunch of hardware that is designed for you to move your machine learning projects out of Jupyter Labs and the feedback off of your monitor and into the physical world as a response. Let’s jump in and take a look at the components!

IoT Relay

Do you want to control a standard wall outlet device with your microcontroller, but don’t want to mess with the high-voltage wiring? The IoT Power Relay is a controllable power relay equipped with four outputs that help you create an Internet of Things project with safe, reliable power control. With the IoT Power Relay you can easily control the power going to a device with an Arduino, Raspberry Pi or other single-board computer or microcontroller. It provides an alternative to the Power Switch Tail.

IoT Power Relay

IoT Power Relay

COM-14236
$29.95
18

The IoT Power Relay is designed to allow you to safely control an outlet device that operates at 3--48VDC or 12--120VAC. Each IoT Power Relay features a single input (from the included C13 power cable) to four outputs: one normally on, one always on, and two normally off. The durable SPDT control relay is rated at 30/40A, for 400,000 operations.

In this kit, we will be using the relay to be able to safely and reliably control larger loads around your house or office without the need to cut wires and deal with high current A/C voltages. The great thing here is that you can also use it to power the project while controlling a device at the same time!

Servo Phat

The SparkFun Servo pHAT allows your Jetson Nano to control up to 16 servo motors in a straightforward and uncomplicated manner via an I2C connection. Thanks to its I2C capabilities, this PWM HAT saves GPIO pins, allowing you to use them for other purposes. The Servo pHAT also adds a serial terminal connection, which will allow you to connect to a number of other devices that are Serial/UART compatible.

SparkFun Servo pHAT for Raspberry Pi

SparkFun Servo pHAT for Raspberry Pi

DEV-15316
$11.95
3

Power to the SparkFun Servo pHAT can be supplied through USB-C connector. This will power either the servo motors only, or power the servo motors as well as the Jetson Nano that is connected to the HAT. We switched to USB-C to allow you to bring more current to your servos than ever before. This USB-C connector can also be used to hook up the Nano via serial port connection to avoid having to use a monitor and keyboard for setting up the Nano. To supply power only to the servo power rail (and not the Pi's 5V power rail), you just need to cut a small trace on the isolation jumper. Doing this allows you to drive heavier loads coming from multiple or larger servos. We've even added power protection circuits to the design, to avoid damage to power sources. Each of this pHAT's 16 servo motor pin headers has been spaced out to the standard 3-pin servo pinout (ground, 5V, signal) to make it easier to attach your servo motors.

Servo

A simple, low-cost, high quality servo for all your mechatronic needs. This servo is very similar in size and specifications to the Hitec HS-55. This little guy is able to take in 6 volts and deliver 20.8 oz-in. of maximum torque at 0.10 sec/60°

Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

ROB-09065
$8.95
12

This small servo comes with a standard 3 pin power and control cable and works perfectly to get your Nvidia Jetson projects to start moving!

Qwiic Button

Buttons are an easy and tactile way to interface with your project, but why would you want to deal with debouncing, polling, and wiring up pull-up resistors? The Qwiic Button with built-in red LED simplifies all of those nasty worries away into an easy to use I2C device! Utilizing our Qwiic Connect System, using the button is as simple as connecting a cable and loading up some pre-written code!

SparkFun Qwiic Button - Red LED

SparkFun Qwiic Button - Red LED

BOB-15932
$4.25
1

If you need multiple buttons for your project, fear not! Each button has a configurable I2C address, so you can daisy-chain multiple buttons over Qwiic and still address each one individually. We've got an example in our Arduino library that provides a super-easy way to configure your Qwiic Button to whatever I2C address you desire. You can download the library through the Arduino library manager by searching 'SparkFun Qwiic Button' or you can get the GitHub repo as a .zip file and install the library from there. In addition to handling blinking and debouncing, the Qwiic Button has configurable interrupts that can be configured to activate upon a button press or click. We've also taken the liberty of implementing a FIFO queue onboard the Qwiic Button where it keeps an internal record of when the button was pressed. This means that code on your microcontroller need not waste valuable processing time checking the status of the button but instead can run a small function whenever the button is pressed or clicked! For more information on interrupts check out our guide here!

Qwiic PIR Motion Sensor

Passive Infrared (PIR) sensors are great for detecting motion in a small area around the sensor. The 170µA SparkFun EKMC4607112K Qwiic PIR uses an EKM-series PIR sensor from Panasonic® paired with an ATTiny84 to interact with it using I2C with the Qwiic system. The EKM-series PIR sensors are optimized for small movements to offer motion-sensing options for continuously powered applications. A great way to enable a webcam or run a machine learning program when there is actually something in front of the project detected!

SparkFun Qwiic PIR - 170uA (EKMC4607112K)

SparkFun Qwiic PIR - 170uA (EKMC4607112K)

SEN-17374
$20.95
1

PIR sensors do not return specific distance data but instead monitor for IR light coming from objects in their field of view and will activate their signal when motion is detected in their sensing area, making them perfect for applications such as turning devices on automatically when motion is detected. Applications include home and building automation for energy saving, automated on/off lighting control, security, appliances, and IoT. Panasonic's low-profile PIR motion sensors (10.9mm versus standard 14.4mm height offer space savings for constrained designs) consist of a lens to create various detection zones, an optical filter to block non-infrared light, pyroelectric sensing elements, electromagnetic shielding to all circuitry, and an impedance converter to get an electrical signal. This PIR sensor offers digital output across 32 zones at 5m detection distance with 90° x 90° detection area.

Qwiic SerLCD Display

The SparkFun SerLCD is an AVR-based, serial enabled LCD that provides a simple and cost effective solution for adding a 16x2 Black on RGB Liquid Crystal Display into your machine learning project.

SparkFun 16x2 SerLCD - RGB Backlight (Qwiic)

SparkFun 16x2 SerLCD - RGB Backlight (Qwiic)

LCD-16396
$19.95

We've seriously overhauled the PCB design on the back of the screen by including an ATmega328P that handles all of the screen control, meaning a backpack is no longer needed! This display can now communicate in three different ways: serial, I2C, and SPI. This version comes equipped with a Qwiic connector, bringing serial LCDs into the Qwiic ecosystem. This simplifies the number of wires needed and allows your project to display all kinds of text and numbers.

Qwiic SparkFun Environmental Combo Sensor

The SparkFun CCS811/BME280 Environmental Combo Breakout takes care of all your atmospheric-quality sensing needs with the popular CCS811 and BME280 ICs. This unique breakout provides a variety of environmental data, including barometric pressure, humidity, temperature, TVOCs and equivalent CO2 (or eCO2) levels. To make it even easier to use this breakout, all communication is enacted exclusively via I2C, utilizing our handy Qwiic system. However, we still have broken out 0.1" spaced pins in case you prefer to use a breadboard.

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SEN-14348
$35.95
20

The CCS811 is an exceedingly popular sensor, providing readings for equivalent CO2 (or eCO2) in the parts per million (PPM) and total volatile organic compounds in the parts per billion (PPB). The CCS811 also has a feature that allows it to fine-tune its readings if it has access to the current humidity and temperature. Luckily for us, the BME280 provides humidity, temperature and barometric pressure! This allows the sensors to work together to give us more accurate readings than they’d be able to provide on their own. We also made it easy to interface with them via I2C.

Software Overview and Setup

This section is going to walk you through getting up and starting from a software perspective. With the advent of the Nvidia Jetson 2GB also came the use of Docker and its Containers as a way to manage different OS images rather than having to burn different OS images to microSD cards and swap them out as needed.

For those unfamiliar with Docker Containers, they are portable units of software that combine an application and all of its dependencies (code, runtime, system tools, system libraries, etc.) into a single package that is agnostic to the host OS. In other words, regardless of its environment the application will always run the same. This removes the need to build complex environments from scratch repetitively and simplifies the process of deploying applications.

For a quick start, we can just burn the basic OS to a microSD card, download whatever containers we need for what content we are working with, and then open those containers. The process is a little different and new for those who are used to managing SD cards for the Raspberry Pi or other single board computers, but it is an improvement and much more efficient in terms of time.

This section is a little long, but the setup is a crucial part of getting your first home automation project up and running! So take your time getting all of the settings configured correctly.

NVIDIA Jetson Nano OS Image

With all of the container talk, we still need a base operating system. You can find the most up-to-date image from Nvidia for the Jetson Nano here.

Once you download it, you can write the image to your microSD card by following Nvidia's instructions according to your computer’s operating system: Windows, macOS, or Linux.

Mac Setup

Setup and Boot Through Display or Headless

You can load the OS Image and setup your Jetson Nano one of two ways: with a display, keyboard, and mouse attached, or in headless mode via a connection with another computer.

If you choose the first method, simply insert the microSD card, and connect the display via HDMI and power via USB-C, as well as the keyboard and mouse via USB. The Nano will boot up - it might take a few minutes - and will lead you to a configuration window. This will guide you through choosing a time-zone, a keyboard language, and setting up a user profile.

Setting up through headless mode is quite similar...you'll still connect the power via USB-C and insert the microSD card, but instead of connecting a display, mouse and keyboard, you'll connect the Micro USB-C to your computer. Using a terminal application (PuTTY is popular for Windows, Serial for Macs), you can communicate with the Jetson Nano through USB serial communication.

If you use PuTTy, you'll have to go to the device manager in Windows and look for Communication Ports to determine which port the Jetson Nano is running under. If you aren't able to find the Communications Port, go to the Action menu within the Device Manager, and then select Add legacy hardware. You'll continue through the menu by clicking next, which will take you to a list of hardware that cana be installed. Select Ports (COM & LPT), continue on clicking next (the Standard port types option will work), and you'll be finished. Within puTTY, enter the COM port number, and set the speed to 115200.

puTTY setup

If you use Serial, the device will show up within the USB tab, and you'll be able to double click on it to enter the Nano's terminal. Remember to press enter once in the terminal to prompt it to ask you user/password settings, otherwise the cursor will just blink.

alt text

Within the Nano's terminal, through whichever method you communicate through USB serial, the Jetson Nano will prompt you with the same configuration setup as it did when connected to the display. It will just be done through the command line versus through a GUI.

Network Settings

Unfortunately, the Jetson Nano does not come equipped with Wifi, but we need it to access the DLI course Docker Container and JupyterLabs. There are a few ways to connect to WiFi - at first glance, it's obvious that the Nano comes equipped with an Ethernet port, so you can connect to your personal network by simply using an Ethernet cable.

However, it's likely you'll want to use the Jetson Nano wirelessly, and the easiest way to go about that is using a wireless network adapter that plugs into the USB port, like the Edimax adapter we carry here. These adapters just work smoothly; in most cases there are no additional drivers to install or setup to go through (and if there are drivers to install, we've written a tutorial on how to do that). Once the USB is plugged into the Nano, the device just automatically recognizes it, and you can go about selecting your network.

If you are using a 2GB and a separate display, connection through the WiFi dongle included should be straightforward using the GUI and selecting your network during setup.

If you are operating your Jetson Nano through headless mode, you'll have to use the command line to connect to the network. We'll start by using the following command:

ifconfig wlan0Enter

ifconfig stands for interface configuration, so it allows you to setup the network interfaces of the Nano. wlan0 is the name of the first wireless network interface. This will tell us the status of wlan0 - if the Wifi adapter dongle is not properly plugged in or working, you won't see the status like shown below.

Testing wlan0

Once we know the adapter is working and the device has the capabilities of connecting to a network, we can list all of the possible network connections by typing the following command, which calls the Network Manager:

nmcli dEnter

As seen below, the wlan0 device is not connected to anything. So, to connect to my network, we'll have to first ensure that the WiFi module is on by using the following prompt:

nmcli r wifi onEnter

And then we can scan the list of visible WiFi networks as well as their signal strenghts, data rate, channel, security, etc.

nmcli d wifi listEnter

Connecting to WiFi

Once you see the wireless network you want to connect to, type the following command, and remember that both the SSID and password are case sensitive.

sudo nmcli d wifi connect [SSID] password [PASSWORD]Enter

If the WiFi is public and doesn't have a password, then the following command works for connecting:

nmcli --ask dev wifi connect [SSID]Enter

Finally, you can check that you are connected by prompting the Network Manager to show you all of the active connections:

nmcli con show --active

Successful Wifi Connection

If you run into issues, refer to the tutorial we wrote that has references for getting unstuck.

Download and Install the DLI Course Container

Once you have your Jetson Nano up and running and the basic configuration complete including connecting it to your personal network, either through WiFi or Ethernet), open a command prompt and type the following command to download the DLI Course container that we will use as our starting point and then add to it as we go!

docker pull nvcr.io/nvidia/dli/dli-nano-ai:v2.0.1-r32.6.1Enter

The container will take some time to download. It is a good time to grab some coffee, watch some YouTube videos or take a nap!

Launch the DLI Course Container

When the container image has completely downloaded you will again gain control of the command prompt. Once you do you can launch the container by typing the following command into the prompt. Make sure to have your USB camera plugged in at this point.

sudo docker run --runtime nvidia -it --rm --network host --volume ~/nvdli-data:/nvdli-nano/data --device /dev/i2c-1 --device /dev/video0  nvcr.io/nvidia/dli/dli-nano-ai:v2.0.1-r32.6.1    

Notice that it is one command that is run on one line - you should run it altogether. NVIDIA does a good job of explaining the command that runs the Docker container and JupyterLabs inside of it:

  • --runtime nvidia will use the NVIDIA container runtime while running the l4t-base container
  • -it means run in interactive mode
  • --rm will delete the container when finished
  • --network host allows the container to use your Jetson host network and ports
  • --volume defines a mounting directory, and is used to share the persistent data files and the USB camera between the Jetson host and the container
  • --device allows access to the video device

This command will start a personal JupyterLab server in a local Docker container. Since you'll be using it whenever you want to build applications, which presumably is often, I recommend creating a Bash script using the nano text editor so that you don't have to go looking for the command each time, you can just run the script. If you'd like to do this, open a text editor like nano (you can always install it using sudo apt install nano), copy and paste the command above, and save the file with a .sh extension. You'll need to set execute permission on your script using the chmod command chmod +x script-name-here.sh and then you'll be able to run your script anytime you want by using ./script-name-here.sh.

If you have run the DLI Course container before, you may notice that this command has been slightly changed from the previous version you find in the course materials. We added a device flag addition for /dev/i2c-1. This option gives the container access to the i2c-1 bus that all of your SparkFun Qwiic Boards will connect through. Without this flag you would get a bunch of errors when you start trying to work with the different boards in your kit.

You'll know that the DLI Course Container is launched and successful when it shows the following message:

JupyterLab Launch

Copy the url (which is simply the Nano's specific IP address followed by :8888) and use the password dlinano to enter JupyterLabs. Notice that we already within the folder nvdli-nano, which gives us access to the DLI-Nano Notebooks directory.

Navigate JupyterLab

Welcome to JupyterLab! JupyterLab enables you to arrange your work area with notebooks, text files, terminals, and notebook outputs. The main page will provide you with options to start from scratch and create your own Python 3 Notebook or Console, as well as open a terminal tab or create a Markdown file. And, because we loaded the DLI course image onto the Nano, we have access to all the associated course documents and examples, as seen in the file directory.

JupyterLab main page

Once you are logged into Jupyter Notebooks you will need to open a new terminal window to download the Jupyter Notebooks for the Qwiic Boards as well as install the Qwiic Python libraries.

Once you open the terminal window from the Launcher window, you can download the SparkFun Qwiic Jupyter Notebooks from GitHub with the following command:

git clone https://github.com/d1runberg/qwiic-jupyter-nb.git[Enter]

This command will download a folder with the contents of our Jupyter Notebooks as well as the assets required to display images, etc. You should now be able to see the SparkFun Qwiic Notebooks directory in the directory tree on the left side of JupyterLabs!

Qwiic libraries in JupyterLabs

Once the SparkFun Qwiic Notebooks downloads you need to install the Qwiic Python libraries before digging in and using them.

Installing Qwiic Libraries

With the terminal window in Jupyter Notebooks still opened you can install the SparkFun Qwiic Python libraries through pip by typing the following command:

pip3 install sparkfun-qwiic[Enter]

This will install the entire Qwiic Py package with libraries for the Qwiic boards that are supported in Python.

Once the installation is complete, you should be good to go and can close the terminal window.

You're officially good to go to start developing applications! Remember, the container we opened is built to delete the container when finished, so if you were to close down JupterLabs as is right now, you'd lose the Qwiic Jupyter Notebooks and Qwiic libraries that you just downloaded and installed.

You can work with nearly any Qwiic device that has a python library, which means you can extend your project well beyond the scope of the Machine Learning Kit. Before you jump into the deep end and working with machine learning, make sure you're well accainted with just running an example with a Qwiic board in JupterLabs.

Workshop 1: Building a Pet Feeder

Alright, let me know if this sounds familiar to you - you've got a rambunctious _____ that tends to steal more food than they're allowed. Fill in the blank...could be a pet, a child, a friend (are they really?) or a roommmate. Whoever it is, it's problematic for you, either because their taking your food or they are simply eating too much. And, it's exhausting to monitor it yourself! What if you could create an automated food bin that would only open for specific people/pets?

This is the kind of problem that the Machine Learning @ Home Kit is well equipped to handle. It requires a system that can use images as data that will determine if a food bin is opened or not. Back in GTC 2021, one of our creative technologists, Derek, actually built it out, as seen linked below. It is highly recommended to just go through and watch the entire presentation, as it provides a thorough framework for making your way through image classification with the Jetson Nano and showcases how changing very little code can build a vastly different project. Furthermore, it's practically a step-by-step explanation for how to build out your own pet/human feeder.

As Derek does such a good job building out the hardware part of the project in the video, we'll just do a run-through of the software changes he made here.

The first thing required is to attach the SparkFun Pi Servo pHAT to the Jetson Nano, and then the servo itself. You can watch the video to get ideas about the mechanics of opening and closing the 'bin'.

Connect pi servo pHAT

As Derek explains, there are two major changes needed to personalize the DLI course example code for this project. The first is to write out a python script for operating the Qwiic servo. The second is change the parameters for the image classification to inputs of yourself and whoever you want to prevent from eating food.

Let's tackle the first part - coding in Python to drive the Qwiic servo through the Pi Servo pHAT. Open up a blank Python 3 Notebook in JupyterLabs, and test out the following script. It will use the Pi Servo Hat library to start the servo and move it specific increments at certain times.

#import the necessary libraries
import pi_servo_hat
import time
import math
import sys

#an object of our servo
myServo = pi_servo_hat.PiServoHat()

#starts up the servo
myServo.restart()

#initializes the position at (0,0)
myServo.move_servo_position(0,0)

#pauses for 1 second
time.sleep(1)

#moves the position 180 degrees
myServo.move_servo_position(0,180)

#pauses for 1 second
time.sleep(1)

#moves back to the initialized position
myServo.move_servo_position(0,0)

Okay, so we've got the servo moving, and we can use it to open and close our food bin. But, we need it to move only when a specific person/pet is in front of the bin. This is where the machine learning classification comes in with the USB camera.

Within JuptyerLabs, go into the classifications folder and open up the classification_interactive.ipynb file. This notebook is a template of sorts for data collection, training, and testing with the Jetson Nano and camera; the DLI Course already has a few examples laid out for you to play with, like determining if your thumbs are up or down, your emotions, how many fingers you're holding up, or your own DIY task. However, no matter which dataset you are training, the data collection and model really remain the same, it's just the content of the data that is changing. Start off by running all of the code blocks up until the Task section.

Things start to change within this notebook once we get here. We'll comment out the task of 'thumbs' and instead call the 'diy' task. Similiarly, the categories will change from 'thumbs up, thumbs down' to the last category of diy. It is here that you'll make the decision of who you want to create this food bin for. In Derek's example, he just did himself, 'Derek', or 'nothing', which is two categories. If that's similiar to your case (you could replace 'nothing' with someone else's name), then fill in the category names and keep the datasets set to two variables. If you're in a situation with two pets and yourself, fill in the variable names, and then uncomment the datasets option with three variables. Now you can run the code block. Here's an example of how it could look:

Tasks

Since we're not changing the model itself, we can keep going down until we hit the Live Execution code block. It's here that we can actually call the servo to move based on who is in front of the camera. Firstly, we'll add the pi_servo_hat library underneath the other library imports. Then, under the live function, we can add the following code to move the servo depending on what the who is in front of the camera in real time.

if prediction_widget.value == 'Pet 1':
    myServo.move_servo_position(0,180) #open the food bin
else:
    myServo.move_servo_position(0,0) #close the food bin

Since only one pet/human is allowed into the food bin, the else statement covers all other scenarios where either nothing is presented or the wrong person/pet is in front of the camera.

alt text

Once you run all of the code blocks, you'll find the interactive tool ready for use. Click on the category you'd like to train (pet 1 or pet two or nothing), and start adding photos of that specific category. The more the better, but shoot for at least 100. Try to get all angles and all situations, maybe that means a dog with or without a collar, before and after going to the groomer, etc. Continue doing so with category you have.

Next is to decide how many epochs, or cycles through the full training dataset, you will need for an accurate application. There's actaully an interesting issue when training machine learning models on sample data called overfitting. Overfitting is when too many epochs are used, and the training model learns patterns that are too specific to the sample data, and therefore perform with less accuracy with real world data. Mess around with how a lower number and higher number of epochs change the way your model reacts to real world inputs, but for now, let's do 5 epochs.

And that's about it, you're ready to train the model! Once trained, you can test how accurate it is by showing the camera real world data, like your face or your dog's face. When you show input of the category you set to open the food bin, it should do exactly that. Now nobody can get your skittles, they're all for you!

Workshop 2: Cooking with Bananas

As you can tell, we're trying to build applications that help out a bit around the home; especially since we're all spending a bit more time at home these days. Specifically, problems that can be solved using hardware, and thus bringing machine learning into the physical and tangible world.

Another problem that could be tackled is food waste in the kitchen. Sometimes, you just don’t get around to eating food when it’s at it’s freshest, but you still don’t want to waste it and throw it away. One of the most common foods for this is bananas! When bananas go bad, it’s fun to mix things up and bake banana bread, but you can get sick of banana bread pretty quick, which makes cooking with overripe bananas pretty tricky. What other recipes can you make with bananas at any ripeness? And can the Machine Learning @ Home Kit tell you what to make just by one look at a banana?

banana cheatsheet

Let’s build it out; it’s fairly similar to the pet feeder, because we’re just giving the model different training data and using a different Qwiic device. For starters, we’ll connect the Qwiic SerLCD up to the Pi Servo pHAT, and do the same thing as before: simply test out if we can get it working within JupyterLabs.

from __future__ import print_function
import qwiic_serlcd
import time
import sys

def runExample():

    print("\nSparkFun Qwiic SerLCD   Example 1\n")
    myLCD = qwiic_serlcd.QwiicSerlcd()

    if myLCD.connected == False:
        print("The Qwiic SerLCD device isn't connected to the system. Please check your connection", \
            file=sys.stderr)
        return

    myLCD.setBacklight(255, 255, 255) # Set backlight to bright white
    myLCD.setContrast(5) # set contrast. Lower to 0 for higher contrast.
    myLCD.clearScreen() # clear the screen - this moves the cursor to the home position as well

    time.sleep(1) # give a sec for system messages to complete

    myLCD.print("Hello World!")
    counter = 0
    while True:
        print("counter: %d" % counter)
        myLCD.setCursor(0,1)
        myLCD.print(str(counter))
        counter = counter + 1
        time.sleep(1)

if __name__ == '__main__':
    try:
        runExample()
    except (KeyboardInterrupt, SystemExit) as exErr:
        print("\nEnding Example 1")
        sys.exit(0)

Great, the display checks out! Now, let’s go back and make a copy of classification_interactive.ipynb for this new project, where we will go and run everything up until the Task section again.

This time, we’ll have five different categories: 'Very Unripe', 'Underripe', 'Ripe', 'Very Ripe', 'Overripe’. This means I’ll have to add additional datasets as well…all the way up to ‘E’.

Again, we can run all of the code blocks up to Live Execution. We’ll still import the SerLCD library like we did with the servo, as well as create an object for it. In this case, we’ll write out a different if statement, one that can accommodate each condition of a banana. So if a banana is underripe, the display will recommend a different recipe than if the banana is very underripe, etc. It could be structured similiarly to this:

if prediction_widget.value == 'Very Unripe':
    myLCD.print("Make some fried green bananas")
if prediction_widget.value == 'Unripe':
    myLCD.print("Make bananas foster")
if prediction_widget.value == 'Ripe':
    myLCD.print("Make some fried green bananas")
if prediction_widget.value == 'Very Unripe':
    myLCD.print("Make a fruit smoothie")
if prediction_widget.value == 'Very ripe':
    myLCD.print("Make banana pancakes")
if prediction_widget.value == 'Overripe':
    myLCD.print("Make banana bread")

This will take us back to the interactive tool again, and will be a bit more time consuming this time, as we'll need data for each stage of ripeness. So buy some bananas that are very unripe, and over the course of a week or two, train them at each stage periodically. Again, it's important you get as many different viewpoints and inputs as possible. Finally, train the data and see what your Qwicc SerLCD display recommends you to make!

Workshop 3: Power Loads

One of the main use cases we see is automating power loads and electrical systems. Let’s say you forget to turn your oven off and leave you house for a period of time - it’s something that’s happened to most of us, and a real safety concern! Or, you just want to be more conscious of turning your lights off when you leave a room. How about if you only want a light on if you’re at your desk? We can implement projects of these nature with the Machine Learning @ Home Kit because it comes with an IoT Power Relay.

NVIDIA has a Python library specifically for manipulating the Jetson GPIO, either for inputs or outputs. We'll have to first install the package natively on the Nano (outside of JupyterLabs) test it, and then add it to the docker command to containerize the library.

Back in whatever terminal emulator you're using (i.e Serial), we can install the Jetson.GPIO library with the following commands:

sudo pip install Jetson.GPIO

Then, we'll have to set permissions by creating a group and add your username to that group that can access the GPIO. If you don't know your username, just write out the command whoami.

sudo groupadd -f -r gpio

sudo usermod -a -G gpio your_user_name

Finally, for the new rule to take place, either reboot the Nano using the command sudo reboot or reload the udev rules by running:

sudo udevadm control --reload-rules && sudo udevadm trigger

Now that the library is installed, we're almost ready to test it. Connect the your jumper wires to the screw terminals in the green socket, and then connect them to a ground pin and a number pin of your choice on the Nano. Now, open up your python3 interpreter by simply typing python3, and run the script below.

#load in libraries
import Jetson.GPIO as GPIO 
import time

#sets the pin getting power sent to
output_pin = 21

#set pin numbering
GPIO.setmode(GPOI.BCM)

#setup GPIO channel with pin, ouput, and what the initial value is
GPIO.setup(output_pin, GPIO.OUT, initial = GPIO.LOW)

#set value of output pin
GPIO.output(output_pin, GPIO.HIGH)

time.sleep(10)

#clean up the channels so that all pins are set in their default state
GPIO.cleanup()

Now you know the drill, it’s time to go into Task, and change the categories and datasets needed. If you only want the lamp to turn on when you’re at your desk, you’ll really only need two datasets: you, and nothing else.

alt text

Down in Live Execution, we’ll set the IoT relay to only turn on when the category is set to your face. So the if statement will look very similar to the pet feeder situation…it’ll either be if you are in the frame, else for any other scenario. The full code is set up here.

Nearly any home automation is accessible to you through the Machine Learning @ Home Kit, and now that you know how to go through and train a wide variety of datasets, we can being deploying them as real world applications. That’s what we’ll get to next, as this living hookup guide continues.


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

Dialog ULP WiFi DA16200 R3 Shield Hookup Guide

$
0
0

Dialog ULP WiFi DA16200 R3 Shield Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Ultra. Low. Power. Arguably the best three words in the IoT world. SparkFun has teamed up with ARM and Dialog to provide you with the ULP WiFi R3 Shield based around the DA16200 module. The DA16200 is a fully integrated WiFi module with a 40MHz crystal oscillator, 32.768KHz RTC clock, RF Lumped RF filter, 4MB flash memory, and an onboard chip antenna. With the addition of a Qwiic connector, multiple GPIO options, JTAG connectors for deep dive programming, and you've got everything you need to get your R3 layout device ready to set up your next IoT project.

The SparkFun Qwiic WiFi Shield is ideal for door locks, thermostats, sensors, pet trackers, and other home IoT projects, thanks in part to the multiple sleep modes that allow you to take advantage of current draws as low as 0.2uA-3.5uA.

Additionally, the DA16200 module's certified WiFi alliance for IEEE802.11b/g/n, WiFi Direct, and WPS functionalities means that it has been approved for use by multiple countries and using the WiFi Alliance transfer policy, each WiFi Certification can be transferred without being tested again.

SparkFun Qwiic WiFi Shield - DA16200

SparkFun Qwiic WiFi Shield - DA16200

WRL-18567
$19.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.

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
14
Solder Lead Free - 15-gram Tube

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
3

Suggested Reading

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

Connectivity of the Internet of Things

An overview of the different protocols that can be used for the development of Internet of Things (IoT)-based projects.

Arduino Shields v2

An update to our classic Arduino Shields Tutorial! All things Arduino shields. What they are and how to assemble them.

Hardware Overview

There's a lot to cover with this board. Let's get started!

DA16200

At the heart of this board is the DA16200 from Dialog - a fully integrated Wi-Fi® module with ultra-low power consumption, 40 MHz crystal oscillator, 32.768 KHz RTC clock, RF Lumped RF filter, 4 M-byte flash memory, and an onboard chip antenna. This chip is chock full of features - for more information, refer to the datasheet.

The dialog module is at the bottom front middle of the board

Power

Power is available via a number of pins on the shield.

Power pins selected on the left side of the board as well as at the top

Wake

Integral to the ultra low power functionality is the wake-up controller. It is designed to wake up the DA16200 from a sleep mode by an external signal that selects either the rising edge or the falling edge on either WAKE1 or WAKE2. The RTC_PWR_KEY is used to enable the RTC block and switch between the various sleep modes. See the datasheet for more information.

Pins to wake from Low Power mode

Current Draw in Low Power Modes

Current Draw in Low Power Modes

UART

The DA16200 module has two UART interfaces. UART0 is used for updating the firmware to module, and UART1 is used for sending AT commands.

UART0 for the Dialog module sits at the top of the board.

UART0 pins are the second and third pins at the top of the board  from the right

UART1 is used for sending AT commands and is routed through a switch to communicate through either the hardware UART pins D0/D1 for RX/TX, or software UART through D9/D8 for RX/TX.

UART1 SW and HW pins and the switch are highlighted

SPI

SPI functionality is found on pins 10-13 on the right side of the board. If you wish to bypass the SPI pins and instead use the ADC on GPIOA0-GPIOA3, there are jumpers on the back of the board to accomplish this. Refer to the Jumpers section below for more information.

SPI pins 10-13 are highlighted as well as  GPIOA0-GPIOA3

DA16200 GPIO

General purpose IO pins for the Dialog module are available at the top of the board.

DA16200 specific GPIO

Qwiic Connector

A Qwiic connector is provided such that if you have an older RedBoard without a Qwiic connector, you can still add on a Qwiic sensor of your choice. Or you can use both the existing Qwiic connector on your RedBoard as well as the Qwiic connector on your shield. The RedBoard itself acts as the I2C controller. If you need help choosing a Qwiic sensor, check out our Qwiic Ecosystem.

The Qwiic connector is at the top right hand side of the board

Pins A0-A5

These pins are present on the board, but are not routed to anything on the shield.

Pins A0-A5 are highlighted on the lower left side of the board

Buttons

A general reset button is located on the upper left side of the board.

Arduino reset button is the button on the left of the board

Pressing and holding GPIOA7 will perform a factory reset, which clears configurations that might have been saved to the module.

GPIO A7 reset button is the button on the right of the board

Jumpers

JP1

Cutting this jumper removes power from the LED on the front of the board.

LED Jumper is on the right side of the back of the board - bottom most jumper on that side

Click on the image for a closer view of the jumper.

JP2

SPI CIPO is the default functionality for this shield. Cutting this jumper and closing the jumper between GPIOA0 and Header selects for GPIO A0 (Analog to Digital Converter functionality for Dialog Chip).

JP2 is the top right jumper set and chooses between D12 and GPIOA0

Click on the image for a closer view of the jumper.

JP3

SPI COPI is the default functionality for this shield. Cutting this jumper and closing the jumper between GPIOA1 and Header selects for GPIO A1 (Analog to Digital Converter functionality for Dialog Chip).

JP3 is the top left jumper set and chooses between D11 and GPIOA1

Click on the image for a closer view of the jumper.

JP4

SPI CS is the default functionality for this shield. Cutting this jumper and closing the jumper between GPIOA2 and Header selects for GPIO A2 (Analog to Digital Converter functionality for Dialog Chip).

JP4 is the bottom right jumper set and chooses between D10 and GPIOA2

Click on the image for a closer view of the jumper.

JP5

SPI SCK is the default functionality for this shield. Cutting this jumper and closing the jumper between GPIOA3 and Header selects for GPIO A3 (Analog to Digital Converter functionality for Dialog Chip).

JP5 is the bottom left jumper set and chooses between D13 and GPIOA3

Click on the image for a closer view of the jumper.

JP6

Selects SPI Interrupt to Arduino (default) or PWM to GPIO header

JP6 is below the Measurement jumper and JP5 and chooses between D3 and GPIOA10

Click on the image for a closer view of the jumper.

Current Measurement Jumper

To enable measurements and to isolate the power hungry devices, we've added a NC (normally closed) jumper. By cutting the jumper on the back of the board, the VDD trace to the module is interrupted. Soldering in a male jumper or wires into the accompanying holes will give you the ability to insert a current meter and precisely monitor how much current your application is consuming.

Current Measurement jumper holes are on the back of the board in the middle, midway up from the middle

I2C Jumper

Cutting this jumper will disable the pull up resistors on the bus.

I2C jumper is on the back of the board on the lower left

JTAG

An unpopulated JTAG footprint is available for more advanced users who need breakpoint level debugging. We recommend checking out our JTAG section for the compatible male header and a compatible JTAG programmer and debugger.

The JTAG footprint is on the front of the board just above the Dialog Module

Board Outline

Board measures 2.1 by 2.35 inches

Hardware Hookup

The Dialog ULP Wifi DA16200 Shield comes with headers pre-soldered to the Arduino facing pins. This makes the shield pretty much plug and play when using our standard RedBoard footprint. However, should you wish to use the edge pins for the DA16200 or the ADC, you'll need to solder headers to those plated through holes.

To plug your shield into the RedBoard, line up the pin labels and gently push the connectors together. Voila!

Plugging the shield into the RedBoard is fairly straightforward.

Example 1: Baud Rate Shenanigans

Note: This code has been written and tested on the latest Arduino IDE version. Make sure you are using the latest stable version of the Arduino IDE on your desktop.

If this is your first time using Arduino IDE, library, or board add-on, please review the following tutorials.

Note: The primary mode of communication with the DA16200 unit is using AT commands. If you're unfamiliar with AT commands, feel free to refer to Dialog's DA16200 AT Command User Manual.

Now that we have the nitty-gritty out of the way, let's look at a few use cases for our Shield.

In this first example, we're going to show you how to change the baud rate to manage serial communications. For boards that have a second hardware UART available, you'll be able to operate at the default baud rate. For other boards, like those based around the ATmega328 (like the RedBoard Qwiic), softwareSerial has a difficult time reading data sent at the higher baud, and it's recommended to lower the baud rate down to 9600 using the ATB command, and then changing the softwareSerial baud down from 115200 to 9600. This example will show you how to do that.

To begin with, copy and paste the code below into a fresh Arduino sketch.

language:c
#include<SoftwareSerial.h>

#define RX1 8
#define TX1 9
#define RTC_PWR_KEY 4

#define SOFTWARE_SERIAL_BAUD 115200
//#define SOFTWARE_SERIAL_BAUD 9600

SoftwareSerial WiFiSerial(RX1,TX1); //Configure SoftwareSerial

void setup() {
  Serial.begin(9600);
  WiFiSerial.begin(SOFTWARE_SERIAL_BAUD); //Set SoftwareSerial baud


  //Enable DA16200 Module RTC power block
  pinMode(RTC_PWR_KEY,OUTPUT);
  digitalWrite(RTC_PWR_KEY,HIGH);

  Serial.println("DA16200 AT Command example sending/receiving commands\n");


  //Listen for ready message ("+INIT:DONE")
  byte count = 0;
  String msg = "";
  while(count<20)
  {
    while(WiFiSerial.available())
    {
      msg += char(WiFiSerial.read());
    }
    if(msg.length() > 5) break;
    count++;
    delay(100);
  }
  msg = msg.substring(3,msg.length());

  if(msg.length()>5)
  {
    Serial.println("Expecting: \"INIT:DONE,(0 or 1)");
    Serial.println("Received: " + msg);
  }
  else
  {
    Serial.println("Failed to receive initialization message\n");

    Serial.println("Make sure the baud rate for WiFiSerial matches the baud rate\n" \
                   "saved to the DA16200. You can also perform a factory reset by\n" \
                   "pressing and holding the GPIOA7 button for ~5s, which will\n" \
                   "reset the baud rate back to 115200");
  }

  Serial.println("\nTry entering \"?\" or \"help\" to print out the list of AT commands\n" \
                 "\nIf the received text is unreadable, try changing the baud rate to\n" \
                 "9600 with the command \"ATB=9600\" in the terminal. Next, update the\n" \
                 "example code by setting SOFTWARE_SERIAL_BAUD to 9600 baud and trying again.\n");
}

void loop() {
    while(Serial.available())
    {
      WiFiSerial.print(char(Serial.read()));
    }

    while(WiFiSerial.available())
    {
      Serial.print(char(WiFiSerial.read()));
    }
}

Set your Board and Serial Port, and then upload the sketch to your Arduino. Then open the serial monitor. You'll begin to see output.

If you type "?" or "help" it will print out all of the AT commands. However, at the higher baud rate of 115200 there's a lot of receive errors on a 328 board. To fix this, send the baud rate command for 9600 - "ATB=9600" and you should get an "OK" response. Once that's done you can go back to sketch and comment out the #define SOFTWARE_SERIAL_BAUD 115200, uncomment the line below that defines the software serial baud for 9600, and then re-upload the sketch.

Make sure the baud rate on the serial monitor is set to 9600 and then try typing "?" or "help" again.

Output of successful AT Command
Note: The baud rate setting is saved to the module, so if you want to go back to 115200, you'll have to rerun the command with 115200, or do a factory reset.

Example 2: GPIO and LEDs

In this example, we're going to show you how to use the provided GPIO. Before we get started, let's get our hardware all hooked up.

To start with, you'll need to solder headers to the DA16200 GPIO PTH pins.

Headers are soldered to the 16200 pins
Note: The LEDs used in this example contain a built-in resistor. If you do not use the LEDs we have recommended (or similar), make sure you add appropriate resistors to the circuit below!

With your shield plugged into a SparkFun RedBoard (with 3.3V logic!!!), connect up your LEDs like so:

  • Connect LED1 with current limiting resistor to GPIOC6
  • Connect LED2 with current limiting resistor to GPIOC7
  • Connect LED3 with current limiting resistor to GPIOC8

Make sure switch is in the "SW" position. Here's a Fritzing image to help you sort out the connections:

Fritzing hookup image

Our actual hookup looks like this:

Actual image of the LEDs all hooked up

Click the image for a closer view.

Plug your board into your computer, and copy and paste the code below into a fresh Arduino sketch. Find the lines that define the SOFTWARE_SERIAL_BAUD and uncomment the line that contains the appropriate baud rate.

language:c
/******************************************************************************
  Example_02 Basic Communication

  Configure GPIOC6-8 as output pins, and toggle each LED individually.

  Development environment specifics:
  IDE: Arduino 1.8.13
  Hardware Platform: SparkFun RedBoard Qwiic (3.3V LOGIC!!!!)

  Hardware Connections:
  - Connect the shield to a 3.3V logic Arduino R3 board
  - Connect LED1 with current limiting resistor to GPIOC6
  - Connect LED2 with current limiting resistor to GPIOC7
  - Connect LED3 with current limiting resistor to GPIOC8
  - Make sure switch is in the "SW" position

  ARDUINO --> WiFi Shield --> External
  8       --> RX1
  9       --> TX1
  4       --> RTC_PWR_KEY
  -       --> GPIOC6      --> LED1
  -       --> GPIOC7      --> LED2
  -       --> GPIOC8      --> LED3
  3.3V    --> 3.3V
  GND     --> GND         --> GND

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/

#include<SoftwareSerial.h>

#define RX1 8
#define TX1 9
#define RTC_PWR_KEY 4

//#define SOFTWARE_SERIAL_BAUD 115200
//#define SOFTWARE_SERIAL_BAUD 9600

SoftwareSerial WiFiSerial(RX1,TX1); //Configure SoftwareSerial

void setup() {
  Serial.begin(9600);
  WiFiSerial.begin(SOFTWARE_SERIAL_BAUD); //Set SoftwareSerial baud

  //Enable DA16200 Module RTC power block
  pinMode(RTC_PWR_KEY,OUTPUT);
  digitalWrite(RTC_PWR_KEY,HIGH);

  Serial.println("DA16200 AT Command Example: Controlling GPIO\n");

  //Listen for ready message ("+INIT:DONE")
  byte count = 0;
  String msg = "";
  while(count<20)
  {
    while(WiFiSerial.available())
    {
      msg += char(WiFiSerial.read());
    }
    if(msg.length() > 5) break;
    count++;
    delay(100);
  }
  msg = msg.substring(3,msg.length());

  if(msg.length()>5)
  {
    Serial.println("Expecting: \"INIT:DONE,(0 or 1)");
    Serial.println("Received: " + msg);
  }
  else
  {
    Serial.println("Failed to receive initialization message.\n" \
                   "Make sure you're using the correct baud rate.\n");
    while(1); //Unable to communcation with module, so don't move forward
  }


  WiFiSerial.println("AT+GPIOSTART=2,1C0,1"); //Configure GPIOC6, GPIOC7, GPIOC8 as outputs
}

void loop() {
  WiFiSerial.println("AT+GPIOWR=2,100,1"); //Set GPIOC8 high
  WiFiSerial.println("AT+GPIOWR=2,0C0,0"); //Set GPIOC6, GPIOC7 low
  delay(200);
  WiFiSerial.println("AT+GPIOWR=2,080,1"); //Set GPIOC7 high
  WiFiSerial.println("AT+GPIOWR=2,140,0"); //Set GPIOC6, GPIOC8 low
  delay(200);
  WiFiSerial.println("AT+GPIOWR=2,040,1"); //Set GPIOC6 high
  WiFiSerial.println("AT+GPIOWR=2,180,0"); //Set GPIOC7, GPIOC8 low
  delay(200);
}

Set your Board and Serial Port, and then upload the sketch to your Arduino. If you've hooked it all up right, you'll see the LEDs flash in order!

Flashing LEDS

Example 3: Connecting to WiFi

Let's check out the WiFi with a simple example to grab the time.

Copy and paste the code below into a fresh Arduino sketch. Find the lines that define the SOFTWARE_SERIAL_BAUD and uncomment the line that contains the appropriate baud rate.

language:c
/******************************************************************************
  Example_03 WiFi Communcation

  Connect WiFi using the provided network credentials
  Talk to NTP server to set the current date/time
  Update the time to the correct time zone
  Print the current time approx. once every second

  Development environment specifics:
  IDE: Arduino 1.8.13
  Hardware Platform: SparkFun RedBoard Qwiic (3.3V LOGIC!!!!)

  Hardware Connections:
  Connect the shield to a 3.3V logic Arduino R3 board
  Make sure switch is in the "SW" position

  ARDUINO --> WiFi Shield
  8       --> RX1
  9       --> TX1
  4       --> RTC_PWR_KEY
  3.3V    --> 3.3V
  GND     --> GND

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include<SoftwareSerial.h>

#define RX1 8
#define TX1 9
#define RTC_PWR_KEY 4

//#define SOFTWARE_SERIAL_BAUD 115200
//#define SOFTWARE_SERIAL_BAUD 9600

String wifiSSID = "SSID";
String wifiPass = "PASSWORD";

int timezoneOffset = 0; //The hours offset from UTC (Mountain time is -6 for daylight savings, and -7 for standard)

SoftwareSerial WiFiSerial(RX1,TX1); //Configure SoftwareSerial

void setup() {
  Serial.begin(9600);
  WiFiSerial.begin(SOFTWARE_SERIAL_BAUD); //Set SoftwareSerial baud

  //Enable DA16200 Module RTC power block
  pinMode(RTC_PWR_KEY,OUTPUT);
  digitalWrite(RTC_PWR_KEY,HIGH);

  Serial.println("DA16200 AT Command Example: Connecting to WiFi\n");

  //Listen for ready message ("+INIT:DONE")
  byte count = 0;
  String msg = "";
  while(count<20)
  {
    while(WiFiSerial.available())
    {
      msg += char(WiFiSerial.read());
    }
    if(msg.length() > 5) break;
    count++;
    delay(100);
  }
  msg = msg.substring(3,msg.length()); //Remove NULL,CR,LF characters from response

  if(msg.length()>5)
  {
    Serial.println("Expecting: \"INIT:DONE,(0 or 1)");
    Serial.println("Received: " + msg);
  }
  else
  {
    Serial.println("Failed to receive initialization message.\n" \
                   "Make sure you're using the correct baud rate.\n");
    while(1);
  }

  //Configure module for STA mode
  Serial.println("Sending:AT+WFMODE=0");
  WiFiSerial.println("AT+WFMODE=0");

  //Wait for "OK" response
  while(1)
  {
    msg = "";
    while(WiFiSerial.available())
    {
      msg += char(WiFiSerial.read());
      delay(1);
    }
    Serial.print(msg);
    if(msg.length() > 1) break;
  }

  //Apply a software reset to finish changing the mode
  Serial.println("Sending:AT+RESTART");
  WiFiSerial.println("AT+RESTART");

  //Wait for "OK" response
  while(1)
  {
    msg = "";
    while(WiFiSerial.available())
    {
      msg += char(WiFiSerial.read());
      delay(1);
    }
    Serial.print(msg);
    if(msg.length() > 1) break;
  }

  //Listen for ready message ("+INIT:DONE") after the reset is finished
  count = 0;
  msg = "";
  while(count<20)
  {
    while(WiFiSerial.available())
    {
      msg += char(WiFiSerial.read());
    }
    if(msg.length() > 5) break;
    count++;
    delay(100);
  }

  Serial.println(count);
  Serial.println(msg);
  msg = msg.substring(3,msg.length()); //Remove NULL,CR,LF characters from response

  if(msg.length()>5)
  {
    Serial.println("Expecting: \"INIT:DONE,(0 or 1)");
    Serial.println("Received: " + msg);
  }
  else
  {
    Serial.println("Failed to receive initialization message.\n" \
                   "Continuing anyway...\n");
  }

  //Connect to WiFi using the provided credentials
  Serial.println("Sending:AT+WFJAPA=" + wifiSSID + "," + wifiPass);
  WiFiSerial.println("AT+WFJAPA=" + wifiSSID + "," + wifiPass);

  Serial.println("Waiting for connection response...");
  while(1)
  {
    msg = "";
    while(WiFiSerial.available())
    {
      msg += char(WiFiSerial.read());
      delay(1);
    }

    if(msg.length() > 10) 
    {
      Serial.print("Response:");
      Serial.println(msg);
      break;
    }
  }

  msg = msg.substring(3,msg.length()); //Remove NULL,CR,LF characters from response

  //If connection to AP is successful, response will be WFJAP:1,SSID,IP_ADDRESS, or WJAP:0 if failed
  if(msg.startsWith("WFJAP:1"))
  {
      //Talk to NTP server to get the current time, along with how often to get time sync
      Serial.println("Sending:AT+NWSNTP=1,pool.ntp.org,86400");
      WiFiSerial.println("AT+NWSNTP=1,pool.ntp.org,86400");

      //Wait for "OK" response
      while(1)
      {
        String msg = "";
        while(WiFiSerial.available())
        {
          msg += char(WiFiSerial.read());
          delay(1);
        }
        Serial.print(msg);
        if(msg.length() > 1) break;
      }

      //Provides the correct UTC offset for the current time
      Serial.println("Sending:AT+TZONE="+String(timezoneOffset*3600));
      WiFiSerial.println("AT+TZONE="+String(timezoneOffset*3600));

      //Wait for "OK" response
      while(1)
      {
        String msg = "";
        while(WiFiSerial.available())
        {
          msg += char(WiFiSerial.read());
          delay(1);
        }
        Serial.print(msg);
        if(msg.length() > 1) break;
      }  
  }
  else
  {
    Serial.println("Connection unsucessful :(\n\n" \
                   "Make sure the WiFi credentials are correct, and the module is in the station mode");
    while(1);
  }
}

void loop() {
  //Get the current time
  Serial.println("Sending:AT+TIME");
  WiFiSerial.println("AT+TIME");

  while(WiFiSerial.available())
  {
    Serial.print(char(WiFiSerial.read()));
    delay(1);
  }

  delay(1000);
}

Set your Board and Serial Port, and then upload the sketch to your Arduino. Then open the serial monitor. Make sure your baud rate is set to 9600. You'll begin to see output.

Serial monitor output for WiFi example

Troubleshooting

Resources and Going Further

For more information on the WiFi Shield or the DA16200, check out the resources below:

Need some inspiration for your next project? Check out some of these related tutorials:

Loading Debian (Ubilinux) on the Edison

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

Electric Imp Breakout Hookup Guide

An electric imp HUG! Provides an overview of the imp card and breakout. Both hardware and firmware subjects are covered.

Experiment Guide for the Johnny-Five Inventor's Kit

Use the Tessel 2 and the Johnny Five Inventors kit to explore the world of JavaScript enabled hardware through 14 awesome experiments!

Raspberry Pi 4 Kit Hookup Guide

Guide for hooking up your Raspberry Pi 4 Model B basic, desktop, or hardware starter kit together.


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


SparkFun Qwiic Alphanumeric Display Hookup Guide

$
0
0

SparkFun Qwiic Alphanumeric Display Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Seven segment displays are SO 2020. I mean, we see them in our clocks, ovens, and microwaves on the daily. But what happens when you add more segments to each digit? You can upgrade your appliances and let everyone know how you REALLY feel. Introducing SparkFun's newest Qwiic-Enabled Alphanumeric Display in both Pink and Green. Customize that microwave alert - "Your food is done, fool!" Or hack those oven messages - "I pity the fool that doesn't pre-heat!" These fourteen-segment digits allow you display all sorts of numbers, characters, and symbols. Let's jump in and have a look, shall we?

SparkFun Qwiic Alphanumeric Display - Pink

SparkFun Qwiic Alphanumeric Display - Pink

COM-16919
$9.95
SparkFun Qwiic Alphanumeric Display - Green

SparkFun Qwiic Alphanumeric Display - Green

COM-18566
$9.95

Required Materials

You will need a microcontroller to control the Qwiic Alphanumeric Display in order to follow along with this tutorial. Below are a few options that come Qwiic-enabled out of the box:

SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)

DEV-15795
$19.95
4
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
9
SparkFun Thing Plus - ESP32 WROOM

SparkFun Thing Plus - ESP32 WROOM

WRL-15663
$20.95
7
SparkFun RedBoard Artemis

SparkFun RedBoard Artemis

DEV-15444
$19.95
8

If your chosen microcontroller is not already Qwiic-enabled, you can add that functionality with one or more of the following items:

SparkFun Qwiic Adapter

SparkFun Qwiic Adapter

DEV-14495
$1.50
1
SparkFun Qwiic Shield for Arduino

SparkFun Qwiic Shield for Arduino

DEV-14352
$6.95
6

You will also need at least one Qwiic cable to connect your Alphanumeric Display to your microcontroller.

Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 500mm

Qwiic Cable - 500mm

PRT-14429
$1.95
1
Qwiic Cable - 50mm

Qwiic Cable - 50mm

PRT-14426
$0.95
Qwiic Cable - 200mm

Qwiic Cable - 200mm

PRT-14428

Suggested Reading

If you aren't familiar with the Qwiic system, we recommend reading here for an overview:

Qwiic Connect System

We would also suggest reading through the following tutorials if you are not familiar with the concepts covered in them:

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.

Hardware Overview

As mentioned in the introduction, the Qwiic Alphanumeric Displays use the VK16K33 LED driver chip to control the segments. In this section of the guide we'll go into more detail on the LED driver and the display, as well as the other components included on the board.

VK16K33 LED Driver

The Qwiic Alphanumeric Display boards use the VK16K33 LED driver chip to control the segments. The VK16K33 is a memory mapping and multifunction LED controller driver with a maximum display segment number of 128 patterns (16 segments and 8 commons) and a 13×3 matrix key scan circuit. There's an integrated RC oscillator and a 16-step dimming circuit as well. More information can be found in the VK16K33 Datasheet.

LED Driver on the back of the board

Alphanumeric Display

Look at all those beautiful segments ready to display (almost) whatever your heart desires!

Display screen on the front of the board

Qwiic

Our Qwiic Ecosystem makes sensors pretty much plug and play. There are two Qwiic connectors on either side of the Alphanumeric Display board to provide power and I2C connectivity simultaneously.

The default I2C address of the board is 0x70. Additional addresses are available - see the Jumpers section below.

Qwiic connectors on either side of the back of the board

I2C Address Jumpers

Two jumpers have been provided to allow you to choose the I2C address of the peripheral. See the table below for configuration details.

A0 and A1 jumpers are on the far right of the back of the board
AddressA0A1
0x70OpenOpen
0x71ClosedOpen
0x72OpenClosed
0x73ClosedClosed

I2C Bus Resistor Jumper

The Qwiic Alphanumeric Display Breakout has onboard I2C pull up resistors; if multiple sensors are connected to the bus with the pull-up resistors enabled, the parallel equivalent resistance will create too strong of a pull-up for the bus to operate correctly. As a general rule of thumb, disable all but one pair of pull-up resistors if multiple devices are connected to the bus. If you need to disconnect the pull up resistors they can be removed by cutting the traces on the corresponding jumpers highlighted below.

Jumper is on the lower left side of the back of the board

I2C Pins

If you've got mad soldering skillz and really want to access the I2C pins, we've made these bad boys available to you. Check it:

  • C - SCL
  • D - SDA
  • 3 - 3.3V
  • G - GND

Four pins on the back of the board are highlighted just to the right of the Driver Chip

Board Outline

Each Alphanumeric Display Breakout board measures 1.6" x 1.1".

The board measures 1.6" x 1.1"

Hardware Hookup

Using the Qwiic system, assembling the hardware is a breeze. All you need to do is connect your SparkFun Qwiic Alphanumeric Display to your chosen development board with a Qwiic cable or adapter cable.

Alphanumeric plugged into RedBoard via Qwiic cables

If you decide to use the PTH pins broken out on the display you will need to solder some headers to them. If you are not familiar with through-hole soldering take a look at this tutorial:

How to Solder: Through-Hole Soldering

September 19, 2013

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

Pins are soldered to the extra PTH

With the display connected to your microcontroller it's time to get started using the SparkFun Alphanumeric Display Library!

Alphanumeric Display Arduino Library

Note: Make sure you are using the latest stable version of the Arduino IDE on your desktop. If this is your first time using Arduino IDE, library, or board add-on, please review the following tutorials.

Before we get started, we'll need to download and install SparkFun's Alphanumeric Display Arduino library. You can use the Arduino Library Manager by searching "SparkFun Alphanumeric Display" to automatically install. Or you can download the library and install it using the button below.

Before we get started developing a sketch, let's look at the available functions of the library.

  • bool setBrightness(uint8_t duty); --- This sets the brightness for all units
  • setBrightnessSingle(uint8_t displayNumber, uint8_t duty); --- This sets the brightness for a single unit
  • setBlinkRate(float rate); --- Set the refresh rate for all units.
  • setBlinkRateSingle(uint8_t displayNumber, float rate); --- Set the refresh rate for a single unit
  • displayOn(); --- Turn all display units on
  • displayOff(); --- Turn all display units off
  • displayOnSingle(uint8_t displayNumber); --- Turn a single display unit on
  • displayOffSingle(uint8_t displayNumber); --- Turn a single display unit off
  • setDisplayOnOff(uint8_t displayNumber, bool turnOnDisplay); --- Set or clear the display on/off bit
  • enableSystemClock(); --- Turn on the system oscillator for all displays on the I2C bus
  • disableSystemClock(); --- Turn off the system oscillator for all displays on the bus
  • enableSystemClockSingle(uint8_t displayNumber); --- Turn on the system oscillator for normal operation mode
  • disableSystemClockSingle(uint8_t displayNumber); --- Turn off the system oscillator for standby mode
  • illuminateSegment(uint8_t segment, uint8_t digit); --- Given a segment and a digit, set the matching bit within the RAM of the Holtek RAM set
  • illuminateChar(uint16_t disp, uint8_t digit); --- Given a binary set of segments and a digit, store this data into the RAM array
  • printChar(uint8_t displayChar, uint8_t digit); --- Print a character, for a given digit, on display
  • updateDisplay(); --- Push the contents of displayRAM out to the various displays in 16 byte chunks
  • defineChar(uint8_t displayChar, uint16_t segmentsToTurnOn); --- Update the list to define a new segments display for a particular character
  • getSegmentsToTurnOn (uint8_t charPos); --- Get the character map from the definition list or default table
  • decimalOn(); --- Turn the decimal on for all displays on bus
  • decimalOff(); --- Turn the decimal off for all displays on bus
  • decimalOnSingle(uint8_t displayNumber); --- Turn the decimal point on for a single display
  • decimalOffSingle(uint8_t displayNumber); --- Turn the decimal point off for a single display
  • setDecimalOnOff(uint8_t displayNumber, bool turnOnDecimal); --- Set or clear the decimal on/off bit
  • colonOn(); --- Turn the colon on for all displays on the bus
  • colonOff(); --- Turn the colon off for all displays on the bus
  • colonOnSingle(uint8_t displayNumber); --- Turn the colon on for a single display
  • colonOffSingle(uint8_t displayNumber); --- Turn the colon off for a single display
  • setColonOnOff(uint8_t displayNumber, bool turnOnColon); --- Set or clear the colon on/off bit
  • shiftRight(uint8_t shiftAmt = 1); --- Shift the display content to the right one digit
  • shiftLeft(uint8_t shiftAmt = 1); --- Shift the display content to the left one digit

Arduino Examples - The Basics

Now that we have our library installed, we're ready to run some examples. The library currently comes with a set of 10 examples to get you started on your way. Let's look at the first few examples!

Example_01_PrintString

Once the library is installed, go ahead and open up File->Examples->SparkFun Qwiic Alphanumeric Display Library->Example_01_PrintString.

Alternatively, you can copy and paste the code below to a shiny new Arduino file:

    language:c
/*****************************************************************************************
 * This example tests illuminating whole 4 letter strings on the 14-segment display.
 * 
 * Priyanka Makin @ SparkFun Electronics
 * Original Creation Date: February 3, 2020
 * 
 * SparkFun labored with love to create this code. Feel like supporting open source hardware?
 * Buy a board from SparkFun! https://www.sparkfun.com/products/16391
 * 
 * This code is Lemonadeware; if you see me (or any other SparkFun employee) at the 
 * local, and you've found our code helpful, please buy us a round!
 * 
 * Hardware Connections:
 * Attach Red Board to computer using micro-B USB cable.
 * Attach Qwiic Alphanumeric board to Red Board using Qwiic cable.
 * 
 * Distributed as-is; no warranty is given.
 ****************************************************************************************/
#include <Wire.h>

#include <SparkFun_Alphanumeric_Display.h> //Click here to get the library: http://librarymanager/All#SparkFun_Qwiic_Alphanumeric_Display by SparkFun
HT16K33 display;

void setup()
{
  Serial.begin(115200);
  Serial.println("SparkFun Qwiic Alphanumeric - Example 1: Print String");

  Wire.begin(); //Join I2C bus

  if (display.begin() == false)
  {
    Serial.println("Device did not acknowledge! Freezing.");
    while (1);
  }
  Serial.println("Display acknowledged.");

  display.print("Milk");
}

void loop()
{
}

Once you have the code, make sure you've got the correct port selected, and then go ahead and click on the upload button. If all goes well, you'll see your Display light up with "Milk"!

"Milk" is displayed on the alphanumeric board

Example_02_TurnOnOneSegment

This example lights up a single segment on the display. Head on back to your File Menu and open up File->Examples->SparkFun Qwiic Alphanumeric Display Library->Example_02_TurnOnOneSegment.

Alternatively, you can copy and paste the code below to a shiny new Arduino file:

language:c
/*******************************************************************************************
 * This example tests illuminating individual segments of the display. Pass in the segment
 * and digit you wish to illuminate to illuminateSegement().
 * 
 * Priyanka Makin @ SparkFun Electronics
 * Original Creation Date: January 31, 2020
 * 
 * SparkFun labored with love to create this code. Feel like supporting open source hardware?
 * Buy a board from SparkFun! https://www.sparkfun.com/products/16391
 * 
 * This code is Lemonadeware; if you see me (or any other SparkFun employee) at the 
 * local, and you've found our code helpful, please buy us a round!
 * 
 * Hardware Connections:
 * Attach Red Board to computer using micro-B USB cable.
 * Attach Qwiic Alphanumeric board to Red Board using Qwiic cable.
 * 
 * Distributed as-is; no warranty is given.
 *****************************************************************************************/
#include <Wire.h>

#include <SparkFun_Alphanumeric_Display.h>  //Click here to get the library: http://librarymanager/All#SparkFun_Qwiic_Alphanumeric_Display by SparkFun
HT16K33 display;

void setup()
{
  Serial.begin(115200);
  Serial.println("SparkFun Qwiic Alphanumeric - Example 2: Turn On One Segment");
  Wire.begin(); //Join I2C bus

  //check if display will acknowledge
  if (display.begin() == false)
  {
    Serial.println("Device did not acknowledge! Freezing.");
    while(1);
  }
  Serial.println("Display acknowledged.");

  display.illuminateSegment('A', 0);
  display.illuminateSegment('L', 1);
  display.illuminateSegment('I', 2);
  display.illuminateSegment('G', 3);
  display.updateDisplay();
}

void loop()
{
}

As before, once you have the code, make sure you've got the correct port selected, and then go ahead and click on the upload button. You won't need your serial monitor for this one though, unless you want it. If all goes well, you should see your display light up like so:

One segment of each display bit is lit up

It looks weird, but it's one segment of each letter lit up.

Example_03_PrintChar

Let's print some stuff! Grab Example 3 by going to File->Examples->SparkFun Qwiic Alphanumeric Display Library->Example_03_PrintChar.

Alternatively, you can copy and paste the code below to a shiny new Arduino file:

language:c
/*****************************************************************************************
 * This example tests illuminating whole characters on the 14-segment display.
 * 
 * Priyanka Makin @ SparkFun Electronics
 * Original Creation Date: February 3, 2020
 * 
 * SparkFun labored with love to create this code. Feel like supporting open source hardware?
 * Buy a board from SparkFun! https://www.sparkfun.com/products/16391
 * 
 * This code is Lemonadeware; if you see me (or any other SparkFun employee) at the
 * local, and you've found our code helpful, please buy us a round!
 * 
 * Hardware Connections:
 * Attach Red Board to computer using micro-B USB cable.
 * Attach Qwiic Alphanumeric board to Red Board using Qwiic cable.
 * 
 * Distributed as-is; no warranty is given.
 *****************************************************************************************/
#include <Wire.h>

#include <SparkFun_Alphanumeric_Display.h>  //Click here to get the library: http://librarymanager/All#SparkFun_Qwiic_Alphanumeric_Display by SparkFun
HT16K33 display;

void setup()
{
  Serial.begin(115200);
  Serial.println("SparkFun Qwiic Alphanumeric - Example 3: Print Character");
  Wire.begin(); //Join I2C bus

  //check if display will acknowledge
  if (display.begin() == false)
  {
    Serial.println("Device did not acknowledge! Freezing.");
    while(1);
  }
  Serial.println("Display acknowledged.");

  display.printChar('W', 0);
  display.printChar('H', 1);
  display.printChar('A', 2);
  display.printChar('T', 3);

  display.updateDisplay();
}

void loop(){
}

Check your port, and then click on the upload button. Voila! Are you starting to get the picture?

"WHAT" is displayed

This is just the beginning - there are more examples to get you going with your SparkFun Qwiic Alphanumeric Display. We won't go through them all here, but feel free to tinker with these to see what all you can come up with!

If you haven't downloaded the library yet, get it either here or by clicking on the link below and get hackin!

Arduino Examples - The Fun Stuff

Okay. You got the basics done - you can light up segments, yes? Now lets do a couple of fun things!

Example_08_MultiDisplay

This example tests printing across multiple displays. In order to make this example work, you'll need to do some soldering on the jumpers on the back of the board. For this example, we'll use 0x70 and 0x71 as the addresses, so the jumpers for the second display should look like this:

A0 Jumper is soldered together


Once your jumper is soldered, go ahead and hook your boards together with your Qwiic cables and plug em on into your RedBoard.

Image of RedBoard daisy chained to two Alphanumeric boards via Qwiic cables

Once your hardware is ready to go, head back to your File Menu and open up File->Examples->SparkFun Qwiic Alphanumeric Display Library->Example_08_MultiDisplay.

Alternatively, you can copy and paste the code below to a shiny new Arduino file:

language:c
/**************************************************************************************
 * This example tests printing across multiple alpha displays.
 * 
 * Priyanka Makin @ SparkFun Electronics
 * Original Creation Date: February 26, 2020
 * 
 * SparkFun labored with love to create this code. Feel like supporting open source hardware?
 * Buy a board from SparkFun! https://www.sparkfun.com/products/16391
 * 
 * This code is Lemonadeware; if you see me (or any other SparkFun employee) at the
 * local, and you've found our code helpful, please buy us a round!
 * 
 * Hardware Connections:
 * Attach Red Board to computer using micro-B USB cable.
 * Attach Qwiic Alphanumeric board to Red Board using Qwiic cable. 
 *  Don't close any of the address jumpers so that it defaults to address 0x70.
 * Attach a second Alphanumeric display using Qwiic cable.
 *  Close address jumper A0 so that this display's address become 0x71.
 * 
 * Distributed as-is; no warranty is given.
 *****************************************************************************************/
#include <Wire.h>

#include <SparkFun_Alphanumeric_Display.h>  //Click here to get the library: http://librarymanager/All#SparkFun_Qwiic_Alphanumeric_Display by SparkFun
HT16K33 display;

void setup() {
  Serial.begin(115200);
  Serial.println("SparkFun Qwiic Alphanumeric - Example 8: Multi Display");
  Wire.begin(); //Join I2C bus

  //check if displays will acknowledge
  //The first address in the begin() function should be the left-most display, traveling to the right from there
  //This is how the string will print across displays, reading from left to right.
  if (display.begin(0x70, 0x71) == false)
  {
    Serial.println("Device did not acknowledge! Freezing.");
    while(1);
  }
  Serial.println("Displays acknowledged.");

  display.print("Get Milk");
}

void loop() 
{
}

Once you've got your code, make sure you've got the correct port selected, and then go ahead and click on the upload button. You should see the following:

GET Milk is displayed on multiple boards

Example_09_ScrollingString

This example SCROLLS! Let's start by plugging your Alphanumeric board into your RedBoard with your handy dandy Qwiic cables.

Once your hardware is ready to go, head back to your File Menu and open up File->Examples->SparkFun Qwiic Alphanumeric Display Library->Example_09_ScrollingString.

Alternatively, you can copy and paste the code below to a shiny new Arduino file:

language:c
/**************************************************************************************
 * This example tests scrolling functionality of alphanumeric displays.
 * 
 * Priyanka Makin @ SparkFun Electronics
 * Original Creation Date: February 26, 2020
 * 
 * SparkFun labored with love to create this code. Feel like supporting open source hardware?
 * Buy a board from SparkFun! https://www.sparkfun.com/products/16391
 * 
 * This code is Lemonadeware; if you see me (or any other SparkFun employee) at the
 * local, and you've found our code helpful, please buy us a round!
 * 
 * Hardware Connections:
 * Attach Red Board to computer using micro-B USB cable.
 * Attach Qwiic Alphanumeric board to Red Board using Qwiic cable. 
 *  Don't close any of the address jumpers so that it defaults to address 0x70.
 * Attach a second Alphanumeric display using Qwiic cable.
 *  Close address jumper A0 so that this display's address become 0x71.
 * 
 * Distributed as-is; no warranty is given.
 *****************************************************************************************/
#include <Wire.h>

#include <SparkFun_Alphanumeric_Display.h>  //Click here to get the library: http://librarymanager/All#SparkFun_Qwiic_Alphanumeric_Display by SparkFun
HT16K33 display;

void setup() {
  Serial.begin(115200);
  Serial.println("SparkFun Qwiic Alphanumeric - Example 9: Scrolling String");
  Wire.begin(); //Join I2C bus

  //check if displays will acknowledge
  if (display.begin(0x70) == false)
  {
    Serial.println("Device did not acknowledge! Freezing.");
    while(1);
  }
  Serial.println("Display acknowledged.");

  display.print("MILK");
}

void loop() 
{  
  delay(300);
  display.shiftLeft();
  //Alternatively - you could also shift the string to the right
  //display.shiftRight();
}    

Once you've got your code, make sure you've got the correct port selected, and then go ahead and click on the upload button. You should see the following:

GIF of scrolling "Milk"

Troubleshooting

Resources and Going Further

Congratulations! Now that you've got your Alphanumeric Display(s) up and running, you can hack that boring ol' microwave message with something more "fool" proof! YES!

If you want or need information on your Alphanumeric Display, check out some of the resources below:

Need inspiration? Check out some of these Qwiic related tutorials:

Transparent Graphical OLED Breakout Hookup Guide

The future is here! Our Qwiic Transparent Graphical OLED Breakout allows you to display custom images on a transparent screen using either I2C or SPI connections.

SparkFun SAMD21 Pro RF Hookup Guide

Using the super blazing, nay blinding, fast SAMD21 whipping clock cycles at 48MHz and the RFM96 module to connect to the Things Network (and other Radio woodles).

TFMini - Micro LiDAR Module (Qwiic) Hookup Guide

The TFMini is a ToF (Time of Flight) LiDAR sensor capable of measuring the distance to an object as close as 30 cm and as far as 12 meters! The TFMini allows you to easily integrate LiDAR into applications traditionally reserved for smaller sensors such as the SHARP GP-series infrared rangefinders. With the added Qwiic feature, you can quickly connect to the sensor via I2C!

SparkFun GPS Breakout (ZOE-M8Q and SAM-M8Q) Hookup Guide

The SparkFun ZOE-M8Q and SAM-M8Q are two similarly powerful GPS units but with different project applications. We'll compare both chips before getting each up and running.


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

smôl Hookup Guide

$
0
0

smôl Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Our RedBoards are great. But don't they sometimes seem a little BIG?!

Enter smôl, a new range of boards which are both small in size and small on current draw. It's a smôl world!

alt text

Above is a GNSS receiver, a satellite transceiver, and an ESP32 with WiFi and 16MB storage, all running for 100 days off a 400mAh battery.😲

When we designed our ARGOS Satellite Transceiver Shield - ARTIC R2, we knew that people would want to use it for applications like wildlife tracking, ocean buoys, environmental monitoring or transferring emergency medical information. But what if you want to develop something much smaller? Say, a small dart for whale tracking, or a small backpack for avian tracking. Or you just need your battery to last for months. smôl is designed to meet those needs.

The stack in the above photo is a complete ARTIC R2 satellite tracker capable of transmitting 2.5m accuracy position fixes five times per day to the ARGOS satellite network (ARGOS provides global coverage, including the oceans and the polar regions) using a 400mAh battery for over 100 days!

The smôl family of boards includes:

Processor Boards

smôl ESP32

smôl ESP32

SPX-18619
$17.95

GNSS (GPS) Boards

smôl ZOE-M8Q

smôl ZOE-M8Q

SPX-18623
$39.95

Satellite Communication Boards

smôl ARTIC R2

smôl ARTIC R2

SPX-18618
$199.95

Power Boards

smôl Power Board LiPo

smôl Power Board LiPo

SPX-18622
$17.95
smôl Power Board AAA

smôl Power Board AAA

SPX-18621
$17.95

Essentials

smôl 36mm 16-way Flexible Printed Circuit

smôl 36mm 16-way Flexible Printed Circuit

CAB-18731
$0.95

Accessories

smôl Header

smôl Header

SPX-18620
$2.95

Skill Level - Competent: We think smôl is brilliant and we will be releasing more smôl boards over the coming months. We have plans for: environmental monitoring, IMU, RFID, radio and GNSS peripheral boards; plus additional processor boards. However, we recognize that the smôl format is - intentionally - very small and that the FPC connections can be a little bit fiddly until you get used to working with them. So, we're recommending smôl for those with Level 3 (Competent) DIY and Electrical Prototyping skills:
  • Whether it's for assembling a kit, hacking an enclosure, or creating your own parts; the DIY skill is all about knowing how to use tools and the techniques associated with them.
  • If it requires power, you need to know how much, what all the pins do, and how to hook it up. You may need to reference datasheets, schematics, and know the ins and outs of electronics.

What is smôl?

smôl is a new board format and, as the name suggests, they're really small!

Each smôl board measures just 1.60" by 0.42" (40.6mm by 10.7mm). We made the boards just wide enough so we could squeeze USB-C and 16-way Flexible Printed Circuit (FPC) connectors on there. Some of the boards have components on both top and bottom layers which again helps keep the boards small.

smol board dimensions

Having a hard time seeing everything? Click the image for a closer look.

smôl boards are designed to stack one on top of the other, using 16-way 0.5mm-pitch FPCs to provide the interconnect from one board to the next. Each board has an IN FPC connector on the bottom layer and an OUT FPC connector on the top layer. The boards stack in a zig-zag daisy chain; signals and power are passed from one board to the next up and down the chain through the FPCs.

We've designed a smôl Header too, which you can use to mount your smôl stack on a standard breadboard or another PCB. The Header only has an OUT connector so it needs to go at the bottom of your stack.

The order in which you connect the boards is important and we'll cover that in the next sections.

FPC Connections

We love Flexible Printed Circuit (FPC) connections and we're using them in more and more of our products.

Each smôl board (except the Header) comes with two 16-way FPC connectors, labelled IN and OUT. The IN connector is on the bottom of each board, the OUT is on top. Matching FPCs connect the OUT connector on one board to the IN connector on the next.

Our 36mm FPC is the perfect length if you want the smôl boards to stack neatly, one on top of the other. The connectors have "dual contacts" (contacts top and bottom) and so it does not matter which way round you insert the FPC, it will always make contact.

We wanted the smôl boards to be as small as possible and so we've put a lot of thought into the signals on those 16 FPC connections to make them as efficient as possible. The standard pin-out of the connector is as follows:

Connector Pin No.Signal NameFunction
1PROC_PWR_ENProcessor Power Enable
23V33.3V Power Rail
3GNDPower Ground / 0V
4SCLKSPI Clock
5COPISPI Controller Out Peripheral In
6CIPOSPI Controller In Peripheral Out
7CS0SPI Chip Select 0
8CS1SPI Chip Select 1
8CS2SPI Chip Select 2
10GPIO0General Purpose Input / Output 0
11GPIO1General Purpose Input / Output 1
12SDAI2C Data
13SCLI2C Clock
14GNDPower Ground / 0V
153V33.3V Power Rail
16V_USBUSB Power Rail (5V)

On our Eagle schematics, the connections usually look like this:

alt text

We say "usually" because the exact connections depend on the board type. More about that in a moment.

First, let's talk about what each pin does:

Pin 1: PROC_PWR_EN

Processor Power Enable is a signal which is passed up and down the smôl stack. It is connected to the enable pin of the 3.3V voltage regulator on the processor board. If PROC_PWR_EN is pulled high, or is left floating, the processor board voltage regulator will be enabled and will generate 3.3V from USB-C.

When you connect a Power Board to your smôl stack, PROC_PWR_EN allows the power board to disable the regulator on the processor board. The power board is then responsible for generating the 3.3V power rail for the entire smôl stack. We do this for two reasons: to prevent the power board and processor board regulators from fighting each other; and to allow the power board to power down the entire smôl stack even if USB is connected.

One of the clever features of smôl is that the power boards can be instructed to power down the whole stack for a pre-defined duration. Power down durations of a few 10's of milliseconds to several days are possible. During power down the only device left running is the ATtiny processor on the power board, which typically consumes less than 10 microamps. PROC_PWR_EN allows smôl to avoid the quiescent current normally drawn by the processor regulator.

Pins 2 and 15: 3.3V Power

Pins 2 and 15 carry 3.3V power up and down the smôl stack. 3.3V can be generated by a processor board, powered by USB-C. Or, 3.3V power can be generated by one of our power boards.

As described above, the power board can disable the regulator on the processor board via the PROC_PWR_EN pin, avoiding the associated quiescent current draw.

Pins 3 and 14: GND

Pins 3 and 14 are the smôl Power Ground or 0V pins.

You will note that the highest speed smôl signals (SPI SCLK and I2C SCL) are run adjacent to the GND connections to minimize EMI.

Pins 4-6: SPI SCLK, COPI and CIPO

Pins 4-6 carry the clock and data signals for the Serial Peripheral Interface (SPI).

The Processor Board is the SPI Controller and can communicate with smôl Peripheral boards at high data rates.

SPI devices share common clock and data signals but require an individual Chip Select signal. The smôl Chip Select signals are described in the next paragraph.

Pins 7-9: SPI CS0, CS1 and CS2

Pins 7-9 are the smôl SPI Chip Select signals and allow up to three SPI Peripheral Boards to be connected into your smôl stack.

We use a technique called waterfalling when linking the chip select lines from one smôl board to the next. There is a full description of this in the SPI Chip Select Waterfalling section of this guide.

If your favorite 3.3V SPI breakout board is not yet available in smôl format, you can connect it via the breakout pins on the smôl Header.

Pins 10 and 11: GPIO0 and GPIO1

Pins 10 and 11 carry two General Purpose Input / Output signals: GPIO0 and GPIO1. These are typically used as power control signals to power down individual Peripheral Boards, again to allow the current draw to be minimized as much as possible.

Just like the SPI Chip Select signals, GPIO0 and GPIO1 are also waterfalled. If a Peripheral Board uses GPIO0, then GPIO1 is waterfalled onto GPIO0 of the board's OUT connector. Please see the full description of this in the GPIO Waterfalling section of this guide.

Pins 12 and 13: I2C SDA and SCL

Pins 12 and 13 carry the data and clock signals for Inter-Integrated Circuit (I2C) communication.

Multiple I2C boards can be connected to smôl provided each has a unique address.

If your favorite Qwiic board is not yet available in smôl format, you can connect it via the Qwiic connector on the smôl Header.

Pin 16: V_USB

Pin 16 carries 5V power from the USB-C connector on the Processor Board up and down the smôl stack.

V_USB is used by the smôl Power Board LiPo to recharge the LiPo battery when USB-C is connected. We limited the charge current to 100mA to avoid drawing too much current through the single V_USB FPC trace.

Pin Numbering

Just to clarify which is pin 1:

When viewed from the front or top of the board, pin 1 of the OUT connector is on the right.

When the board is turned over, pin 1 of the IN connector is on the left.

alt text

SPI Chip Select Waterfalling

smôl allows you to connect up to three Serial Peripheral Interface (SPI) peripheral boards into your stack.

SPI devices share common clock and data signals but require an individual Chip Select signal. Here's how we connect the Chip Select signal on smôl using a technique called waterfalling.

The three chip select signals are called CS0, CS1 and CS2. On the ESP32 Processor Board, these are connected to GPIO5, GPIO14 and GPIO13 respectively. In Arduino terms, they are D5, D14 and D15, or Digital Pins 5, 14 and 13.

Waterfalling is a technique where:

  • if a Peripheral Board needs an SPI Chip Select, it will always use CS0 from the IN connector
  • the unused Chip Select lines CS1 and CS2 are then passed to the OUT connector as CS0 and CS1

Let's see that in action. Here are the FPC connections on the smôl ARTIC R2:

alt text

The smôl ARTIC R2 uses SPI communication and so uses CS0 (Pin 7) from the IN connector.

CS1 (IN Pin 8) and CS2 (IN Pin 9) are not used and so are connected directly to the OUT connector but as Pins 7 and 8 (not Pins 8 and 9).

If the ARTIC R2 is placed immediately above the ESP32 Processor Board in the smôl stack, its Chip Select is connected to ESP32 Digital Pin 5.

If another SPI Peripheral Board were placed above the ARTIC R2 board, it too would use CS0 but its CS0 would be connected to ESP32 Digital Pin 14 (not 5) thanks to the waterfalling.

The important 'rule' is: Peripheral Boards must be placed above the Processor Board in the smôl stack

If you accidentally place a Peripheral Board below the processor board, no damage will be done. But the Peripheral Board will not function because its Chip Select signal will be left floating.

Power Boards are a special case. They only use I2C for communication and so can be placed anywhere in the stack. The natural place for them is below the Processor Board, but you can place them above if you want to.

The smôl Header only has an OUT connector so it needs to go at the very bottom of your stack.

GPIO Waterfalling

smôl provides two General Purpose Input / Output signals. These are generally used for power control, allowing individual smôl boards to be completely powered down to minimise the current draw

Just like the SPI Chip Select signals, the two GPIO signals also use waterfalling.

The two GPIO signals are called GPIO0 and GPIO1. On the ESP32 Processor Board, these are connected to GPIO27 and GPIO26 respectively. In Arduino terms, they are D27 and D26, or Digital Pins 27 and 26.

Here are the FPC connections on the smôl ARTIC R2 again:

alt text

The smôl ARTIC R2 uses GPIO0 for power control and so uses GPIO0 (Pin 10) from the IN connector.

GPIO1 (IN Pin 11) is not used and so is connected directly to the OUT connector but as Pin 10 (not Pin 11).

If the ARTIC R2 is placed immediately above the ESP32 Processor Board in the smôl stack, its Power Enable is connected to ESP32 Digital Pin 27.

If another Peripheral Board were placed above the ARTIC R2 board, it too could use GPIO0 but it would be connected to ESP32 Digital Pin 26 (not 27) thanks to the waterfalling.

The important 'rule' is: Peripheral Boards must be placed above the Processor Board in the smôl stack

If you accidentally place a Peripheral Board below the processor board, no damage will be done. But the Peripheral Board will not function as expected because its GPIO signal will be left floating.

Power Boards are a special case. They only use I2C for communication and so can be placed anywhere in the stack. The natural place for them is below the Processor Board, but you can place them above if you want to.

The smôl Header only has an OUT connector so it needs to go at the very bottom of your stack.

Assembly

smôl boards are designed to stack one on top of the other, using 16-way 0.5mm-pitch FPCs to provide the interconnect from one board to the next. Each board has an IN FPC connector on the bottom layer and an OUT FPC connector on the top layer. The boards stack in a zig-zag daisy chain; signals and power are passed from one board to the next up and down the chain through the FPCs.

We use "back-flip""dual contact" connectors to make inserting the FPCs as frustration-free as possible. The "back-flip" makes the connector very compact and it is easy to flip the lever with your fingernail. We find them much easier to use than traditional slide connectors. "dual contact" connectors have contacts both top and bottom so it does not matter which way round you insert the FPC. Either way up is OK.

There are some simple steps you need to follow when connecting your boards:

Lift the Back-Flip Lever

Lift the back-flip lever with your fingernail or a small screwdriver:

Assembly: lift the connector back-flip lever
Having a hard time seeing everything? Click the image for a closer look.

Insert the FPC

Insert the FPC. Give it a little jiggle and apply a little pressure until it is fully inserted. You can insert the FPC either way up:

Assembly: insert the FPC
Having a hard time seeing everything? Click the image for a closer look.

Close the Back-Flip Lever

Use your fingernail or a small screwdriver to close the back-flip lever, securing the FPC:

Assembly: close the connector back-flip lever
Having a hard time seeing everything? Click the image for a closer look.

Expert Tip:

Let's say you are connecting a ZOE-M8Q GNSS Peripheral Board to an ESP32 Processor Board. As described in the previous section, you are going to position the ZOE-M8Q above the ESP32. Our expert tip is to:

  • Turn the ZOE-M8Q board over and lift the back-flip lever on the IN connector
  • Orientate the FPC so the writing and gold fingers will be against the underside of the ZOE-M8Q board. This reveals the brown stiffener on the back of the FPC.
  • Start to insert the FPC into the IN connector and then put your fingernail against the edge of the stiffener. There is a small step on the edge of the stiffener.
  • Use your fingernail to gently drag the FPC stiffener into position, making sure the FPC ends up fully inserted into the connector.
  • Close the back-flip lever on the IN connector.
  • Lift the back-flip lever on the ESP32 OUT connector.
  • Start to insert the other end of the FPC into the OUT connector.
  • Hold the ZOE-M8Q board and give it a little jiggle to help insert the FPC. It is easier to hold the ZOE-M8Q board than it is to hold the FPC itself.
  • Make sure the FPC is fully inserted, then close the OUT connector back-flip lever.

Simples!

Completed Stack

Here's how your completed smôl stack should look once fully assembled:

alt text
Having a hard time seeing everything? Click the image for a closer look.

alt text
Having a hard time seeing everything? Click the image for a closer look.

The stack in the above photos is a complete ARTIC R2 satellite tracker capable of transmitting 2.5m accuracy position fixes five times per day to the ARGOS satellite network (ARGOS provides global coverage, including the oceans and the polar regions) using a 400mAh battery for over 100 days!

Lithium Ion Battery - 400mAh

Lithium Ion Battery - 400mAh

PRT-13851
$4.95
9
Molex Flexible GNSS Antenna - U.FL (Adhesive)

Molex Flexible GNSS Antenna - U.FL (Adhesive)

GPS-15246
$3.95
1
ARGOS Omnidirectional Antenna - 401MHz

ARGOS Omnidirectional Antenna - 401MHz

WRL-17523
$6.95
smôl ARTIC R2

smôl ARTIC R2

SPX-18618
$199.95
smôl ESP32

smôl ESP32

SPX-18619
$17.95
smôl Power Board LiPo

smôl Power Board LiPo

SPX-18622
$17.95
smôl ZOE-M8Q

smôl ZOE-M8Q

SPX-18623
$39.95
smôl 36mm 16-way Flexible Printed Circuit

smôl 36mm 16-way Flexible Printed Circuit

CAB-18731
$0.95

Current Draw

If you are using smôl to develop your own wildlife tracker, you will of course be very interested in how much current the board draws.

The fantastic Otii Arc Power Analyzer has allowed us to capture the exact peak transmit current draw of the smôl ARTIC R2 satellite transceiver and to study the average current drawn when the chip is idle. We've used this data to help optimize the code in this example to extend the battery life as much as possible when using the smôl ARTIC R2 with the smôl ESP32 Processor Board, smôl ZOE-M8Q GNSS Board and the smôl Power Board LiPo.

The picture below shows the current draw captured by Otii Arc for a complete transmit cycle using this example. The gain here is set to maximum.

Pictured is the current draw during a complete transmit cycle
Having a hard time seeing? Click the image for a closer look.

At the start of the transmit cycle, the ESP32 Processor Board is woken up by the Power Board. It turns on the ZOE-M8Q GNSS board and waits for a fix. The current draw here is approximately 100mA for ~10 seconds.

Once the ESP32 has a location fix, it can calculate the time of the next ARGOS satellite pass. The power board woke the ESP32 up 1 minute before the start of the next pass, so the ESP32 goes in and out of light sleep for the next ~30 seconds.

The ARTIC R2 is powered on at the 40 second mark and the first of five transmits takes place just after the one minute mark.

The code example transmits five times on each satellite pass. The gap between the transmits is 90 seconds with a mandatory &pm;10% jitter. In between, you can see the ESP32 going in and out of light sleep with the ARTIC R2 being powered up 20-30 seconds before the next transmit is due.

The phenomenal data captured by Otii Arc allows us to zoom right in on the transmit itself and capture the true maximum current draw:

Pictured is the peak current draw during the transmit
Having a hard time seeing? Click the image for a closer look.

It's then child's play to extract the data we need!

  • LiPo Battery Voltage: 3.7V
  • Peak Current Draw ESP32 + ARTIC R2 (maximum gain): 238mA
  • Peak Current Draw ESP32 + ARTIC R2 (minimum gain): 114mA
  • Average Current Draw during a complete 5*TX transmit cycle (maximum gain): 29.9mA
  • Average Current Draw during a complete 5*TX transmit cycle (minimum gain): 24.9mA
  • Average continuous ESP32 + ZOE-M8Q GNSS Current Draw: 97mA
  • Current Draw during deep sleep: 6.4µA
  • Power Consumption during a complete 5*TX transmit cycle (maximum gain): 13.3mWh
  • Power Consumption during a complete 5*TX transmit cycle (minimum gain): 11.1mWh

We can then use this data to predict the battery life based on the transmit power and the number of transmissions per day. The satellite pass-prediction code in our Arduino Library can calculate the timing of the satellite passes with the highest elevation each day to maximize the chance of the transmission being received. Transmitting five times per day at maximum power, we could expect our very modest 400mAh battery to last over 100 days!

Resources and Going Further

Check out the individual board hookup guides for more information:


Skill Level - Competent: We think smôl is brilliant and we will be releasing more smôl boards over the coming months. We have plans for: environmental monitoring, IMU, RFID, radio and GNSS peripheral boards; plus additional processor boards. However, we recognize that the smôl format is - intentionally - very small and that the FPC connections can be a little bit fiddly until you get used to working with them. So, we're recommending smôl for those with Level 3 (Competent) DIY and Electrical Prototyping skills:
  • Whether it's for assembling a kit, hacking an enclosure, or creating your own parts; the DIY skill is all about knowing how to use tools and the techniques associated with them.
  • If it requires power, you need to know how much, what all the pins do, and how to hook it up. You may need to reference datasheets, schematics, and know the ins and outs of electronics.

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

smôl ESP32 Hookup Guide

$
0
0

smôl ESP32 Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

smôl is a new board format and, as the name suggests, they're really small!

smôl ESP32

smôl ESP32

SPX-18619
$17.95

The smôl ESP32 is a Processor Board for smôl, based on the excellent Espressif ESP32 processor.

Each smôl board measures just 1.60" by 0.42" (40.6mm by 10.7mm). We made the boards just wide enough so we could squeeze USB-C and 16-way Flexible Printed Circuit (FPC) connectors on there. Some of the boards have components on both top and bottom layers which again helps keep the boards small.

smôl boards are designed to stack one on top of the other, using 16-way 0.5mm-pitch FPCs to provide the interconnect from one board to the next. Each board has an IN FPC connector on the bottom layer and an OUT FPC connector on the top layer. The boards stack in a zig-zag daisy chain; signals and power are passed from one board to the next up and down the chain through the FPCs.

Required Materials

As a minimum, you're going to need a USB-C cable to connect your smôl ESP32 to your computer:

USB 3.1 Cable A to C - 3 Foot

USB 3.1 Cable A to C - 3 Foot

CAB-14743
$4.95
3
Reversible USB A to C Cable - 2m

Reversible USB A to C Cable - 2m

CAB-15424
$7.95

The ESP32 Processor Board is part of the smôl ecosystem. Why not pair it with one of the smôl Peripheral Boards?

smôl ARTIC R2

smôl ARTIC R2

SPX-18618
$199.95
smôl ZOE-M8Q

smôl ZOE-M8Q

SPX-18623
$39.95

To be able to reduce the sleep current below 10µA, you're going to want to pair the ESP32 with one of our intelligent smôl Power Boards:

smôl Power Board AAA

smôl Power Board AAA

SPX-18621
$17.95
smôl Power Board LiPo

smôl Power Board LiPo

SPX-18622
$17.95

Don't forget that you will need Flexible Printed Circuits to connect your smôl boards together. You're going to need one FPC per board. Our 36mm FPC is the perfect length if you want the smôl boards to stack neatly, one on top of the other.

smôl 36mm 16-way Flexible Printed Circuit

smôl 36mm 16-way Flexible Printed Circuit

CAB-18731
$0.95















Need to do some prototyping with smôl? Or want to connect standard SPI or Qwiic (I2C) boards to your stack? The smôl Header is perfect for that:

smôl Header

smôl Header

SPX-18620
$2.95













Suggested Reading

This is the hookup guide for the smôl ESP32 Processor Board. Click the button below if you want to find out more about smôl itself.

We recommend taking a look through the following tutorials if you are not familiar with the concepts covered in them:

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.

Hardware Overview

In this section we'll cover what's included on the smôl ESP32 Processor Board.

Espressif ESP32

Ahhh, the Espressif ESP32. It's one of the most unique microcontrollers on the market. In it's native form, it has a laundry list of features. On the smôl Processor Board, we include the following:

  • Dual-core Tensilica LX6 microprocessor
  • Up to 240MHz clock frequency
  • 520kB internal SRAM
  • Integrated 802.11 B/G/N WiFi transceiver
  • Hardware accelerated encryption (AES, SHA2, ECC, RSA-4096)
  • 16MByte Flash Storage
  • 500µA sleep current under hibernation
    • The sleep current can be reduced to less than 10µA by pairing the smôl ESP32 with one of our intelligent Power Boards

Espressif chip highlighted

WS2812C RGB Status LED

We've included a miniature WS2812C RGB LED for visual status feedback:

Status LED highlighted

Wireless Antenna

Need wireless? The Espressif chip provides a WiFi transceiver which sends and receives data through a 2.4GHz Antenna.

Wireless Antenna highlighted

USB-C Connector and CP210x USB Interface

The USB-C connector allows you to connect the smôl ESP32 to your computer for programming and diagnostics.

Important: If you've never connected a CP210x device to your computer before, you will need to install drivers for the USB-to-serial converter. Check out our section on How to Install CP2104 Drivers for help with the installation. If you try to use a default generic USB driver, automatic uploading from the Arduino IDE is likely to fail.

USB highlighted

FPC Connections

Like all of our smôl boards, the ESP32 Processor Board is equipped with two 16-way 0.5mm-pitch Flexible Printed Circuit connectors. FPCs are used to link the smôl boards together in a daisy-chain.

The pin-out for the smôl ESP32 is as follows:

FPC connections pin 1
Connector Pin No.Signal NameFunctionArduino Digital Pin No.
1PROC_PWR_ENProcessor Power EnableN/A
23V33.3V Power RailN/A
3GNDPower Ground / 0VN/A
4SCLKSPI Clock18
5COPISPI Controller Out Peripheral In23
6CIPOSPI Controller In Peripheral Out19
7CS0SPI Chip Select 05
8CS1SPI Chip Select 114
8CS2SPI Chip Select 213
10GPIO0General Purpose Input / Output 027
11GPIO1General Purpose Input / Output 126
12SDAI2C Data21
13SCLI2C Clock22
14GNDPower Ground / 0VN/A
153V33.3V Power RailN/A
16V_USBUSB Power Rail (5V)N/A

The IN and OUT pin connections are identical on the smôl ESP32. (That's not always true on smôl Peripheral Boards. Check the Peripheral Board Hookup Guide for full details.)

We use a technique called waterfalling on the SPI Chip Select and GPIO signals. If you haven't used waterfalling before, please check out the smôl Hookup Guide.

The smôl ESP32 has an on-board 3.3V regulator for stand-alone use, powered by 5V from the USB-C connector. The PROC_PWR_EN signal allows a smôl Power Board to disable the Processor Board regulator. Please see the smôl Hookup Guide for more details.

Software Setup and Programming

Note: All of the examples in this tutorial assume 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.
Important: If you've never connected a CP210x device to your computer before, you will need to install drivers for the USB-to-serial converter. Check out our section on How to Install CP2104 Drivers for help with the installation. If you try to use a default generic USB driver, automatic uploading from the Arduino IDE is likely to fail.

To get started with the smôl ESP32 Processor Board, you'll need to install the ESP32 Board Definition. Open the Arduino IDE (must be v1.8.13 or later) and navigate to File->Preferences, like so:

Arduino Preferences, under File

Having a hard time seeing? Click the image for a closer look.

In the "Additional Board Manager URL" box, make sure you have the following two json files included. If you do not have them, add them to your preferences.

language:c
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
https://raw.githubusercontent.com/sparkfun/Arduino_Boards/main/IDE_Board_Manager/package_sparkfun_index.json

If you have more than one json file, you can click on the button outlined in red and add the json links at the end. It'll look something like the following:

Additional Boards Manager URL location in the Preferences Dialog

Having a hard time seeing? Click the image for a closer look.


Once you've got your preferences updated, go to Tools ->Board and select the Boards Manager like so:

Arduino Boards Manager Dialog, under Tools

Having a hard time seeing? Click the image for a closer look.


Search for "ESP32", and you should find both the esp32 and SparkFun ESP32 Boards board packages. Make sure the latest version selected and click Install for the esp32 boards. Repeat for the SparkFun ESP32 Boards.

Board manager showing SparkFun ESP32 Boards install

Having a hard time seeing? Click the image for a closer look.


Once the board definitions have been installed, you should see the SparkFun ESP32 Thing Board under your Tools -> Board -> SparkFun ESP32 Arduino menu. The smôl ESP32 uses the same board definition as the SparkFun ESP32 Thing; select that (and ignore the Thing Plus, MicroMod and LoRa Gateway options).

DropDown showing tools->Board->SparkFun ESP32 Arduino->SparkFun ESP32 MicroMod


Note: Our board definition package should install all of the tools needed to compile code for the ESP32. If you run into trouble having code compile or downloading due to tools not being found, you may need to install Espressif's Arduino ESP32 package manually.

Voila! You're ready to rock with your smôl ESP32 Processor Board!

Arduino Example: RGB_LED

With the SparkFun ESP32 Arduino core installed, you're ready to begin programming. Make sure you have the ESP32 Thing definition selected under your Tools>Board menu, then it is time to connect your smôl ESP32 to your computer using a USB-C cable.

Next, select your serial port under the Tools>Port menu.

Port Selection for the ESP32 MicroMod Processor Board
Having a hard time seeing? Click the image for a closer look.


You can also select the Upload Speed: "921600" baud -- the fastest selectable rate -- will get the code loaded onto your ESP32 the fastest, but may fail to upload once-in-a-while. (It's still way worth it for the speed increase!)

Loading the RGB_LED Demo

To make sure your toolchain and board are properly set up, we'll upload a simple sketch -- RGB_LED! The WS2812C LED on the ESP32 Processor Board is perfect for this test. Copy and paste the example sketch below into a fresh Arduino sketch:

language:c
// smôl ESP32 LED Demo
//
// Select SparkFun ESP32 Thing as the board
//
// Make sure you have the correct drivers installed for the Silicon Labs
// CP210x USB to UART Bridge otherwise the automatic upload may fail
// https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers

#include <FastLED.h> // http://librarymanager/All#FastLED

#define LED_PIN     25 //GPIO25 on smôl ESP32 is connected to WS2812 LED
#define COLOR_ORDER GRB
#define CHIPSET     WS2812
#define NUM_LEDS    1

#define BRIGHTNESS  50

CRGB leds[NUM_LEDS];

uint8_t gHue = 0; // rotating "base color" used by many of the patterns

void setup() {
    delay(30); // sanity delay
    FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
    FastLED.setBrightness( BRIGHTNESS );
}

void loop()
{
  fill_rainbow( leds, NUM_LEDS, gHue, 7);
  FastLED.show();

  EVERY_N_MILLISECONDS( 10 ) { gHue++; } // cycle the "base color" through the rainbow
}

With everything set up correctly, click the arrow icon to upload the code! Once the code finishes transferring, the RGB LED should start cycling through all the colors of the rainbow. Hypnotic isn't it?!

Troubleshooting

If you haven't used the fantastic FastLED library before, you will need to install it through the IDE Library Manager. The easiest way to do that is to click the link next to the #include <FastLED.h>. When the Library Manager has finished searching, select the latest version of FastLED and click Install.

If the code fails to upload when you click the upload (arrow) icon, check you have the correct port selected and have the official CP210x driver installed. If you're trying to use a generic USB driver, it won't be able to initialize the Bootloader via DTR and RTS pins.

Further Examples

You can find more tried-and-tested examples in the GitHub repo:

  • SPIFFS_Test will format part of the Processor Board's flash memory as an SPI Flash File System and check it is working correctly by creating, editing, renaming and deleting a text file
  • SimpleWiFiServer is a fun little demo:
    • Edit the code and replace yourssid and yourpasswd with the name and password of your WiFi network
    • Upload the code and open the Arduino IDE Tools>Serial Monitor at 115200 baud to see the diagnostic messages
    • Make a note of the smôl ESP32's IP Address
    • Open a web browser on your computer and open the web page at http://nnn.nnn.nnn.nnn where nnn.nnn.nnn.nnn is the smôl ESP32's IP address
    • Click the web page buttons to change the color of the RGB LED

Troubleshooting

Not working as expected and need help?SparkX products are rapidly produced to bring you the most cutting edge technology as it becomes available. These products are tested but come with no guarantees. Live technical support is not available for SparkX products. Head on over to our forum for support or to ask a question and we will get back to you as soon as we can.

Resources and Going Further

For more information about the smôl ESP32 Processor Board, check out the following links:

smôl Documentation:

ESP32 Documentation:


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

smôl ZOE-M8Q Hookup Guide

$
0
0

smôl ZOE-M8Q Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

smôl is a new board format and, as the name suggests, they're really small!

smôl ZOE-M8Q

smôl ZOE-M8Q

SPX-18623
$39.95

The smôl ZOE-M8Q is a GNSS (Global Navigation Satellite System) receiver board based on the excellent u-blox ZOE-M8Q.

Each smôl board measures just 1.60" by 0.42" (40.6mm by 10.7mm). We made the boards just wide enough so we could squeeze USB-C and 16-way Flexible Printed Circuit (FPC) connectors on there. Some of the boards have components on both top and bottom layers which again helps keep the boards small.

smôl boards are designed to stack one on top of the other, using 16-way 0.5mm-pitch FPCs to provide the interconnect from one board to the next. Each board has an IN FPC connector on the bottom layer and an OUT FPC connector on the top layer. The boards stack in a zig-zag daisy chain; signals and power are passed from one board to the next up and down the chain through the FPCs.

Required Materials

As a minimum, you're going to need a u.FL GNSS antenna:

Molex Flexible GNSS Antenna - U.FL (Adhesive)

Molex Flexible GNSS Antenna - U.FL (Adhesive)

GPS-15246
$3.95
1















The ZOE-M8Q Peripheral Board is part of the smôl ecosystem. Why not pair it with one of the smôl Processor Boards?

smôl ESP32

smôl ESP32

SPX-18619
$17.95













To be able to reduce the sleep current below 10µA, you're going to want to pair the ESP32 with one of our intelligent smôl Power Boards:

smôl Power Board AAA

smôl Power Board AAA

SPX-18621
$17.95
smôl Power Board LiPo

smôl Power Board LiPo

SPX-18622
$17.95

Don't forget that you will need Flexible Printed Circuits to connect your smôl boards together. You're going to need one FPC per board. Our 36mm FPC is the perfect length if you want the smôl boards to stack neatly, one on top of the other.

smôl 36mm 16-way Flexible Printed Circuit

smôl 36mm 16-way Flexible Printed Circuit

CAB-18731
$0.95















Need to do some prototyping with smôl? Or want to connect the smôl ZOE-M8Q to another Qwiic board? The smôl Header is perfect for that:

smôl Header

smôl Header

SPX-18620
$2.95













Suggested Reading

This is the hookup guide for the smôl ZOE-M8Q Peripheral Board. Click the button below if you want to find out more about smôl itself.

We recommend taking a look through the following tutorials if you are not familiar with the concepts covered in them:

I2C

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

Three Quick Tips About Using U.FL

Quick tips regarding how to connect, protect, and disconnect U.FL connectors.

Hardware Overview

In this section we'll cover what's included on the smôl ZOE-M8Q Peripheral Board.

GNSS Capabilities

The u-blox ZOE-M8Q is able to connect to up to three different GNSS constellations at a time making it very accurate for its size.

smôl ZOE-M8Q and support components

Below are the listed capabilities of the GNSS unit:

GNSSGPS and GLONASSGPSGLONASSBeiDouGalileo
Horizontal Position Accuracy2.5m2.5m4m3m3m
Max Navigation Update RateROM10Hz18Hz18Hz18Hz18Hz
Flash5Hz10Hz10Hz10Hz10Hz
Time-To-First-FixCold Start26s29s30s34s45s
Hot Start1s1s1s1s1s
SensitivityTracking and Navigation-167dBm-166dBm-166dBm-160dBm-159dBm
Reacquisition-160dBm-160dBm-156dBm-157dBm-153dBm
Cold Start-148dBm-148dBm-145dBm-143dBm-138dBm
Hot Start-157dBm-157dBm-156dBm-155dBm-151dBm
Velocity Accuracy0.05m/s
Heading Accuracy0.3 degrees

Power

Power for this board - and all smôl boards - should be 3.3V.

Battery

The small metal disk in the center of the board 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 be about ~29 seconds, but after the product has a lock, that battery will allow for a one 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 year's worth of power to the backup system and charges slowly when smôl 3.3V is powered.

smôl ZOE-M8Q backup battery

Jumpers

There is only one jumper on the top of this product, labelled V_ANT. By default, 3.3V power is provided on the u.FL connector for an active antenna. Cutting the V_ANT jumper disconnects the 3.3V power.

This is a picture of the board with the V_ANT jumper highlighted.

u.FL Connector

The u.FL connector on the board is where you will plug in your antenna. This is a compact connector for RF antennas, that has the same function as the traditional SMA connector. You may be more familiar and even own some antennas that use SMA connectors; never fear, we carry a U.FL to SMA cable adapter. Check out our tutorial on using U.FL connectors, if this is your first.

Pictured is the small u.FL connector

Power Switching

The smôl ZOE-M8Q includes an on-board power switch (MOSFET):

smôl ZOE-M8Q power switch

Power for the ZOE-M8Q is controlled via the smôl GPIO0 signal. Leave GPIO0 floating or pull high to disable power to the ZOE-M8Q (default state). Pull the smôl GPIO0 signal low to enable power for the ZOE-M8Q.

FPC Connections

Like all of our smôl boards, the ZOE-M8Q Peripheral Board is equipped with two 16-way 0.5mm-pitch Flexible Printed Circuit connectors. FPCs are used to link the smôl boards together in a daisy-chain.

The pin-out for the smôl ZOE-M8Q IN connector is as follows:

IN Connector Pin No.Signal NameFunctionNotes
1PROC_PWR_ENProcessor Power EnableNot used
23V33.3V Power Rail
3GNDPower Ground / 0V
4SCLKSPI ClockNot used
5COPISPI Controller Out Peripheral InNot used
6CIPOSPI Controller In Peripheral OutNot used
7CS0SPI Chip Select 0Not used
8CS1SPI Chip Select 1Not used
8CS2SPI Chip Select 2Not used
10GPIO0ZOE-M8Q Power ControlPull low to enable power for the ZOE-M8Q
11GPIO1General Purpose Input / Output 1Connected to Pin 10 (GPIO0) on the OUT connector
12SDAI2C DataUsed for ZOE-M8Q communication
13SCLI2C ClockUsed for ZOE-M8Q communication
14GNDPower Ground / 0V
153V33.3V Power Rail
16V_USBUSB Power Rail (5V)Not used

The pin-out for the smôl ZOE-M8Q OUT connector is as follows:

OUT Connector Pin No.Signal NameFunctionNotes
1PROC_PWR_ENProcessor Power EnableNot used
23V33.3V Power Rail
3GNDPower Ground / 0V
4SCLKSPI ClockNot used
5COPISPI Controller Out Peripheral InNot used
6CIPOSPI Controller In Peripheral OutNot used
7CS0SPI Chip Select 0Not used
8CS1SPI Chip Select 1Not used
8CS2SPI Chip Select 2Not used
10GPIO0General Purpose Input / Output 0Connected to Pin 11 (GPIO1) on the IN connector
11GPIO1Not connected
12SDAI2C DataUsed for ZOE-M8Q communication
13SCLI2C ClockUsed for ZOE-M8Q communication
14GNDPower Ground / 0V
153V33.3V Power Rail
16V_USBUSB Power Rail (5V)Not used

We use a technique called waterfalling on the GPIO signals. If you haven't used waterfalling before, please check out the smôl Hookup Guide.

smôl Specifics

Interface:

  • I2C
  • Default Address: 0x42 (unshifted)

GPIO:

  • GPIO0 controls the power for the ZOE-M8Q
    • Pull GPIO0 high or leave floating to disable power for the ZOE-M8Q (default state)
    • Pull GPIO0 low to enable power for the ZOE-M8Q

Please remember that the smôl GPIO pins use waterfalling. The Arduino digital pin number for GPIO0 will depend on which Processor Board you are using and where the ZOE-M8Q is placed in the smôl stack. Please consult the smôl Hookup Guide for more details.

Arduino Example: Get Position

If you are using the smôl ESP32 Processor Board, you are going to want to install the CP210x USB Driver and Arduino Boards Package for the ESP32 first. Please see the smôl ESP32 Hookup Guide for more details.

The smôl ZOE-M8Q GNSS peripheral board is fully compatible with the SparkFun u-blox GNSS Arduino Library. You can install the library through the Arduino IDE Library Manager by searching for SparkFun u-blox GNSS. Alternatively, you can grab the library from GitHub or can download it as a zip file by clicking the button below:

The following example is based on Example3_GetPosition from the u-blox GNSS library. The only difference is the two extra lines of code which pull GPIO0 low to enable power for the ZOE-M8Q. Upload the code onto your processor board and open the Serial Monitor or a terminal emulator at 115200 baud to see the output.

language:c
#include <Wire.h> //Needed for I2C to GNSS

#include <SparkFun_u-blox_GNSS_Arduino_Library.h> //http://librarymanager/All#SparkFun_u-blox_GNSS
SFE_UBLOX_GNSS myGNSS;

void setup()
{
  delay(1000);

  Serial.begin(115200);
  Serial.println("SparkFun u-blox example for the smôl ZOE-M8Q");

  // GNSS power is disabled by default on the smôl ZOE-M8.
  // We need to pull GPIO0 low to enable the power.
  // On the smôl ESP32, GPIO0 is connected to digital pin 27.
  // smôl uses waterfalling:
  //  If you have an intermediate smôl board between the ESP32 and the ZOE-M8Q
  //  and that board also uses GPIO0, then the ZOE-M8Q's power enable will be connected
  //  to GPIO1 instead which is digital pin 26 on the smôl ESP32.
  pinMode(27, OUTPUT);
  digitalWrite(27, LOW); // Pull GPIO0 (digital pin 27) low to enable power for the ZOE-M8Q

  delay(1000); // Give the ZOE-M8Q some time to power up

  Wire.begin();

  //myGNSS.enableDebugging(); //Uncomment this line to enable helpful debug messages on Serial

  if (myGNSS.begin() == false) //Connect to the u-blox module using Wire port
  {
    Serial.println(F("u-blox GNSS not detected at default I2C address. Please check wiring. Freezing."));
    while (1);
  }

  myGNSS.setI2COutput(COM_TYPE_UBX); //Set the I2C port to output UBX only (turn off NMEA noise)
  myGNSS.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT); //Save (only) the communications port settings to flash and BBR
}

void loop()
{
  //The module only responds when a new position is available

  Serial.print(myGNSS.getYear());
  Serial.print("/");
  Serial.print(myGNSS.getMonth());
  Serial.print("/");
  Serial.print(myGNSS.getDay());
  Serial.print("");
  Serial.print(myGNSS.getHour());
  Serial.print(":");
  Serial.print(myGNSS.getMinute());
  Serial.print(":");
  Serial.print(myGNSS.getSecond());

  Serial.print(F(" Lat: "));
  Serial.print(myGNSS.getLatitude());

  Serial.print(F(" Long: "));
  Serial.print(myGNSS.getLongitude());
  Serial.print(F(" (degrees * 10^-7)"));

  Serial.print(F(" Alt: "));
  Serial.print(myGNSS.getAltitudeMSL());
  Serial.print(F(" (mm)"));

  Serial.print(F(" SIV: "));
  Serial.print(myGNSS.getSIV());

  Serial.println();
}

Troubleshooting

If the smôl ZOE-M8Q does not appear to be working, have you remembered to pull its GPIO0 signal low to enable the power? By default, power for the ZOE-M8Q is disabled. Pulling GPIO0 low enables the power.

If you are connecting to the smôl ZOE-M8Q via the smôl Header - without a Processor Board - you will need to tie the correct GPIO signal to GND with a jumper wire.

The Molex Flexible GNSS Antenna - u.FL is designed to work without a ground plane. It works best when positioned at least 40mm away from a ground plane. You will get little or no signal if: you stick the antenna to a metal enclosure, or position the antenna close to your battery or circuit boards. Position the antenna in clear space for best results. Please refer to the antenna Application Specification for more details.

Not working as expected and need help?SparkX products are rapidly produced to bring you the most cutting edge technology as it becomes available. These products are tested but come with no guarantees. Live technical support is not available for SparkX products. Head on over to our forum for support or to ask a question and we will get back to you as soon as we can.

Resources and Going Further

For more information about the smôl ZOE-M8Q Peripheral Board, check out the following links:

smôl ZOE-M8Q Documentation:

smôl Documentation:


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

smôl Power Board LiPo Hookup Guide

$
0
0

smôl Power Board LiPo Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

smôl is a new board format and, as the name suggests, they're really small!

smôl Power Board LiPo

smôl Power Board LiPo

SPX-18622
$17.95

The smôl Power Board LiPo is an intelligent power board for smôl. It provides 3.3V power for your smôl stack from a Li-Ion / Li-Polymer battery and has a built-in charger and fuel gauge.

Each smôl board measures just 1.60" by 0.42" (40.6mm by 10.7mm). We made the boards just wide enough so we could squeeze USB-C and 16-way Flexible Printed Circuit (FPC) connectors on there. Some of the boards have components on both top and bottom layers which again helps keep the boards small.

smôl boards are designed to stack one on top of the other, using 16-way 0.5mm-pitch FPCs to provide the interconnect from one board to the next. Each board has an IN FPC connector on the bottom layer and an OUT FPC connector on the top layer. The boards stack in a zig-zag daisy chain; signals and power are passed from one board to the next up and down the chain through the FPCs.

Required Materials

As a minimum, you're going to need a Lithium-Ion / Lithium-Polymer rechargeable battery to go with your power board:

Lithium Ion Battery - 1Ah

Lithium Ion Battery - 1Ah

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

Lithium Ion Battery - 2Ah

PRT-13855
$12.95
7
Lithium Ion Battery - 400mAh

Lithium Ion Battery - 400mAh

PRT-13851
$4.95
9
Lithium Ion Battery - 850mAh

Lithium Ion Battery - 850mAh

PRT-13854
$9.95
2
Lithium Ion Battery - 18650 Cell (2600mAh)

Lithium Ion Battery - 18650 Cell (2600mAh)

PRT-12895
$5.95
Lithium Ion Battery - 6Ah

Lithium Ion Battery - 6Ah

PRT-13856
$29.95
7

The Power Board LiPo is part of the smôl ecosystem. Why not pair it with one of the smôl Processor Boards and a Peripheral Board?

smôl ARTIC R2

smôl ARTIC R2

SPX-18618
$199.95
smôl ESP32

smôl ESP32

SPX-18619
$17.95
smôl ZOE-M8Q

smôl ZOE-M8Q

SPX-18623
$39.95

Don't forget that you will need Flexible Printed Circuits to connect your smôl boards together. You're going to need one FPC per board. Our 36mm FPC is the perfect length if you want the smôl boards to stack neatly, one on top of the other.

smôl 36mm 16-way Flexible Printed Circuit

smôl 36mm 16-way Flexible Printed Circuit

CAB-18731
$0.95















Need to do some prototyping with smôl? Or want to connect your smôl stack to a Qwiic board? The smôl Header is perfect for that:

smôl Header

smôl Header

SPX-18620
$2.95













Suggested Reading

This is the hookup guide for the smôl Power Board LiPo. Click the button below if you want to find out more about smôl itself.

We recommend taking a look through the following tutorials if you are not familiar with the concepts covered in them:

Battery Technologies

The basics behind the batteries used in portable electronic devices: LiPo, NiMH, coin cells, and alkaline.

I2C

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

Hardware Overview

In this section we'll cover what this board does and what is included on the smôl Power Board LiPo.

What Does This Board Do?

What does this board do? Excellent question! Let's answer that right now.

Many SparkFun boards, especially our Thing Plus boards, come with a Li-Ion battery connector and built-in charger so you can power your project from a rechargeable battery. smôl is no different. The smôl Power Board LiPo is equipped with: one of our standard JST-PH battery connectors; an MCP73831 Li-Ion and Li-Polymer charger; and a MAX17048 I2C battery fuel gauge. But it also comes with an on-board ATtiny841 AVR microcontroller. This is an intelligent power board!

The main job of the Power Board is to provide power for your smôl ecosystem. smôl is designed to be both small in size and small on current draw. The Power Board plays a critical role in reducing the current draw of smôl as much as possible.

When you want your project to go into a low power or deep sleep state, it is standard practice to put your processor into the lowest power state it offers. But you may find that the current draw is still something like 100µA to 500µA depending on which processor you are using. Then there is the quiescent current drawn by the voltage regulator. The quiescent current is the current drawn by the regulator when it is on but has no load attached. Again, it varies from regulator to regulator but you may find this adds another 55µA to your current draw. Those little currents add up and reduce your battery life considerably.

With smôl, we took a new approach. The Power Board takes control and provides the 3.3V power for the whole smôl stack. When instructed to by the Processor Board, the on-board ATtiny microcontroller will turn off that power completely and then put itself into a low power sleep state for a pre-defined interval. Sleep intervals from a few 10's of milliseconds to several days are possible. We have used the fantastic Otii Arc Power Analyzer to help us reduce the sleep current to just 6µA. Yes, you read that right, 6 microamps! smôl makes it possible for your battery life to be measured in months not days!

Battery Connector

By far the biggest component on the board is the JST-PH connector for the battery.

Pictured is the Battery Connector
Battery Polarity: Please make sure that you use one of our recommended Lithium Ion batteries. Some batteries use the same JST connector as ours but have the opposite polarity. Connecting one of these to your smôl power board could destroy it. If you are going to use your own battery, it is up to you to ensure it has the correct polarity. In the above photo, the positive pin is on the right.

MCP73831 Li-Ion and Li-Polymer Charger

Like our Thing Plus boards, the smôl Power Board LiPo comes with a MCP73831 Li-Ion and Li-Polymer Charger IC. We've set the charge current to 100mA to prevent the board drawing too much current through the Flexible Printed Circuit interconnect and to make it safe to use small Li-Ion batteries like our 400mAh battery.

The yellow CHG LED will light up when the battery is charging from USB power via the Processor Board.

Pictured is the MCP73831 battery charger

MAX17048 Fuel Gauge

Like our Thing Plus C - ESP32 WROOM, the smôl Power Board LiPo comes with a MAX17048 I2C Fuel Gauge IC. The processor board can communicate with the power board via I2C and read the battery voltage, State-of-Charge and other parameters.

Pictured is the MAX17048 fuel gauge

ATtiny841 AVR Microcontroller

The smôl Power Board LiPo is an intelligent power board. The on-board ATtiny841 microcontroller can monitor the battery voltage, State-of-Charge and other parameters. When the Processor Board requests it to, the ATtiny841 will turn off the smôl 3.3V power completely and place itself into deep sleep for a pre-defined interval. This is what makes it possible to reduce the sleep current to just 6µA.

Pictured is the ATtiny841 microcontroller

Our SparkFun smôl Power Board Arduino Library does all of the heavy lifting for you, making it easy to communicate with the ATtiny through simple function calls.

A Note About Temperature Sensing

The ATtiny841 has a built-in temperature sensor, which can be accessed via the SparkFun smôl Power Board Arduino Library. However, the quoted typical accuracy of the sensor is &pm;10°C. Yes, plus or minus ten degrees C. The sensor measurement requires external calibration to be useful.

Voltage Regulators

The smôl Power Board LiPo has two 3.3V regulators on-board: an AP2112K-3.3V and a STLQ015-3.3V.

Pictured are the two 3.3V regulators

The AP2112K-3.3V is one of our favorite regulators. It provides 3.3V at up to 600mA with a typical voltage drop of 250mV. The AP2112K provides 3.3V to the smôl stack and can be switched off completely by the ATtiny841 processor. This avoids the regulator's 55µA quiescent current draw depleting your battery.

The STLQ015-3.3V is a new friend. It provides 3.3V at up to 150mA with a typical voltage drop of 112mV. The STLQ015 provides 3.3V power for the ATtiny841 microcontroller (only) and has a truly tiny quiescent current draw of 1.4µA.

FPC Connections

Like all of our smôl boards, the Power Board LiPo is equipped with two 16-way 0.5mm-pitch Flexible Printed Circuit connectors. FPCs are used to link the smôl boards together in a daisy-chain.

The pin-out for the smôl Power Board LiPo is as follows:

Connector Pin No.Signal NameFunctionNotes
1PROC_PWR_ENProcessor Power EnableThe power board pulls this signal low to disable the voltage regulator on the power board
23V33.3V Power Rail
3GNDPower Ground / 0V
4SCLKSPI ClockNot used
5COPISPI Controller Out Peripheral InNot used
6CIPOSPI Controller In Peripheral OutNot used
7CS0SPI Chip Select 0Not used
8CS1SPI Chip Select 1Not used
8CS2SPI Chip Select 2Not used
10GPIO0General Purpose Input / Output 0Not used
11GPIO1General Purpose Input / Output 1Not used
12SDAI2C DataUsed for ATtiny841 and Fuel Gauge communication
13SCLI2C ClockUsed for ATtiny841 and Fuel Gauge communication
14GNDPower Ground / 0V
153V33.3V Power Rail
16V_USBUSB Power Rail (5V)USB power is used to recharge the battery

The IN and OUT pin connections are identical on the smôl Power Board LiPo. (That's not always true on smôl Peripheral Boards. Check the appropriate Peripheral Board Hookup Guide for full details.)

The order in which you connect smôl boards is important. However, because the Power Board LiPo only uses I2C communication, it can be placed anywhere in the stack. Please see the smôl Hookup Guide for more details.

smôl Specifics

Interface:

  • Interface: I2C
    • ATtiny841 Default Address: 0x50
    • MAX17048 Fuel Gauge Address: 0x36

PROC_PWR_EN:

  • PROC_PWR_EN:
    • The power board pulls PROC_PWR_EN low to disable the regulator on the processor board

Arduino Example: Battery Voltage

If you are using the smôl ESP32 Processor Board, you are going to want to install the CP210x USB Driver and Arduino Boards Package for the ESP32 first. Please see the smôl ESP32 Hookup Guide for more details.

The smôl Power Boards have their own Arduino Library to make communicating with the board as simple as calling a function. You can install the library through the Arduino IDE Library Manager by searching for SparkFun smol power. Alternatively, you can grab the library from GitHub or can download it as a zip file by clicking the button below:

You are also going to need to install the SparkFun MAX1704x Fuel Gauge Arduino Library. Again, you can install this library through the Arduino IDE Library Manager by searching for SparkFun MAX1704x. Alternatively, you can grab the library from GitHub or can download it as a zip file by clicking the button below:

The Power Board library contains a set of tried-and-tested examples which will work with both the smôl Power Board LiPo and the smôl Power Board AAA. There is only one line of code to change when switching from one to the other.

The following code is a simplified version of Example2_BatteryVoltage. Upload the code onto your processor board and open the Serial Monitor or a terminal emulator at 115200 baud to see the output.

language:c
#include <Wire.h>

#include <SparkFun_MAX1704x_Fuel_Gauge_Arduino_Library.h> // Click here to get the library: http://librarymanager/All#SparkFun_MAX1704x_Fuel_Gauge_Arduino_Library
#include <SparkFun_smol_Power_Board.h> //Click here to get the library:  http://librarymanager/All#SparkFun_smol_Power_Board

smolPowerLiPo myPowerBoard;

void setup()
{
  Serial.begin(115200);
  while (!Serial)
    ; // Wait for the user to open the Serial console
  Serial.println(F("smôl Power Board example"));
  Serial.println();

  Wire.begin();

  if (myPowerBoard.begin() == false) // Begin communication with the power board using the default I2C address (0x50) and the Wire port
  {
    Serial.println(F("Could not communicate with the power board. Please check the I2C connections. Freezing..."));
    while (1)
      ;
  }

  float voltage = myPowerBoard.getBatteryVoltage(); // Read the battery voltage from the fuel gauge
  Serial.print(F("The battery voltage reads as: "));
  Serial.println(voltage);

  if (voltage == -99.0)
  {
    Serial.println(F("A voltage of -99.0V indicates an error."));
  }
}

void loop()
{
  //Nothing to do here
}

Troubleshooting

If your smôl stack is not communicating, it is probably in deep sleep. When the Power Board is commanded into deep sleep by the Processor Board, the only way it will wake it up again is when the sleep interval expires. You cannot wake or reset the system via the USB interface.

Removing and re-inserting the battery connection will reset the power board and wake it up again.

We did not include a reset button on the smôl Power Board to keep the board as small as possible. However, you can reset it via the ISP programming test points on the bottom of the board. Briefly connect RESET to GND to reset the board.

Pictured are the RESET and GND test points on the bottom of the board
Not working as expected and need help?SparkX products are rapidly produced to bring you the most cutting edge technology as it becomes available. These products are tested but come with no guarantees. Live technical support is not available for SparkX products. Head on over to our forum for support or to ask a question and we will get back to you as soon as we can.

Resources and Going Further

For more information about the smôl Power Board LiPo, check out the following links:

smôl Power Board LiPo Documentation:

Li-Ion / Li-Polymer Charger:

Battery Fuel Gauge:

Microcontroller:

smôl Documentation:


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>