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

SparkFun Qwiic AS3935 Lightning Detector Hookup Guide

$
0
0

SparkFun Qwiic AS3935 Lightning Detector Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Qwiic AS3935 Lightning Detector adds lightning detection to your next weather station or to your next bike ride. Are you worried about the looming clouds in the distance, how far away is that storm exactly? The lightning detector can tell you the distance to the front of the storm 40 km away with an accuracy of 1km. It has false positive rejection and comes with many configurable features. To get at those features we have written a library that gives you access to settings such as storm sensing sensitivity when detecting indoors vs outdoors, or the number of lightning strikes needed to trigger an interrupt! The board supports both I2C and SPI, and so we've whipped out the Qwiic connector to make this easy to integrate into the Qwiic environment.

SparkFun Lightning Detector - AS3935 (Qwiic)

SparkFun Lightning Detector - AS3935 (Qwiic)

SEN-15276
$24.95

Required Materials

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

SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

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

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
12
Qwiic Cable - 50mm

Qwiic Cable - 50mm

PRT-14426
$0.95
IC Hook with Pigtail

IC Hook with Pigtail

CAB-09741
$4.95
6

If you need different size Qwiic cables we offer a kit that contains many sizes but we also carry them individually as well:

SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
1
Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - Breadboard Jumper (4-pin)

Qwiic Cable - Breadboard Jumper (4-pin)

PRT-14425
$1.50
Qwiic Cable - 500mm

Qwiic Cable - 500mm

PRT-14429
$1.95

Tools

Depending on your setup, you will may need a soldering iron, solder, and general soldering accessories.

Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

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

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2

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 Peripheral Interface (SPI)

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

I2C

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

How to Work with Jumper Pads and PCB Traces

Handling PCB jumper pads and traces is an essential skill. Learn how to cut a PCB trace, add a solder jumper between pads to reroute connections, and repair a trace with the green wire method if a trace is damaged.

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.

Hardware Overview

Power

You can provide 3.3V through the Qwiic connector on the board or through the 3V3 labeled pin on the through hole header. When you correctly power the board, the on board power LED will turn on.

Input Power

LED

There is one red LED on the product that will turn on when power is supplied to the board. You can disconnect this LED by cutting the jumper on the underside of the product labeled LED.

Power LED

Qwiic Connector or I2C Pins

There is one Qwiic connector on the board to easily connect to the sensor via I2C. If you prefer the old school method of connecting to the I2C pins, we've also broken out those four pins on the side of the board as plated through holes.

Qwiic Connector or I2C

Interrupt Pin

The interrupt pin turns high when the lightning detector has sensed an event, whether it's lightning, a disturber, or noise. Make sure to connect to this pin to check if there is an event detected.

Interrupt Pin

Jumpers

There are four jumpers on this product all on its underside.

Jumpers on Back of Board

From left to right starting at the bottom: there are two address jumpers labeled ADR that allow you to change. The default I2C address is 0x03 but it can be changed to three other options: 0x02, 0x01, 0x00. We recommend 0x03 and 0x02, but if you really know what you're doing then you can also use 0x01 or 0x00. These two addresses are reserved for special I2C commands and you can read more about I2C addressing from this article.

Next to the two address jumpers are the I2C pull-up resistor jumpers. If you have many I2C devices chained together you may have to cut these jumpers. Next to that you, have the SPI jumper that enables SPI when closed. Finally, in the upper right is the power LED disconnect jumper. If that power LED is irritating or unnecessary, then cut that jumper.

Antenna

The large-ish part on the board is the board's antenna. Keep the area around the antenna free as it is what picks up lightning events. With that said, check below for some common sources of false positives and noise.

Antenna

False Positives and Noise

There are a number of sources that can cause false positives but the lightning detector itself can reliably filter these out by default. If not, there are a number of settings you can configure using the lightning detector library to increase the chip's robustness to noise and false positives. However, it can help to know some potential sources of noise (from the AS3935 fact sheet) fluorescent lighting, microwave ovens, and switches. From the datasheet, it states that smartphone and smartwatch displays, and DC-DC converters can also trigger as noise. Keep in mind that you would probably have to put your lightning detector on top of your phone for it to register. I found that using the lightning detector in the office was near impossible because I'm surrounded by at least ten computers, three 3D-printers, and numerous soldering irons.

Hardware Assembly

This one is very easy to put together if you have a Qwiic enabled microcontroller like the RedBoard Qwiic. Plug a Qwiic cable between the RedBoard Qwiic and the SparkFun AS3935 Lightning Detector. You will also need to solder wire between the RedBoard Qwiic's pin 4 and the Qwiic AS3935's INT pin. For quick testing, an IC hook was used. For a secure connection, we recommend soldering a header or wire between the two.

AS3935 Connected to Arduino
Note: The sensor has a logic level of 3.3V. I have attached the interrupt to pin 4 on the Redboard Qwiic even though the pin is at 5 volts. This will not harm the Qwiic RFID since we're doing a simple digitalRead().

Library Installation

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 provided a library for the SparkFun Lightning Detector that configures every available setting the IC offers. Some of the features include modifying the sensitivity of the antenna, whether you're inside or outside, or fine tuning when the IC triggers an interrupt. If you haven't already, click the button below to get the library. You can also download it manually from the GitHub Repo.

Example Code

The example below will start with the basic functionality in Example1_BasicLightning.ino. Open the example up to follow along.

At the very top, we have a few defines that will help us to distinguish what sort of event the lightning detector has sensed. There are three possible "events". The first of course is lightning, but we may also get a false lightning event called a disturber, and finally we may hear noise.

language:c
#include <SPI.h>
#include <Wire.h>
#include "SparkFun_AS3935.h"

// 0x03 is default, but the address can also be 0x02, 0x01, or 0x00
// Adjust the address jumpers on the underside of the product. 
#define AS3935_ADDR 0x03 
#define INDOOR 0x12 
#define OUTDOOR 0xE
#define LIGHTNING_INT 0x08
#define DISTURBER_INT 0x04
#define NOISE_INT 0x01

// If you using SPI, instantiate class without address: 
//SparkFun_AS3935 lightning;

// If you're using I-squared-C then keep the following line. Address is set to
// default. 
SparkFun_AS3935 lightning(AS3935_ADDR);

// Interrupt pin for lightning detection 
const int lightningInt = 4; 
int noiseFloor = 2;

// This variable holds the number representing the lightning or non-lightning
// event issued by the lightning detector. 
int intVal = 0;

In the setup, we set the IC to be run inside because I'm assuming you're at your computer running this code. If you're outside change the parameter to OUTDOOR.

language:c
void setup()
{
  // When lightning is detected the interrupt pin goes HIGH.
  pinMode(lightningInt, INPUT); 

  Serial.begin(115200); 
  Serial.println("AS3935 Franklin Lightning Detector"); 

  //SPI.begin() 
  Wire.begin(); // Begin Wire before lightning sensor. 

  if( !lightning.begin() ) { // Initialize the sensor. 
  //if( !lightning.beginSPI(9, 2000000){ // Uncomment for SPI.
    Serial.println ("Lightning Detector did not start up, freezing!"); 
    while(1); 
  }
  else
    Serial.println("Schmow-ZoW, Lightning Detector Ready!");

  // The lightning detector defaults to an indoor setting at 
  // the cost of less sensitivity, if you plan on using this outdoors 
  // uncomment the following line:
  //lightning.setIndoorOutdoor(OUTDOOR); 
}

...and finally the meat. Here we're just monitoring the interrupt pin. If the pin reads high, then the IC has heard some sort of event. Afterwards we're going to read the interrupt register to see what the event is, whether it's lightning, a disturber, or noise. Each of these events are printed out in the serial window at 115200 baud. The lightning event however will also print out the estimated distance to the front of the storm. Keep in mind that this is not the distance to the lightning but rather the storm.

language:c
void loop()
{
  if(digitalRead(lightningInt) == HIGH){
    // Hardware has alerted us to an event, now we read the interrupt register
    // to see exactly what it is. 
    intVal = lightning.readInterruptReg();
    if(intVal == NOISE_INT){
      Serial.println("Noise."); 
      //reduceNoise(); //See note below above reduceNoise function.
    }
    else if(intVal == DISTURBER_INT){
      Serial.println("Disturber."); 
    }
    else if(intVal == LIGHTNING_INT){
      Serial.println("Lightning Strike Detected!"); 
      // Lightning! Now how far away is it? Distance estimation takes into
      // account any previously seen events in the last 15 seconds. 
      byte distance = lightning.distanceToStorm(); 
      Serial.print("Approximately: "); 
      Serial.print(distance); 
      Serial.println("km away!"); 
    }
  }
  delay(100); //Let's not be too crazy.
}

In case you're sitting at a computer and there's a lot of RF noise in your area then you may need a way to make the lightning detection less sensitive to these events. Call this function and feed it a number lower than seven to increase it's noise threshold. Likewise, you could put this function in the noise if-statement listed above and it will increase that threshold every time a noise event occurs. This may give you an idea of which number works best for the area you're in.

language:c
void reduceNoise(){
  ++noiseFloor; // Manufacturer's default is 2 with a max of 7. 
  if(noiseFloor > 7){
    Serial.println("Noise floor is at max!"); 
    return;
  }
  Serial.println("Increasing the event threshold.");
  lightning.setNoiseLevel(noiseFloor);  
}

If you've heard some lightning, than you'll see the following in your Arduino serial window.

Example Output With Noise and Lightning Emulated

Resources and Going Further

For more on the AS3935, check out the links below:

Need some other weather sensing parts for your project? Check out some of the ones listed below.

Weather Meters

Weather Meters

SEN-08942
$76.95
25
SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SEN-14348
$35.95
12
SparkFun Pressure Sensor Breakout - MS5803-14BA

SparkFun Pressure Sensor Breakout - MS5803-14BA

SEN-12909
$59.95
7
SparkFun Weather Shield

SparkFun Weather Shield

DEV-13956
$39.95
3

Need some inspiration for your next project? Check out some of these related tutorials to sense your environment!

Si4707 Hookup Guide

Instructions on hooking up to and communicating with the Si4707 Weather Band Radio Breakout using an Arduino.

T5403 Barometric Pressure Sensor Hookup Guide

T5403 Barometric Pressure Sensor Hookup Guide

LED Cloud-Connected Cloud

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

Arduino Weather Shield Hookup Guide V12

Read humidity, pressure and luminosity quickly and easily. Add wind speed, direction and rain gauge for full weather station capabilities.

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


LED Gumball Machine

$
0
0

LED Gumball Machine a learn.sparkfun.com tutorial

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

Introduction

Do you need an LED? The answer is always yes. But what if you need one right now? Build yourself an LED gumball machine and never run out again!

Gumball machine filled with LEDs

Approximately 3,000 red 5mm LEDs ready to blink

This machine was created for the BTU Lab at CU Boulder because students constantly needed LEDs but filling parts bins always seemed to fall to the tragedy of the commons. We’d put 1,000 LEDs into the bin and they’d be gone in less than 2 weeks.

Dispensing LEDs

With the LED Gumball dispenser the LEDs last for more than a semester. It’s amazing how much a 15 second pause will cause people to think twice.

Suggested Reading

What is an Arduino?

What is this 'Arduino' thing anyway?

Pulse Width Modulation

An introduction to the concept of Pulse Width Modulation.

Switch Basics

A tutorial on electronics' most overlooked and underappreciated component: the switch! Here we explain the difference between momentary and maintained switches and what all those acronyms (NO, NC, SPDT, SPST, ...) stand for.

Hobby Servo Tutorial

Servos are motors that allow you to accurately control the rotation of the output shaft, opening up all kinds of possibilities for robotics and other projects.

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.

And if you really want to get geeky, have a look at this posting on state machines. State machines are a good way to change between the states 'wait for user to press button' to 'ignore buttons and don't dispense right now'.

Hardware Overview

Here’s the list of parts for this project:

SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
Servo - Generic High Torque Continuous Rotation (Standard Size)

Servo - Generic High Torque Continuous Rotation (Standard Size)

ROB-09347
$13.95
6
Wall Adapter Power Supply - 5V DC 2A (Barrel Jack)

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

TOL-12889
$5.95
16
SparkFun ProtoShield Kit

SparkFun ProtoShield Kit

DEV-13820
$10.95
Metal Pushbutton - Momentary (16mm, Red)

Metal Pushbutton - Momentary (16mm, Red)

COM-11966
$5.95
5

A proto shield works great. We used an old shield we had lying around but you can use any shield that has a few GPIO broken out that you can solder to.

You’ll of course need a gumball machine. We haven’t verified the continuous servo works with different brands but we’re pretty confident this Gumball Machine will work with this tutorial.

Tools:

The tools for this project are pretty common. You may or may not have the various tools around so double check that you have access to the follow:

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

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

PRT-11367
$16.95
29
Solder Lead Free - 100-gram Spool

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Wire Strippers - 22-30AWG

Wire Strippers - 22-30AWG

TOL-14762
$12.95
Weller WLC100 Soldering Station

Weller WLC100 Soldering Station

TOL-14228
$44.95

Continuous Rotation Servo

The magic of the LED Gumball Machine is the fact that a continuous rotation servo mates utterly fantastically with the dispensing cogs within the machine.

Head of servo lining up with cogs on bottom of bowl

A high torque continuous rotation servo is just the ticket for getting electronic control of the dispenser mechanism.

Most servos come with a variety of control horns. These are the plastic bits of different shapes that you screw into the servo to connect the servo to your application. In this tutorial we’ll want the star control horn (highlighted below). Out of complete luck, this horn has roughly the same pitch as the teeth on the gumball machine.

Various servo control horns

The servo has quite a lot of torque and we want that applied to the dispenser mechanism. We mounted the servo with zip ties and hot glue. First use zip ties to roughly mount the servo in place. Once you get the alignment between the servo head and dispenser gear use hot glue to solidify everything in place. This combination creates the right combination of rough alignment and rigidity so that as much of the torque from the servo is transferred to the dispenser.

Mounted servo with zip ties and hot glue

Button

Single button where knob should be

We chose a momentary light up button. This fit superbly into the existing hole where the twist knob originally resided. Once mounted, it was a small matter to figure out which pins illuminated the LED and which pins shorted together when the button was pressed.

Wiring behind the momentary button

RedBoard

All parts wired together

To tie it all together we used a RedBoard and an old MIDI shield. The MIDI part is not important. Instead, the row of breakout pins at the edge of the board made it easy to solder the handful of wires from the servo and button onto the board and then plug the shield onto the RedBoard.

RedBoard with shield connected to servo and button

This was a more resilient connection method than point soldering to the SMD pads on the IO of the RedBoard. We could have also used a the Proto Shield or an Arduino Pro Mini but we had these parts lying around.

Power

The servo requires a fair amount of current at 5V so we used 5V 2A wall supply. The power cable was routed up through the pedestal column and through the mounting plates to plug into the Arduino.

Gumball Machine

Obviously you’re going to need a gumball machine.

Gumball machine filled with LEDs

These are amazing little machines that are well designed for rough use and easy maintenance. We aren’t charging money for the LEDs so we used the area where quarters usually get stored for our electronics.

Cavity showing electronics inside machine

Be sure to get a machine with a metal base and a hollow post. The metal base makes your installation last much longer (students are only slightly less tough on equipment than hyenas) and the hollow post allows us to route power up through the base. I had to enlarge a few holes to ½” in order to allow the DC barrel plug through.

Software

We want the gumball machine to dispense LEDs when the button is pressed, that’s straightforward enough. But we want to avoid dispensing all the LEDs. Also, we don’t want someone to stand in front of the free machine and continually hit the ‘gimme’ button. We implement a timeout of 15 seconds that prevents users from activating the servo constantly. You can get the software here.

Dispensing with PWM

Almost all servos operate on PWM. Before installing the continuous servo in our machine we found the servo responded in the follow ways:

  • gumballServo.write(95); - Stops movement of continous servo
  • gumballServo.write(200); - Servo turns CCW rapidly
  • gumballServo.write(10); - Servo turns CW rapidly (but not used)

Our gumball dispenser was designed to operate clock wise so we only operate our servo counter clockwise.

Handful of LEDs

The dispenser was designed for gumballs obviously so when dispensing LEDs the number of LEDs that actually come out varies wildly. In general the user gets 1 to 5 LEDs when the servo is activated for 1 second. This works well. In the eventual case that LEDs fail to dispense, the user just has to wait 15 seconds to try again. Since we're not charging anything this is an acceptable outcome.

gumballServo.detach(); //Be sure the servo won't move

After dispensing we detach the servo. This turns off the PWM signal going to the servo guaranteeing the servo won't move. We noticed the servo jittered or moved very slowly at 90 (when it shouldn't be moving) so this extra step insures the LED Gumball Machine won't slowly disgorge itself onto the carpet overnight.

Along those same lines of concern, we noticed that the dispensing mechanism will sometimes bind up causing the servo to draw significantly more current for a short period of time. This can cause the power supply to shut down, causing the Arduino to reset. You'll see at the beginning of setup()

gumballServo.attach(GUMBALL_SERVO); //Be sure the servo won't move
gumballServo.write(95); //Stop movement on continous servo
gumballServo.detach(); //Be sure the servo won't move

The above code is the first thing the Arduino runs and insures any previous servo movement is stopped. This helps prevent weird rolling reset situations where the servo causes a brownout and as the Arduino comes back on line the servo begins moving, causing a brownout, etc...

Button Monitoring

The button shorts to ground when pressed so we use the internal pullups to pull the button pin high when the button is not pressed.

The button has a built in LED so we connect the +/- pins on the back of the button directly to a PWM enabled pin and Ground. The LED measured 12mA at 5V, well below the 20mA max so we didn't need a resistor.

//Check if we are allowed to dispense
else if (millis() - lastDispenseTime < minTimeBetweenPresses)
{
    Serial.println("Uh-huh Mr. Eager. Wait your turn.");
    while (digitalRead(BUTTON) == LOW) delay(10); //Wait for user to stop pressing button
    return; //No soup for you!
}

In the code above we check to see if enough time has passed since the last button press for us to vend again.

unsigned long minTimeBetweenPresses = 15 * 1000; //Make users wait this amount of ms between dispenses

We found 15 seconds (15,000 milliseconds) between vends was enough time to dissuade students from taking all the LEDs.

Resources and Going Further

We hope you've enjoyed reading about our LED dispensing gumball machine. If you liked this one, there's tons more!

Serial Peripheral Interface (SPI)

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

Metric Prefixes and SI Units

This tutorial will explain how to use and convert between the standard metric prefixes.

Motors and Selecting the Right One

Learn all about different kinds of motors and how they operate.

Getting Started with LTspice

LTspice is a high performance SPICE simulator, schematic capture and waveform viewer with an impressive library of passive devices. Over 1000 models are included in the download but you can also add third party models.

MMA8452Q Accelerometer Breakout Hookup Guide

How to get started using the MMA8452Q 3-axis accelerometer -- a solid, digital, easy-to-use acceleration sensor.

SparkFun BME280 Breakout Hookup Guide

A guide for connecting the BEM280 sensor to a microcontroller, and for using the Sparkfun Arduino library.

Raspberry Pi Zero Helmet Impact Force Monitor

How much impact can the human body handle? This tutorial will teach you how to build your very own impact force monitor using a helmet, Raspberry Pi Zero, and accelerometer!

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.

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

Wireless Glove Controller

$
0
0

Wireless Glove Controller a learn.sparkfun.com tutorial

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

Introduction

In this tutorial, we will build a wireless glove controller with Arduino to trigger an LED remotely using XBees!

Full Demo

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 wire, wire strippers, a soldering iron, solder, and general soldering accessories.

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

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

PRT-11367
$16.95
29
Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

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

Solder Lead Free - 15-gram Tube

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

Wire Strippers - 20-30AWG

TOL-14763
$14.95
2

You Will Also Need

  • Glove
  • Scissors
  • Non-Conductive Thread
  • Tape

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.

LDK Experiment 5: Make Your Own Switch

Learn to create and integrate your own handmade switch into an e-textile circuit.

XBee Shield Hookup Guide

How to get started with an XBee Shield and Explorer. Create a remote-control Arduino!

Exploring XBees and XCTU

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

LilyPad Basics: E-Sewing

Learn how to use conductive thread with LilyPad components.

Understanding Your Circuit

Wireless Glove Controller

The simplest form of input is a button press, so we'll control LEDs remotely using buttons for this project as shown in the diagram below.

Circuit Diagram Transmitting XBee

Custom Button

Since the electronics are going on a glove, the usual momentary button won't be the most comfortable on the fingers. Instead, we'll make our own custom button using snappable pins, conductive thread, and wire. You'll need to make a contact between your thumb, middle, ring, and pinky to GND, pin 4, pin 11, and pin 12, respectively.

LEDs

For feedback to indicate that we have sent a character wirelessly, we'll solder an LED and 330&ohm; current limiting resistor to the protoboard between pin 13 and ground. You could use the on-board LED on the RedBoard but it would be harder to see under the shield. Additionally, we'll attach a diffused, common cathode RGB LED to pins 5, 6, and 9. Make sure to add a second 330&ohm; current limiting resistor between the common cathode and GND, respectively.


Receiving XBee Node

For the receiving XBee, we'll just mimic the LEDs used for feedback on the glove. The circuit is the same, that is without the custom buttons as shown in the diagram below. The board is flipped over to illustrate the receiving XBee node.

Circuit Diagram Receiving XBee

Hardware Hookup

Modify the XBee Shield

Using the circuit diagram from earlier, solder the components to the XBee shield. Then strip solid, core hook-up wire and solder them between the pins. If you are following along, your board should look similar to the images below.

Top View of Modified XBee Wireless ShieldBottom View of XBee Wireless Shield
Top View Components Soldered on XBee ShieldBottom View with Wires and Jumpers

Making a Connection Between Hard to Soft Materials

Grab four 12" F/F jumper wires of different colors and cut them in half. At this point, we'll need solder a wire loop from the standed wire so that we can easily connect the conductive thread to each of the finger's snappable pins. The other option is to thread the stranded wire through one of the holes on the snappable pin and solder them together.

Hard to Soft Connection

Securing the Boards and Wires to the Glove

When you are finished, grab a needle, thread the non-conductive thread through the eye, and sew the RedBoard's mounting holes to the glove of your choice. I found that three of the holes was sufficient enough. Make sure to not sew the top and bottom of the glove together. Stack a configured XBee, XBee shield, and RedBoard together. Then insert the female housing into the right angle headers of the shield.

Braid the wires together and secure it to the glove using some non-conductive thread. For each wire, you will need to separate the wires as it gets closer to the fingers. Make sure there is enough space between the board and connections so that the board is not pressing against the wires. Test it out to ensure that there is enough tolerance so that the wires do not get damaged when the hand is moving.

Sew RedBoard and Wires to the Glove Using Non-Conductive Thread

Sewing the Custom Buttons

To make a connection to the snappable pins using conductive thread, we'll need to use a small needle. The two small needles provided in the needle set will be needed to sew the pin down. Find a spot for the snappable pin to make contact with the other finger. We'll start with the thumb. Grab the small needle, thread the conductive thread through the needle's eye, and sew the pin down. Sewing one of the four holes with conductive fabric should be sufficient enough if you loop it a few times. You could use non-conductive thread on the remaining holes. Again, avoid sewing the top and bottom fabric together.

Sew Female Snap Pin with Conductive Thread and Connect with the Wire's Loop

After a few loops around the the snappable pin's hole, make a running stitch to the top of the hand and make a connection to the wire loop to the respective pin connection. Following the circuit diagram, the thumb should be connected to the GND wire. Tie and cut off any excess thread.

Connecting to a Wire

Repeat for each snappable pin.

Snap (Metal Poppers) Pins Sewed on Glove

Assembled Wireless Glove Controller

When finished, your glove should look like the images below! Feel free to click on the images for a closer look.

Top View of Assembled Wireless GloveBottom View of Assembled Wireless Glove
Top View Bottom View

If you decide to use the glove remotely, add a 9V battery and secure it to the glove. In this case, electrical tape was used to hold the battery to the board. Feel free to sew together a 9V battery pouch to the glove for a more secure method.

Glove with Battery Secured

Configuring XBees

To configure the XBees, we will be using the XBee Series 1 firmware. It is recommended to configure each XBee using the XBee Explorer USB.

XBee Inseted int XBee Explorer USB to Configure

If you have not already, check out the Starting with XCTU section under Exploring XBees and XCTU to configure your XBees. If you are using an XBee 3, make sure to configure the firmware with the Series 1 firmware to follow along with this tutorial.

Exploring XBees and XCTU

March 12, 2015

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

Point-to-Point Configuration

For simplicity, we will be sending commands with the XBees in transparent mode set for a point-to-point configuration. Make sure to configure each XBee with a unique MY address if there are more than two XBees in your CH and PAN ID. You will then need to adjust the DL address for each respective XBee.

SettingAcronymTransmitting XBee Node 1
(Wireless Glove Controller)
Receiving XBee Node 2
(i.e. LED/Robot/Dance Suit)
ChannelCHCC
PAN IDID33333333
Destination Address HighDH00
Destination Address LowDL10
16-bit Source AddressMY01

Example 1: Sending and Receiving

Note: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE.

If you've never connected an FTDI device to your computer before, you may need to install drivers for the USB-to-serial converter. Check out our How to Install FTDI Drivers tutorial for help with the installation.

Example 1a: Sending a Character with the Glove

In this part of the example, we'll have the glove send a character when a button is pressed. While you could just open a serial terminal to check if characters were received during testing, it would just not be as fun as blinking an LED wirelessly after a button press.

Copy the code, paste it into the Arduino IDE, select your board (Arduino/Genuino Uno), and COM port. Then upload the code to the glove.

language:c
// We'll use SoftwareSerial to communicate with the XBee:

#include <SoftwareSerial.h>

//For Atmega328P's
// XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX)
SoftwareSerial XBee(2, 3); // RX, TX

//For Atmega2560, ATmega32U4, etc.
// XBee's DOUT (TX) is connected to pin 10 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 11 (Arduino's Software TX)
//SoftwareSerial XBee(10, 11); // RX, TX


//Send
const int button1Pin = 4; //push button
const int status_LED = 13;  //LED on the push button

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

//initialize variables to read buttons
int button1State;

//variables to check for button1 state
boolean prev_button1State = false;
boolean current_button1State = false;

/*******************Setup Loop***************************/
void setup() {
  //Declare pin modes
  pinMode(button1Pin, INPUT_PULLUP); //use internal pullup resistor with send button
  pinMode (status_LED, OUTPUT);//LED to indicate when character has been sent

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

  //Declare serial connections for debugging
  Serial.begin(9600);
  Serial.println("Arduino Serial Ready");

  XBee.begin(9600);
  Serial.println("Glove Controller's XBee Ready to Communicate");

}//end setup()

void loop() {

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

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

    if (prev_button1State != current_button1State) //check to see if button is still being pressed
    {
      Serial.println("Button is pressed.");
      XBee.write(send_CHAR);//Sending a character
    }
    else {
      //do nothing because finger is still on button
    }
    prev_button1State = current_button1State;
  }

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

    prev_button1State = current_button1State;
  }
}//end loop()

Example 1b: Receiving XBee Node

In this part of the code, we'll have the receiving XBee blinking the LED connected to pin 13 as well. Copy the code below, paste it into the Arduino IDE, select your board (Arduino/Genuino Uno), and COM port. The Arduino should enumerate on a different COM port so make sure to adjust the COM port. Then upload the code to the receiving XBee's Arduino.

language:c

// We'll use SoftwareSerial to communicate with the XBee:

#include <SoftwareSerial.h>

//For Atmega328P's
// XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX)
SoftwareSerial XBee(2, 3); // RX, TX

//For Atmega2560, ATmega32U4, etc.
// XBee's DOUT (TX) is connected to pin 10 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 11 (Arduino's Software TX)
//SoftwareSerial XBee(10, 11); // RX, TX


//Declare character 'c_data'
char c_data;

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

/*******************Setup Loop***************************/
void setup() {
  // put your setup code here, to run once:

  //Declare pin modes
  pinMode (status_LED, OUTPUT);//LED to indicate when character has been sent

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

  //Declare serial connections for debugging
  Serial.begin(9600);
  Serial.println("Arduino Serial Ready");

  XBee.begin(9600);
  Serial.println("XBee Ready to Receive");

}//end setup()

void loop() {

  //Check if XBee is receiving data from other XBee

  if (XBee.available() || Serial.available()) {
    if (XBee.available()) {
      c_data = XBee.read();//store received value from XBee into variable

    }

    else if (Serial.available()) {
      c_data = Serial.read();//store received value from Serial Monitor into variable

    }

    //Check to see if character sent is letter A
    if (c_data == 'A') {
      digitalWrite(status_LED, HIGH); //turn ON Status LED
      Serial.println("Character Received, ");
      Serial.println(c_data);
    }

    else {
      //do nothing
    }
  }
  delay(100);
  digitalWrite(status_LED, LOW); //turn OFF Status LED

}//end loop()

What You Should See

After uploading, touch the metal snap pins between your thumb and middle finger. This should send one character from the glove to the receiving XBee. As a result, the LED on the glove will stay on as long as the button is pressed. The receiving XBee's LED will blink whenever a character is received. As part of the design, we'll only send a character once when the button press. To send another character, move your thumb away from the middle finger and then touch the metal snap pins together again.

Glove Wirelesly Controlling an LED

Example 2: Controlling an RGB LED

Example 2a: RGB Wireless Glove Controller

We'll build on the first example and have the glove a send character to control an RGB LED. We'll use the snappable pins on the ring and pinky to switch between the colors.

Copy the code, paste it into the Arduino IDE, select your board (Arduino Uno), and COM port. Make sure to switch the COM port back what the glove enumerated to before uploading. When ready, upload the code to the glove.

language:c
// We'll use SoftwareSerial to communicate with the XBee:

#include <SoftwareSerial.h>

//For Atmega328P's
// XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX)
SoftwareSerial XBee(2, 3); // RX, TX

//For Atmega2560, ATmega32U4, etc.
// XBee's DOUT (TX) is connected to pin 10 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 11 (Arduino's Software TX)
//SoftwareSerial XBee(10, 11); // RX, TX


//SEND Button
const int button1Pin = 4; //push button
const int status_LED = 13;  //LED on the push button

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

//initialize variables to read buttons
int button1State;

//variables to check for button1 state
boolean prev_button1State = false;
boolean current_button1State = false;

//UP Button
const int button2Pin = 11; //push button

int button2State;
boolean prev_button2State = false;
boolean current_button2State = false;

//DOWN Button
const int button3Pin = 12;

int button3State;
boolean prev_button3State = false;
boolean current_button3State = false;

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

int pattern = 0; //pattern

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

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

  pinMode(button2Pin, INPUT_PULLUP); //use internal pullup resistor
  pinMode(button3Pin, INPUT_PULLUP); //use internal pullup resistor

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

  // initialize the digital pins as an output for LEDs
  pinMode(ledR, OUTPUT);
  pinMode(ledG, OUTPUT);
  pinMode(ledB, OUTPUT);

  sequenceTest();//visually initialization

  //Declare serial connections for debugging
  Serial.begin(9600);
  Serial.println("Arduino Serial Ready");

  XBee.begin(9600);
  Serial.println("Glove Controller's XBee Ready to Communicate");

}//end setup()

void loop() {

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

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

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

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

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

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

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

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

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

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

  delay(50);

  //save send character into variable depending on button press and change status LED
  switch (pattern) {
    case 1:
      redON();
      delay(50);
      send_CHAR = 'B';
      break;
    case 2:
      magentaON();
      delay(50);
      send_CHAR = 'C';
      break;
    case 3:
      blueON();
      delay(50);
      send_CHAR = 'D';
      break;
    case 4:
      cyanON();
      delay(50);
      send_CHAR = 'E';
      break;
    case 5:
      greenON();
      delay(50);
      send_CHAR = 'F';
      break;
    case 6:
      yellowON();
      delay(50);
      send_CHAR = 'G';
      break;
    case 7:
      allOFF();
      delay(50);
      send_CHAR = 'H';
      break;
    default:
      allON();
      send_CHAR = 'A';
      break;
  }//end switch


}//end loop()

/*
  Check out the Venn Diagram on Basic Color Mixing:
  https://learn.sparkfun.com/tutorials/lilypad-protosnap-plus-activity-guide/2-basic-color-mixing

*/

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

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

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

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

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

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

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

void allON() {//white
  analogWrite(ledR, 150);
  analogWrite(ledG, 255);
  analogWrite(ledB, 255);
}

void sequenceTest() {

  redON();
  delay(50);
  allOFF();
  delay(50);

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

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

  cyanON();
  delay(50);
  allOFF();
  delay(50);

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

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

  allON();
  delay(50);
  allOFF();
  delay(50);
}

Example 2b: RGB Receiving XBee Node

In this part of the example, we'll mimic the color being sent from the glove. Copy the code, paste it into the Arduino IDE, select your board (Arduino Uno), and COM port. Make sure to switch the COM port back to the receiving XBee's Arduino before uploading. When ready, upload the code to the receiving XBee's Arduino.

language:c
// We'll use SoftwareSerial to communicate with the XBee:

#include <SoftwareSerial.h>

//For Atmega328P's
// XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX)
SoftwareSerial XBee(2, 3); // RX, TX

//For Atmega2560, ATmega32U4, etc.
// XBee's DOUT (TX) is connected to pin 10 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 11 (Arduino's Software TX)
//SoftwareSerial XBee(10, 11); // RX, TX


//Declare character 'c_data'
char c_data;

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

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

/*******************Setup Loop***************************/
void setup() {
  // put your setup code here, to run once:

  //Declare pin modes
  pinMode (status_LED, OUTPUT);//LED to indicate when character has been sent

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


  // initialize the digital pins as an output for LEDs
  pinMode(ledR, OUTPUT);
  pinMode(ledG, OUTPUT);
  pinMode(ledB, OUTPUT);

  sequenceTest();//visually initialization

  //Declare serial connections for debugging
  Serial.begin(9600);
  Serial.println("Arduino Serial Ready");

  XBee.begin(9600);
  Serial.println("XBee Ready to Receive");

}//end setup()

void loop() {

  //Check if XBee is receiving data from other XBee

  if (XBee.available() || Serial.available()) {
    if (XBee.available()) {
      c_data = XBee.read();//store received value from XBee into variable

    }

    else if (Serial.available()) {
      c_data = Serial.read();//store received value from Serial Monitor into variable

    }

    //Check to see if character sent is letter A
    if (c_data == 'A') {
      digitalWrite(status_LED, HIGH); //turn ON Status LED
      allON();
      Serial.println("Character Received, ");
      Serial.println(c_data);
    }

    else if (c_data == 'B') {
      digitalWrite(status_LED, HIGH); //turn ON Status LED
      redON();
      Serial.println("Character Received, ");
      Serial.println(c_data);
    }

    else if (c_data == 'C') {
      digitalWrite(status_LED, HIGH); //turn ON Status LED
      magentaON();
      Serial.println("Character Received, ");
      Serial.println(c_data);
    }

    else if (c_data == 'D') {
      digitalWrite(status_LED, HIGH); //turn ON Status LED
      blueON();
      Serial.println("Character Received, ");
      Serial.println(c_data);
    }

    else if (c_data == 'E') {
      digitalWrite(status_LED, HIGH); //turn ON Status LED
      cyanON();
      Serial.println("Character Received, ");
      Serial.println(c_data);
    }
    else if (c_data == 'F') {
      digitalWrite(status_LED, HIGH); //turn ON Status LED
      greenON();
      Serial.println("Character Received, ");
      Serial.println(c_data);
    }
    else if (c_data == 'G') {
      digitalWrite(status_LED, HIGH); //turn ON Status LED
      yellowON();
      Serial.println("Character Received, ");
      Serial.println(c_data);
    }
    else if (c_data == 'H') {
      digitalWrite(status_LED, HIGH); //turn ON Status LED
      allOFF();
      Serial.println("Character Received, ");
      Serial.println(c_data);
    }
    else {
      //do nothing
    }
  }

  delay(100);
  digitalWrite(status_LED, LOW); //turn OFF Status LED

}//end loop()

/*
  Check out the Venn Diagram on Basic Color Mixing:
  https://learn.sparkfun.com/tutorials/lilypad-protosnap-plus-activity-guide/2-basic-color-mixing

*/

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

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

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

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

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

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

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

void allON() {//white
  analogWrite(ledR, 150);
  analogWrite(ledG, 255);
  analogWrite(ledB, 255);
}

void sequenceTest() {

  redON();
  delay(50);
  allOFF();
  delay(50);

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

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

  cyanON();
  delay(50);
  allOFF();
  delay(50);

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

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

  allON();
  delay(50);
  allOFF();
  delay(50);
}

What You Should See

By using the thumb to make contact with either the ring and pinky's snappable pin, the RGB LED will switch between colors. Pressing on the thumb and middle finger will send a character associated with the RGB LED. The receiving XBee should mimic the color of the RGB LED whenever a character is sent.

Glove Wirelessly Controlling an RGB LED

Resources and Going Further

Need some inspiration for your next project? Check out some of these related tutorials to add more functionality for your wireless glove!

Flex Sensor Hookup Guide

An overview of the flex sensor - a bendable variable resistor. Plus, example circuits and Arduino code to get you started!

LilyPad Vibe Board Hookup Guide

The LilyPad Vibe Board is a small vibration motor that can be sewn into projects with conductive thread and controlled by a LilyPad Arduino. The board can be used as a physical indicator on clothing and costumes for haptic feedback.

Qwiic Flex Glove Controller Hookup Guide

Is your finger bent? Is your finger straight? The Qwiic Flex Glove controller board will answer this age old question for you with the flex sensor!
New!

Wireless Gesture Controlled Robot

Control the RedBot wirelessly based on the movement of your hand using an accelerometer, Arduino, and XBees!

Looking for more examples of data gloves? Check out the various gloves from Kobakant.

Example Gloves from Kobakant
Various E-Textile Data Glove Projects Courtesy of Kobakant

Or check out some of these blog posts for ideas:


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

Wireless Gesture Controlled Robot

$
0
0

Wireless Gesture Controlled Robot a learn.sparkfun.com tutorial

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

Introduction

Control the RedBot wirelessly based on the movement of your hand using an accelerometer and XBees!

Full Demo

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 wire, wire strippers, a soldering iron, solder, and general soldering accessories.

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

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

PRT-11367
$16.95
29
Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

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

Solder Lead Free - 15-gram Tube

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

Wire Strippers - 20-30AWG

TOL-14763
$14.95
2

You Will Also Need

  • Glove
  • Scissors
  • Non-Conductive Thread

Suggested Reading

If you aren’t familiar with the following concepts, we recommend checking out these tutorials before continuing. This tutorial continues on from the Wireless Glove Controller and Wireless RC Robot with Arduino and XBees tutorials. Make sure to check through guides.

New!

Wireless Glove Controller

April 24, 2019

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

Wireless RC Robot with Arduino and XBees

March 12, 2019

In this tutorial, we will expand on the SIK for RedBot to control the robot wirelessly with XBee radios! We'll explore a different microcontroller and wirelessly control the RedBot at a distance.

Accelerometer Basics

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

XBee Shield Hookup Guide

How to get started with an XBee Shield and Explorer. Create a remote-control Arduino!

Assembly Guide for RedBot with Shadow Chassis

Assembly Guide for the RedBot Kit. This tutorial includes extra parts to follow to go along with the RedBot Inventor's Kit tutorial.

Exploring XBees and XCTU

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

Experiment Guide for RedBot with Shadow Chassis

This Experiment Guide offers nine experiments to get you started with the SparkFun RedBot. This guide is designed for those who are familiar with our SparkFun Inventor's Kit and want to take their robotics knowledge to the next level.

Understanding Your Circuit

Wireless Glove Controller

The connection for this project should be the same as the initial circuit. The only differences are the connections for the accelerometer and analog reference pin as shown in the diagram below.

Wireless Gesture Controller Circuit Diagram

Analog Accelerometer

Since the ADXL335 requires 3.3V, we'll need to connect the VCC pin to 3.3V. To complete the connection for power, you will need to connect GND to GND. Then for the x, y, and z pins, you'll need to connect them to pin 2, 1, and 0, respectively.

Configuring AREF

Since the ADXL335 is 3.3V, we'll need to connect the Arduino's AREF pin to the 3.3V pin. This will configure the reference voltage used for the analog output from the accelerometer. As a result, we can measure smaller voltages (i.e. your 3.3V output) with the best resolution on a 5V Arduino.

Assembled Shadow Chassis

We'll assume that you have a fully assembled robot with the Shadow Chassis.

Assembly Guide for RedBot with Shadow Chassis

May 28, 2015

Assembly Guide for the RedBot Kit. This tutorial includes extra parts to follow to go along with the RedBot Inventor's Kit tutorial.

Hardware Hookup

Modify the XBee Shield

Adding on to the glove that was built in the Wireless Glove Controller tutorial, remove the tape and disconnect the braided wire from the shield. Then pull the XBee shield off the RedBoard.

Top View v1 Glove

Using the circuit diagram with the accelerometer, solder the ADXL335 breakout board to the shield. In this case, female headers were used with male headers soldered on the breakout. Then strip solid core, hook-up wire and solder them between the pins. If you are following along, your board should look similar to the images below. When you are ready, stack the board back on top of the RedBoard and secure the battery.

Top View of Components Soldered on XBee ShieldBottom View with Wires and Jumpers
Top View of Components Soldered on XBee ShieldBottom View with Wires and Jumpers

Configuring XBees

To configure the XBees, we will be using the XBee Series 1 firmware. It is recommended to configure each XBee using the XBee Explorer USB.

XBee Inseted int XBee Explorer USB to Configure

If you have not already, check out the Starting with XCTU section under Exploring XBees and XCTU to configure your XBees.

Exploring XBees and XCTU

March 12, 2015

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

Point-to-Point Configuration

For simplicity, we will be sending commands with the XBees in transparent mode set for a point-to-point configuration. Make sure to configure each XBee with a unique MY address if there are more than two XBees in your CH and PAN ID. You will then need to adjust the DL address for each respective XBee.

SettingAcronymTransmitting XBee Node 1
(Wireless Glove Controller)
Receiving XBee Node 2
(Robot)
ChannelCHCC
PAN IDID33333333
Destination Address HighDH00
Destination Address LowDL10
16-bit Source AddressMY01

Setting Up Arduino

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.

RedBot Mainboard

FTDI Drivers

Remember, to program your robot, you will first need to install some FTDI drivers. Follow the steps in How to Install FTDI Drivers to do so. This is also explained in the RedBot Guides.

How to Install FTDI Drivers

June 4, 2013

How to install drivers for the FTDI Basic on Windows, Mac OS X, and Linux.

Arduino Library

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

Make sure to install the RedBot library as explained in the RedBot Library Quick Reference. You'll also find the quick overview of the RedBot Library, classes, methods, and variables.


Example

Wireless Glove Code

In this part of the example, we'll have the glove send a character when the thumb and middle finger make contact. As long as the two fingers have contact, the robot will move forward, forward-left, back, or forward -right based on the orientation of your hand. When the custom button is not pressed, the buzzer will make a familiar 8-bit sound when waving your hand or "jabbing" the air. The RGB LED will light up based on the mode and orientation of the hand.

Copy the code, paste it into the Arduino IDE, select your board (Arduino/Genuino Uno), and COM port. Then upload the code to the glove.

language:c
// We'll use SoftwareSerial to communicate with the XBee:

#include <SoftwareSerial.h>

//For Atmega328P's
// XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX)
SoftwareSerial XBee(2, 3); // RX, TX

//For Atmega2560, ATmega32U4, etc.
// XBee's DOUT (TX) is connected to pin 10 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 11 (Arduino's Software TX)
//SoftwareSerial XBee(10, 11); // RX, TX

//set analog read pins
const int xPin = 2;//x=A2
const int yPin = 1;//y=A1
const int zPin = 0;//z=A0

//read the analog values from the accelerometer
int xRead = analogRead(xPin);
int yRead = analogRead(yPin);
int zRead = analogRead(zPin);

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

//Accelerate Button
#define ACCELERATE_BUTTON 4 // Pin used for accelerate button
const int ledPin1 = 13;  //LED on the push button

boolean current_buttonACCELERATE_State;

void setup() {
  // initialize the digital pins as an output for LEDs
  pinMode(ledPin1, OUTPUT);
  pinMode(ledR, OUTPUT);
  pinMode(ledG, OUTPUT);
  pinMode(ledB, OUTPUT);

  analogReference(EXTERNAL);//reference 3.3V since using 3.3V accelerometer

  pinMode(ACCELERATE_BUTTON, INPUT_PULLUP); // Enable pullup resistor for accelerate button D2

  // Set up both ports at 9600 baud. This value is most important
  // for the XBee. Make sure the baud rate matches the config
  // setting of your XBee.
  XBee.begin(9600);

  for (int i = 0; i < 3; i++) {
    digitalWrite(ledPin1, HIGH);
    delay(50);
    digitalWrite(ledPin1, LOW);
    delay(50);
  }
  sequenceTest();//visually initialization

  Serial.begin(9600);
  Serial.println("Wireless XBee Glove Controller Initialized");
}

void loop() {

  current_buttonACCELERATE_State = digitalRead(ACCELERATE_BUTTON);


  //Read accelerometer axes using through the ADC
  //Note: Check description at top for results based on Accelerometer Mode's Features
  xRead = analogRead(xPin);
  Serial.print("Analog xPin (A2) = ");
  Serial.println(xRead);
  yRead = analogRead(yPin);
  Serial.print("Analog yPin (A1) = ");
  Serial.println(yRead);
  zRead = analogRead(zPin);
  Serial.print("Analog zPin (A2) = ");
  Serial.println(zRead);
  Serial.println("");
  //delay(500); //slow down the print to read, adjust as necessary for testing

  if (current_buttonACCELERATE_State == LOW) {
    if (xRead < 430) {
      Serial.print("Drive Forward, xRead = ");
      Serial.println(xRead);
      Serial.println('A');

      XBee.write('A');
      greenON();
    }
    else if (xRead > 590) {
      Serial.print("Drive Backward, xRead = ");
      Serial.println(xRead);
      Serial.println('C');

      XBee.write('C');
      blueON();
    }
    else if (yRead > 590) {
      Serial.print("Drive Forward Right, yRead = ");
      Serial.println(yRead);
      Serial.println('B');

      XBee.write('B');
      cyanON();
    }
    else if (yRead < 430) {
      Serial.print("Drive Forward Left, yRead = ");
      Serial.println(yRead);
      Serial.println('D');

      XBee.write('D');
      cyanON();
    }
    else {
      Serial.println("Coast");
      Serial.println('J');

      XBee.write('J');
      magentaON();
    }

  }
  else {
    if (xRead > 670) {

      Serial.println("Coin Sound, xRead = ");
      Serial.println(xRead);
      Serial.println('X');

      XBee.write('X');
      allOFF();
      delay(50);
      yellowON();
      delay(50);
    }
    if (zRead < 400) {

      Serial.println("Fireball Sound, zRead = ");
      Serial.println(zRead);
      Serial.println('Y');

      XBee.write('Y');
      redON();
      delay(50);
      allOFF();
      delay(50);
      redON();
      delay(50);
      allOFF();
      delay(50);

    }
    else {
      Serial.println("Stop");
      Serial.println('K');

      XBee.write('K');
      redON();
      delay(750);
    }
  }

  //show that we are sending a character
  digitalWrite(ledPin1, HIGH);
  delay(50);
  digitalWrite(ledPin1, LOW);
  delay(50);
}//end loop

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

void allON() {
  analogWrite(ledR, 150);
  analogWrite(ledG, 255);
  analogWrite(ledB, 255);
}

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

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

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

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

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

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

void sequenceTest() {
  redON();
  delay(50);
  magentaON();
  delay(50);
  blueON();
  delay(50);
  cyanON();
  delay(50);
  greenON();
  delay(50);
  yellowON();
  delay(50);
  allON();
  delay(50);
  allOFF();
  delay(50);
}

Receiving XBee Robot Code

The commands to control the RedBot should be the same code that was used in the last example of the Wireless RC Robot with Arduino and XBees tutorial. Head over to Experiment 4.2: Adding Audio with the ATmega328P to upload code to the RedBot mainboard if you have not already.

What You Should See

After uploading, touch the metal snap pins between your thumb and middle finger to move the robot forward-left, forward, forward-right, or backward. The RGB LED will light up based on the orientation of your hand. Separate your fingers and punch the air as if there is a question mark block above you to hear coin sound effect! Wave your hand to see if you can make a fireball sound effect!

Full Demo of Glove Controlling Robot

Resources and Going Further

Need some inspiration for your next project? Check out some of these related tutorials to add more functionality for your wireless glove!

Flex Sensor Hookup Guide

An overview of the flex sensor - a bendable variable resistor. Plus, example circuits and Arduino code to get you started!

LilyPad Vibe Board Hookup Guide

The LilyPad Vibe Board is a small vibration motor that can be sewn into projects with conductive thread and controlled by a LilyPad Arduino. The board can be used as a physical indicator on clothing and costumes for haptic feedback.

Qwiic Flex Glove Controller Hookup Guide

Is your finger bent? Is your finger straight? The Qwiic Flex Glove controller board will answer this age old question for you with the flex sensor!

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

Keyboard Shortcut, Qwiic Keypad

$
0
0

Keyboard Shortcut, Qwiic Keypad a learn.sparkfun.com tutorial

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

Introduction

You may not realize it, but you probably often use keyboard shortcuts for common tasks that, otherwise, were previously extremely monotonous. A perfect example of these shortcuts are the Cut, Copy, and Paste commands, which are almost universally used in every computer application today. Originally, people used to cut (with special scissors) and paste these changes manually.

In this guide, we will cover how to utilize the RedBoard Turbo to emulate an HID keyboard that responds to inputs from the Qwiic Keypad to create your own custom shortcut keypad. This is perfect for gaming hotkeys, keyboard shortcuts that require more than two button combinations, or for command line/data/text entries.

Hotkey Keypad

This will be similar to the Enginursday Blog Post: Pressing Our Buttons, but without the complex soldering. Although not necessary, it would be good to review the blog post.

Please be aware that the example code below is written to run explicitly on Windows 10.
  • You can use previous Windows operating systems- If you get around the issue that the SparkFun SAMD21 driver for the RedBoard Turbo is NOT currently supported on Windows OS prior to Win 8.
  • You can use previous Mac OS- If you modify the code for the appropriate Mac OS keycodes.

Required Materials

For this project, you will need the following products. You may already have a few of these items, so feel free to modify your cart based on your needs.

SparkFun RedBoard Turbo - SAMD21 Development Board

SparkFun RedBoard Turbo - SAMD21 Development Board

DEV-14812
$24.95
1
Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
SparkFun Qwiic Keypad - 12 Button

SparkFun Qwiic Keypad - 12 Button

COM-15290
$9.95

Suggested Reading

If you haven't already gone through the hookup guides for each of these parts, we highly suggest starting off there to understand the basic functionality of each board:

New!

Qwiic Keypad Hookup Guide

If you are tired of taking up GPIO pins, wiring a bunch of pull up resistors, and using firmware that scans the keys taking up valuable processing time... check out the new Qwiic Keypad.

RedBoard Turbo Hookup Guide

An introduction to the RedBoard Turbo. Level up your Arduino-skills with the powerful SAMD21 ARM Cortex M0+ processor!

For a better understanding of how example codes work, please review the following references for the platform you are interested in:

Project Overview

In this example project, we will be focusing on three different types of shortcuts that will probably be the most useful for readers.

Button Combinations

These are shortcuts that require a combination of buttons. This is not just limited to easy ones like Ctrl + x that you may use often. Often in program applications, there will be a number of shortcut button combinations available for users. These shortcuts may even use combinations of +3 buttons or may not always seem intuitive.

Win10/Linux:

  • Ctrl + Alt + F1: Used to switch between virtual desktops.

Force Quit Application

  • Win 10: Ctrl + Alt + Esc
  • Mac OSX: + Option + Esc

Microsoft Excel:

  • Ctrl + Shift + U: Expand or collapse the formula bar
  • Alt + F8: Create, run, edit, or delete a macro
  • Alt + F11: Open the Microsoft Visual Basic For Applications Editor
  • Alt + H + D + C: Delete column
  • Alt + H + H: Select a fill color
  • Alt + H + B: Add a border

Functional Buttons

These are consumer functions or multimedia buttons available on modern keyboards. Usually these buttons have special icons and may lie outside the normal keyboard layout. (If inside the keyboard layout, they may require special buttons like Fn.)

Example Functions: Web Search , Volume Up/Down , Mute , Calculator, or Increase/Decrease Screen Brightness.

Text Strings

Text strings, these may be things that you must commonly write everyday. Think of it as a quick type or saved clipboard. Essentially, these buttons will automatically generate keyboard entries for saved text strings.

For example, I am in charge of writing tutorials and hookup guides and often I need to create HTML features like the ones listed below. I have most of them memorized, but it still takes a few seconds to type everything out. We'll use the HTML table as an example for the one of the buttons code below.

HTML Ordered List:

Example:
Code:
  1. Thing A
  2. Thing B
  3. Thing C
<ol>
    <li>Thing A</li>
    <li>Thing B</li>
    <li>Thing C</li>
</ol>

HTML Table:

Example:
Code:
A
B
C
BC
123
*+=
<table border="1">
    <tr style="padding:10px">
        <td width="25%" style="padding:10px">
            A<br>
            B<br>
            C
        </td>
        <td width="25%" style="padding:10px" valign="center">B</td>
        <td width="25%" style="padding:10px" valign="top">C</td>
    </tr>
    <tr>
        <td style="padding:1px">1</td>
        <td style="padding:10px">2</td>
        <td style="padding:5px">3</td>
    </tr>
    <tr>
        <td>*</td>
        <td>+</td>
        <td>=</td>
    </tr>
</table>

HTML Alerts or Wells:

Example:
Heads up! This is some kind of warning.
Code:
<div class="alert alert-warning"><b>Heads up!</b> This is some kind of warning.</div>

Hardware Assembly

Note: Don't forget to install the SAMD21 driver for the RedBoard Turbo, if necessary.

With the Qwiic connector system, assembling the hardware is simple. All you need to do is connect your Qwiic Keypad to a RedBoard Turbo with a Qwiic cable.

Hardware assembly

If you wish to create a custom enclosure, this can easily be done with a laser cutter and or 3D printer. For custom button faces, you can use printable stickers or some paper and glue.

Example stickers
Stickers
Stickers on Keypad
Stickers on keypad. (Click to enlarge)

Arduino Example

Note: This tutorial assumes you are familiar with Arduino products and 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.

Arduino Library

The easiest way to install the Arduino libraries are by searching SparkFun Qwiic Keypad and HID-Project inside the Arduino library manager. To manually install, head on over to their respective GitHub repositories:

or feel free to download the libraries below:

Using the Qwiic Keypad Library

The functionality of the Qwiic Keypad library is pretty straight forward. The example code, primarily draws from the Example1_ReadButton.ino sketch. Below is a quick summary of the library functions that are used in the example code.

  • keypad1.begin()- Used to connect to Qwiic Keypad.
  • keypad1.updateFIFO()- Used to increment the FIFO.
  • char button = keypad1.getButton()- Used to read button press from FIFO with value stored as a character in the variable button.

Using the HID-Project Library

The HID-Project library, built by NicoHood work similarly to the Arduino Keyboard library. It is also compatible with the original key definitions, just make sure you use the name, not the number. (i.eKeyboard.write(0xB0)will not work, useKeyboard.write(KEY_RETURN)instead.)

Button Combinations

To create shortcut using button combinations, find out the button combination for your shortcut. These should be listed in the user manual for your program or operating system; otherwise, the internet is a great resource. Make sure to test that the shortcut works before programming it.

To code your shortcut in Arduino, use the Keyboard.press(Define_Key) function, designating the individual key. To press multiple keys together, call this function again while designating each of the individual keys. Then use Keyboard.releaseAll() to release all the keys pressed at once. Please refer to the ImprovedKeylayouts.h header file from the HID-Project library for the naming convention (or keycode) of each keyboard key.

Example: Ctrl + Alt + F1

Code:

language:c
Keyboard.press(KEY_CTRL);
Keyboard.press(KEY_F1);
Keyboard.press(KEY_ALT);
Keyboard.releaseAll();

Functional Buttons

To create a functional shortcut in Arduino, use the Consumer.write(Define_Key) function, designating the functional key to implement. Please refer to the ConsumerAPI.h header file from the HID-Project library for the naming convention (or keycode) of the available keys.

Example:

Code:

language:c
Consumer.write(MEDIA_VOLUME_DOWN);
delay(50);
Keyboard.releaseAll();

Text String

To type out a string of text in Arduino, use the Keyboard.print("Text") or Keyboard.println("Text") function.

Example Text:
<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>
Code:
Keyboard.println("<table border=\"1\">");
Keyboard.println("<tr style=\"padding:10px\">");
Keyboard.println("<td style=\"padding:10px\" valign=\"center\"></td>");
Keyboard.println("<td style=\"padding:10px\" valign=\"center\"></td>");
Keyboard.println("<td style=\"padding:10px\" valign=\"center\"></td>");
Keyboard.println("</tr>");
Keyboard.println("<tr style=\"padding:10px\">");
Keyboard.println("<td style=\"padding:10px\" valign=\"top\"></td>");
Keyboard.println("<td style=\"padding:10px\"></td>");
Keyboard.println("<td style=\"padding:10px\"></td>");
Keyboard.println("</tr>");
Keyboard.println("<tr style=\"padding:10px\">");
Keyboard.println("<td></td>");
Keyboard.println("<td></td>");
Keyboard.println("<td></td>");
Keyboard.println("</tr>");
Keyboard.println("</table>");

Example Code

In the example code below I have implemented specific keyboard shortcuts for my personal needs. You will also notice, that in certain instances, I have combined a series of different shortcuts for greater functionality.

language:c
/*
  Hot-Shortcut KeyPad
  By: Wes Furuya
  SparkFun Electronics
  Date: March 27th, 2019
  License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).

  Feel like supporting our work? Buy a board from SparkFun!
  https://www.sparkfun.com/products/14641
  https://www.sparkfun.com/products/14812

  This sketch allows the RedBoard Turbo to emulate a HID keyboard. The buttons on the Qwiic Keypad are set for
  specific keyboard entries. For more details, please refer to the project guide:
  https://learn.sparkfun.com/tutorials/keyboard-shortcut-qwiic-keypad

*/
//#include "Keyboard.h"
#include "HID-Project.h"
#include <Wire.h>

#include "SparkFun_Qwiic_Keypad_Arduino_Library.h" //Click here to get the library: http://librarymanager/All#SparkFun_keypad
KEYPAD keypad1; //Create instance of this object

void setup(void)
{
//  Initializes serial output
//  SerialUSB is used for debug messages to the serial monitor
  SerialUSB.begin(9600);
  delay(3000);
  SerialUSB.println("Qwiic KeyPad Example");

//  Connects Turbo to the Qwiic Keypad
  if (keypad1.begin() == false)   // Note, using begin() like this will use default I2C address, 0x4B. 
                  // You can pass begin() a different address like so: keypad1.begin(Wire, 0x4A).
  {
    SerialUSB.println("Keypad does not appear to be connected. Please check wiring. Freezing...");
    while (1);
  }
  SerialUSB.print("Initialized. Firmware Version: ");
  SerialUSB.println(keypad1.getVersion());
  SerialUSB.println("Press a button: * to do a space. # to go to next line.");

//  Initializes keyboard functions
  Keyboard.begin();
  Consumer.begin();
}

void loop(void)
{
//  Checks for next keypad press
  keypad1.updateFIFO();  // necessary for keypad to pull button from stack to readable register
  delay(50);
  char button = keypad1.getButton();

  if (button == -1)
  {
    SerialUSB.println("No keypad detected");
    delay(1000);
  }
  else if (button != 0)
  {
    SerialUSB.print(button);
    if (button == '1')
    {
      //Mute Button
      Consumer.write(MEDIA_VOLUME_MUTE);
      Keyboard.releaseAll();
    }
    else if (button == '2')
    {
      //Volume Down
      Consumer.write(MEDIA_VOLUME_DOWN);
      Keyboard.releaseAll();
    }
    else if (button == '3')
    {
      //Volume Up
      Consumer.write(MEDIA_VOLUME_UP);
      Keyboard.releaseAll();
    }
    else if (button == '4')
    {
      //Calculator
      Consumer.write(CONSUMER_CALCULATOR);
      Keyboard.releaseAll();
    }
    else if (button == '5')
    {
      //Used custom shortcut to launch Snipping tool
      //In shorcut properties, set to: Ctrl+Alt+Insert
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_LEFT_ALT);
      Keyboard.press(KEY_INSERT);
      Keyboard.releaseAll();
    }
    else if (button == '6')
    {
      //Windows Button
      Keyboard.press(KEY_LEFT_WINDOWS);
      Keyboard.releaseAll();
      delay(50);

      //Enters "ter" into search
      Keyboard.println("ter");
      delay(50);

      //Presses enter button to select entry
      //On my computer, this is TeraTerm
      Keyboard.press(KEY_ENTER);
      Keyboard.releaseAll();
    }
    else if (button == '7')
    {
      //Cuts selected entry
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_X);
      Keyboard.releaseAll();
      delay(50);

      //Types text
      Keyboard.print("<!-- product_big(");
      delay(50);

      //Pastes entry
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_V);
      Keyboard.releaseAll();
      delay(50);

      //Types text
      Keyboard.println(") -->");
      Keyboard.print("<!-- products_by_id(");
      delay(50);

      //Pastes entry
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_V);
      Keyboard.releaseAll();
      delay(50);

      //Types text
      Keyboard.println("ID1, ID2) -->");
      Keyboard.println("<div class=\"clearfix\"></div>");
    }
    else if (button == '8')
    {
      //Types text
      Keyboard.println("<table border=\"1\">");
      Keyboard.println("<tr style=\"padding:10px\">");
      Keyboard.println("<td style=\"padding:10px\" valign=\"center\"></td>");
      Keyboard.println("<td style=\"padding:10px\" valign=\"center\"></td>");
      Keyboard.println("<td style=\"padding:10px\" valign=\"center\"></td>");
      Keyboard.println("</tr>");
      Keyboard.println("<tr style=\"padding:10px\">");
      Keyboard.println("<td style=\"padding:10px\" valign=\"top\"></td>");
      Keyboard.println("<td style=\"padding:10px\"></td>");
      Keyboard.println("<td style=\"padding:10px\"></td>");
      Keyboard.println("</tr>");
      Keyboard.println("<tr style=\"padding:10px\">");
      Keyboard.println("<td></td>");
      Keyboard.println("<td></td>");
      Keyboard.println("<td></td>");
      Keyboard.println("</tr>");
      Keyboard.println("</table>");
    }
    else if (button == '9')
    {
      //Cuts selected entry
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_X);
      Keyboard.releaseAll();
      delay(50);

      //Types text
      Keyboard.print("<div class=\"alert alert-info\"><b>Note:</b>");
      delay(50);

      //Pastes entry
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_V);
      Keyboard.releaseAll();
      delay(50);

      //Types text
      Keyboard.println("</div>");
    }
    else if (button == '*')
    {
      //Cuts selected entry
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_X);
      Keyboard.releaseAll();
      delay(50);

      //Types text
      Keyboard.print("-> [![alt text](");
      delay(50);

      //Pastes entry
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_V);
      Keyboard.releaseAll();
      delay(50);

      //Types text
      Keyboard.print(")](");
      delay(50);

      //Pastes entry
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_V);
      Keyboard.releaseAll();
      delay(50);

      //Types text
      Keyboard.println(") <-");
      Keyboard.println("
*Caption*
"); } else if (button == '0') { //Cuts selected entry Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_X); Keyboard.releaseAll(); delay(50); //Types text Keyboard.print("<center><a href=\""); delay(50); //Pastes entry Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_V); Keyboard.releaseAll(); delay(50); //Types text Keyboard.print("\"><img src=\""); delay(50); //Pastes entry Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_V); Keyboard.releaseAll(); delay(50); //Types text Keyboard.println("\" alt=\"\"></a></center>"); Keyboard.println("<center><i>Caption</i></center>"); } else if (button == '#') { //Cuts selected entry Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_X); Keyboard.releaseAll(); delay(50); //Types text Keyboard.print("<kbd>"); delay(50); //Pastes entry Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_V); Keyboard.releaseAll(); delay(50); //Types text Keyboard.print("</kbd>"); } else { Keyboard.println(button); } } //Do something else. Don't call your Keypad a ton otherwise you'll tie up the I2C bus delay(25); //25 is good, more is better }

CircuitPython Example

In an effort to utilize the CircuitPython capability of the RedBoard Turbo, I also have included CircuitPython example code. When you plug the RedBoard Turbo into the computer, it should show up as an USB drive. If not, check out the Troubleshooting section below on how to re-install CircuitPython. To upload your code to your board, you must save the python file on the drive that appears when the board is plugged in.

Note: This tutorial assumes you are familiar with Arduino products and CircuitPython. If you need help, please consult the CircuitPython documentation.

Import CircuitPython Libraries

Installing the Libraries

There may be better instructions than these, but this is what I did to get the CircuitPython libraries onto the RedBoard Turbo. You can also download the library directly using the button below.

  1. Go to the Releases tab for the GitHub Repository.
  2. Download the .zip file containing "bundule-3.x-mpy" in the name or click the button below.
  3. Unzip the file.
  4. Copy the lib folder from file onto the board.

Note: The instructions for importing the CircuitPython libraries were confusing for me; I originally ended up downloading the master .zip file, instead of the release .zip file.

Utilizing the Libraries

To utilize the libraries in your code, you need to import them. Below, are the lines used for importing the libraries in the example python code.

language:python
import time
import board
import busio

from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.keycode import Keycode
from adafruit_hid.consumer_control import ConsumerControl
from adafruit_hid.consumer_control_code import ConsumerControlCode

Implementing CircuitPython

Querying the Keypad

Using the description of the FIFO operation from the Qwiic Keypad hookup guide, the Qwiic Keypad utilizes two registers for querying button presses. The first is register 0x03, that is read for the oldest entry in the FIFO (first-in, first-out) stack. The second is the FIFO increment command register, 0x06, used to update register 0x03 with the next button value.

Setup for I2C

To setup your I2C connection, you need to import the following libraries. You also need to define the pins used for the I2C bus, which was built into the board library for the SAMD21 used on the Turbo. Finally, the I2C address for the Qwiic Keypad was store as a variable.

language:python
import time
import board
import busio

i2c = busio.I2C(board.SCL, board.SDA)
i2caddress = 75 #equals 0x4B in HEX
Read Register

The following code is used to read the value of the oldest button press out of the FIFO stack from register 0x03.

language:python
i2c.writeto(i2caddress, bytes([0x03]), start=0, end=8, stop=True)
time.sleep(.2)
i2c.readfrom_into(i2caddress, result2, start=0, end=1)
Write/Set Register

The following code is used to write 0x01 to register 0x06 to increment the FIFO stack, updating the value stores in register 0x03.

language:python
i2c.writeto(i2caddress, bytes([0x06,0x01]), start=0, end=16, stop=True)

Creating Shortcuts

Utilizing HID Library

The CircuitPython HID library works similarly to the Arduino library used in the previous section. To reference keycodes and naming conventions I used a combination of the following documentation:

Button Combinations

To create shortcut using button combinations, find out the button combination for your shortcut. These should be listed in the user manual for your program or operating system; otherwise, the internet is a great resource. Make sure to test that the shortcut works before programming it.

To code your shortcut in CircuitPython, use the kbd.press(Define_Key) function, designating the individual key. To press multiple keys together, call this function again while designating each of the individual keys. Then use kbd.release_all() to release all the keys pressed at once. Please refer to the documentation listed above for the naming convention (or keycode) of each keyboard key.

Example: Ctrl + Alt + F1

Code:

language:python
kbd.press(Keycode.CONTROL)
kbd.press(Keycode.ALT)
kbd.press(Keycode.INSERT)
kbd.release_all()

Functional Buttons

To create a functional shortcut in CircuitPython, use the cc.send(Define_Key) function, designating the functional key to implement. Please refer to the documentation listed above for the naming convention (or keycode) of the available keys.

Example:

Code:

language:python
cc.send(ConsumerControlCode.VOLUME_DECREMENT)

Text String

To type out a string of text in CircuitPython, use the layout.write('Text') function.

Example Text:
<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>
Code:
layout.write('<table border="1">\n')
layout.write('    <tr style="padding:10px">\n')
layout.write('        <td style="padding:10px" valign="center"></td>\n')
layout.write('        <td style="padding:10px" valign="center"></td>\n')
layout.write('        <td style="padding:10px" valign="center"></td>\n')
layout.write('    </tr>\n')
layout.write('    <tr style="padding:10px">\n')
layout.write('        <td style="padding:10px" valign="top"></td>\n')
layout.write('        <td style="padding:10px"></td>\n')
layout.write('        <td style="padding:10px"></td>\n')
layout.write('    </tr>\n')
layout.write('    <tr style="padding:10px">\n')
layout.write('        <td></td>\n')
layout.write('        <td></td>\n')
layout.write('        <td></td>\n')
layout.write('    </tr>\n')
layout.write('</table>\n')

Example Code

In the example code below I have implemented specific keyboard shortcuts for my personal needs. You will also notice, that in certain instances, I have combined a series of different shortcuts for greater functionality.

Note: Your code must be saved in a file named code.py on the drive that appears when the RedBoard Turbo is plugged into your computer.
language:python
"""   Hot-Shortcut KeyPad
By: Wes Furuya
SparkFun Electronics
Date: March 27th, 2019
License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).

Feel like supporting our work? Buy a board from SparkFun!
https://www.sparkfun.com/products/14641
https://www.sparkfun.com/products/14812

This sketch allows the RedBoard Turbo to emulate a HID keyboard. The buttons on the Qwiic Keypad are set for specific keyboard entries. For more details, please refer to the project guide:
https://learn.sparkfun.com/tutorials/keyboard-shortcut-qwiic-keypad """

import time

import board
import busio

# https:#github.com/adafruit/Adafruit_CircuitPython_Bundle/releases/tag/20190326
# 1. Download "bundule-3.x":
#    https:#github.com/adafruit/Adafruit_CircuitPython_Bundle/releases/download/20190326/adafruit-circuitpython-bundle-3.x-mpy-20190326.zip
# 2. Unzip
# 3. Copy lib folder on to board

from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.keycode import Keycode
from adafruit_hid.consumer_control import ConsumerControl
from adafruit_hid.consumer_control_code import ConsumerControlCode

cc = ConsumerControl()
kbd = Keyboard()
layout = KeyboardLayoutUS(kbd)

i2c = busio.I2C(board.SCL, board.SDA)
i2caddress = 75 #equals 0x4B in HEX
CALCULATOR = 402 #equals 0x192 in HEX

while not i2c.try_lock():
    pass

while True:
    result2 = bytearray(1)
    i2c.writeto(i2caddress, bytes([0x03]), start=0, end=8, stop=True)
    i2c.readfrom_into(i2caddress, result2, start=0, end=1)

    if result2 != bytes([0x00]):
        if result2 == b'1':
            cc.send(ConsumerControlCode.MUTE)
            print(result2)

        elif result2 == b'2':
            cc.send(ConsumerControlCode.VOLUME_DECREMENT)
            print(result2)

        elif result2 == b'3':
            cc.send(ConsumerControlCode.VOLUME_INCREMENT)
            print(result2)

        elif result2 == b'4':
            cc.send(CALCULATOR) #cc.send(402)
            print(result2)

        elif result2 == b'5':
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.ALT)
            kbd.press(Keycode.INSERT)
            kbd.release_all()
            print(result2)

        elif result2 == b'6':
            kbd.send(227) #Windows Button
            time.sleep(.05)
            layout.write('ter')
            time.sleep(.1)
            kbd.send(Keycode.ENTER)
            print(result2)

        elif result2 == b'7':
            # Cuts selected entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.X)
            kbd.release_all()
            time.sleep(.05)

            layout.write('<!-- product_big(')
            time.sleep(.05)

            #Pastes entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.V)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write(') -->\n')
            layout.write('<!-- products_by_id(')
            time.sleep(.05)

            #Pastes entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.V)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write('ID1, ID2) -->\n')
            layout.write('<div class="clearfix"></div>')

        elif result2 == b'8':
            #Types text
            layout.write('<table border="1">\n')
            layout.write('    <tr style="padding:10px">\n')
            layout.write('        <td style="padding:10px" valign="center"></td>\n')
            layout.write('        <td style="padding:10px" valign="center"></td>\n')
            layout.write('        <td style="padding:10px" valign="center"></td>\n')
            layout.write('    </tr>\n')
            layout.write('    <tr style="padding:10px">\n')
            layout.write('        <td style="padding:10px" valign="top"></td>\n')
            layout.write('        <td style="padding:10px"></td>\n')
            layout.write('        <td style="padding:10px"></td>\n')
            layout.write('    </tr>\n')
            layout.write('    <tr style="padding:10px">\n')
            layout.write('        <td></td>\n')
            layout.write('        <td></td>\n')
            layout.write('        <td></td>\n')
            layout.write('    </tr>\n')
            layout.write('</table>\n')

        elif result2 == b'9':
            #Cuts selected entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.X)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write('<div class="alert alert-info"><b>Note:</b>')
            time.sleep(.05)

            #Pastes entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.V)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write('</div>')

        elif result2 == b'*':
            #Cuts selected entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.X)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write('-> [![alt text](')
            time.sleep(.05)

            #Pastes entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.V)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write(')](')
            time.sleep(.05)

            #Pastes entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.V)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write(') <-')
            layout.write('<div class="center-block text-center"> *Caption* </div>')

        elif result2 == b'0':
            #Cuts selected entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.X)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write('<center><a href="')
            time.sleep(.05)

            #Pastes entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.V)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write('"><img src="')
            time.sleep(.05)

            #Pastes entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.V)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write('" alt=""></a></center>')
            layout.write('<center><i>Caption</i></center>')

        elif result2 == b'#':
            #Cuts selected entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.X)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write('<kbd>')
            time.sleep(.05)

            #Pastes entry
            kbd.press(Keycode.CONTROL)
            kbd.press(Keycode.V)
            kbd.release_all()
            time.sleep(.05)

            #Types text
            layout.write('</kbd>')

        else:
            print(result2)

    time.sleep(.05)
    i2c.writeto(i2caddress, bytes([0x06,0x01]), start=0, end=16, stop=True)

Troubleshooting

Drivers

After plugging in your board into the computer, make sure that the drivers for the SAMD21 are installed on your computer. For MAC OSX and Win 10, this should be done automatically once the board is plugged in. I believe this also applies for the more popular flavors of Linux as well.

If needed, you can download the Windows driver using the button below. You can find instructions for this process in the SAMD21 MiniDev Hookup Guide.

Please be aware that the SparkFun SAMD21 driver is NOT currently supported on Windows OS prior to Win 8.

Double-Tapping Into the Bootloader

The bootloader is what allows us to load code over a simple USB interface. If you have bricked your board, try to upload code from bootloader mode. To manually enter bootloader mode, rapidly double-tapping the reset button (after hitting the reset button once, you have about half a second to hit it again). The board will remain in bootloader mode until power cycles (happens automatically after uploading code) or the reset button is hit again (once).

On the Turbo, the there are a clues to if it is in bootloader mode:

  • RGB LED (on Pin 44) will be solid green.
  • The D13 LED indicator will be a solid blue (might fade in and out a little).
  • Charge indicator LED will be flashing constantly.
  • Board will show up under a different COM port.

Dual Serial Ports

One global issue to be aware of is that each SAMD21 Board appears to your computer as two USB devices, and your computer will assign two different port numbers to your SAMD21 Board - one for the bootloader, the other for the sketch.

  • Verify that you are selecting the available serial port for the board.
  • If your computer isn't registering the board try double-tapping it into bootloader mode.

Serial Port Not Appearing in Port Menu

If your SAMD21 board is plugged in -- power LED illuminated -- but it isn't appearing in your Arduino port list, first of all, make sure you have the drivers installed (Windows computers only). Then follow these steps to see if you can get the port back:

  1. Close all Arduino windows. (Don’t forget to save!)
  2. Unplug SAMD21 Board from your computer.
  3. Wait a few seconds for the device to be detached.
  4. Plug SAMD21 Board back in.
  5. Open Arduino back up, check the Ports menu again.

Upload Fails or Freezes

If a sketch upload is taking longer than usual, or fails entirely, try resetting into the bootloader and uploading directly there. If the SAMD21 is in bootloader mode, you may need to re-select your port -- this time selecting the bootloader port.

  • Closing the serial monitor before uploading may also make for more reliable uploading.

Reinstalling CircuitPython

If you do your developing in Arduino, you'll find that after uploading your first sketch, the RedBoard Turbo no longer pops up like a removable USB device as it did previously. That's to be expected. In this section we'll walk through a few simple steps to getting CircuitPython re-uploaded onto your RedBoard Turbo.

  1. Reset board to Bootloader

    We want the board to reset to the UF2 bootloader, which enables the board to act like a flash drive. To do that we'll double tap the reset button. Shortly after you do that, the board will pop up as a USB drive named TURBOBOOT.

  2. Download and Drag CircuitPython Firmware

    Download the CircuitPython firmware below (also found in the GitHub product repository). Drag the contents named turbo-boot_cp.uf2 onto your TURBOBOOT USB drive and the USB drive should disappear momentarily only to reappear as a CIRCUITPY USB drive instead.

  3. Re-install the CircuitPython Libraries (to get example code working)

    Download the CircuitPython library bundle below and then drag the lib folder over to the USB drive for the RedBoard Turbo. For more details see the instructions above.

Project Notes

This is the end of the project documentation, excluding the resources linked below. Here are a few notes I had following the completion of the project tutorial.

CircuitPython

Unfortunately, this was my first time using CircuitPython and there was a little confusion getting everything working. Specifically, I am not sure if I implemented the I2C functionality properly (as intended) for CircuitPython, but it worked for the purpose of this project. Feel free to comment below on any changes that should be made.

In my initial attempt to get the Qwiic Keypad running, I was able to read from all the registers. However, I wasn't able to implement a write to set individual register values in a similar fashion using the writeto function. It wasn't until I looked at how the code was operating with a logic analyzer, that I realized that these functions operated at a lower level. Despite being able to read a whole register block, the functions actually were meant for read and write bit operations as demonstrated above.

language:python
try:
    #initial attempt
    result1 = bytearray(8)
    i2c.readfrom_into(i2caddress, result1, start=0, end=7)
    print(result1)
    time.sleep(3)

finally:
    i2c.unlock()

Going Further with Macros

Do you have a repetitive task that you perform daily on your computer that you wish to automate? If you are more computer savy, you may already use or have created your own simple macro for more complex tasks that can't be handled with a mere keyboard shortcut or hotkey. Although we won't cover macros in this guide, they are simple, yet powerful tools.

How simple...

Even a grade schooler, could easily use Microsoft Excel to record a custom macro in VBA.

How powerful...

Macros can perform essentially, almost any function you can with a mouse and keyboard. If you are particularly diabolical, this is an easy way to prank your friends... you could easily create and hide a macro to cause mouse movements or play a particular audio file randomly. However, please be aware of the security risks involved in using macros (see note below).

Danger: When enabled, macros, although useful, may open up your computer to security risks. In the past macros, have been known to be exploited as security flaws to access computers for private information. Please make sure to research the risks thoroughly before using or enabling macros on any computer.

Resources and Going Further

For more information, check out the resources below:

If you haven't already gone through the hookup guides for components used in this project, we highly suggest starting off there to understand the basic functionality of each board:

New!

Qwiic Keypad Hookup Guide

If you are tired of taking up GPIO pins, wiring a bunch of pull up resistors, and using firmware that scans the keys taking up valuable processing time... check out the new Qwiic Keypad.

RedBoard Turbo Hookup Guide

An introduction to the RedBoard Turbo. Level up your Arduino-skills with the powerful SAMD21 ARM Cortex M0+ processor!

Check out other Qwiic products and tutorials here:

New!

Qwiic Keypad Hookup Guide

If you are tired of taking up GPIO pins, wiring a bunch of pull up resistors, and using firmware that scans the keys taking up valuable processing time... check out the new Qwiic Keypad.

Qwiic Flex Glove Controller Hookup Guide

Is your finger bent? Is your finger straight? The Qwiic Flex Glove controller board will answer this age old question for you with the flex sensor!

ESP32 Thing Plus Hookup Guide

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

SparkFun Edge Hookup Guide

Get to know your Edge board, including both the hardware features for you to utilize as well as how to get talking to it.

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

Qwiic Keypad Hookup Guide

$
0
0

Qwiic Keypad Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Keypads are very handy input devices, but who wants to tie up 7 GPIO pins, wire up a handful of pull-up resistors, and write firmware that wastes valuable processing time scanning the keys for inputs? Let’s make the development process easier! The SparkFun Qwiic Keypad comes fully assembled and uses the simple Qwiic interface. No soldering, no voltage translation, no figuring out which I2C pin is SDA or SCL, just plug and go!

SparkFun Qwiic Keypad - 12 Button

SparkFun Qwiic Keypad - 12 Button

COM-15290
$9.95

The Qwiic Keypad reads and stores the last 15 button presses in a First-In, First-Out (FIFO) stack, so you don’t need to constantly poll the keypad from your microcontroller. This information, then, is accessible through the Qwiic interface. Qwiic Keypad even has a software configurable I2C address so you can have multiple I2C devices on the same bus.

Required Materials

The SparkFun Qwiic Keypad does need a few additional items for you to get started; a Qwiic enabled microcontroller and a Qwiic cable. You may already have a few of these items, so feel free to modify your cart based on your needs.

SparkFun Thing Plus - ESP32 WROOM

SparkFun Thing Plus - ESP32 WROOM

WRL-14689
$20.95
3
SparkFun RedBoard Turbo - SAMD21 Development Board

SparkFun RedBoard Turbo - SAMD21 Development Board

DEV-14812
$24.95
1
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
1

Suggested Reading

If you're unfamiliar with 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.

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.

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.
Note: For a greater understanding of how the firmware works to multiplex the keys, check out these tutorials.

Button Pad Hookup Guide

An introduction to matrix scanning, using the SparkFun 4x4 Button Pad.

Multiplexer Breakout Hookup Guide

How to use the 74HC4051 multiplexer breakout to drive eight LEDs, read eight button inputs, or monitor eight potentiometers.

Arduino Kepad Tutorials
Arduino Keypad Library
Arduino Keypad Tutorial

Hardware Overview

Keypad

This is a basic 12 button keypad that has been designed for easy user input and functionality. The buttons are set up in a matrix format. This allows the ATtiny84 to scan the 7 output pins to see which of the 12 buttons are being pressed.

Annotated image of buttons

Each of the keypad's 12 buttons has been labeled 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, *, and # and has been formatted to into the same layout as a telephone keypad. Each keypress resistance ranges between 10 - 150Ω.

Power LED

There is a power status LED to help make sure that your Qwiic Keypad is getting power. You can power the board either through the polarizedQwiic connector system or the breakout pins (PWR 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. Qwiic Keypad is very low power and uses less than 4mA at 3.3V.

Annotated image of Power LED

ATtiny84

With the pre-installed firmware, the ATtiny84 is acts as an intermediary (microcontroller) multiplexing the buttons for inputs. This allows the Qwiic Keypad to store the button presses in the FIFO stack to be read over I2C. Although the ATtiny84 has a wide voltage range, since this is a Qwiic product, users should power the board with the labeled 3.3V.

Annotated image of ATtiny84

First-In, First-Out (FIFO) Stack

In the firmware, the FIFO stack stores the most recent 15 button inputs. Once the stack is full, any previous inputs are overwritten. The FIFO stack is manually incremented using the FIFO Command register. If there are no more values stored in the FIFO stack, the output will be 0x00 or Null.

demonstration of a FIFO
Demonstration of the FIFO: (1) Filling the FIFO stack with inputs, (2) overwriting old inputs, and (3) incrementing & reading the FIFO.
Note: Technically, the FIFO stack is actually a circular buffer that tracks the beginning and end index of the stack.

The condition for a FIFO incrementation is a request event (register is read) after the updateFIFO register has already been set to 0x01.

Order of operations for FIFO incrementation:
  1. Input: Set updateFIFO register to 0x01.
  2. Firmware: Wait for request event.
  3. Input: Create a request event (read a register).
  4. Firmware:
    1. Set updateFIFO register to 0x00.
    2. Increment new index for the FIFO buffer.
    3. Determines the "next button" value.
    4. Calculates time since the "next button" was pressed.
    5. Updates register with new values (for the "next button" and time since the "next button" was pressed).
  5. Input: Wait for next updateFIFO command.

Qwiic and I2C

I2C Address

In the firmware, the Qwiic Keypad’s I2C address is configurable so you can add a bunch of them to the same bus without collision issues.

Factory Default I2C Slave Address: 0x4B

I2C Registers

AddressDescription
0x00Default I2C Slave Address (Stored in EEPROM)
0x01 - 0x02Firmware Version (MSB First)
0x03Oldest Button Press (aka First-Out from FIFO stack)
0x04 - 0x05Time in ms since the button was pressed (MSB First, 16-bit = Max Value of 65,535 ms).
0x06FIFO Increment Command: Set bit 0 to increment FIFO.
0x07Current/Set I2C Slave Address (Write). Stored in EEPROM.

Connections

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

Annotated image of  Qwiic connectors
Qwiic connectors.

However, the board also provides six labeled breakout pins. You can connect these lines to the I2C bus of your microcontroller and power pins (3.3V and GND), if it doesn't have a Qwiic connector. The interrupt and reset pins are also broken out to use for triggered events.

Annotated image of  I2C connections
I2C Connections- The pins are tied to the Qwiic connectors.

Interrupt Pin

The interrupt pin (active low) is used to indicate that there are available entries in the FIFO stack. Effectively, if it is tied to an interrupt on your microcontroller and you are using it to increment the FIFO stack, then it will get triggered every time a button is pressed. The INT pin is pulled up with a 4.7kΩ resistor and will be low if there are entries. The INT pin will return high once the FIFO has been cleared.

Annotated image of interrupt pin

Reset Pin

Reset pin tied to the reset pin on the ATtiny. When pulled low, this will effectively reset the Qwiic Keypad and restart the device, loading the I2C address that was stored in EEPROM. It is mostly, broken out for reprogramming the ATtiny84.

Annotated image of reset pin

Jumpers

There are jumpers on the board allowing the user to select between different I2C addresses as well as to remove the pull up resistors from the I2C pins, if needed.

I2C Address

Bridging the I2C address jumper changes the slave address from the value stored in EEPROM to the I2C Jumper Default (or alternate): 0x4A.

  • Open/Cut: Factory or Set I2C Slave Address: 0x4B (Factory Set) or 0x## (User Set)
  • Bridged: I2C Jumper Default Slave Address: 0x4A (Alternate)

Annotated image of I2C address jumper

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. Not sure how to cut a jumper? Read here!

Annotated image of pullup jumper

Hardware Assembly

With the Qwiic connector system, assembling the hardware is simple. All you need to do is connect your Qwiic Keypad to Qwiic enabled microcontroller with a Qwiic cable. Otherwise, you can use the I2C pins, if you don't have a Qwiic connector on your microcontroller board. Just be aware of your input voltage and any logic level shifting you may need to do.

Example setup with RedBoard Qwiic

Example setup with RedBoard Qwiic.

Arduino Library

Note: This tutorial assumes you are familiar with Arduino products and you 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. If you have not previously installed an Arduino library, please check out our installation guide.

The easiest way to install the Arduino library is by searching SparkFun Qwiic Keypad inside the Arduino library manager. To manually install, head on over to the GitHub repository or feel free to download the library here!

Library Functions

The Arduino library is commented and the functions should be self-explanatory. However, below is a detailed list of the available library functions.

.begin() or .begin(Wire, deviceAddress)
Creates a connection to an I2C device over the I2C bus using the default or specified I2C address.

Input: uint8_t deviceAddress
Unasssigned 8-bit integer for device address. If not defined, the library will use the default I2C address stored in the I2C library (0x4B).
Output: Boolean

True- Connected to I2C device.
False- No device found or connected.

.isConnected()
Tries to connect to the device at the I2C address stored in the library.

Output: Boolean

True- Connected to I2C device.
False- No device found or connected.

.getVersion()
Returns a string of the firmware version number.

Output: String AAA.BBB

AAA - Firmware Version (Major)
BBB - Firmware Version (Minor)

.setI2CAddress(newAddress)
Changes the I2C address to newAddress. Once changed, the new I2C address is saved in the EEPROM of the Qwiic Keypad. Reconnects to device using new I2C address. (The new address is printed out in the Serial Monitor.)

Input: uint8_t newAddress

Unasssigned 8-bit integer for device address.

Output: Serial

Address: 0x##, where 0x## is the new I2C address.
Address Change Failure- Error output if the the microcontroller wasn't able to change the I2C address.
ERROR: Address outside 8-119 range- Error output if the new I2C address is outside the available range.

Caution: Will not work if I2C address jumper is bridged. If the function is able to connect to the device, the library function may change the I2C address stored in EEPROM. However, by default the firmware will stay at the alternate I2C jumper address (0x4A) and the last part of this function won't be able to connect to the keypad for the firmware printout and future I2C address changes.

.getButton()
Returns the button at the top of the stack (aka the oldest button). In order to read this register for the first time, the FIFO needs to be incremented with the .updateFIFO() function first.

Output: byte

Value of the button.

.getTimeSincePressed()
This function reads the register that holds the time since the button (at the top of the FIFO stack) was pressed. In the firmware, the ATtiny85 actually responds to a request event (register read) and calculates the time since the button was pressed at that moment and updated the register. Like the .getButton() function, in order to use this function for the first time, the FIFO needs to be incremented with the .updateFIFO() function first.

Output: uint16_t

Unasssigned 16-bit integer [0 - 65,535] for time since button was pressed (in milliseconds).

Note: Since the time calculation occurs just before all the register values are updated and the time calculation only happens if there is a FIFO increment, the time calculation can only happen once during the first register read. Therefore, calling this function multiple times without a FIFO incrementation will report the same value, which corresponds to the time of the initial register read.

.updateFIFO()
Used to increment the FIFO stack- In the library, this function sets the updateFIFO register to 0x01. Once there is a request event (i.e .getButton() or .getTimeSincePressed()), the FIFO is incremented and the firmware clears the updateFIFO register back to 0x00.

Note: In the firmware, the FIFO isn't incremented until there is a request event (or register read). Therefore, you can't use this function multiple times without a request event, to scroll through the FIFO. Once the FIFO is incremented, the firmware clears the updateFIFO register back to 0x00.

Examples

There are six examples in the Qwiic Keypad Arduino Library to get you started with using Qwiic Keypad. These example files are named with self-explanatory titles, but in case you want more information, see the descriptions below.

  • Example1_ReadButton

    This example connects to the Qwiic Keypad using the default I2C address saved in the library. The sketch loops through reading the register for the button at the top of the FIFO stack and incrementing the FIFO. The example then prints out the value over the Serial Monitor. The * is represented by a space and the # is represented with a new line (or carriage return).

  • Example2_ReadWithTime

    This example operates exactly like the Example1_ReadButton, except the time since the button was pressed is outputted with the button that was pressed in the Serial Monitor. With a ~1 second delay between checks for button presses.

  • Example3_ChangeI2CAddress

    Caution: Will not work if I2C address jumper is bridged.

    This example connects to the Qwiic Keypad using the default I2C address set in the library and then prints out the I2C address and firmware version over the Serial Monitor. The sketch then, takes an input from the Serial Monitor to change the I2C address using a decimal value (DEC). Once the I2C address is changed, it is stored in the EEPROM of the Qwiic Keypad. After, the sketch connects to the keypad using the new I2C address and reads the registers for the firmware version again. The example then prints out those values over the Serial Monitor again.

  • Example4_I2CScanner

    This example is from the I2C scanner example from the Arduino Playground webpage. The sketch scans for devices on the I2C bus and reports them on the Serial Monitor. This is useful for users who have forgotten the changed I2C address of their boards.

  • Example5_InterruptRead

    Note: This example is requires soldering. A wire must be soldered to the INT pin and connected to an interrupt pin on your microcontroller. As written, the example assumes you are using a Arduino UNO based board, like our RedBoard. The sketch designates Pin 2 as the interrupt pin.

    This example operates exactly like the Example1_ReadButton, except that instead of constantly polling the keypad for button presses in the main loop, it responds to the interrupt (INT) pin. Utilizing an interrupt allows the MCU to execute a specific set of instructions (i.e. button read), outside of the main loop. For more details on interrupts, check out this tutorial on Processor Interrupts with Arduino .

  • Example6_Keycode

    This example is a use case example, in which the user must input the correct key code: 1, 2, 3, 4. The sketch also implements a timeout, so that the user must input the correct code within 30 seconds.

Arduino Examples

Example 1: Read Button

The code for Example1_ReadButton connects to the Qwiic Keypad and prints out the value over the Serial Monitor. Below is a sample readout from the Serial Monitor using sequential button presses of: 1, 2, 3, 4, 5, 6, 7, 8, 9, *, 0, and #.

Serial Monitor readout for Example 1

Serial Monitor readout for Example 1.

Example 2: Read with Time

The code for Example2_ReadWithTime operates exactly like the Example1_ReadButton, except the time between since the last button press is printed. Below is a sample readout.

Serial Monitor readout for Example 2

Serial Monitor readout for Example 2.

Example 3: Change I2C Address

Caution: Will not work if I2C address jumper is bridged.

The code for Example3_ChangeI2CAddress connects to the Qwiic Keypad using the default I2C address set in the library and then prints out the I2C address and firmware version over the Serial Monitor. The sketch then, takes an input from the Serial Monitor to change the I2C address using a decimal value (DEC). Once the I2C address is changed, it is stored in the EEPROM of the Qwiic Keypad. After, the sketch connects to the keypad using the new I2C address and reads the registers for the firmware version again. The example then prints out those values over the Serial Monitor again. As shown in the sample readout below, the input value must between 8-119 (DEC) of unreserved I2C addresses.

Serial Monitor readout for Example 3

Serial Monitor readout for Example 3.

Example 4: I2C Scanner

The forth example, Example4_I2CScanner, scans for devices on the I2C bus and reports them on the Serial Monitor. This is useful for users who have forgotten the changed I2C address of their boards.

Serial Monitor readout for Example 4

Serial Monitor readout for Example 4.

Example 5: Read with Interrupt Pin

Note: This example is requires soldering. A wire must be soldered to the INT pin and connected to an interrupt pin on your microcontroller. As written, the example assumes you are using a Arduino UNO based board, like our RedBoard. The sketch designates Pin 2 as the interrupt pin.

The code for Example5_InterruptRead operates similar to Example1_ReadButton, except that instead of constantly polling the keypad for button presses in software, it responds to a hardware trigger on the interrupt (INT) pin. For more details on interrupts, check out this tutorial on Processor Interrupts with Arduino .

Serial Monitor readout for Example 5

Serial Monitor readout for Example 5.

Example 6: Key in Code

The last example, Example6_Keycode, is a use case example, in which the user must input the correct key code: 1, 2, 3, 4.

Serial Monitor readout for Example 6

Serial Monitor readout for Example 6.

Resources and Going Further

For more information, check out the resources below:

Need help getting started with Arduino and I2C? Check out these resources here:

Need some inspiration for your next project? Check out this Hotkey Project, similar to this blog post by ALEX THE GIANT from a few years ago.

Check out some of these other Qwiic product tutorials:

SparkFun Pro nRF52840 Mini Hookup Guide

A hardware overview and hookup guide for the SparkFun Pro nRF52840 Mini -- a breakout for Nordic's impossibly cool Bluetooth/ARM Cortex M4 SoC.

Qwiic Proximity Sensor (VCNL4040) Hookup Guide

The SparkFun Qwiic Proximity Sensor is a great, qualitative proximity (up to 20 cm) and light sensor. This hookup guide covers a few examples to retrieve basic sensor readings.
New!

Qwiic Scale Hookup Guide

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

Keyboard Shortcut, Qwiic Keypad

A simple project using the Qwiic Keypad and the RedBoard Turbo to create your own custom hotkey-pad.

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

Displaying Your Coordinates with a GPS Module

$
0
0

Displaying Your Coordinates with a GPS Module a learn.sparkfun.com tutorial

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

Introduction

What’s better than learning GPS? Learning it Qwiic-ly! Today we will be making a simple project to help get your feet wet with GPS. This project is quick and easy thanks to our Qwiic Connect System. The general idea is to push a button and see your latitude and longitude coordinates. We may be starting simple, but there is certainly room for more advanced users to modify and grow the project!

Software developers start with “Hello World!” and every hardware engineer remembers their first LED circuit, right? So let's fuse the ideas by creating a project that receives a GPS signal and outputs it to a screen for a user. Then we can bump it up by making it mobile. I’ve got just the thing in mind!

project parts image

Required Materials

To follow along with this tutorial, you will need the following materials. You may not need everything, 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.

I2C

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

Qwiic Micro OLED Hookup Guide

Get started displaying things with the Qwiic Micro OLED.

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.
New!

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.

Hardware Overview

We’re using three large components, a 9V battery, and Qwiic cables. Let’s look into the bigger components first before we start.

RedBoard Qwiic

First up, the brains of our project. This development board is an evolution on our classic RedBoard. No change to programming with Arduino, so software is still easy. However, this allows us to streamline Qwiic development without the need for a shield. If you have the classic RedBoard and still want to make this project, arm yourself and grab a shield!

SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95

Qwiic Micro OLED

We will read our coordinates using a simple OLED screen. Our product page describes this component best: “This version of the Micro OLED Breakout is exactly the size of its non-Qwiic sibling, featuring a screen that is 64 pixels wide and 48 pixels tall and measuring 0.66" across.” So we have small but powerful screen and that’s perfect for our purposes.

SparkFun Micro OLED Breakout (Qwiic)

SparkFun Micro OLED Breakout (Qwiic)

LCD-14532
$16.95
1

SAM-M8Q Chip Antenna GPS Breakout

Lastly, we will use a GPS module and we have one perfect for this occasion. This new GPS Breakout brings the ease, quality, and affordability from a great line of GPS modules from u-blox. The biggest feature is hot start and low lock time with a rechargeable coin cell battery. This means we have a powerful, inexpensive GPS that fits in a small space and will do all our talking with the satellites up above!

SparkFun GPS Breakout - Chip Antenna, SAM-M8Q (Qwiic)

SparkFun GPS Breakout - Chip Antenna, SAM-M8Q (Qwiic)

GPS-15210
$39.95

Hardware Hookup

Technically, we only have one component to actually solder - the button switch. Truth be told, you could just use some alligator clips and not even need an iron. We have other colors, but I have a bias to green and I really liked the strength and feel of the metal momentary switch. When we solder the connections to jumper wires that fit the headers on the RedBoard, I’m assuming that you’ve developed some skills soldering. If not, that’s fine. We have a tutorial for that as well. Feel free to head over there and then put those wizard skills to work!

If you are soldering, then you can follow my connections. There are many ways to use switches, but I went for a momentary digital high. That just means that when I push the button the voltage on the digital pin assigned will be up from 0 volts to 3.3 volts. On the bottom of the switch you'll see a '+' and a '-'. These are for the LED backlight, and those will go to 5V and GND respectively. When you angle the button and look at that bottom portion, you'll see a few pin indicators labeled 'C1', 'NC1', and 'NO1'. NC1 and NO1 stand for normally closed and normally open. We'll want to solder C1 and NO1. This combination will give us the digital high when we push the button.

Image of the button and it's pins

Attach the button pins to the RedBoard Qwiic as follows:

Button PinRedBoard Pin
+5V
-GND
C13.3V
NO1Digital Pin 2

The next part for assembly is really simple. Just connect our boards together with our Qwiic cables, order doesn’t really matter!

Your final assembly should look something like this:

Fritzing image of assembly

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

If you want to take the above in steps then you can hook up each component separately to the RedBoard to experiment. If you want to skip it and just throw caution to the wind, then please jump down to final code.

Software Setup

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

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

SparkFun Micro OLED library

First, you'll need to download and install the Sparkfun Micro OLED library. You can install the library via the Arduino Library Manager by searching 'SparkFun Micro OLED Breakout'. Alternatively, you can either grab the library from the GitHub repository or use the button below:

SparkFun U-blox Arduino Library

You will also need to install the Ublox library for the GPS unit. The SparkFun U-blox Arduino library can be downloaded with the Arduino library manager by searching 'SparkFun Ublox' or you can grab the zip here from the GitHub repository:

From the hookup guides, I hope you have a good understanding with how we’re setting this project up. We want to read a GPS location and output our latitude and longitude to the Micro OLED screen so we can see where we’re at. Sounds simple enough. So let’s start with our Qwiic Micro OLED Screen.

Example Code

Micro OLED Code

I’ve modified a snippet of code from our hookup guide for a small test of writing text to the OLED screen. Before it can be used, make sure you've installed the micro OLED library as listed in the Software Setup section above. Copy the code, paste it into the Arduino IDE, select the Arduino/Genuino Uno, and the COM port, and hit upload to test!

language:c
#include <Wire.h>  // Include Wire if you're using I2C
#include <SFE_MicroOLED.h>  // Include the SFE_MicroOLED library

//////////////////////////
// MicroOLED Definition //
//////////////////////////
//The library assumes a reset pin is necessary. The Qwiic OLED has RST hard-wired, so pick an arbitrarty IO pin that is not being used
#define PIN_RESET 9  
//The DC_JUMPER is the I2C Address Select jumper. Set to 1 if the jumper is open (Default), or set to 0 if it's closed.
#define DC_JUMPER 1 

//////////////////////////////////
// MicroOLED Object Declaration //
//////////////////////////////////
MicroOLED oled(PIN_RESET, DC_JUMPER);    // I2C declaration

void setup()
{
  delay(100);
  Wire.begin();
  oled.begin();
  oled.clear(ALL);
  oled.display();
  delay(1000);
  oled.clear(PAGE);
}

void loop(){
  printTest("Lat:-45.97760\nLong:42.91841", 0);
}

void printTest(String title, int font)
{
  oled.clear(PAGE);
  oled.setFontType(font);
  oled.setCursor(0,0);
  oled.print(title);
  oled.display();
  delay(1500);
  oled.clear(PAGE);
}

Once the library is installed we can simply compile and see a dummy text on our screen.

Image of MicroOLED with coordinates

GPS Code

One done, two to go. Next we have our SAM-M8Q GPS module to test. I personally found the Example3_GetPosition code by Nathan Seidle to be the easiest and most convenient to experiment with. We find this sketch under File>Examples>Sparkfun Ublox Arduino Library. Can’t find it? Make sure you've got the library for this GPS module installed as explained above in the Software Setup. It’s ok, I’ll wait. I may perhaps make some tea. Let me know when you’re ready and busting out data to the Arduino Serial Monitor. If that’s new to you, just verify and upload the code the board and hit that magnifying glass in the upper right hand corner. Set the baud rate to 115200, unless you want to see what our alien overlords have to say.

GPS module hooked up to RedBoard

Final Code

If you're here, I take it that you’ve mastered the OLED Screen and SAM-M8Q module? Then I believe you’re ready! Seriously, this is the simple part. I blended the two previous sections of code to use the button to trigger a read from the GPS module and output the latitude and longitude to the OLED Screen. If you feel savvy, read through it and reverse engineer what I did so you can make glorious modifications! I say learn by breaking, master by rebuilding.

language:c
#include <Wire.h>
#include <SFE_MicroOLED.h> 
#include "SparkFun_Ublox_Arduino_Library.h" //http://librarymanager/All#SparkFun_Ublox_GPS

#define PIN_RESET 9
#define DC_JUMPER 1

SFE_UBLOX_GPS myGPS;
MicroOLED oled(PIN_RESET, DC_JUMPER);

const int buttonPin = 2;
const int ledPin =  13;

int buttonState = 0;

void setup() {
  Wire.begin();

  delay(100);
  oled.begin();
  oled.clear(ALL);
  oled.display();
  delay(1000);
  oled.clear(PAGE);
  oled.display();

  oled.setFontType(0);
  oled.setCursor(0,0);

  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() { 
    buttonState = digitalRead(buttonPin);
    if (buttonState == HIGH){
      if (myGPS.begin() == false){
        oled.clear(PAGE);
        oled.print("No GPS");
        oled.display();
        delay(1500);
        oled.clear(PAGE);
        oled.display();
        oled.setCursor(0,0);
      }
      if(myGPS.begin() == true){
        myGPS.setI2COutput(COM_TYPE_UBX);
        myGPS.saveConfiguration();

        float latitude = myGPS.getLatitude();
        latitude = latitude / 10000000;

        float longitude = myGPS.getLongitude();
        longitude = longitude / 10000000;
      ////////////////////////////////////////////
      // Uncomment for altitude, add to output  //
      ////////////////////////////////////////////
      //   float altitude = myGPS.getAltitude();//
      ////////////////////////////////////////////

        oled.clear(PAGE);
        oled.print("Lat:");
        oled.print(latitude,6);
        oled.print("\nLong:");
        oled.print(longitude,6);
        oled.display();
        delay(10000);
        oled.clear(PAGE);
        oled.display();
        oled.setCursor(0,0);
      }
    }

}

With everything connected, press the button to view your coordinates on the OLED! Instead of using your USB for power, connect a 9V battery to the RedBoard to go mobile!

GIF of pushing button and getting coordinates

Let's Wrap it Up

“Hey, smart guy! How does this teach me GPS?” We all occupy a particular point on this big blue ball. There are dozens of satellites zooming around above us. This project gives you the tools to talk to them and physically see your coordinates in the simplest of means. The best part is that Google Maps takes Latitude/Longitude coordinates. This means you can see where you are on a map. Yes, yes, your phone has a GPS receiver and Google auto fixes to your position, but this is so much more fun!

For myself, this project has a special purpose. I love to go fishing and I’m a nerd. So my usage for this project is to map my catches. When I make record breaking catch of unearthly magnitudes (okay most of my trophies are around 4 inches, but lets both just move on), I’ll take a photo and then safely release the little guy. What I’d like to do is geo-tag those catches by using the coordinates I write down from my gadget and then pin them to the pictures of my catches. This way I can look back at where my biggest catches were so I can go there again, or just make some hypothesis as to the health of the lake. You know, everyday normal things.

I hope you enjoyed this tutorial as much as I did. Let us know how you used this project or how you modified it. If you catch some giant whoppers then tag that spot as Qwiic as you can!

Resources and Going Further

In case you'd like to delve a little deeper into the bits and bobs we've used in this tutorial, check out some of the links below:

SparkFun RedBoard Qwiic

SparkFun Micro OLED Breakout (Qwiic)

SparkFun GPS Breakout - Chip Antenna, SAM-M8Q (Qwiic)

&nbsp

GPS Constellation

&nbsp


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

Using Home Assistant to Expand Your Home Automations

$
0
0

Using Home Assistant to Expand Your Home Automations a learn.sparkfun.com tutorial

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

Introduction

In this tutorial, you'll learn everything you need to know to get started controlling your home with Home Assistant, an open source home automation hub that puts local control and privacy first, running off of a Raspberry Pi. In this tutorial we'll cover how to set up Home Assistant, and regardless of whether you created the devices yourself or purchased off the shelf IoT devices, get them working together in harmony.

While this guide walks you through the setup of Home Assistant, this is not a tutorial about how to get the most out of Home Assistant (but a quick Google search for Home Assistant tutorials will provide you with endless links to do so).

Home Assistant Logo

Image courtesy of home-assistant.io

Required Materials

To follow along with the examples in this tutorial, you will need the following pieces of hardware. 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.

Optional Materials

Depending on your setup, you may also need the following.

microSD Card with Adapter - 16GB (Class 10)

microSD Card with Adapter - 16GB (Class 10)

COM-13833
$19.95
5
Raspberry Pi LCD - 7" Touchscreen

Raspberry Pi LCD - 7" Touchscreen

LCD-13733
$64.95
39
LCD Touchscreen HAT for Raspberry Pi - TFT 3.5in. (480x320)

LCD Touchscreen HAT for Raspberry Pi - TFT 3.5in. (480x320)

LCD-14776
$24.95
1
Multimedia Wireless Keyboard

Multimedia Wireless Keyboard

WIG-14271
$29.95
3

Suggested Reading

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

Raspberry Pi 3 Starter Kit Hookup Guide

Guide for getting going with the Raspberry Pi 3 Model B and Raspberry Pi 3 Model B+ starter kit.

How to Use Remote Desktop on the Raspberry Pi with VNC

Use RealVNC to connect to your Raspberry Pi to control the graphical desktop remotely across the network.

Introduction to MQTT

An introduction to MQTT, one of the main communication protocols used with the Internet of Things (IoT).

ESP32 Thing Plus Hookup Guide

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

Installing Home Assistant

To get started, we'll first need to install Home Assistant by downloading the image for your device. Home Assistant's installation page does a great job outlining how to flash the image to your SD card, but after you download your image you'll need to install Hass.io by connecting your SD card to your computer and flash the image using a program called balenaEtcher.

Providing an Internet Connection

Next we need to make sure your Pi will have an Internet connection. To get up and running fast and reliably we'll be using a hardwired connection to our router. But if you'd prefer WiFi, you can either use a blank USB stick with a Fat32 partition (with the partition labeled "CONFIG"), and while in the root (/) directory, create a network/my-network file. Or on the Hassio SD card first bootable partition, create CONFIG/network/my-network file. For the structure of the network file, follow the HassOS howto.

Once the network has been setup, insert the SD card and USB stick, if used, into the Pi. Connect power to the Pi, and wait for the OS to boot. For this first boot, Home Assistant will download the latest version, which will take ~20 minutes.

After the very long first boot, you will be able to reach your device from a browser at http://hassio.local:8123 (assuming your router supports mDNS). If your router doesn't support mDNS, or you're unsure, you'll need to use the IP address of your Pi instead (e.g. 192.168.1.108:8123). You can find the IP address by logging into your router (typically by typing 192.168.1.1 into the address bar of your browser), finding your Pi (should be named hassio).

HassIO IP image

Click the image for a closer look.

Logging in to Home Assistant

Once Home Assistant has finished updating and you're able to connect to the Pi, you should be greeted with a login screen to create a user name and password to log into Home Assistant. Make sure to keep track of the login used. we'll need those credentials later when we set up our ESP devices.

Home Assistant Account Creation

Once logged in, you'll be welcomed by the home screen. Home Assistant will automatically scan your network to add devices. You may receive a few notifications to set up the devices found, typically these are home media devices, such as Google cast, Plex, etc.

Home Assistant Home Screen

Click the image for a closer look.

Configuring Home Asssistant

Now that we have Home Assistant set up, we need to configure it. One of the benefits of Home Assistant is it's open source, allowing people from the community to create their own add-ons on top of the officially supported add-ons, which can make customizing it a lot faster and easier than other options. In this section we'll need to enable two extensions: Configurator and MQTT.

To view the available add-ons, click on the Hass.io tab on the left side menu, followed by clicking on the ADD-ON STORE tab along the top as shown below (similarly, you can go to http://hassio.local:8123/hassio/store).

Add-on Store

Click the image for a closer look.

Adding the Configurator Add-On

Regardless of what you ultimately use Home Assistant for, one add-on that will make configuring Home Assistant easy without having to SSH into your Pi is the Configurator under Official add-ons. The Configurator allows you to browse and modify the files on your Pi. Later on we'll be using this add-on to modify the configuration.yaml and automations.yaml files.

To add the Configurator, click on the Configurator add-on, and click install. After the add-on has been installed, you'll want to click start and enable the "Show in Sidebar" option, and that will add a new option to your left menu bar with the name "Configurator" after you reload the page.

Configurator Highlight

Click the image for a closer look.

We'll need to use this add-on later after we get more of our hardware setup.

Adding the Mosquitto Broker

Mosquitto is an open source MQTT broker server that receives and distribute messages over the MQTT server. For more information about MQTT, check out the MQTT tutorial. We'll setup the Mosquitto broker the same way we did the Configurator. First click on the Mosquitto broker under the offical add-ons section of the add-on store. Click install, and wait for Home Assistant to download and add Mosquitto. After it's finished downloading, click start to enable the MQTT broker.

MQTT Add-On

Click the image for a closer look.

Using the Configurator to well... configure

Before we can start using MQTT, we need to configure Home Assistant's MQTT broker. First click on "Configurator" from the left menu bar.

Click On Configurator

Click the image for a closer look.

We enabled MQTT from the add-on store, but now we need to configure it. All of your configurations are stored in the appropriately named file called configuration.yaml. YAML files are a human-readable data serialization language, similar to header files in C++, which are commonly used for configuration files. Similar to python, YAML files use indentations to indicate nesting, so be careful with your indents when you modify a YAML file.

To open the configurations file, first click on the folder icon to browse the file system.

Click On Folder Icon Highlight

Click the image for a closer look.

Navigate to the configuration file located at /config/configuration.yaml

Highlight of the configurations.yaml file

Click the image for a closer look.

This configuration page is where we'll initialize our MQTT broker and devices. The first thing we'll initialize is the broker. Copy the following lines into the configuration file. It doesn't matter where these lines go in the file, but we'll place it just below the discovery. Make sure to replace the IP address with the IP of your Pi.

mqtt:
    broker: 192.168.1.- # This is the IP address of the Pi, which can be found from your client list of your router

Once that's done we can save changes by pressing save icon.

Save icon pointer

Click the image for a closer look.

Every time we make a change to any of the files, we'll want to first check that the configuration is valid, and then restart Home Assistant. To check the configuration, go to the tab labeled Configuration NOT Configurator along the left side, and select General, and click "CHECK CONFIG". If the syntax is correct, it will display a message "Configuration Valid". If not it will show you a debug message showing where the error occurred that needs to be fixed. Once the configuration is valid, press "RESTART" under Server Management, and wait a minute for the changes to be applied.

Configuration tab, click general

Check configuration and restart server

Click the image for a closer look.

Example 1: MQTT + ESP32

Note: This Arduino code used in this example has been written and tested on Arduino IDE version 1.8.6. Otherwise, make sure you are using the latest stable version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you have not previously installed an Arduino library, please check out our installation guide.

Now that we have the MQTT server running, it's time to add some devices. For this first example we'll connect two ESP32 Thing Plus boards to our network over MQTT. If you're unsure of what MQTT is and how it works, there's a guide for that! Check out the MQTT tutorial below:

Introduction to MQTT

November 7, 2018

An introduction to MQTT, one of the main communication protocols used with the Internet of Things (IoT).

The first device we'll add will be a switch that waits for the button connected to IO pin 0 to be pressed. Once pressed the button will publish to the topic room/light with message of "on" or "off". The second ESP32 will subscribe to the same topic room/light and listen for messages from the switch. When the message "on" is received, it will turn on the LED connected to IO pin 13, and when "off" is received, turn the LED off. To do this we'll need to flash the ESP32 Thing Plus boards with some code using Arduino.

MQTT Switch

Copy and paste the code below into your Arduino IDE, make sure to select ESP32 Dev Module as your board, and the correct COM port is selected. Fill in the information for your WiFi credentials (your WiFi network must be on the same network as the Raspberry Pi), your user name and password you created for Home Assistant, and the IP address of the Pi.

language:c
/******************************************************************************
MQTT_Switch_Example.ino
Example for controlling a light using an MQTT switch
by: Alex Wende, SparkFun Electronics

This sketch connects the ESP32 to a MQTT broker and subcribes to the topic
room/light. When the button is pressed, the client will toggle between
publishing "on" and "off".
******************************************************************************/

#include <WiFi.h>
#include <PubSubClient.h>

// WiFi Network Credentials
const char *ssid =  "-----";   // name of your WiFi network
const char *password =  "-----"; // password of the WiFi network

// Home Assistant Credentials
const char *HA_USER = "-----";
const char *HA_PASS = "-----";

// MQTT Network
IPAddress broker(192,168,1,-); // IP address of your MQTT broker eg. 192.168.1.50
const byte SWITCH_PIN = 0;           // Pin to control the light with
const char *ID = "Example_Switch";  // Name of our device, must be unique
const char *TOPIC = "room/light";  // Topic to subcribe to
WiFiClient wclient;

PubSubClient client(wclient); // Setup MQTT client
bool state=0;

// Connect to WiFi network
void setup_wifi() {
  Serial.print("\nConnecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password); // Connect to network

  while (WiFi.status() != WL_CONNECTED) { // Wait for connection
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

// Reconnect to client
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(ID,HA_USER,HA_PASS)) {
      Serial.println("connected");
      Serial.print("Publishing to: ");
      Serial.println(TOPIC);
      Serial.println('\n');

    } else {
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200); // Start serial communication at 115200 baud
  pinMode(SWITCH_PIN,INPUT);  // Configure SWITCH_Pin as an input
  digitalWrite(SWITCH_PIN,HIGH);  // enable pull-up resistor (active low)
  delay(100);
  setup_wifi(); // Connect to network
  client.setServer(broker, 1883);
}

void loop() {
  if (!client.connected())  // Reconnect if connection is lost
  {
    reconnect();
  }
  client.loop();

  // if the switch is being pressed
  if(digitalRead(SWITCH_PIN) == 0) 
  {
    state = !state; //toggle state
    if(state == 1) // ON
    {
      client.publish(TOPIC, "on");
      Serial.println((String)TOPIC + " => on");
    }
    else // OFF
    {
      client.publish(TOPIC, "off");
      Serial.println((String)TOPIC + " => off");
    }

    while(digitalRead(SWITCH_PIN) == 0) // Wait for switch to be released
    {
      delay(20);
    }
  }
}

Once the code has uploaded, open the terminal window to make sure that the switch successfully connected to WiFi, and has connected to the MQTT network. If you're able to connect to the network and not the Pi, make sure the IP address is correct, as well as the credentials for Home Assistant. If both of those are right, the MQTT broker might not have been set up correctly.

MQTT Light

Copy and paste the code below into your Arduino IDE, make sure to select ESP32 Dev Module as your board, and the correct COM port is selected. Fill in the information for your WiFi credentials (your WiFi network must be on the same network as the Raspberry Pi), your user name and password for Home Assistant, and the IP address of the Pi.

language:c
/******************************************************************************
MQTT_Light_Example.ino
Example for controlling a light using MQTT
by: Alex Wende, SparkFun Electronics

This sketch connects the ESP32 Thing Plus to a MQTT broker and subcribes to the topic
room/light. When "on" is recieved, the pin LIGHT_PIN is set HIGH.
When "off" is recieved, the pin LIGHT_PIN is set LOW.
******************************************************************************/

#include <WiFi.h>
#include <PubSubClient.h>

// WiFi Network Credentials
const char *ssid = "-----";   // name of your WiFi network
const char *password = "-----"; // password of the WiFi network

// Home Assistant Credentials
const char *HA_USER = "-----";
const char *HA_PASS = "-----";

// MQTT Network
IPAddress broker(192,168,1,-); // IP address of your MQTT broker eg. 192.168.1.50
const byte LIGHT_PIN = 13;           // Pin to control the light with
const char *ID = "Example_Light";  // Name of our device, must be unique
const char *TOPIC = "room/light";  // Topic to subcribe to
const char *STATE_TOPIC = "room/light/state";  // Topic to publish the light state to


WiFiClient wclient;

PubSubClient client(wclient); // Setup MQTT client

// Handle incomming messages from the broker
void callback(char* topic, byte* payload, unsigned int length) {
  String response;

  for (int i = 0; i < length; i++) {
    response += (char)payload[i];
  }
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  Serial.println(response);
  if(response == "on")  // Turn the light on
  {
    digitalWrite(LIGHT_PIN, HIGH);
    client.publish(STATE_TOPIC,"on");
  }
  else if(response == "off")  // Turn the light off
  {
    digitalWrite(LIGHT_PIN, LOW);
    client.publish(STATE_TOPIC,"off");
  }
}

// Connect to WiFi network
void setup_wifi() {
  Serial.print("\nConnecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password); // Connect to network

  while (WiFi.status() != WL_CONNECTED) { // Wait for connection
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

// Reconnect to client
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if(client.connect(ID,HA_USER,HA_PASS)) {
      client.subscribe(TOPIC);
      Serial.println("connected");
      Serial.print("Subcribed to: ");
      Serial.println(TOPIC);
      Serial.println('\n');

    } else {
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200); // Start serial communication at 115200 baud
  pinMode(LIGHT_PIN, OUTPUT); // Configure LIGHT_PIN as an output
  delay(100);
  setup_wifi(); // Connect to network
  client.setServer(broker, 1883);
  client.setCallback(callback);// Initialize the callback routine
}

void loop() {
  if (!client.connected())  // Reconnect if connection is lost
  {
    reconnect();
  }
  client.loop();
}

Once the code has uploaded, open the terminal window to make sure that the light successfully connected to WiFi, and has connected to the MQTT network. Once both devices have connected, you can press the button connected to IO pin 0 of the ESP32 Thing Plus acting as a switch and the LED on IO pin 13 of the light should turn on. Pressing the button a second time should turn off the LED.

Example 1.5: Controlling the ESP32 from Home Assistant

In the first example, we connected two ESP32 Thing Plus boards to Home Assistant's Mosquitto broker. Even though the server is running in the background, Home Assistant doesn't know what topics the Thing Plus boards are subscribing and publishing to. To fix that, we'll need to get Home Assistant to subscribe to those same topics, which is done by adding the components to the configuration file. Go back to the configurator tab and open the configuration.yaml file again.

The first device we'll add is the switch component, just like when we added the MQTT component, it doesn't matter where we add the switch to the configuration file, but to keep things organized, we'll add the following lines below the mqtt initialization.

switch:
  - platform: mqtt
    name: "Example_Switch"
    command_topic: "room/light"
    payload_on: "on"
    payload_off: "off"

First we told the Home Assistant that we would like to add a switch component. The switch uses the MQTT platform, and has a name called "Example_Switch". The switch will command (or publish to) a topic called "room/light", this is the same name of the mqtt topic we're publishing to in the ESP32's Switch Arduino sketch. The payload is the message being sent over the command topic to turn the light on and off.

The second device we'll add is the light component just below the switch component with an empty line separating the switch component with the light component.

light:
  - platform: mqtt
    name: "Example_Light"
    command_topic: "room/light"
    state_topic: "room/light/state"
    payload_on: "on"
    payload_off: "off"

Similarly to the switch component, we told Home Assistant that we would like to add a light component. The light uses the MQTT platform, and has a name called "Example_Light". The light will listen for commands from the topic "room/light", which is the same topic we defined in the ESP32's Light Arduino sketch. The payload we're listening for is "on" to turn the light on, and "off" to turn the light off. Once those lines have been added, your configuration file should look like this:

Configuration file with light and switch

Click the image for a closer look.

Once the light and switch components have been added, we'll need to save the configuration file again, check that the configuration valid, and restart the server. Once the server has been restarted click Overview from the left menu bar. From the there you should see your light and switch components, if not you may need to troubleshoot.

If you're able to see your components, clicking on the slide switch of the light or the lightning bolt symbol of the switch will turn the ESP32's LED on. You'll also see that from Home Assistant, the light bulb symbol of the light also turned on. Home Assistant is able to know what the state is of the MQTT light by using the state_topic both in the configuration file as well as publishing to the topic from the light's Arduino sketch. If we had removed the state_topic from the light, we would be able to control the light, but we wouldn't be able see from Home Assistant if the light is on or off.

So we can add our own devices, and that's cool I guess, but that was basically working in the MQTT tutorial. So why use Home Assistant? The next example will show that you can not only add your own devices, but devices you can buy and get working out of the box.

Troubleshooting Tips

Unused Entities

If you're not able to see your light and switch, they may be in your unused entities. To view them, click on the 3 vertical dots along the top right and select Unused entities as shown below. Or click on following link to load your unused entities page (http://hassio.local:8123/lovelace/hass-unused-entities).

Show unused entities

Click the image for a closer look.

From this page you'll see all of your unused entities, including the Example_Light and Example Switch:

Unused entities page

Click the image for a closer look.

Components Not Showing Up in Either

If you still can see all of your components, the issue may be your MQTT broker. To fix this, go into the configurator and open your configuration file. From the configuration file, remove the MQTT component and broker IP address, but leave the light and switch components. When done press save, and restart the server. Once it comes back online, click on configuration on the left menu bar, and click on integrations (http://hassio.local:8123/config/integrations/dashboard).

Highlight of Integrations

Click the image for a closer look.

If your Mosquitto broker add-on is enabled and running, you should see a MQTT component in the discovery section; click Configure.

MQTT discovery

Click the image for a closer look.

From this page, you can check the enable discovery box and press submit. And your devices should now be visible either from the overview or unused entities pages.

Setup MQTT

Example 2: Adding Commercial Switches

In our first example we added devices to Home Assistant using devices that we programmed ourselves. Adding devices that are commercially available is even easier. In this example we're going to be adding WiFi plug switches that can easily be bought online. To see what devices are currently supported from Home Assistant, check out the components page. From there you can find popular manufacturers such as Amazon Alexa, Nest, SmartThings, Wink, WeMo, and much much more. If you don't immediately see your device, you can try searching for your device under the left side bar based on its function.

In this example we'll be adding smart plugs under the brand iSelector. There wasn't anything special about them, just an inexpensive wifi plug switch which works with the Amazon Alexa and Google Assistant. They do require that you download the app to connect the plugs to your wireless network. If you're searching for your own smart devices and aren't sure if they'll work with Home Assistant, a Google search with the device + Home Assistant should at the very least give you some Home Assistant forum questions with answers to help you decide.

iSelector Smart Plug

Image courtesy of Amazon.com

With the iSelector plugs, they use an app called Smart Life, which requires you to sign up for a free account. We'll need the name of the app and our login credentials when we add the plugs to Home Assistant.

Adding the Plugs to Home Assistant

Once you have a compatible device and have added it to your network, it's time to integrate it with Home Assistant. iSelector devices work under the Tuya light component, so to add the device we'll the following to our configuration file after our MQTT light:

tuya:
    username: "USERNAME"    # Replace with your username
    password: "PASSWORD"    # Replace with your password
    country_code: "1"       # The country code you used to register. USA is 1
    platform: "smart_life"  # The name of the app used to create the account

After adding those lines, our configuration.yaml file should look like this:

configuration file with mqtt and tuya components added

Once again, save the configuration file, check the configuration, and restart the server. When the server comes back online, you can navigate back over to the Overview's unused entities and you should see your devices added under switches. Clicking on the slider will turn the switch on and off.

Unused entities page with WiFi Plug

Click the image for a closer look.

Example 3: Automations

If you're familiar with If This Then That (IFTTT) automations, they work very similarly. Automations consist of three parts: The trigger which starts the processing of an automation rule, the optional conditions which can be used to prevent an action from happening when triggered (e.g. only during a certain time, or only if a switch is currently on or off), and actions which Home Assistant will do when the automation is triggered.

In this example we'll create an automation to be triggered from the first MQTT example to toggle the Wifi Plug of the second example to show how to use Home Assistant to take a device that you made and programmed to control a commercially available device, or in our case a WiFi plug switch.

Creating an Automation

To create an automation, you can either use the configurator tool to edit the automations.yaml file, or in this case, use the automations tool to generate the code. To create an automation, select configuration from the left menu bar, and click automation (or go to http://hassio.local:8123/config/automation) and click the "Add Automation" button from the bottom right.

Add automation with arrow pointing to add new automation

Click the image for a closer look.

The first thing we need to do is to give the automation a name. The name is only used to remember what the automation does, so we can simply put "MQTT -> WiFi Plug". For the trigger, we'll select MQTT as the trigger type, with the topic set to "room/plug", and for the payload enter "toggle".

Adding MQTT automation trigger

Click the image for a closer look.

We won't need to add any conditions to the automation, so for the actions we'll set the action type to "Call service". For the service we'll select "switch.toggle", and for our service data we'll enter "{ "entity_id": "switch.xxxxxxxxxxxxx" }" where the x's represent your plug's serial number. When done press the save button in the lower right, and go back to configuration -> general and check the config and restart the server.

Adding actions to automation

Click the image for a closer look.

Finding the Entity ID

If you're having a hard time finding the entity ID for a device, you can look it up under the developer tools section of the left menu bar under services.

Opening developer tools

From the Services page, you can select the service "switch.toggle", and from the entity select the plug. From there you can copy all of the service data and paste that into the service data entry for your automation.

inspect service data

Click the image for a closer look.

ESP32 Code

As we wait for the server to restart, we need to modify the switch sketch from the first example. In the first example we sent messages over MQTT of "on" and "off" over the "room/light" topic. To get our automation to trigger correctly, we'll want to change our topic to "room/plug" and change the message we're sending to only be "toggle", to match the trigger event of our automation. Copy and paste the following code into your Arduino IDE and upload to your ESP32.

language:c
/******************************************************************************
MQTT_Switch_Example.ino
Example for controlling a light using an MQTT switch
by: Alex Wende, SparkFun Electronics

This sketch connects the ESP32 to a MQTT broker and publishes the message
"toggle" to the topic "room/plug".
******************************************************************************/

#include <WiFi.h>
#include <PubSubClient.h>

// WiFi Network Credentials
const char *ssid =  "-----";   // name of your WiFi network
const char *password =  "-----"; // password of the WiFi network

// Home Assistant Credentials
const char *HA_USER = "-----";
const char *HA_PASS = "-----";

// MQTT Network
IPAddress broker(192,168,1,-); // IP address of your MQTT broker eg. 192.168.1.50
const byte SWITCH_PIN = 0;           // Pin to control the light with
const char *ID = "Example_Switch";  // Name of our device, must be unique
const char *TOPIC = "room/plug";  // Topic to subcribe to
const char *MESSAGE = "toggle";   // Message to publish to our topic
WiFiClient wclient;

PubSubClient client(wclient); // Setup MQTT client

// Connect to WiFi network
void setup_wifi() {
  Serial.print("\nConnecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password); // Connect to network

  while (WiFi.status() != WL_CONNECTED) { // Wait for connection
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

// Reconnect to client
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(ID,HA_USER,HA_PASS)) {
      Serial.println("connected");
      Serial.print("Publishing to: ");
      Serial.println(TOPIC);
      Serial.println('\n');

    } else {
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200); // Start serial communication at 115200 baud
  pinMode(SWITCH_PIN,INPUT);  // Configure SWITCH_Pin as an input
  digitalWrite(SWITCH_PIN,HIGH);  // enable pull-up resistor (active low)
  delay(100);
  setup_wifi(); // Connect to network
  client.setServer(broker, 1883);
}

void loop() {
  if (!client.connected())  // Reconnect if connection is lost
  {
    reconnect();
  }
  client.loop();

  // if the switch is being pressed
  if(digitalRead(SWITCH_PIN) == 0) 
  {
    client.publish(TOPIC, MESSAGE);
    Serial.println((String)TOPIC + " => toggle");

    while(digitalRead(SWITCH_PIN) == 0) // Wait for switch to be released
    {
      delay(20);
    }
  }
}

Once the code has uploaded, and the server has restarted, go to your overview tab, and then go to your unused entities (http://hassio.local:8123/lovelace/hass-unused-entities) and make sure your automation is enabled. Once it is, when you push the button connected to IO pin 0 on the ESP32, the plug should toggle states.

enabling automations

Click the image for a closer look.

Going Further with Low Power

With a constant power source, the amount of current the ESP32 draws isn't much of a concern. But with having a WiFi remote for your switches, it's likely that battery power would be preferable to allow moving the switch anywhere you'd like. To get the most out of a battery, you'll want to draw as little current as you can, so to do this, we'll put the ESP32 in low power mode, and when the button is pressed we want to wake up the ESP32, connect to WiFi and the MQTT server, send our message and go back to sleep. With the sketch below, the ESP32 Thing Plus will draw around 5mA while in sleep mode, and draw up to 160mA when the MQTT packet is sent.

language:c
/******************************************************************************
Low_Power_MQTT_Switch_Example.ino
Example for controlling a light using an MQTT switch
by: Alex Wende, SparkFun Electronics

This sketch enters low power mode and waits for IO pin 0 to be pressed. Once
pressed, the ESP32 wakes up, connects to WiFi and the MQTT broker, and
publishes "toggle" to the topic "room/plug" and goes back to low power mode.
******************************************************************************/

#include <WiFi.h>
#include <PubSubClient.h>

// WiFi Network Credentials
const char *ssid =  "-----";   // name of your WiFi network
const char *password =  "-----"; // password of the WiFi network

// Home Assistant Credentials
const char *HA_USER = "-----";
const char *HA_PASS = "-----";

// MQTT Network
IPAddress broker(192,168,1,-); // IP address of your MQTT broker eg. 192.168.1.50
const byte SWITCH_PIN = 0;           // Pin to control the light with
const char *ID = "Example_Switch";  // Name of our device, must be unique
const char *TOPIC = "room/plug";  // Topic to subcribe to
const char *MESSAGE = "toggle";   // Message to publish to our topic
WiFiClient wclient;

PubSubClient client(wclient); // Setup MQTT client

// Connect to WiFi network
void setup_wifi() {
  Serial.print("\nConnecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password); // Connect to network

  while (WiFi.status() != WL_CONNECTED) { // Wait for connection
    delay(10);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

// Reconnect to client
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(ID,HA_USER,HA_PASS)) {
      Serial.println("connected");
      Serial.print("Publishing to: ");
      Serial.println(TOPIC);
      Serial.println('\n');

    } else {
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

#define BUTTON_PIN_BITMASK 0x200000000 // 2^33 in hex

/*
Method to print the reason by which ESP32
has been awaken from sleep
*/
void wakeup_reason(){
  esp_sleep_wakeup_cause_t wakeup_reason;

  wakeup_reason = esp_sleep_get_wakeup_cause();

  if(wakeup_reason == ESP_SLEEP_WAKEUP_EXT0)
  {
    setup_wifi(); // Connect to network
    client.setServer(broker, 1883);

    if (!client.connected())  // Reconnect if connection is lost
    {
      reconnect();
    }
    client.loop();

    client.publish(TOPIC, MESSAGE);
    Serial.println((String)TOPIC + " => toggle");

    while(digitalRead(SWITCH_PIN) == 0) // Wait for switch to be released
    {
      delay(20);
    }
  }
}

void setup(){
  Serial.begin(115200);
  wakeup_reason();

  /*
  First we configure the wake up source
  We set our ESP32 to wake up for an external trigger.
  There are two types for ESP32, ext0 and ext1 .
  ext0 uses RTC_IO to wakeup thus requires RTC peripherals
  to be on while ext1 uses RTC Controller so doesnt need
  peripherals to be powered on.
  Note that using internal pullups/pulldowns also requires
  RTC peripherals to be turned on.
  */
  esp_sleep_enable_ext0_wakeup(GPIO_NUM_0,0); //1 = High, 0 = Low

  //Go to sleep now
  Serial.println("Going to sleep now");
  esp_deep_sleep_start();
}

void loop(){
  //This is not going to be called
}

When you push the button this time, you should notice a delay before the plug turns on or off. The main reason is the time it takes to connect to the WiFi network and then to the MQTT server. How else could we take this further? These examples were to demonstrate easy proof-of-concept demonstrations. By soldering a few more buttons and adding a case, you could create a remote that can turn on and off a bunch of lights, either one at a time, or by groups just by adding more automations and setting each button on the remote to send a different MQTT command.

Resources and Going Further

This guide hasn't even scratched the surface of what Home Assistant is capable of. And with the Qwiic Connect System on the ESP32 Thing Plus, you can add a ton of devices to Home Assistant without even having to wait for your soldering iron to heat up. For more information about about Home Assistant, check out some of the links below:

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

SparkFun Blocks for Intel® Edison - microSD Block

A quick overview of the features of the microSD Block.

ESP8266 Thing Development Board Hookup Guide

An overview of SparkFun's ESP8266 Thing Development Board - a development board for the Internet of Things.

Hazardous Gas Monitor

Build a portable gas monitor to check for dangerous levels of hazardous gases.

WiFi IR Blaster Hookup Guide

How to assemble the WiFi IR Blaster and program it using Arduino. You'll be controlling IR devices from the web in no time!

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


Buck-Boost Hookup Guide

$
0
0

Buck-Boost Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

We got tha powah! The Buck-Boost Converter is the latest breakout from SparkFun that allows you to fine tune the amount of power your project receives. It can take an input voltage of anywhere from 3-16V which can then be regulated to an output voltage between 2.5-9V. With the switch on the bottom of the board, you can set the common output voltages of 3.3V and 5V, but we've also broken out a custom setting that allows you to populate a resistor based on your custom voltage needs. What's more, we have broken out the GPIO pins along the top of the board for even more control. Get your boost on!

SparkFun Buck-Boost Converter

SparkFun Buck-Boost Converter

COM-15208
$9.95

Required Materials

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

Tools

You may also need a soldering iron, solder, and general soldering accessories.

Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

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

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2

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

The Buck-Boost board is centered around the TPS63070 Buck-Boost converter, which will take your input power and either regulate the output voltage up or down to your set output voltage. In this section we'll take a closer look at how the converter works and how you can incorporate into your next project.

Buck-Boost board

Power Pins

Power connections highlight

The Buck-Boost board has an input voltage range of 3-16V. You can supply power by either soldering wires directly to the board or by using our 3.5mm screw terminals.

Buck-Boost with screw terminals

The output is adjustable from 2.5-9V using the single-pole-triple-throw switch. The board is configured with two of the more common voltages you might use, 3.3V and 5V, but there's a unpopulated PTH resistor to allow for setting a specific voltage.

Setting The Output Voltage

Highlight of voltage selection switch

The output voltage of the Buck-Boost is set by voltage divider connected to the feedback pin. The Buck-Boost board has one fixed resistor at 68.1kΩ and the switch changes the second resistor between VOUT and the feedback pin. To change the output voltage, move the switch to one of the three positions for 3.3V, 5V, or CUST. The CUST position is there to allow you to set the voltage to whatever you need by soldering a resistor to the PTH resistor pads highlighted below.

Custom resistor highlight

Use the equation below to determine the resistor value needed based on the desired output voltage.

Equation to calculate resistor value

I/O pins

The Buck-Boost board will work out of the box, but if you need a little bit more control, most of the extra pins have been broken out, as shown below.

Highlight of I/O pins
PinDescription
VINSupply voltage for power stage. Can be used to pass power to the rest of the project, or used to set the logic level.
ENEnable input. Pull high to enable the device. Pull Low to disable the device. Default: HIGH through 10kΩ pull-up resistor to VIN.
GNDGround. Can be used to set I/O pin low.
PSPower Save. Pull low for forced PWM. Pull high for power save mode. In power save mode, the switching frequency will adjust to the most efficient frequency. You can also apply a clock signal to synchronize to an external frequency. Default: HIGH through 10kΩ pull-up resistor to VIN.
PG Power good open drain output.
VOUTAdditional buck-boost converter output.

PWR LED

Highlight of power LED

The power LED indicates red when voltage is present on the output pins. Because the LED has a fixed 1k current limiting resistor in series, the brightness of the LED will vary depending on the output voltage. The LED can be disabled by cutting the jumper on the back of the board as shown below.

Cutting LED jumper

Buck-Boost Tips and Tricks

Maximum Output Current VS Input Voltage

One of the benefits of the Buck-Boost, aside from boosting the output voltage up from a lower input voltage, is it uses a switching DC/DC converter, which is more efficient than a linear regulator. More efficiency means less energy is wasted in the form of heat. However, that doesn't mean the TPS63070 doesn't get hot under load. The TPS63070 has an operating die temperature range of -40 to +125°C, using the graphs below should provide a good rule of thumb for the maximum output current available at various output voltages as a function of the input voltage.

The temperature was recorded using a FLIR camera with an air temperature of 25°C, with a maximum case temperature of 100°C. Each output voltage graph has a showing the maximum output current both with and without a heatsink.

Maximum Output Current Graphs

Click on the photo for full resolution

Adding a Heatsink

In the maximum output current section, the graphs are shown both with and without a heatsink. The benefit of a heatsink is it provides more surface area for the air to dissipate the heat, which will allow the Buck-Boost board to output the maximum amount of current across a wider input voltage range. To add a heatsink you'll need two of our products: a heatsink (of course), and our thermal tape.

To add a heatsink first cut the thermal tape to rough size:

Thermal tape cut to rough size

Peel off one of the protective coverings and attach attach heatsink to thermal tape:

Heatsink connected to thermal tape

With a hobby knife, follow the perimeter of the heatsink to cut the tape to it's final size:

Cutting thermal tape

Remove the remaining protective covering of the tape and attach the heatsink to the TPS63070, trying to center the heatsink over the IC:

Heatsink attached to board

Connecting your Load

Depending on the size of the load connected to the output, you may need to wait between when the enable pin is pulled high and the load is connected to the board. The time delay is relatively short (~10ms), but it shouldn't be a problem if the load is <800mA at 3.3V, or <700mA at 5.0V. If the custom resistor is populated to output a voltage greater than 5V, you should be able to leave the load connected if the load is <650mA.

Resources and Going Further

For more information on the Buck Boost, check out some of the links below:

Need more inspiration? Check out these related tutorials!

INA169 Breakout Board Hookup Guide

How to interface with the INA169 Breakout Board to measure current.

Reducing Arduino Power Consumption

A tutorial about different ways to reduce the current draw for your next Arduino project the easy way.

Current Sensor Breakout (ACS723) Hookup Guide

Learn how to measure the current consumption of your project using the ACS723 Current Sensor.

Beginner Parts Kit Identification Guide

The essential parts for beginning (or even experienced) hobbyists that gives you all of the basic through-hole components you will need to get started playing with embedded projects. We'll identify a few parts in the kit and provide a few basic circuits to get started!

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

Qwiic 12-Bit ADC

$
0
0

Qwiic 12-Bit ADC a learn.sparkfun.com tutorial

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

Introduction

An analog to digital converter (ADC) is very useful tool for converting an analog voltage to a digital signal that can be read by a microcontroller. The ability to converting from analog to digital interfaces allows users to use electronics to interface to interact with the physical world.

SparkFun Qwiic 12 Bit ADC - 4 Channel (ADS1015)

SparkFun Qwiic 12 Bit ADC - 4 Channel (ADS1015)

DEV-15334
$9.95

The SparkFun Qwiic (12-bit) ADC provides four channels of I2C controlled ADC input to your Qwiic enabled project. These four channels can be used as single-ended inputs, or in pairs for differential inputs. The ADS1015 uses its own internal voltage reference for measurements, but the ground and 3.3V power are also available on the pin outs for users.

Note: The maximum resolution of the converter is 12-bits in differential mode and 11-bits for single-ended inputs. Step sizes range from 125μV per count to 3mV per count depending on the full-scale range (FSR) setting.

Required Materials

The SparkFun Qwiic ADC does need a few additional items for you to get started; a Qwiic enabled microcontroller, a Qwiic cable, and jewelry/precision screwdrivers (with 1.5mm and 2.5mm flathead bits). You may already have a few of these items, so feel free to modify your cart based on your needs.

SparkFun Thing Plus - ESP32 WROOM

SparkFun Thing Plus - ESP32 WROOM

WRL-14689
$20.95
4
SparkFun RedBoard Turbo - SAMD21 Development Board

SparkFun RedBoard Turbo - SAMD21 Development Board

DEV-14812
$24.95
2
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
SparkFun Thing Plus - SAMD51

SparkFun Thing Plus - SAMD51

DEV-14713
$19.95
SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
1
Magnetic Screwdriver Set (20 Piece)

Magnetic Screwdriver Set (20 Piece)

TOL-15003
$6.95
1

Suggested Reading:

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

Analog to Digital Conversion

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

I2C

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

How to Work with Jumper Pads and PCB Traces

Handling PCB jumper pads and traces is an essential skill. Learn how to cut a PCB trace, add a solder jumper between pads to reroute connections, and repair a trace with the green wire method if a trace is damaged.

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.

Hardware Overview

Power

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

Power LED, VDD, and GND
Annotated image of power LED along with VCC and GND connections.

(*If you want to remove the power LED to conserve power, you will need to de-solder or hotair rework the LED.)

Analog Inputs

Caution: The analog input voltage range is (GND - .3V) to (VDD + .3V); anything slightly higher or lower and you will damage the ADC chip. If you are using the Qwiic system, this is approximately -.3V to 3.6V in reference to the GND pin. If the voltages on the input pins can potentially violate these conditions, use external Schottky diodes and series resistors to limit the input current to safe values (as mentioned in the datasheet).

There are four input measurement channels for the ADS1015, labeled AIN0-3, accessible through the screw pin terminals shown below. With the Qwiic system, the absolute minimum and maximum voltage for these inputs is -.3V and 3.6V, respectively.

Annotated Image of Inputs
Annotated image of input connections on board.
Click to enlarge.
Using Screw Terminals
Example of attaching inputs through screw terminals. Click to enlarge.

Depending on the settings for the multiplexer (MUX) in the ADS1015, the analog voltage readings (or conversions on the ADC) will be either for 4 single-ended inputs or 2 differential pairs.

Pin LabelConfiguration Options
AIN0 Single-Ended
Differential Inputs: AIN1 or AIN3 w/ Programmable Comparator
AIN1 Single-Ended
Differential Ref. w/ Programmable Comparator
Differential Input: AIN3 w/ Programmable Comparator
AIN2 Single-Ended
Differential Input: AIN3 w/ Programmable Comparator
AIN3 Single-Ended
Differential Ref. w/ Programmable Comparator
On-board 10kΩ Potentiometer
Note: For high accuracy measurements, input impedance should be taken into consideration. Additionally, any noise from the power supply to the ADC will be passed on to the output measurements.

Potentiometer

In addition, there is an onboard 10kΩ potentiometer, attached to AIN3 that is used in the examples and can be used for testing. The potentiometer is connected directly to 3.3V and GND so the voltage range will always be defined by the power input to the board.

Annotated Image of Pot
Annotated image of potentiometer on board.
Click to enlarge.
Using Potentiometer
For the potentiometer, we recommend using 1.5mm flathead precision screwdriver. Click to enlarge.

When using AIN3 as the negative/reference input be sure to cut the jumper to remove the potentiometer for accurate differential readings (see Jumper section below).

ADS1015 ADC

The ADS1015 ADC is a low-power 12-bit analog-to-digital converter (ADC), which includes a built-in integrated voltage reference and oscillator. At the core of its operation, the ADC uses a switched-capactior input stage and a delta-sigma (ΔΣ) modulator to determine the differential between AINP (positive analog input) and AINN (negative analog input). Once the conversion is completed, the digital output is accessible over the I2C bus from the internal conversion register.

Interested in how ΔΣ ADCs work? Here are TI's application notes: How delta-sigma ADCs work, Part 1 and Part 2.
Annotated Image of Pot
Annotated image of ADS1015 on board. Click to enlarge.
Functional block diagram
Functional block diagram from datasheet. Click for more details.


Note: The ADS1015 has an integrated voltage reference; an external reference voltage cannot be used.

The ADS1015 is a powerful tool with multiple configuration settings, set by the Config Register, for the analog voltage readings (or conversions). In the following sections, we will cover the general operation of the ADS1015. For exact details of the various configuration settings, please refer to the manufacturer datasheet. The operational characteristics of the ADS1015 are summarized in the table below.

CharacteristicDescription
Operating Voltage (VDD)2.0V to 5.5V (Default on Qwiic System: 3.3V)
Operating Temperature-40°C to 125°C
Operation ModesSingle-Shot (Default), Continuous-Conversion, and Duty Cycling
Analog Inputs Measurement Type: Single-Ended or Differential
Input Voltage Range: GND to VDD (see Caution note, below)
Maximum Voltage Measurement: Smallest ofVDD or FSR
Full Scale Range (FSR): ±.256V to ±6.114V (Default: 2.048V)
Resolution 12-bit (Differential) or 11-bit (Single-Ended)
LSB size: 0.125mV - 3mV (Default: 1 mVbased on FSR)
Sample Rate128 Hz to 3.3 kHz (Default: 1600SPS)
Current Consumption (Typical) Operating: 150μA to 200μA
Power-Down: 0.5μA to 2μA
I2C Address0x48 (Default), 0x49, 0x4A, or 0x4B
Caution: The absolute, analog input voltage range is (GND - .3V) to (VDD + .3V); anything slightly higher/lower may damage the ADC chip. If the voltages on the input pins can potentially violate these conditions, as specified by the datasheet, use external Schottky diodes and series resistors to limit the input current to safe values.

Operational Modes

The ADS1015 has 2 different conversion modes: single-shot and continuous-conversion with the ability to support duty cycling. Through these modes, the ADS1015 is able to optimize its performance between low power consumption and high data rates.

Single-Shot

By default, the ADS1015 operates in single-shot mode. In single-shot mode, the ADC only powers up for ~25μs to convert and store the analog voltage measurement in the conversion register before powering down. The ADS1015 only powers up again for data retrieval. The power consumption in this configuration is the lowest, but it is dependent on the frequency at which data is converted and read.

Duty Cycling

In single-shot mode, the ADS1015 can be duty cycled to periodically request high data rate readings. This emulates an intermediary configuration between the low power consumption of the single-shot mode and the high data rates of the continuous-conversion mode.

Continuous-Conversion

In this mode, the ADS1015 continuously performs conversions on analog voltage measurements and places the data in the conversion register. If the configuration settings are changed in the middle of the conversion process, the settings take effect once the current process is completed.

Input Multiplexer (MUX)

There are four input measurement channels for the ADS1015, labeled AIN0-3. The input multiplexer controls which of those channels operates as the AINP (positive analog input) and AINN (negative analog input) to the ADC. Depending on the input MUX configuration, the voltage measurements will be either on single-ended inputs or as differential pairs.

MUX functional block diagram
Operational digram of multiplexer from datasheet.

There are 8 MUX configurations to designate the analog voltage inputs to the ADC of the ADS1015, shown in the table below. The default configuration of the ADS1015 uses inputs AIN0 and AIN1 as highlighted in bold in the table below.

InputsMUX Configurations
DifferentialSingle-Ended
AINpAIN0AIN0AIN1AIN2AIN0AIN1AIN2AIN3
AINNAIN1AIN3AIN3AIN3GNDGNDGNDGND

Programmable Gain Amplifier

A programmable gain amplifier (PGA) is implemented before the ΔΣ ADC. The ADS1015 has 6 programmable gain settings, which are expressed in the full-scale range (FSR) of the ADC scaling. The maximum analog measurement is then defined by the smaller of the FSR or VDD. By default, the ADS1015 has a resolution of 1mV by using an FSR of ±2.048V as highlighted in bold in the table below.

Gain:1684212/3
Resolution (LSB):0.125 mV0.25 mV0.5 mV1 mV2 mV3 mV
FSR (12-bit):±256 mV±512 mV±1.024 V±2.048 V±4.048 V±6.144 V

Analog-to-Digital Conversion

Although, it is listed as a 12-bit ADC, the ADS1015 operates as an 11-bit ADC when used with single-ended (individual) inputs. The 12th bit only comes into play in differential mode, as a sign (+ or -) indicator for the digital output. This allows the digital output to represent the full positive and negative range of the FSR (see table and figure below).

Data format
Explanation of how data output and sign bit work from datasheet.
Limitation of ADS1015

Since the ADS1015 only uses an internal reference voltage, the FSR is to be defined by the design of the 12-bit ADC:

FSR = LSB x 212
where, the LSB = 0.125, 0.25, 0.5, 1, 2, or 3 mV.

Due to the configuration options, it is difficult to make full use of the full-scale range of the ADS1015 with common (useful) voltages. See the examples below for a more detailed explanation:

If the FSR = 2.048V and VDD = 3.3V:

  • Resolution of the digital data: 1mV (defined by FSR)
  • Input voltage range: 0-3.3V (defined by VDD)
  • Data Range: 0000h-7FF0h (HEX) or 0-2.048V
  • The range of the input voltage that can be read by the ADC is limited by FSR. Any voltage higher than the FSR (but less than VDD) reads the same maximum value in the digital output because the FSR is maxed out. In this case, you are maximizing the resolution (use of the data output), but not the full, allowable range of analog input (0-3.3V).

If the FSR = 4.096V and VDD = 3.3V:

  • Resolution of the digital data: 2mV (defined by FSR)
  • Input voltage range: 0-3.3V (defined by VDD)
  • Data Range: 0000h-0672h (HEX) or 0-3.3V
  • The data range is limited by VDD, any higher input voltage will continue to have data up to the electrical specifications of the ADS1015 ~VDD + 0.3V, where the IC gets damaged. In this case, the input voltage is being maximized to the electrical specification (0-3.3V). However, this means you are effectively only using 80% of the full resolution of the ADC (i.e. a 10.8-bit ADC at 3.3V).
Data Rate & Conversion Time

The ADS1015 offers 7 selectable output data rates of 128 SPS, 250 SPS, 490 SPS, 920 SPS, 1600 SPS, 2400 SPS, or 3300 SPS. Conversions for the ADS1015 settle within a single cycle; thus, the conversion time is equal to 1/DR.

Programmable Digital Comparator

The ADS1015 features a programmable digital comparator that can trigger the ALERT/RDY pin to indicate when conversion data is ready. By default, the comparator is disabled. However, when activated, the comparator operates in either a traditional or window mode. The upper and lower thresholds for the comparator are set by the last two registers on the ADS1015; while, the polarity (active low/high), latching or non-latching, operational mode, and enabling of the ALERT/RDY pin are set in the Config register.

Qwiic or I2C

I2C Address

The ADS1015 has 4 available I2C addresses, which are set by the address pin, ADDR. On the Qwiic ADC, the default slave address of the ADS1015 is 0x48 (HEX) of 7-bit addressing, following I2C protocol. The ADS1015 does have an additional general call address that can be used to reset all internal registers and power down the ADS1015 (see datasheet).

Default I2C Slave Address: 0x48

I2C Registers

The ADS1015 has four 16-bit registers, which are accessible through the I2C bus using the Address Pointer register. The Address Pointer register is an 8-bit byte that is written immediately after the slave address byte, low R/W bit.

AddressDescription
N/AAddress Pointer Register (8-bit): Used to grant R/W access to the four available registers on the ADS1015.
0x00Conversion Register (16-bit): Contains result of last conversion (i.e. measurement).
0x01Config Register (16-bit): Used the for configuration setting of the ADS1015.
0x02Low Threshold Register (16-bit): Low threshold value for digital comparator.
0x03High Threshold Register (16-bit): High threshold value for digital comparator.

Connections

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

Qwiic Connectors
Annotated image of the Qwiic connectors.

However, the board also provides five labeled breakout pins. You can connect these lines to the I2C bus of your microcontroller and power pins (3.3V and GND), if it doesn't have a Qwiic connector. The ALERT/RDY pin is broken out to use for triggered events (requires pull-up resistor).

Breakout Pins
Annotated image of the breakout pins.
Pin LabelPin FunctionInput/OutputNotes
3.3VPower SupplyInput3.3V on Qwiic system (should be stable)
GNDGroundInputGround and Single-Ended Reference Voltage for ADC.
SDAI2C Data SignalBi-directionalBi-directional data line. Voltage should not exceed power supply (e.g. 3.3V).
SCLI2C Clock SignalInputMaster-controlled clock signal. Voltage should not exceed power supply (e.g. 3.3V).
ALERT/RDYAlert/InterruptOutputComparator

Jumpers

Caution: Be careful when cutting traces, as not to unintentionally cut other traces.

There are jumpers on the board allowing the user to select between different I2C addresses, to remove the pull up resistors from the I2C pins, and to disconnect the potentiometer on AIN3.

I2C Address

The ADS1015 has four available I2C addresses, which can be configured by the jumpers on the back of the board. The address selection pin is connected to the center pad of the jumpers, the below table shows the addresses available when the address selection pin is tied to each of the 4 available pads.

PinGNDVCCSDASCL
Address0x48 (Default)0x490x4A0x4B
Note: Make sure this jumper is only shorted on one of the four available pads. There is a pullup jumper on the 3.3V pad, but to help prevent a shorts if multiple pads are accidentally bridged.

The address selection pin, by default is tied to GND on the PCB. Cutting the trace and bridging the I2C address jumper to another pad changes the slave address from I2C Jumper Default: 0x48. The location of the jumpers is shown in the image below.

Address Jumpers
Annotated image of the I2C address jumper.

I2C Pull-up Jumper

Cutting the I2C jumper will remove the 2.2 kΩ pull-up resistors from the I2C bus. If you have multiple devices with pull-up resistors on your I2C bus, you may want to cut these jumpers. (When there are multiple devices on the bus with pull-up resistors, the equivalent parallel resistance may create too strong of a pull-up for the bus to operate correctly.) Not sure how to cut a jumper? Read here!

Pull-up Jumper
Annotated image of the I2C pull-up jumper.

Potentiometer

Cutting the potentiometer jumper will disconnect 10kΩ potentiometer from the AIN3 input pin.

Potentiometer Jumper
Annotated image of the potentiometer jumper.

Hardware Assembly

With the Qwiic connector system, assembling the hardware is fairly simple. For the examples below, all you need to do is connect your Qwiic ADC to Qwiic enabled microcontroller with a Qwiic cable. Otherwise, you can use the I2C pins, if you don't have a Qwiic connector on your microcontroller board. Just be aware of your input voltage and any logic level shifting you may need to do.

Example setup with RedBoard Qwiic
Example setup with RedBoard Qwiic.

Additionally, you can connect your input voltages to the available inputs on the screw terminals and or use the breakout pins on the board. Make sure the connections are fully inserted and that you are ground looping your inputs. Ground looping can be done by connecting the ground of your input to the ground of the ADC.

Using Screw Terminals
Example of attaching inputs through screw terminals.

Arduino Library

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

We've written a library to easily get setup and take readings from the Qwiic 12-bit ADC. However, before we jump into getting data from the sensor, 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 ADS1015 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:

Let's get started by looking at the functions that set up the Qwiic 12-bit ADC.

Setup and Settings

  • .begin() or .begin(i2caddr, Wire)
Creates a connection to an I2C device over the I2C bus using the default or specified I2C address.

Input: i2caddr
Unassigned 8-bit integer for device address. If not defined, the library will use the default I2C address stored in the I2C library (0x48). Other available addresses are 0x49, 0x4A, 0x4B (set by a 4-way solder jumper on the bottom side of the board).
Input: Wire
Wire port assignment. If not defined, the library will use the default Wire port. Note, this is only available to change on boards that in fact have multiple Wire Ports (like the Teensey).
Output: Boolean

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


  • .isConnected()
Checks to see if a device over the I2C bus is connected. Returns boolean true or false depending on if the slave device has correctly ack'd to an I2C request.

Output: Boolean

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


  • .setMode(uint16_t mode)
Set the read mode of the sensor (continuous or single-shot).

Input: Unassigned 16-bit integer

0 - Continuous.
1 - Single-shot.


  • .getMode()
Returns which read mode you are currently in: continuous (0) or single-shot (1).

Output: Unassigned 16-bit integer

0 - Continuous.
1 - Single-shot.


  • .setGain(uint16_t gain)
Sets the gain of the programmable gain amplifier (PGA) inside the ADS1015. Note, this gain amplifier is located just before the ADC converter, so it greatly effects your readings and can cause your readings to "max out". Pass in one of the following #define variables from the library to easily set the gain.

Input: Unassigned 16-bit integer

ADS1015_CONFIG_PGA_TWOTHIRDS : &pm; 6.144V
ADS1015_CONFIG_PGA_1 : &pm; 4.096V
ADS1015_CONFIG_PGA_2 : &pm; 2.048V (default)
ADS1015_CONFIG_PGA_4 : &pm; 1.024V
ADS1015_CONFIG_PGA_8 : &pm; 0.512V
ADS1015_CONFIG_PGA_16 : &pm; 0.256V


  • .getGain()
Returns the gain of the programmable gain amplifier (PGA) inside the ADS1015. This returns a 16-bit hex value. The values and their corresponding gains and voltage ranges are as follows.

Output: Unassigned 16-bit integer

0x0000 - gain:2/3, input range:&pm; 6.144V
0X0200 - gain:1, input range: &pm; 4.096V
0X0400 - gain:2, input range: &pm; 2.048V
0X0600 - gain:4, input range: &pm; 1.024V
0X0800 - gain:8, input range: &pm; 0.512V
0X0A00 - gain:16, input range: &pm; 0.256V


  • .setSampleRate(uint16_t sampleRate)
Sets the sample rate of the ADS1015. Use the following #define variables.

Input: Unassigned 16-bit integer

ADS1015_CONFIG_RATE_128HZ
ADS1015_CONFIG_RATE_250HZ
ADS1015_CONFIG_RATE_490HZ
ADS1015_CONFIG_RATE_920HZ
ADS1015_CONFIG_RATE_1600HZ (default)
ADS1015_CONFIG_RATE_2400HZ
ADS1015_CONFIG_RATE_3300HZ


  • .setComparatorSingleEnded(uint8_t channel, int16_t threshold)
Sets up a single ended comparator that will effect the ALERT pin on the ADS1015 (active LOW by default) when a reading above the threshold is read. Note, you must call .getLastConversionResults() for this to reset. See Example5_Alert.ino in the library for more info.

Input: channel

Unassigned 8-bit integer. Available values are 0, 1, 2, and 3 (for the corresponding A0, A1, A2, and A3).

Input: threshold

Signed 16-bit integer. Possible values are decimal 0-2047. 1000 is about 3V.


  • .getSampleRate()
Returns the sample rate of the ADS1015 as an unassigned 16-bit integer value. The values and their corresponding sample rates are as follows.

Output: Unassigned 16-bit integer

0x0000 : 128HZ
0X0200 : 250HZ
0X0400 : 490HZ
0X0600 : 920HZ
0X0800 : 1600HZ
0X0A00 : 2400HZ
0X0A00 : 3300HZ


  • .getAnalogData()
    .getScaledAnalogData()
    .calibrate()
    .setCalibration()
    .getCalibration()
    .resetCalibration()
These functions are used primarily for use with the Qwiic Flex Glove Controller (which uses the same Arduino library). Please see the Qwiic Flex Glove Controller hookup guide for more information.


Readings

  • .getSingleEnded(uint8_t channel);
Returns the single ended analog value from the sensor on the specified channel.

Input: channel
Unasssigned 8-bit integer for channel you'd like to read. Available channels are 0, 1, 2, 3. These correspond to the channels on the board labeled A0, A1, A2, and A3.
Output: Unasssigned 16-bit integer

This return values from decimal 0 - 2047 (or HEX 0x0000 - 0x07FF). Note, this is only 11 bits of precision on a single-ended input. 12-bit resolution is only available on differential inputs.


  • .getDifferential() or .getDifferential(uint8_t channel)
Returns a signed differential analog value from the sensor on the specified pairs of channels. If no argument is passed, then it will use the default pair of channels (A0 and A1).

Input: channel
ADS1015_CONFIG_MUX_DIFF_P0_N1 (default)
ADS1015_CONFIG_MUX_DIFF_P0_N3
ADS1015_CONFIG_MUX_DIFF_P1_N3
ADS1015_CONFIG_MUX_DIFF_P2_N3

Output: Signed 16-bit integer

This return signed values from decimal -2047 up to +2047.


Arduino Examples

Example 1: Read Basic

The code for Example1_ReadBasic.ino connects to the Qwiic 12-bit ADC and prints out the value of channel A3 over the Serial Monitor at BAUD 9600. Below is a sample readout from the Serial Monitor rotating the onboard trimpot from MIN (all the way CCW) to MAX (all the way CW), and then back to MIN again. Notice how it "maxes out" at 2047, this is because the trimpot is inputing voltages from 0 to 3.3V. And with the default gain of 2 the input range of the ADC is only up to 2.048V.

Serial readout for example 1 numbers go from 0 up to 2047 then back down again to 0

Serial Monitor readout for Example 1.

Example 2: Change Gain

The code for Example2_ChangeGain.ino operates exactly like the Example1_ReadBasic.ino, except the gain is set to 2. This means that it can now accept voltages from 0 to 4.096V with a resolution of 2mV. Below is a sample readout. Notice how when rotating the trimpot (0-3.3V), I can only get the reading up to 1651. This is because we are not reaching the top of the ADC's range (at this gain of 1).

Serial Monitor readout for Example 2 numbers go up from 0 to 1651 then bakc down again

Serial Monitor readout for Example 2.

Example 3: Address

Caution: This example will not work if multiple I2C address jumpers are closed. Be sure to only close one of them.

The code for Example3_Address.ino connects to your Qwiic ADC on a specific address. You must modify the address jumper located on the bottom side of the board. Cut the trace connecting the default jumper, and then close the jumper that is labeled with the desired address. Example3_Address.ino works the same as Example1_ReadBasic.ino, however it passes an address argument to the .begin() function like so: adcSensor.begin(0x49);

screen capture of arduino ide highlighting the special use of dot begin with address argument included

Code screenshot with highlight on address argument for Example 3.

Example 4: Differential

The forth example, Example4_Differential.ino, shows how to read the ADC in differential mode using channels A0 and A1. For this example, I am using two trimpots (tied to GND and 3.3V) to supply voltage sources to A0 and A1. I have the A0 trimpot set to 2.5V, and it will stay there as a reference. In the readout below, I am rotating the A1 trimpot from 0V all the way up to 3.3V. You can see that I actually start at a negative value, because my rotating trimpot is actually sitting at 0V (or negative 2.5 Volts in relation to the other input).

differential readout

Serial Monitor readout for Example 4.

Example 5: Alert

Note: This example is requires soldering. A wire must be soldered to the ALERT pin and connected to a digital pin on your microcontroller. As written, the example assumes you are using a Arduino UNO based board, like our RedBoard. The sketch designates Pin 2 as the read pin.

The code for Example5_Alert.ino sets up a single ended comparator in the ADS1015 chip. It is watching A3, and it if it sees a value about the threshold of 1000 (about 3V), it will drop the ALERT pin. The serial monitor below shows state of the alert pin (as read from D2) and the value from the ADC. This shows that when you cross 1000, then the alert pin changes accordingly.

Serial Readout for Example 5 Alert pin the values start at 0 then increase to 1000 and engage the alert then drop back down to 0.

Serial Monitor readout for Example 5.

Example 6: Display MilliVolts

The last example, Example6_DisplayMillivolts.ino, will work much like Example1_ReadBasic.ino, however it also will print out the reading in millivolts. To convert from the raw reading values from the ADC, you must use a multiplier to get to millivolts. This changes depending on what gain setting you are using. For ease of use, we have included a function in the library that looks at your current gain settings, and then returns the correct multiplier you need. It is named .getMultiplier().

highlights code in sketch

Code highlight of .getMultiplier() in Example 6.

In the following serial monitor readout, you can see me turning the on-board trimpot on A3 (from 0V up to 3.3V) as it prints out both the return values and millivolts.

Serial monitor readout for example 6 showing raw values and mV for each reading

Serial Monitor readout for Example 6.

Troubleshooting

Here are a few tips for troubleshooting this device.

Power

If you are not using the Qwiic system, make sure your supply voltage is within the electrical specifications of the ADS1015.

Connections

Make sure your inputs have proper contacts and that you are grounding looping them. If you are using the inputs in differential mode, be sure to cut the potentiometer jumper for accurate readings.

Inputs Voltages

If the input voltage was outside (GND - .3)V - (VDD + .3) V, it is very likely that the ADS1015 was damaged and you probably need a new board.

Not Getting a Full 12-bits

If you are expecting to use the full resolution of the 12-bit for the ADC, but you are having issues; check out the brief explanation of the data in the hardware section. The ADS1015 is effectively a 10.6-bit ADC when powered at 3.3V and using a 4.096 FSR.

No Available Devices in Examples

Usually an issue in attempt to connect to the Qwiic ADC.

  • Check the I2C address jumper on the board and the defined I2C address in the code.
  • Check Qwiic cables and make sure they are fully inserted. Try a another cable if possible.
  • If you aren't using the Qwiic system, double check your logic levels. You should be using a logic level converter between different logic levels.
  • Try the I2C scanner code to search for devices on the I2C bus. You may have changed the I2C address (code or hardware) and forgotten.

Resources and Going Further

For more product information, check out the resources below:

Need some inspiration for your next project? Check out some of these other Qwiic product tutorials:

Qwiic Micro OLED Hookup Guide

Get started displaying things with the Qwiic Micro OLED.

Qwiic IR Array (MLX90640) Hookup Guide

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

Qwiic Quad Relay Hookup Guide

SparkFun’s Qwiic Quad Relay is a product designed for switching not one but four high powered devices from your Arduino or other low powered microcontroller using I2C.
New!

Displaying Your Coordinates with a GPS Module

This Arduino tutorial will teach you how to pinpoint and display your GPS coordinates with a press of a button using hardware from our Qwiic Connect System (I2C).

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

ARM Programming

$
0
0

ARM Programming a learn.sparkfun.com tutorial

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

Introduction

Heads up! This tutorial was written for ARM microcontrollers with SWD or JTAG pins. You will need a dedicated programmer (i.e. J-Link EDU Mini or J-Link EDU Base) to connect to the port. If you are using an AVR microcontroller with an Arduino bootloader using ICSP pins, you'll need to head on over to the Installing an Arduino Bootloader tutorial.

SparkFun has been a fan of Arduino for a long time. We've programmed ATMega328s (and 168s, and 8s before that), written tutorials, and hacked all sorts of fun projects. But now the market is maturing and we are looking at a lot more ARM chips. One advantage of the newer chips is that they generally do not need a USB-to-serial adapter; instead they have USB built in (at least the ones we are using do). You still need to add a bootloader to use them with Arduino, and since ARM programmers are also a little more complicated than AVR programmers you'll want to invest in a stand alone programmer instead of trying to use the Uno you have laying around.

A few ARM boards:

The Due: Arduino's first ARM boardMKR Vidor 4000: One of Arduino's newer Arm boardsRedBoard Turbo: One of SparkFun's newer boards SamD21 Dev Mini: One of SparkFun's ARM boardsSmD51 Thing Plus board: SparkFun's newest ARM board

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 following concepts, we recommend checking out these tutorials before continuing.

PCB Basics

What exactly IS a PCB?

Installing an Arduino Bootloader

This tutorial will teach you what a bootloader is and why you would need to install or reinstall it. We will also go over the process of burning a bootloader by flashing a hex file to an Arduino microcontroller.

Installing Arduino IDE

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

Integrated Circuits

An introduction to integrated circuits (ICs). Electronics' ubiquitous black chips. Includes a focus on the variety of IC packages.

What is an ARM?

Let's start with what an ARM processor is. They are used in everything from the Redboard Turbo to the Raspberry Pi to most cellphones, but that's a large range of performance. ARM is actually a unique business model. Arm Holdings does the design work for the cores and holds the patents/copyright/other legal things and then licenses the design out. The cores are then put into CPUs, microcontrollers, SOCs (System on Chip), etc. A company might decide they want to build a camera that uses the ARM core. They can license the core, maximize power efficiency, add some silicone for the camera sensor interface, and build the entire system onto a chip.

If you look around you'll actually see quite a few naming conventions. The v7 architectures lists 3 different profiles:

  • Cortex-A: the Application profile
  • Cortex-R: the Real-time profile
  • Cortex-M: the Microcontroller profile

We are going to be looking at Cortex-Ms. The Cortex M0/M0+ and M1 are actually from the v6 architecture and can be considered a subset for the v7 profile. All that to say that we are going to be looking at programming the SamD21 on our Redboard Turbo (and other boards) as well as the SamD51 on the Thing Plus. The SAMD21 is an ARM Cortex-M0, where the SAMD51 is an ARM Cortex-M4F.

Bootloaders

A bootloader is a small piece of code that looks at the programming port (in this case USB) to see if there is new code coming in. If there is, then it takes the code and puts it in a predetermined location. If there isn't, then it runs the code currently at that location.

Most Arduino boards have a bootloader that allows us to upload code over a USB port (or UART Serial connection). This way, once the bootloader is installed, we can program the board much easier. But sometimes we want to change the function of the bootloader, install a bootloader on a brand new board, or just skip the bootloader and install our code directly (makes it harder for other people to change the code on, say, a commercial product).

The bootloader we recommend using is the UF2 bootloader. You can go here for more information on UF2 bootloaders, or click on the button below to go to SparkFun's SAMD Bootloaders GitHub Repo:


UF2 is a file format designed by Microsoft that stands for USB Flashing Format. This format was designed for PXT (also known as Microsoft MakeCode) and allows for programming boards over the Mass Storage Class (removable drive). The bootloader is also compatible with BOSSA which is what the Arduino IDE uses. In other words, UF2 lets you write MakeCode, use Circuit Python, and use the Arduino IDE, all in one bootloader.

Whether you use the UF2 bootloader or another bootloader, you're going to have to download the file. Make sure the file you download is compatible with the board/configuration you are using. Check out our GitHub Respository for the SAMD bootloaders; the Turbo bootloader should work with these boards (you want the *.bin file).

JTAG and SWD

Joint Test Action Group

JTAG stands for Joint Test Action Group (the group who defined the JTAG standard) and was designed as a way to test boards. JTAG allows the user to talk to the bits and pieces of the microcontroller. In many cases, this involves giving them a set of instructions or programming the board. The JTAG standard defines 5 pins:

  • TCK: Test Clock
  • TMS: Test Mode Select
  • TDI: Test Data-In
  • TDO: Test Data-out
  • TRST: Test Reset (Optional)

The reduced pin count JTAG definition really only consists of 2 pins:

  • TMSC: Test Serial Data
  • TCKS: Test Clock

The 20 pin connector you see on some programmers was designed for JTAG and all those extra pin can be used for power, ground, and other things. While JTAG does not define a physical pin layout, there are a few common options. The 20 pin connector you see on Segger's J-Link EDU Base and Base Compact programmer is a good example.

JTAG Pinout

Serial Wire Debug

Serial Wire Debug (SWD) is really just a modification/implementation of JTAG specifically for ARM processors. SWD puts the 2 pins (SWDIO and SWCLK) on top of the JTAG pins allowing a user to use either JTAG or SWD without the need to breakout more pins.

SWD Pinout

SparkFun now carries 3 different ARM programmers from Segger. If you are just getting started and don't plan on making any money off your project, then the EDU Mini is a great place to start. If you want something a bit more powerful, the J-Link Base EDU is a good option. If you are planning on making money, you cannot use the EDU versions, in which case I recommend the Base Compact that we carry. This is the cheapest Segger ARM programmer without an EDU license. There are plenty of higher end programmers as well, but based on their price, you are only going to grab those if you know exactly what features you need from them. But don't worry, all these are more than capable of programming our boards.

J-Link EDU Mini Programmer

J-Link EDU Mini Programmer

PGM-15345
$18.00
J-Link EDU Base Programmer

J-Link EDU Base Programmer

PGM-15346
$60.00
J-Link BASE Compact Programmer

J-Link BASE Compact Programmer

PGM-15347
$378.00

First step is to download the J-Link Software. This software is good for updating the firmware on the programmers. Go ahead and open the Jlink Configurator and see if your programmer needs an update. The J-Link Software packages has a lot of features you can dig into, but we aren't going to use them. Feel free to play around and explore the software and all the debugging has to offer.

Hardware Hookup

Now it's time to hook things up. We will need to make sure that SWCLK and SWDIO are both connected to the microcontroller. On some of our larger boards, like the SAMD21 Dev board and the RedBoard Turbo, we managed to get the full 10 pin header. Our footprint shows a small dash where pin 1 goes. If you check the pinout above you'll notice that the notch goes on the same side as pin 1. You will probably want a 2x5 header to connect the cable to the board (you can either solder it on, or hold it on securely while programming).

10 Pin Headers on Various SparkFun Boards
SAMD21 MiniRedBoard TurboSAMD21 Dev

On other boards such as the ProRF or the SAMD51 Thing Plus you may have to dig into the schematic or board files to find the test points. There is at least one test point on all our boards since we program the boards after they are assembled and need access to them. Programming these might be a bit trickier without a jig, but I recommend holding a pair of jumper wires against the pads while uploading. It should only take a few seconds to program, but might be tricky and require an extra pair of hands.

Test Pads on the SparkFun SAMD51 Thing Plus Board
SAMD51 Board with SWDIO above MISO and SWDCLK below MIOSBack of SAMD51 board showing the 2 testpads

With the 2x5 header soldered into the 10 pin headers, connecting to the RedBoard Turbo is fairly straightforward:

Plugged in programmer

AVR Studio

Now that we've gotten everything hooked up it is time to program. There are a few different options for programming. Atmel studio is a great option (assuming you are using an ATMEL ARM processor like the SAMD line). Atmel Studio also lets you write programs in C, and compile your code. The Arduino IDE also lets you compile and download a *.hex file of your code. Make sure you download and install Atmel Studio (Windows 7 or later only)

Let's go ahead and open Atmel Studio. Then we'll go to Tools and then Device Programming. From the drop down you'll need to select your programmer as well as your device (you might have to agree to the Terms of Use first). Then hit Apply and it should verify your programmer. Then go ahead and read the Device signature and Target Voltage, this make sure everything is being read correctly. Feel free to look around, you can get quite a bit of Tool Information as well as Device Information.

Next, we'll go to the Memories tab, you'll probably want to select "Erase Flash before programming", and then select the location of your bootloader or other code. Hit Program and you should be good to go after a second or 2.

J Links Device programming Memories window

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

Troubleshooting

  • If you get an error when trying to program, check the Fuses tab. On many of our boards we set the bootloader protection to protect from accidental overwriting. Basically this defines the size of the bootloader. Setting this value to 0x07 will set the bootloader size to 0 and allow you to write to that space.

Setting boot protection

Resources and Going Further

Need more information? Check out some of the links below:

Check out these other great tutorials for ARM based boards from SparkFun:

SAMD21 Mini/Dev Breakout Hookup Guide

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

9DoF Razor IMU M0 Hookup Guide

How to use and re-program the 9DoF Razor IMU M0, a combination of ATSAMD21 ARM Cortex-M0 microprocessor and MPU-9250 9DoF-in-a-chip.

Wireless Joystick Hookup Guide

A hookup guide for the SparkFun Wireless Joystick Kit.

LoRaWAN with ProRF and The Things Network

Learn how to make a LoRaWAN node for your next long range IoT project and connect it to the internet with The Things Network!

RedBoard Turbo Hookup Guide

An introduction to the RedBoard Turbo. Level up your Arduino-skills with the powerful SAMD21 ARM Cortex M0+ processor!

Adding More SERCOM Ports for SAMD Boards

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

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

Qwiic pHAT for Raspberry Pi Hookup Guide

$
0
0

Qwiic pHAT for Raspberry Pi Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

This Qwiic pHAT for Raspberry Pi is based on the Qwiic Hat. The board adds the quickest and easiest way to utilize SparkFun's Qwiic ecosystem while still using that Raspberry Pi that you've come to know and love. This Qwiic pHAT connects the I2C bus (GND, 3.3V, SDA, and SCL) on your Raspberry Pi to an array of Qwiic connectors. Since the Qwiic system allows for daisy chaining (as long as your devices are on different addresses), you can stack as many sensors as you'd like to create a tower of sensing power!

SparkFun Qwiic pHAT for Raspberry Pi

SparkFun Qwiic pHAT for Raspberry Pi

DEV-15351
$5.95

Required Materials

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

Single Board Computer

You will need Raspberry Pi with 2x20 male headers installed.

Raspberry Pi 3 B+

Raspberry Pi 3 B+

DEV-14643
$39.95
28

A Pi Zero W will also work but you will need to make sure to solder some male headers to it.

Raspberry Pi GPIO Male Header - 2x20

Raspberry Pi GPIO Male Header - 2x20

PRT-14275
$0.95
Raspberry Pi Zero W

Raspberry Pi Zero W

DEV-14277
$10.00
24

Or you could stack it on any single board computer (like the NVIDIA Jetson Nano) that utilizes the 40-pin Raspberry Pi header footrpint.

NVIDIA Jetson Nano Developer Kit

NVIDIA Jetson Nano Developer Kit

DEV-15297
$99.00
4

Qwiic Board

Now you probably didn't buy the Qwiic pHAT if you didn't have any Qwiic products to use with it, right? If you don't have any Qwiic products, the following might not be a bad place to start.

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SparkFun Environmental Combo Breakout - CCS811/BME280 (Qwiic)

SEN-14348
$35.95
12
SparkFun GPS Breakout - XA1110 (Qwiic)

SparkFun GPS Breakout - XA1110 (Qwiic)

GPS-14414
$49.95
4
SparkFun Spectral Sensor Breakout - AS7262 Visible (Qwiic)

SparkFun Spectral Sensor Breakout - AS7262 Visible (Qwiic)

SEN-14347
$25.95
1
SparkFun Qwiic Adapter

SparkFun Qwiic Adapter

DEV-14495
$1.50

Finally, you'll need our handy Qwiic cables to easily connect sensors to your Qwiic pHAT. Below are a few options.

Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - 500mm

Qwiic Cable - 500mm

PRT-14429
$1.95
Qwiic Cable - 200mm

Qwiic Cable - 200mm

PRT-14428
$1.50
Qwiic Cable - 50mm

Qwiic Cable - 50mm

PRT-14426
$0.95

Required Setup Tools

As a desktop, these devices are required:

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.

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 pHAT has 4x Qwiic connect ports, all on the same I2C bus. A 3.3V regulator is included to regulate voltage down for any Qwiic boards connected.

Top View of Qwiic Hat

There are built-in pull-up resistors on board. If necessary, you can cut the traces to disable depending on the number of boards connected to the I2C bus.

Pull-Up Resistors

Hardware Assembly

To get started with your Qwiic pHAT, simply plug it into the headers on the Raspberry Pi with the letters facing you.

Qwiic pHat Being Inserted into Raspberry Pi

Once the pHAT is plugged in, you can start plugging in any Qwiic enabled sensors you might have on either side.

Qwiic pHat Inserted on Raspberry Pi and Connected to a Qwiic Sensor

Depending on your project, you can mount a qwiic enabled board on the mounting holes using standoffs.

Qwiic Distance Sensor Mounted on the Raspberry  Pi's pHat

Note: When placing a Raspberry Pi and the pHat in an enclosure (like the Pi Tin), we noticed that the pHAT was not fully inserted in Pi's header pins. You will need an additional stackable header for a secure connection depending on your enclosure.

I2C on Raspberry Pi

OS and Library Install

If you're starting from scratch, with a blank microSD card, you'll want to install Raspbian. If you've already got a working Raspbian system, skip ahead to step 3.

  1. Download the NOOBS image. As of this writing, it's at version 2.4.4.
  2. Follow the official installation instructions.
  3. Follow the Wiring Pi Instructions to get git, update and upgrade your Rasbpian packages, then install WiringPi.

Be patient -- each of these steps takes a while.

Once you've got wiringPi installed, run the gpio commands shown below.

language:bash
>gpio -v
>gpio readall

It should respond with some information about the wiringPi version and the Pi that its running on, then draw a table illustrating the configuration for the pins in the 40-pin connector.

Configuration

Like the SPI peripheral, I2C is not turned on by default. Again, we can use raspi-config to enable it.

  1. Run sudo raspi-config.
  2. Use the down arrow to select 5 Interfacing Options
  3. Arrow down to P5 I2C.
  4. Select yes when it asks you to enable I2C
  5. Select OK and then Finish

Once you return to terminal, enter this command:

language:bash
>ls /dev/*i2c*

The Pi should respond with:

language:bash
/dev/i2c-1

Which represents the user-mode I2C interface.

Utilities

There is a set of command-line utility programs that can help get an I2C interface working. You can get them with the apt package manager.

language:bash
sudo apt-get install -y i2c-tools

In particular, the i2cdetect program will probe all the addresses on a bus, and report whether any devices are present. Call i2cdetect -y 1 to probe the first I2C bus, which is what the Qwiic pHAT is connected to.

language:bash
pi@raspberrypi:~/$ i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: 60 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --

This map indicates that there is a peripheral at address 0x60. We can read and write its registers using the i2cget, i2cset and i2cdump commands.

Resources and Going Further

For more information, check out the resources below:

Now that you have your Qwiic pHAT ready to go, it's time to check out some of Qwiic enabled products.

Qwiic Cable - 200mm

Qwiic Cable - 200mm

PRT-14428
$1.50
SparkFun Qwiic HAT for Raspberry Pi

SparkFun Qwiic HAT for Raspberry Pi

DEV-14459
$5.95
1
SparkFun Thing Plus - SAMD51

SparkFun Thing Plus - SAMD51

DEV-14713
$19.95
Zio Current and Voltage Sensor - INA219 (Qwiic)

Zio Current and Voltage Sensor - INA219 (Qwiic)

SEN-15176
$7.95
1

But I Already Have Sensors!

If you already have a handful of SparkFun sensors and parts? SparkFun has been putting our standard GND/VCC/SDA/SCL pinout on all our I2C boards for many years. This makes it possible to attach a Qwiic Adapter that will get your SparkFun I2C sensor or actuator onto the Qwiic system.

Here is the list of the boards that have the standard I2C pinout and will work with the Qwiic adapter board:

Check out this related tutorial:

Raspberry Pi SPI and I2C Tutorial

October 29, 2015

Learn how to use serial I2C and SPI buses on your Raspberry Pi using the wiringPi I/O library for C/C++ and spidev/smbus for Python.

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

Qwiic 12-Bit ADC Hookup Guide

$
0
0

Qwiic 12-Bit ADC Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

An analog to digital converter (ADC) is very useful tool for converting an analog voltage to a digital signal that can be read by a microcontroller. The ability to converting from analog to digital interfaces allows users to use electronics to interface to interact with the physical world.

SparkFun Qwiic 12 Bit ADC - 4 Channel (ADS1015)

SparkFun Qwiic 12 Bit ADC - 4 Channel (ADS1015)

DEV-15334
$9.95

The SparkFun Qwiic (12-bit) ADC provides four channels of I2C controlled ADC input to your Qwiic enabled project. These four channels can be used as single-ended inputs, or in pairs for differential inputs. The ADS1015 uses its own internal voltage reference for measurements, but the ground and 3.3V power are also available on the pin outs for users.

Note: The maximum resolution of the converter is 12-bits in differential mode and 11-bits for single-ended inputs. Step sizes range from 125μV per count to 3mV per count depending on the full-scale range (FSR) setting.

Required Materials

The SparkFun Qwiic ADC does need a few additional items for you to get started; a Qwiic enabled microcontroller, a Qwiic cable, and jewelry/precision screwdrivers (with 1.5mm and 2.5mm flathead bits). You may already have a few of these items, so feel free to modify your cart based on your needs.

SparkFun Thing Plus - ESP32 WROOM

SparkFun Thing Plus - ESP32 WROOM

WRL-14689
$20.95
4
SparkFun RedBoard Turbo - SAMD21 Development Board

SparkFun RedBoard Turbo - SAMD21 Development Board

DEV-14812
$24.95
2
SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
SparkFun Thing Plus - SAMD51

SparkFun Thing Plus - SAMD51

DEV-14713
$19.95
SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
1
Magnetic Screwdriver Set (20 Piece)

Magnetic Screwdriver Set (20 Piece)

TOL-15003
$6.95
1

Suggested Reading:

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

Analog to Digital Conversion

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

I2C

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

How to Work with Jumper Pads and PCB Traces

Handling PCB jumper pads and traces is an essential skill. Learn how to cut a PCB trace, add a solder jumper between pads to reroute connections, and repair a trace with the green wire method if a trace is damaged.

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.

Hardware Overview

Power

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

Power LED, VDD, and GND
Annotated image of power LED along with VCC and GND connections.

(*If you want to remove the power LED to conserve power, you will need to de-solder or hotair rework the LED.)

Analog Inputs

Caution: The analog input voltage range is (GND - .3V) to (VDD + .3V); anything slightly higher or lower and you will damage the ADC chip. If you are using the Qwiic system, this is approximately -.3V to 3.6V in reference to the GND pin. If the voltages on the input pins can potentially violate these conditions, use external Schottky diodes and series resistors to limit the input current to safe values (as mentioned in the datasheet).

There are four input measurement channels for the ADS1015, labeled AIN0-3, accessible through the screw pin terminals shown below. With the Qwiic system, the absolute minimum and maximum voltage for these inputs is -.3V and 3.6V, respectively.

Annotated Image of Inputs
Annotated image of input connections on board.
Click to enlarge.
Using Screw Terminals
Example of attaching inputs through screw terminals. Click to enlarge.

Depending on the settings for the multiplexer (MUX) in the ADS1015, the analog voltage readings (or conversions on the ADC) will be either for 4 single-ended inputs or 2 differential pairs.

Pin LabelConfiguration Options
AIN0 Single-Ended
Differential Inputs: AIN1 or AIN3 w/ Programmable Comparator
AIN1 Single-Ended
Differential Ref. w/ Programmable Comparator
Differential Input: AIN3 w/ Programmable Comparator
AIN2 Single-Ended
Differential Input: AIN3 w/ Programmable Comparator
AIN3 Single-Ended
Differential Ref. w/ Programmable Comparator
On-board 10kΩ Potentiometer
Note: For high accuracy measurements, input impedance should be taken into consideration. Additionally, any noise from the power supply to the ADC will be passed on to the output measurements.

Potentiometer

In addition, there is an onboard 10kΩ potentiometer, attached to AIN3 that is used in the examples and can be used for testing. The potentiometer is connected directly to 3.3V and GND so the voltage range will always be defined by the power input to the board.

Annotated Image of Pot
Annotated image of potentiometer on board.
Click to enlarge.
Using Potentiometer
For the potentiometer, we recommend using 1.5mm flathead precision screwdriver. Click to enlarge.

When using AIN3 as the negative/reference input be sure to cut the jumper to remove the potentiometer for accurate differential readings (see Jumper section below).

ADS1015 ADC

The ADS1015 ADC is a low-power 12-bit analog-to-digital converter (ADC), which includes a built-in integrated voltage reference and oscillator. At the core of its operation, the ADC uses a switched-capactior input stage and a delta-sigma (ΔΣ) modulator to determine the differential between AINP (positive analog input) and AINN (negative analog input). Once the conversion is completed, the digital output is accessible over the I2C bus from the internal conversion register.

Interested in how ΔΣ ADCs work? Here are TI's application notes: How delta-sigma ADCs work, Part 1 and Part 2.
Annotated Image of Pot
Annotated image of ADS1015 on board. Click to enlarge.
Functional block diagram
Functional block diagram from datasheet. Click for more details.


Note: The ADS1015 has an integrated voltage reference; an external reference voltage cannot be used.

The ADS1015 is a powerful tool with multiple configuration settings, set by the Config Register, for the analog voltage readings (or conversions). In the following sections, we will cover the general operation of the ADS1015. For exact details of the various configuration settings, please refer to the manufacturer datasheet. The operational characteristics of the ADS1015 are summarized in the table below.

CharacteristicDescription
Operating Voltage (VDD)2.0V to 5.5V (Default on Qwiic System: 3.3V)
Operating Temperature-40°C to 125°C
Operation ModesSingle-Shot (Default), Continuous-Conversion, and Duty Cycling
Analog Inputs Measurement Type: Single-Ended or Differential
Input Voltage Range: GND to VDD (see Caution note, below)
Maximum Voltage Measurement: Smallest ofVDD or FSR
Full Scale Range (FSR): ±.256V to ±6.114V (Default: 2.048V)
Resolution 12-bit (Differential) or 11-bit (Single-Ended)
LSB size: 0.125mV - 3mV (Default: 1 mVbased on FSR)
Sample Rate128 Hz to 3.3 kHz (Default: 1600SPS)
Current Consumption (Typical) Operating: 150μA to 200μA
Power-Down: 0.5μA to 2μA
I2C Address0x48 (Default), 0x49, 0x4A, or 0x4B
Caution: The absolute, analog input voltage range is (GND - .3V) to (VDD + .3V); anything slightly higher/lower may damage the ADC chip. If the voltages on the input pins can potentially violate these conditions, as specified by the datasheet, use external Schottky diodes and series resistors to limit the input current to safe values.

Operational Modes

The ADS1015 has 2 different conversion modes: single-shot and continuous-conversion with the ability to support duty cycling. Through these modes, the ADS1015 is able to optimize its performance between low power consumption and high data rates.

Single-Shot

By default, the ADS1015 operates in single-shot mode. In single-shot mode, the ADC only powers up for ~25μs to convert and store the analog voltage measurement in the conversion register before powering down. The ADS1015 only powers up again for data retrieval. The power consumption in this configuration is the lowest, but it is dependent on the frequency at which data is converted and read.

Duty Cycling

In single-shot mode, the ADS1015 can be duty cycled to periodically request high data rate readings. This emulates an intermediary configuration between the low power consumption of the single-shot mode and the high data rates of the continuous-conversion mode.

Continuous-Conversion

In this mode, the ADS1015 continuously performs conversions on analog voltage measurements and places the data in the conversion register. If the configuration settings are changed in the middle of the conversion process, the settings take effect once the current process is completed.

Input Multiplexer (MUX)

There are four input measurement channels for the ADS1015, labeled AIN0-3. The input multiplexer controls which of those channels operates as the AINP (positive analog input) and AINN (negative analog input) to the ADC. Depending on the input MUX configuration, the voltage measurements will be either on single-ended inputs or as differential pairs.

MUX functional block diagram
Operational digram of multiplexer from datasheet.

There are 8 MUX configurations to designate the analog voltage inputs to the ADC of the ADS1015, shown in the table below. The default configuration of the ADS1015 uses inputs AIN0 and AIN1 as highlighted in bold in the table below.

InputsMUX Configurations
DifferentialSingle-Ended
AINpAIN0AIN0AIN1AIN2AIN0AIN1AIN2AIN3
AINNAIN1AIN3AIN3AIN3GNDGNDGNDGND

Programmable Gain Amplifier

A programmable gain amplifier (PGA) is implemented before the ΔΣ ADC. The ADS1015 has 6 programmable gain settings, which are expressed in the full-scale range (FSR) of the ADC scaling. The maximum analog measurement is then defined by the smaller of the FSR or VDD. By default, the ADS1015 has a resolution of 1mV by using an FSR of ±2.048V as highlighted in bold in the table below.

Gain:1684212/3
Resolution (LSB):0.125 mV0.25 mV0.5 mV1 mV2 mV3 mV
FSR (12-bit):±256 mV±512 mV±1.024 V±2.048 V±4.048 V±6.144 V

Analog-to-Digital Conversion

Although, it is listed as a 12-bit ADC, the ADS1015 operates as an 11-bit ADC when used with single-ended (individual) inputs. The 12th bit only comes into play in differential mode, as a sign (+ or -) indicator for the digital output. This allows the digital output to represent the full positive and negative range of the FSR (see table and figure below).

Data format
Explanation of how data output and sign bit work from datasheet.
Limitation of ADS1015

Since the ADS1015 only uses an internal reference voltage, the FSR is to be defined by the design of the 12-bit ADC:

FSR = LSB x 212
where, the LSB = 0.125, 0.25, 0.5, 1, 2, or 3 mV.

Due to the configuration options, it is difficult to make full use of the full-scale range of the ADS1015 with common (useful) voltages. See the examples below for a more detailed explanation:

If the FSR = 2.048V and VDD = 3.3V:

  • Resolution of the digital data: 1mV (defined by FSR)
  • Input voltage range: 0-3.3V (defined by VDD)
  • Data Range: 0000h-7FF0h (HEX) or 0-2.048V
  • The range of the input voltage that can be read by the ADC is limited by FSR. Any voltage higher than the FSR (but less than VDD) reads the same maximum value in the digital output because the FSR is maxed out. In this case, you are maximizing the resolution (use of the data output), but not the full, allowable range of analog input (0-3.3V).

If the FSR = 4.096V and VDD = 3.3V:

  • Resolution of the digital data: 2mV (defined by FSR)
  • Input voltage range: 0-3.3V (defined by VDD)
  • Data Range: 0000h-0672h (HEX) or 0-3.3V
  • The data range is limited by VDD, any higher input voltage will continue to have data up to the electrical specifications of the ADS1015 ~VDD + 0.3V, where the IC gets damaged. In this case, the input voltage is being maximized to the electrical specification (0-3.3V). However, this means you are effectively only using 80% of the full resolution of the ADC (i.e. a 10.8-bit ADC at 3.3V).
Data Rate & Conversion Time

The ADS1015 offers 7 selectable output data rates of 128 SPS, 250 SPS, 490 SPS, 920 SPS, 1600 SPS, 2400 SPS, or 3300 SPS. Conversions for the ADS1015 settle within a single cycle; thus, the conversion time is equal to 1/DR.

Programmable Digital Comparator

The ADS1015 features a programmable digital comparator that can trigger the ALERT/RDY pin to indicate when conversion data is ready. By default, the comparator is disabled. However, when activated, the comparator operates in either a traditional or window mode. The upper and lower thresholds for the comparator are set by the last two registers on the ADS1015; while, the polarity (active low/high), latching or non-latching, operational mode, and enabling of the ALERT/RDY pin are set in the Config register.

Qwiic or I2C

I2C Address

The ADS1015 has 4 available I2C addresses, which are set by the address pin, ADDR. On the Qwiic ADC, the default slave address of the ADS1015 is 0x48 (HEX) of 7-bit addressing, following I2C protocol. The ADS1015 does have an additional general call address that can be used to reset all internal registers and power down the ADS1015 (see datasheet).

Default I2C Slave Address: 0x48

I2C Registers

The ADS1015 has four 16-bit registers, which are accessible through the I2C bus using the Address Pointer register. The Address Pointer register is an 8-bit byte that is written immediately after the slave address byte, low R/W bit.

AddressDescription
N/AAddress Pointer Register (8-bit): Used to grant R/W access to the four available registers on the ADS1015.
0x00Conversion Register (16-bit): Contains result of last conversion (i.e. measurement).
0x01Config Register (16-bit): Used the for configuration setting of the ADS1015.
0x02Low Threshold Register (16-bit): Low threshold value for digital comparator.
0x03High Threshold Register (16-bit): High threshold value for digital comparator.

Connections

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

Qwiic Connectors
Annotated image of the Qwiic connectors.

However, the board also provides five labeled breakout pins. You can connect these lines to the I2C bus of your microcontroller and power pins (3.3V and GND), if it doesn't have a Qwiic connector. The ALERT/RDY pin is broken out to use for triggered events (requires pull-up resistor).

Breakout Pins
Annotated image of the breakout pins.
Pin LabelPin FunctionInput/OutputNotes
3.3VPower SupplyInput3.3V on Qwiic system (should be stable)
GNDGroundInputGround and Single-Ended Reference Voltage for ADC.
SDAI2C Data SignalBi-directionalBi-directional data line. Voltage should not exceed power supply (e.g. 3.3V).
SCLI2C Clock SignalInputMaster-controlled clock signal. Voltage should not exceed power supply (e.g. 3.3V).
ALERT/RDYAlert/InterruptOutputComparator

Jumpers

Caution: Be careful when cutting traces, as not to unintentionally cut other traces.

There are jumpers on the board allowing the user to select between different I2C addresses, to remove the pull up resistors from the I2C pins, and to disconnect the potentiometer on AIN3.

I2C Address

The ADS1015 has four available I2C addresses, which can be configured by the jumpers on the back of the board. The address selection pin is connected to the center pad of the jumpers, the below table shows the addresses available when the address selection pin is tied to each of the 4 available pads.

PinGNDVCCSDASCL
Address0x48 (Default)0x490x4A0x4B
Note: Make sure this jumper is only shorted on one of the four available pads. There is a pullup jumper on the 3.3V pad, but to help prevent a shorts if multiple pads are accidentally bridged.

The address selection pin, by default is tied to GND on the PCB. Cutting the trace and bridging the I2C address jumper to another pad changes the slave address from I2C Jumper Default: 0x48. The location of the jumpers is shown in the image below.

Address Jumpers
Annotated image of the I2C address jumper.

I2C Pull-up Jumper

Cutting the I2C jumper will remove the 2.2 kΩ pull-up resistors from the I2C bus. If you have multiple devices with pull-up resistors on your I2C bus, you may want to cut these jumpers. (When there are multiple devices on the bus with pull-up resistors, the equivalent parallel resistance may create too strong of a pull-up for the bus to operate correctly.) Not sure how to cut a jumper? Read here!

Pull-up Jumper
Annotated image of the I2C pull-up jumper.

Potentiometer

Cutting the potentiometer jumper will disconnect 10kΩ potentiometer from the AIN3 input pin.

Potentiometer Jumper
Annotated image of the potentiometer jumper.

Hardware Assembly

With the Qwiic connector system, assembling the hardware is fairly simple. For the examples below, all you need to do is connect your Qwiic ADC to Qwiic enabled microcontroller with a Qwiic cable. Otherwise, you can use the I2C pins, if you don't have a Qwiic connector on your microcontroller board. Just be aware of your input voltage and any logic level shifting you may need to do.

Example setup with RedBoard Qwiic
Example setup with RedBoard Qwiic.

Additionally, you can connect your input voltages to the available inputs on the screw terminals and or use the breakout pins on the board. Make sure the connections are fully inserted and that you are ground looping your inputs. Ground looping can be done by connecting the ground of your input to the ground of the ADC.

Using Screw Terminals
Example of attaching inputs through screw terminals.

Arduino Library

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

We've written a library to easily get setup and take readings from the Qwiic 12-bit ADC. However, before we jump into getting data from the sensor, 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 ADS1015 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:

Let's get started by looking at the functions that set up the Qwiic 12-bit ADC.

Setup and Settings

  • .begin() or .begin(i2caddr, Wire)
Creates a connection to an I2C device over the I2C bus using the default or specified I2C address.

Input: i2caddr
Unassigned 8-bit integer for device address. If not defined, the library will use the default I2C address stored in the I2C library (0x48). Other available addresses are 0x49, 0x4A, 0x4B (set by a 4-way solder jumper on the bottom side of the board).
Input: Wire
Wire port assignment. If not defined, the library will use the default Wire port. Note, this is only available to change on boards that in fact have multiple Wire Ports (like the Teensey).
Output: Boolean

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


  • .isConnected()
Checks to see if a device over the I2C bus is connected. Returns boolean true or false depending on if the slave device has correctly ack'd to an I2C request.

Output: Boolean

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


  • .setMode(uint16_t mode)
Set the read mode of the sensor (continuous or single-shot).

Input: Unassigned 16-bit integer

0 - Continuous.
1 - Single-shot.


  • .getMode()
Returns which read mode you are currently in: continuous (0) or single-shot (1).

Output: Unassigned 16-bit integer

0 - Continuous.
1 - Single-shot.


  • .setGain(uint16_t gain)
Sets the gain of the programmable gain amplifier (PGA) inside the ADS1015. Note, this gain amplifier is located just before the ADC converter, so it greatly effects your readings and can cause your readings to "max out". Pass in one of the following #define variables from the library to easily set the gain.

Input: Unassigned 16-bit integer

ADS1015_CONFIG_PGA_TWOTHIRDS : &pm; 6.144V
ADS1015_CONFIG_PGA_1 : &pm; 4.096V
ADS1015_CONFIG_PGA_2 : &pm; 2.048V (default)
ADS1015_CONFIG_PGA_4 : &pm; 1.024V
ADS1015_CONFIG_PGA_8 : &pm; 0.512V
ADS1015_CONFIG_PGA_16 : &pm; 0.256V


  • .getGain()
Returns the gain of the programmable gain amplifier (PGA) inside the ADS1015. This returns a 16-bit hex value. The values and their corresponding gains and voltage ranges are as follows.

Output: Unassigned 16-bit integer

0x0000 - gain:2/3, input range:&pm; 6.144V
0X0200 - gain:1, input range: &pm; 4.096V
0X0400 - gain:2, input range: &pm; 2.048V
0X0600 - gain:4, input range: &pm; 1.024V
0X0800 - gain:8, input range: &pm; 0.512V
0X0A00 - gain:16, input range: &pm; 0.256V


  • .setSampleRate(uint16_t sampleRate)
Sets the sample rate of the ADS1015. Use the following #define variables.

Input: Unassigned 16-bit integer

ADS1015_CONFIG_RATE_128HZ
ADS1015_CONFIG_RATE_250HZ
ADS1015_CONFIG_RATE_490HZ
ADS1015_CONFIG_RATE_920HZ
ADS1015_CONFIG_RATE_1600HZ (default)
ADS1015_CONFIG_RATE_2400HZ
ADS1015_CONFIG_RATE_3300HZ


  • .setComparatorSingleEnded(uint8_t channel, int16_t threshold)
Sets up a single ended comparator that will effect the ALERT pin on the ADS1015 (active LOW by default) when a reading above the threshold is read. Note, you must call .getLastConversionResults() for this to reset. See Example5_Alert.ino in the library for more info.

Input: channel

Unassigned 8-bit integer. Available values are 0, 1, 2, and 3 (for the corresponding A0, A1, A2, and A3).

Input: threshold

Signed 16-bit integer. Possible values are decimal 0-2047. 1000 is about 3V.


  • .getSampleRate()
Returns the sample rate of the ADS1015 as an unassigned 16-bit integer value. The values and their corresponding sample rates are as follows.

Output: Unassigned 16-bit integer

0x0000 : 128HZ
0X0200 : 250HZ
0X0400 : 490HZ
0X0600 : 920HZ
0X0800 : 1600HZ
0X0A00 : 2400HZ
0X0A00 : 3300HZ


  • .getAnalogData()
    .getScaledAnalogData()
    .calibrate()
    .setCalibration()
    .getCalibration()
    .resetCalibration()
These functions are used primarily for use with the Qwiic Flex Glove Controller (which uses the same Arduino library). Please see the Qwiic Flex Glove Controller hookup guide for more information.


Readings

  • .getSingleEnded(uint8_t channel);
Returns the single ended analog value from the sensor on the specified channel.

Input: channel
Unasssigned 8-bit integer for channel you'd like to read. Available channels are 0, 1, 2, 3. These correspond to the channels on the board labeled A0, A1, A2, and A3.
Output: Unasssigned 16-bit integer

This return values from decimal 0 - 2047 (or HEX 0x0000 - 0x07FF). Note, this is only 11 bits of precision on a single-ended input. 12-bit resolution is only available on differential inputs.


  • .getDifferential() or .getDifferential(uint8_t channel)
Returns a signed differential analog value from the sensor on the specified pairs of channels. If no argument is passed, then it will use the default pair of channels (A0 and A1).

Input: channel
ADS1015_CONFIG_MUX_DIFF_P0_N1 (default)
ADS1015_CONFIG_MUX_DIFF_P0_N3
ADS1015_CONFIG_MUX_DIFF_P1_N3
ADS1015_CONFIG_MUX_DIFF_P2_N3

Output: Signed 16-bit integer

This return signed values from decimal -2047 up to +2047.


Arduino Examples

Example 1: Read Basic

The code for Example1_ReadBasic.ino connects to the Qwiic 12-bit ADC and prints out the value of channel A3 over the Serial Monitor at BAUD 9600. Below is a sample readout from the Serial Monitor rotating the onboard trimpot from MIN (all the way CCW) to MAX (all the way CW), and then back to MIN again. Notice how it "maxes out" at 2047, this is because the trimpot is inputing voltages from 0 to 3.3V. And with the default gain of 2 the input range of the ADC is only up to 2.048V.

Serial readout for example 1 numbers go from 0 up to 2047 then back down again to 0

Serial Monitor readout for Example 1.

Example 2: Change Gain

The code for Example2_ChangeGain.ino operates exactly like the Example1_ReadBasic.ino, except the gain is set to 2. This means that it can now accept voltages from 0 to 4.096V with a resolution of 2mV. Below is a sample readout. Notice how when rotating the trimpot (0-3.3V), I can only get the reading up to 1651. This is because we are not reaching the top of the ADC's range (at this gain of 1).

Serial Monitor readout for Example 2 numbers go up from 0 to 1651 then bakc down again

Serial Monitor readout for Example 2.

Example 3: Address

Caution: This example will not work if multiple I2C address jumpers are closed. Be sure to only close one of them.

The code for Example3_Address.ino connects to your Qwiic ADC on a specific address. You must modify the address jumper located on the bottom side of the board. Cut the trace connecting the default jumper, and then close the jumper that is labeled with the desired address. Example3_Address.ino works the same as Example1_ReadBasic.ino, however it passes an address argument to the .begin() function like so: adcSensor.begin(0x49);

screen capture of arduino ide highlighting the special use of dot begin with address argument included

Code screenshot with highlight on address argument for Example 3.

Example 4: Differential

The forth example, Example4_Differential.ino, shows how to read the ADC in differential mode using channels A0 and A1. For this example, I am using two trimpots (tied to GND and 3.3V) to supply voltage sources to A0 and A1. I have the A0 trimpot set to 2.5V, and it will stay there as a reference. In the readout below, I am rotating the A1 trimpot from 0V all the way up to 3.3V. You can see that I actually start at a negative value, because my rotating trimpot is actually sitting at 0V (or negative 2.5 Volts in relation to the other input).

differential readout

Serial Monitor readout for Example 4.

Example 5: Alert

Note: This example is requires soldering. A wire must be soldered to the ALERT pin and connected to a digital pin on your microcontroller. As written, the example assumes you are using a Arduino UNO based board, like our RedBoard. The sketch designates Pin 2 as the read pin.

The code for Example5_Alert.ino sets up a single ended comparator in the ADS1015 chip. It is watching A3, and it if it sees a value about the threshold of 1000 (about 3V), it will drop the ALERT pin. The serial monitor below shows state of the alert pin (as read from D2) and the value from the ADC. This shows that when you cross 1000, then the alert pin changes accordingly.

Serial Readout for Example 5 Alert pin the values start at 0 then increase to 1000 and engage the alert then drop back down to 0.

Serial Monitor readout for Example 5.

Example 6: Display MilliVolts

The last example, Example6_DisplayMillivolts.ino, will work much like Example1_ReadBasic.ino, however it also will print out the reading in millivolts. To convert from the raw reading values from the ADC, you must use a multiplier to get to millivolts. This changes depending on what gain setting you are using. For ease of use, we have included a function in the library that looks at your current gain settings, and then returns the correct multiplier you need. It is named .getMultiplier().

highlights code in sketch

Code highlight of .getMultiplier() in Example 6.

In the following serial monitor readout, you can see me turning the on-board trimpot on A3 (from 0V up to 3.3V) as it prints out both the return values and millivolts.

Serial monitor readout for example 6 showing raw values and mV for each reading

Serial Monitor readout for Example 6.

Troubleshooting

Here are a few tips for troubleshooting this device.

Power

If you are not using the Qwiic system, make sure your supply voltage is within the electrical specifications of the ADS1015.

Connections

Make sure your inputs have proper contacts and that you are grounding looping them. If you are using the inputs in differential mode, be sure to cut the potentiometer jumper for accurate readings.

Inputs Voltages

If the input voltage was outside (GND - .3)V - (VDD + .3) V, it is very likely that the ADS1015 was damaged and you probably need a new board.

Not Getting a Full 12-bits

If you are expecting to use the full resolution of the 12-bit for the ADC, but you are having issues; check out the brief explanation of the data in the hardware section. The ADS1015 is effectively a 10.6-bit ADC when powered at 3.3V and using a 4.096 FSR.

No Available Devices in Examples

Usually an issue in attempt to connect to the Qwiic ADC.

  • Check the I2C address jumper on the board and the defined I2C address in the code.
  • Check Qwiic cables and make sure they are fully inserted. Try a another cable if possible.
  • If you aren't using the Qwiic system, double check your logic levels. You should be using a logic level converter between different logic levels.
  • Try the I2C scanner code to search for devices on the I2C bus. You may have changed the I2C address (code or hardware) and forgotten.

Resources and Going Further

For more product information, check out the resources below:

Need some inspiration for your next project? Check out some of these other Qwiic product tutorials:

I2C

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

CCS811/BME280 (Qwiic) Environmental Combo Breakout Hookup Guide

Sense various environmental conditions such as temperature, humidity, barometric pressure, eCO2 and tVOCs with the CCS811 and BME280 combo breakout board.

Qwiic IR Array (MLX90640) Hookup Guide

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

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!

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

SAMD51 Thing Plus Hookup Guide

$
0
0

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

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

Introduction

SparkFun is proud to welcome the SAMD51 Thing Plus to our microcontroller lineup! With a 32-bit ARM Cortex-M4F MCU, it is one of our most powerful microcontroller boards yet.

SparkFun Thing Plus - SAMD51

SparkFun Thing Plus - SAMD51

DEV-14713
$19.95

The ATSAMD51J20 microcontroller boasts a maximum CPU speed of 120MHz, 1MB of flash memory, 256KB of SRAM, up to 6 SERCOM interfaces, amongst other features (see datasheet). The SAMD51 Thing Plus provides a USB interface for programming and power, a Qwiic connector, 600mA 3.3V regulator, and LiPo charger all in a feather pin layout. For a full list of details, check out the Hardware Overview section below. In addition, this board comes flashed with the same convenient, UF2 bootloader as the RedBoard Turbo.

This tutorial aims to familiarize you with the new SAMD51 Thing Plus and help you get started using it. If you are new to the world of Arduino or microcontrollers, please check out our RedBoard Qwiic and RedBoard Qwiic Hookup Guide.

Required Materials

To get started, all you need is a few things:

  • SAMD51 Thing Plus - You'll definitely need this; otherwise, you are probably on the wrong tutorial page (wink).
  • USB micro-B Cable - 6 Foot - The USB interface serves two purposes: it powers the board and allows you to upload programs to it. (You might even have a few of these in you drawer!)
  • Computer with the Arduino IDE installed on it - That is how we will program the board and interface with it.
    Troubleshooting Tip: If you are not a technical or computer savy individual and you have your choice of computers, a Windows 10 computer is highly recommended. You will usually run into the the least issues, if any, with this operating systems.

That is ALL... pretty simple right? Now you won't be able to do much since there are no additional sensors to interact with the physical world. However, you can at least blink an LED and do some math calculations.

Click the buttons above to toggle the additional materials based on the tasks you
wish to perform. Feel free to modify the items in your cart to fit your needs.

Jumper Modification

If you would like to modify the 3.3V/5V I/O jumper or A4/A5 Qwiic connector jumpers, you will need soldering equipment and/or a knife.

Solder Lead Free - 100-gram Spool

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Weller WLC100 Soldering Station

Weller WLC100 Soldering Station

TOL-14228
$44.95
1
Chip Quik No-Clean Flux Pen  - 10mL

Chip Quik No-Clean Flux Pen - 10mL

TOL-14579
$7.95
2
Hobby Knife

Hobby Knife

TOL-09200
$2.95
2

Qwiic Example

If you would like to follow along with the examples below to interact with the physical world, you will also need the following items:

Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Magnetic Screwdriver Set (20 Piece)

Magnetic Screwdriver Set (20 Piece)

TOL-15003
$6.95
1
SparkFun Qwiic 12 Bit ADC - 4 Channel (ADS1015)

SparkFun Qwiic 12 Bit ADC - 4 Channel (ADS1015)

DEV-15334
$9.95

Headers & Accessories

If you would like to add headers to your board, check out some of the following items:

Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
SparkFun Beginner Tool Kit

SparkFun Beginner Tool Kit

TOL-14681
$54.95
Feather Stackable Header Kit

Feather Stackable Header Kit

PRT-15187
$1.50

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

Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
Female Headers

Female Headers

PRT-00115
$1.50
7
Arduino Stackable Header Kit - R3

Arduino Stackable Header Kit - R3

PRT-11417
$1.50
12
Break Away Male Headers - Right Angle

Break Away Male Headers - Right Angle

PRT-00553
$1.95
4
Insulated Silicone Soldering Mat

Insulated Silicone Soldering Mat

TOL-14672
$9.95
3
Weller WE1010 Soldering Station

Weller WE1010 Soldering Station

TOL-14734
$129.00
1
Solder Lead Free - 100-gram Spool

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
7
Solder - 1/4lb Spool (0.020") Special Blend

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

TOL-10242
$29.95
7

ARM Programmers

If you would like to debug or flash your ARM processor on your own, here are some of our ARM Programmers:

JTAG USB OCD Programmer/Debugger for ARM processors

JTAG USB OCD Programmer/Debugger for ARM processors

PGM-07834
$71.95
1
Atmel-ICE Programmer and Debugger

Atmel-ICE Programmer and Debugger

PGM-14950
$149.95
J-Link EDU Mini Programmer

J-Link EDU Mini Programmer

PGM-15345
$18.00
J-Link EDU Base Programmer

J-Link EDU Base Programmer

PGM-15346
$60.00

Suggested Reading

Before continuing on with this tutorial, you may want to familiarize yourself with some of these topics if they’re unfamiliar to you:

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.

What is an Arduino?

What is this 'Arduino' thing anyway?

Installing Arduino IDE

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

Adding More SERCOM Ports for SAMD Boards

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

How to Solder: Through-Hole Soldering

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

Logic Levels

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

I2C

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

ARM Programming

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

Qwiic Connect System

One of the new, advanced features of the board is that it takes advantage of the Qwiic connect system. We recommend familiarizing yourself with the Logic Levels and I2C tutorials (above) before using it, as all Qwiic sensors utilize an I2C communication protocol. Click on the banner above to learn more about Qwiic products.

UF2 Bootloader & Driver Verification

UF2 Bootloader

The SAMD51 Thing Plus is now easier than ever to program, thanks the the UF2 bootloader. With the UF2 bootloader, the SAMD51 Thing Plus shows up on your computer as a USB storage device without having to install drivers for Windows 10, Mac, and Linux!

From the Arduino IDE, you'll still need to select the correct port on your machine, but you can just as easily use another programming language such as CircuitPython or MakeCode, which will be available in the near future.

What is UF2?

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

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

Double-Tap to Launch the Bootloader

The bootloader is what allows us to load code over a simple USB interface. To upload code, you will need to manually enter bootloader mode by rapidly double-tapping the reset button (after hitting the reset button once, you have about half a second to hit it again). The board will remain in bootloader mode until power cycles (happens automatically after uploading code) or the reset button is hit again (once).

Bootloader GIF
Double-tapping the reset button to enter bootloader mode.

On the SAMD51 Thing Plus, the there are a clues to if it is in bootloader mode:

  • The D13 LED indicator will be a solid blue (may appear to be slowly fading or blinking).
  • Board will show up under a different COM port.
  • The board will appear as a USB mass storage device under the name 51THINGBOOT.

Driver Verification

To verify that your driver is working, you should see the difference in the following pictures after plugging in your SparkFun SAMD51 Thing Plus. Alternatively, once you have the Arduino IDE installed, you should also see a change in the number of available Serial/COM Ports (you may need to restart the Arduino IDE for the board to populate).

Windows

Check that the board shows up in your device manager. You can click the Start or (Windows) button and type "device" to quickly search for the application. (*On Windows 10, the quick search function is picky on the spelling of the application you are searching for. For example, you may get results using "devi" and none for "device".)

Windows 10 Device Manager Window
Screenshot of Window 10 Device Manager with the SAMD51 Thing Plus on COM113. Click to enlarge.

Mac OSX

Open the Terminal and run the following command ls /dev/cu.* in the Terminal and check for the following changes (your board may show up under a different device name). To open the Terminal, open your Applications folder, Utilities folder, then double-click on Terminal. Otherwise, press (Command) + space bar (Space Bar) to launch Spotlight and type "Terminal," then double-click the search result.

Mac OSX CLI Command Entry
Screenshot of Mac OSX terminal with the SAMD51 Thing Plus on cu.usbmodemFA121. Click to enlarge.
ls /dev/cu.*
Note: If you are still unsure of how to access the Terminal, watch this video or read this Apple support article.

Raspbian

Run the following command ls /dev/ttyACM* in the CLI/Terminal and check for the following changes (your board may show up under a different device name).

Raspbian CLI Command Entry
Screenshot of Raspberry Pi CLI with the SAMD51 Thing Plus on ttyACM0. Click to enlarge
ls /dev/ttyACM*

Setting Up the Arduino IDE

Download/Install Arduino

You can download the Arduino IDE from their website. They have installation instructions, but we will also go over the installation process as well. Make sure you download the version that matches your operating system.

Click for Arduino IDE Download Page

The installation procedure is fairly straightforward, but it does vary by OS. Here are some tips to help you along. We've also written a separate Installing Arduino tutorial in case you get stuck.

Troubleshooting Tips:
  • We recommend using a computer with a full desktop operating system like Windows 10 (avoid Windows 7/8 due to driver issues), Mac OSX, and certain flavors Linux (check the Arduino FAQ page for compatibility).

  • We do NOT recommend using a Chromebook, Netbook, tablet, phone, or the Arduino Web IDE in general. You will be responsible for troubleshooting any driver or Arduino Web IDE issues.

  • As of writing this tutorial (05-21-2019), the most recent and stable release of the Arduino IDE is version 1.8.5. We recommend using that version of the Arduino IDE; you can download the previous releases here.

  • On Windows 10, we do NOT recommend installing the Arduino IDE from the app store. You may run into issues because the OS will automatically update to the most recent release of the Arduino IDE, which may have unknown bugs (like the compiler errors in versions 1.8.6 and 1.8.7).

  • Raspberry Pi users with Raspbian installed should use the Linux ARM download. We do not recommend using the command line installation. It will install the oldest release of Arduino, which is useless when it comes to installing new boards definitions or libraries.

  • For additional troubleshooting tips, here is a troubleshooting guide from Arduino.

Click the buttons above for OS specific instructions.

Windows Install Tips

The Windows version of Arduino is offered in two options: an installer or a zip file. The installer is the easier of the two options, just download that, and run the executable file to begin the installation.

Windows 10- Arduino Installation Diagram
Windows install steps. Click the image to get a bigger view.

When you're prompted to install a driver during installation, select "Install". This will install drivers for Arduino specific boards (like the Uno, Nano, etc.) that you may use in the future.

  • If you choose to download the zip file version of Arduino, you'll need to extract the files yourself. Don't forget which folder you extract the files into! You will need to run the executable Arduino file in the folder to start the Arduino IDE.

  • On Windows 10, there is an option to install Arduino through their app store. we do not recommend installing the Arduino IDE from the app store. You may run into issues because the OS will automatically update to the most recent release of the Arduino IDE, which may have unknown bugs.

Mac Install Tips

The Mac download of Arduino is only offered in a zip file version. After the download is finished, simply double-click the .zip file to unzip it.

Mac Install Screenshot
Mac OSX Arduino.app

Following that, you'll need to copy the Arduino application into your applications folder to complete the installation.

Linux Install Tips

As Linux users are no doubt aware, there are many flavors of Linux out there, each with unique installation routines. Check out the FAQ section of the Arduino webpage for more details. Otherwise, you can also use the Linux section of our Installing Arduino tutorial for some helpful links for an assortment of Linux distributions.
Raspbian Stretch
Raspberry Pi users with Raspbian installed should use the Linux ARM download. Do not use the command line installation process. For more information, please refer to this blog post from Arduino.
Ubuntu and Debian
For Ubuntu and Debian users, installing Arduino should only need a simple "apt-get" command like:

sudo apt-get update && sudo apt-get install arduino arduino-core
Other Distributions
Other Linux distros aren't too dissimilar from the Ubuntu and Debian instructions.

With Arduino downloaded and installed, the next step is to plug the board in and test it out! Pretty soon you'll be blinking LEDs, reading buttons, and doing some physical computing!

Board Definitions for the SAMD Core

While the SAMD MCU alone is a powerful tool, what truly makes it special is its growing support in the Arduino IDE. With just a couple clicks, copies, and pastes, you can add support for our SAMD core to your Arduino IDE. This page will list every step required for adding the SAMD51 Thing Plus board definition into your Arduino IDE.

Note: If you have already installed our SAMD board definitions previously, you only need to update the SAMD cores for both SparkFun and Arduino to the most recent release.

Include SparkFun's Cores

Lets begin by making SparkFun's cores available to the Arduino IDE. This doesn't install the core/board definitions, but it does make them available for ease of use for future installations. Open the Arduino preferences (File>Preferences). Then find the Additional Board Manager URLs text box, and copy the below link in:

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

Arduino IDE Preferences Additional Moard Manager URLs
Preferences window from Arduino IDE with URL section highlighted. Click to enlarge.

For additional details, check out this guide on how cores work in the Arduino IDE.

Install the Arduino SAMD Core

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

To install the Arduino SAMD board definitions, navigate to your board manager (Tools>Board>Boards Manager...), then find an entry for Arduino SAMD Boards (32-bits ARM Cortex-M0+). It may help to enter *SAMD** into the search bar. Select the Arduino SAMD core and install the latest version (recently updated to _v1.6.21_).

Installing the Arduino SAMD boards
Board Manager in Arduino IDE with Arduino SAMD core highlighted. Click to enlarge.

Downloading and installing the tools may take a couple minutes -- arm-gcc in particular will take the longest, it's about 250MB unpacked. Once installed, the INSTALLED text should appear next to the SAMD boards list entry.

Install the SparkFun SAMD Add-on

Now that your ARM tools are installed, one last bit of setup is required to add support for the SparkFun SAMD boards. You should be able to find an entry for SparkFun SAMD Boards (dependency: Arduino SAMD Boards 1.6.19) at the end of the SAMD search results. If you don't see it, close the board manager and open it again. Select the add-on package and install the latest version (*recently updated to v1.6.1, but any version after should still work). Again, the INSTALLED text should appear next to the SparkFun SAMD boards list entry.

Installing the SparkFun SAMD Boards
Board Manager in Arduino IDE with SparkFun's SAMD (add-on) core highlighted. Click to enlarge.

Select the Board and Serial Port

Once the board definition for the SAMD51 Thing Plus is installed, you should see a new entry in your Tools>Board list under SparkFun SAMD51 Thing Plus.

SAMD51 Thing Plus board menu entry
Selecting board from Tools menu. Click to enlarge.

Finally, select your board's port. Navigate back up to the Tool>Port menu. The port menu may magically know which of your ports (if you have more than one) is the SAMD51 Thing Plus board. On a Windows machine, the serial port should come in the form of "COM#". On a Mac or Linux machine, the port will look like "/dev/cu.usbmodem####".

Selecting the SAMD51 Thing Plus port
Selecting serial port from Tools menu. Click to enlarge.

Once you find it, select it! That is all you need to get started in the Arduino IDE. In the next section we will go over the hardware and capabilities of the board. However, if you are eager to upload your first Arduino sketch (and review the hardware information later), you can jump over to the Hardware Assembly and Examples sections.

Hardware Overview

Below is a graphical datasheet for the SAMD51 Thing Plus, which highlights the important features and pin functionality of the SparkFun SAMD51 Thing Plus:

Annotated image of SAMD51

Click the buttons below for more details.

Power/Reset

The SparkFun SAMD51 Thing Plus can be powered via the USB and/or Li-Po battery JST connections. If you choose to power it via USB, the other end of the USB cable can be connected to either a computer or a 5V (regulated)USB wall charger. Otherwise, should you choose to use a Li-Po battery (single-cell only), there is a built in charge circuit to recharge your battery from the USB connection.

Annotated image of power features
Annotated image of SAMD51 Thing Plus with power and reset features highlighted. Click to enlarge.

Note: Only use single cell Li-Po batteries with the battery JST connector. The MCP73831T charging IC is only designed to handle single cell batteries.

USB

A USB micro-B cable is usually the easiest way to power the board, especially when you're programming it because the USB interface is required for uploading code too. Power for the Li-Po battery charging circuit is provided by the USB.

USB connection example
An example of how to pull USB cable straight out from a Qwiic RedBoard.

Troubleshooting Tip: Users should take care NOT to pry or leverage on the connector when inserting/removing the USB cable. Doing so, WILL damage the board and cause the pads and/or traces to tear off as well. The cable should be removed by pulling straight outwards from the board.

JST for Li-Po Battery

There is a 2-Pin JST PH connector available for single cell Li-Po batteries. Check out this tutorial for more information on power connectors.

Battery JST connector
Annotated image of the battery JST connector.

Dual Power

It is fine to connect both a Li-Po battery and a USB connector at the same time. The SparkFun SAMD51 Thing Plus has power-control circuitry to automatically select the best power source. In addition, the charge controller will charge the Li-Po battery from the USB power.

USB and Li-Po connected
USB and Li-Po battery connected.

MCP73831 Charge Controller

The MCP73831 is a single-cell charge controller. Power for the charge controller comes directly from the USB or VUSB pin. The input voltage range for the MCP73831 is 3.75-6V and it has set charge current of 550mA.

MCP73831
Annotated image of the MCP73831 charge controller.

Charge Indicator LED

Just above the battery JST connector on your circuit board, there’s a tiny LED next to the word VBATT. This yellow LED should light up whenever your battery is charging.

Charge LED
Annotated image of the charge LED.

AP2112 Voltage Regulator

The APA2112 is a robust 3.3V regulator, capable of sourcing up to 600mA from an external voltage of 3.5V to 6V. The external voltage for the APA2112 is provided through the USB and battery connections (also tied to the VUSB and VBATT pins, respectively). The APA2112 regulates 3.3V power to the SAMD51 IC and the Qwiic system. If supplied with less than 3.5V, the power may be unstable; and using more than 6V, the voltage regulator may overheat and damage itself and/or the board.

AP2112
Annotated image of the AP2112 voltage regulator.

For more technical details about voltage regulators and thermal dissipation, I suggest taking a look at these blog posts and tutorial:

Reset Button

Just like the original Nintendo, the board has a reset button. Pushing it will temporarily connect the reset pin to ground and restart any code that is loaded. This can be very useful if your code doesn't repeat, but you want to test it multiple times. Unlike the original Nintendo however, blowing on the Arduino doesn't usually fix any problems.

Reset Button
Annotated image of the reset button.

Launch Bootloader Mode

The reset button is used to manually enter and exit bootloader mode. Simply, double-tap the reset button to launch the board into the bootloader (used to program the SAMD51 Thing Plus). The board will remain in bootloader mode until power cycles (happens automatically after uploading code) or the reset button is hit again (once).

Bootloader GIF
Double-tapping the reset button to enter bootloader mode.

Use the indicators below to verify that the board is in bootloader mode:

  • The D13 LED indicator will be a solid blue (may appear to be slowly fading or blinking).
  • Board will show up under a different COM port.
  • The board will appear as a USB mass storage device under the name 51THINGBOOT.

Don't for get to make sure you have the proper serial port selected in the Arduino IDE. The SAMD51 Thing Plus changes to its secondary serial port in bootloader mode.

The Power Pins

There are breakout pins available for all your input/output voltages and reset.

Power Pins
SAMD51 Thing Plus Power Pins

  • VUSB- The input voltage to the Arduino board when it's using an external power source. You can provide an external supply voltage through this pin or access the external supply voltage from the power jack through this pin. If only powered through a USB connection, voltage will be around 5V. The input voltage range for this pin is 3.5-6V.
  • EN- Tied to Enable pin of the AP2112 voltage regulator.
  • VBATT- Provides a connection to the positive terminal of Li-Po battery connector.
  • 3V3- The 3.3 volt supply generated by the on-board regulator. Maximum current draw is 600 mA.
  • GND- Ground pins.
  • RESET- This pin is tied to the Reset pin of the microcontroller and Reset Button. If this pin is toggled low or shorted to the GND pin, it will trigger a reset of the microcontroller.
Danger: It is possible to connect an external 5V power supply to the USB and GND pins. This is not recommended, as it may cause unexpected behavior when plugging the board into your computer's USB port. There is a possibility of back-powering the USB port, which could confuse or damage your computer. (*There is no protection circuitry like on more robust platforms; for example, the Arduino Uno.)

Status Indicator LEDs

There are 2 status LEDs on the SparkFun SAMD51 Thing Plus, a charge indicator and a test/status LED.

Annotated image of status LEDs
Status LEDs on the SAMD51 Thing Plus.

Charge (Yellow)

This LED indicates that the Li-Po Battery is getting charged. A good secondary test for this status indicator is to use a multimeter to test the VBATT and VUSB pins against the GND pin.

Pin 13 (Blue)

The last indicator is the Pin 13 LED. This is typically only used as a test LED to make sure that a board is working or for basic debugging. However, for the SparkFun SAMD51 Thing Plus, this LED also indicates if the board is in bootloader mode.

Troubleshooting Tips:
  • New boards will come programmed with a test sketch that the Pin 13 LED.
  • Pin 13 is difficult to use as a digital input because of the voltage drop from status LED and resistor soldered in series to it. If the pin is enabled as an input with the internal 20k pullup resistor, it will always read a LOW state; an expected 5V (HIGH) signal will instead read around 1.7V (LOW).

    If you must use pin 13 as a digital input, it is recommended that you set the pinMode() as an INPUT and use an external pulldown resistor.

    pinMode(13, INPUT);

Microcontroller

The microcontroller (ATSAMD51J20 IC) is the work horse of the SparkFun SAMD51 Thing Plus. The ATSAMD51 is an 32-bit ARM microcontroller manufactured by Atmel, now Microchip. Once an Arduino sketch is uploaded to the board, the program is stored in the memory of the ATSAMD51. The microcontroller will then run/execute the program while the SparkFun SAMD51 Thing Plus is powered.

ATSAMD51
Image of the ATSAMD51 IC.

Note: You can find the datasheet for the ATSAMD51J20 from the Microchip product page.

Clock

An external 32.768kHz crystal is used as the clock for the ATSAMD51. However, the MCU itself has a maximum CPU speed of 120MHz.

Memory

The ATSAMD51 has Flash memory, SRAM (Static Random Access Memory), and backup RAM (Random Access Memory). In addition, there is also 4MB of external Flash memory.

  • 1MB Flash Memory - where the Arduino sketch/program is stored (including the UF2 bootloader).
  • 256KB SRAM - where the sketch/program creates and manipulates variables when it runs.
  • 4MB (External) Flash Memory - accessed through SPI.

External memory
Image of the external Flash memory IC.

The Flash memory is non-volatile; the data is still stored even when the board is no longer powered. The SRAM, on the other hand, is volatile and the data is only available while the board is powered. There is a small bit of SRAM that can retain memory when the SAMD51 is in Standby or Hibernation modes, but that isn't enabled in Arduino yet.

Troubleshooting Tips: When you run out of SRAM, the sketch may fail or act strangely after it is uploaded. If you suspect this is the issue, try to comment out any long strings or large data structures. If the sketch starts to run normally, then you may need to modify your data requirements.

UF2 Bootloader

The bootloader is a unique piece of firmware at the end of the address space of the flash memory. Without a bootloader, you would need to external programmer and program the microcontroller through the SPI interface (normally, the ISP/ICSP headers).

For Arduino users, the UF2 bootloader is BOSSA compatible, which the Arduino IDE expects on ATSAMD boards. Additionally, the UF2 bootloader allows the SAMD51 Thing plus to show up on your computer as a USB storage device.

For more details on the ATSAMD51, memory, and the bootloader check out these tutorials:

Bootloader Mode to Program

As mentioned previously, you will need to manually enter bootloader mode (by double-tapping the reset button) to program the SAMD51 Thing Plus. Once the Arduino IDE is finished programming the board, it should automatically exit the bootloader by resetting the board.

Bootloader GIF
Double-tapping the reset button to enter bootloader mode.

Use the indicators below to verify that the board is in bootloader mode:

  • The D13 LED indicator will be a solid blue (may appear to be slowly fading or blinking).
  • Board will show up under a different COM port.
  • The board will appear as a USB mass storage device under the name 51THINGBOOT.

Don't for get to make sure you have the proper serial port selected in the Arduino IDE. The SAMD51 Thing Plus changes to its secondary serial port in bootloader mode.

Programming

There are two ways to program the SparkFun SAMD51 Thing Plus. The most common way for users is through the USB connection. The other slightly less common method is through the ISP headers or pins.

Annotated image of programming connections
SAMD51 Thing Plus programming connections.

USB Connection

The USB micro-B connector is the most convenient way to power and program the board. To program the board through the USB connection, you will need a USB micro-B cable and there must be a bootloader flashed to the microcontroller (don't worry... we have already "factory installed" one). For the SparkFun SparkFun SAMD51 Thing Plus, this is a UF2 bootloader similar to the [RedBoard Turbo](https://www.sparkfun.com/products/14812). Most users will program the SAMD51 Thing Plus through a USB connection with the Arduino IDE.

Troubleshooting Tip: Users should take care NOT to pry or leverage on the connector when inserting/removing the USB cable. Doing so, WILL damage the board and cause the pads and/or traces to tear off as well. The cable should be removed by pulling straight outwards from the board.


USB connection example
An example of how to pull USB cable straight out from a Qwiic RedBoard.

Bootloader Mode to Program

The bootloader is what allows us to load code over a simple USB interface. When using the Arduino IDE, the board needs to be manually launched into the bootloader prior to any attempts to upload a sketch. To manually enter bootloader mode, rapidly double-tapping the reset button (after hitting the reset button once, you have about half a second to hit it again). The board will remain in bootloader mode until power cycles (happens automatically after uploading code) or the reset button is hit again (once).

Bootloader GIF
Double-tapping the reset button to enter bootloader mode.

Use the indicators below to verify that the board is in bootloader mode:

  • The D13 LED indicator will be a solid blue (may appear to be slowly fading or blinking).
  • Board will show up under a different COM port.
  • The board will appear as a USB mass storage device under the name 51THINGBOOT.

Don't forget to make sure you have the proper serial port selected in the Arduino IDE. The SAMD51 Thing Plus changes to its secondary serial port in bootloader mode.

Using SPI pins for ISP or ICSP Programming

The least common way for most users to program the microcontroller on their board, is to use the Serial Peripheral Interface (SPI) pins for in-system programming (ISP). A more experienced user, with a firm grasp on digital electronics and the microcontroller (datasheet), will probably use a software package like Atmel studio, which is easier to debug code through the available software debug pins.

ISP and Debug Pins
Annotated image of programming and debug pins.

The most common reasons for programming with this method are:

  • ISP is faster and more reliable- We use this method in our QC process for most boards.
  • There is no bootloader on the microcontroller or your board wasn't flashed properly:
    • This is probably the only way to program the microcontroller without a bootloader.
  • You want to use your own, custom bootloader.
  • Configure fuse bits for various settings.
  • Program without bootloader, when you need just a little bit more space for your program to load.

Pin Functions

All of the SparkFun SAMD51 Thing Plus's pins are broken out to 0.1" spaced through holed on the outer edges of the board.

Power Pins

The power pins aren't really I/O (Input/Output) pins for the microcontroller; however, they are pertinent to the board. For more details on these pins, see the tab.

Annotated image of power pins
SAMD51 Thing Plus power pins.

The pins mostly operate as voltage supply pins. These pins are traditionally used as power sources for other pieces of hardware (like LEDs, potentiometers, and other circuits).

  • 3.3V- A regulated 3.3V voltage source.
  • VUSB- The (normally 5V) voltage from the USB connection.
  • VBAT- The voltage from the Li-Po battery connection. Usually, used for checking remaining charge on battery.
  • GND- The common ground or the 0V reference for the voltage supplies.
  • EN- Tied to Enable pin of the AP2112 voltage regulator.
  • RESET- The RESET pin can be shorted to the GND pin to reset the microcontroller, similar to using the reset button.

Microcontroller I/O Pins

All of the I/O pins on this board are digitalinputs or outputs for the microcontroller (ATSAMD51J20). Most pins are configurable for other capabilities.

Digital I/O

There are 21 I/O pins on this board, which can be operate as either digital inputs or outputs for the microcontroller (ATSAMD51). This includes the pins labeled as Analog, which may be configured and used in the same manner as the digital pins. Digital pins are what you connect to buttons, LEDs, sensors, etc. to interface the Arduino with other pieces of hardware.

Input
By default, all digital I/O pins are configured as inputs. It is best practice to define the pinMode() in the setup of each sketch (programs written in the Arduino IDE) for the pins used. When configured properly, an input pin will be looking for a HIGH or LOW state. Input pins are High Impedance and takes very little current to move the input pin from one state to another.

Troubleshooting Tips:
  • If an input pin is read and that is floating (with nothing connected to it), you will see random data/states. In practice, it may be useful to tie an input pin to a known state with a pullup resistor (to VCC), a pulldown resistor (to GND), or configure the pin as a pull-up/down input.
  • Pin 13 is difficult to use as a digital input because of the voltage drop from status LED and resistor soldered in series to it.
Output
When configured as an output the pin will be at a HIGH or LOW voltage. Output pins are Low Impedance: This means that they can provide a substantial amount of current to other circuits.

Troubleshooting Tip:
The maximum current an I/O pin can source (provide positive current) or sink (provide negative current) is .5 - 8 mA (milliamps). For more details, you can refer to the ATSAMD51 datasheet or this reference page. Attempting to run high current devices may damage the pin or entire ATSAMD51 chip.
Note: For more details about digital pins, check out this reference page and pg 2025 of the ATSAMD51 datasheet.

Additional Functions

There are several pins that have special functionality in addition to general digital I/O. These pins and their additional functions are listed in the tabs below. For more technical specifications on the I/O pins, you can refer to the ATSAMD51 datasheet or the below table, which outlines which SERCOM ports each pin has been conected to (shown in green) along with the available SERCOM Ports. For more information on SERCOM and how it can help you with your hardware peripherals, check out our guide here.

SERCOM OUTLINE


Analog Input Pins
There are 6 labeled analog inputs. These pins tie to a 12-bit (12-bit = 4096 different values) analog to digital converter (ADC), which can be used to read in an analog voltage between 0 and 2.82V or VCC (depending on the configuration). These are useful if you need to read the output of a potentiometer or other analog sensors.
Annotated image of analog inputs
SAMD51 Thing Plus analog input pins. Click to enlarge.

For more details on the analog inputs, check out these tutorials:
Pulse Width Modulation (PWM) Output Pins
Digital pins can be configured as 24-bit PWM capable outputs, which you can use to dim LEDs or run servo motors.
Troubleshooting Tip:
Novice users often mistake PWM pins as an analog output. Although, it can somewhat mimic that functionality, it is not a true analog output.
For more details on pulse width modulation, check out these tutorials:
Serial Communication Pins
Digital pins 0 (RX) and 1 (TX) are also dedicated serial communication pins. These pins are used to receive (RX) and transmit (TX) TTL serial data. Other digital pins can be use to emulate serial communication with SoftwareSerial().
Annotated image of serial communication pins
SAMD51 Thing Plus dedicated serial communication pins. Click to enlarge.

For more details on serial communication, check out these tutorials:
SPI Communication Pins
Digital pins 23 (MOSI), 22 (MISO), and 24 (SCK) support Serial Peripheral Interface (SPI) communication. (*The slave select (SS) pin is user defined.*)
Annotated image of SPI pins
SAMD51 Thing Plus SPI pins. Click to enlarge.

Note:

Using the Serial Peripheral Interface, configures the SCK and MOSI pins to be directly managed by the SPI hardware. Therefore, while in use, pins 11 and 13 can't be used (i.e. the LED on pin 13 can no longer be used as a debug/status indicator.)

Executing "SPI.end();" allows those pins 11 and 13 to be used as general I/O again.

For more details on the serial peripheral interface, check out these tutorials:
I2C Communication Pins
Analog pins 20 (SDA) and 21 (SCL) support I2C (TWI) communication.
Annotated image of I2C pins
SAMD51 Thing Plus I2C pins. Click to enlarge.
Qwiic System

The Qwiic system is intended a quick, hassle-free cabling/connector system for I2C devices. The Qwiic connector is tied to the I2C pins.

Troubleshooting Tip:
Be sure to double check that you are not trying to use an I2C device while you are trying use pins 20 and 21, you will run into issues. You can only do one or the other.
For more details on the serial peripheral interface, check out these tutorials:
Interrupt Pins
Interrupts allow you to interrupt the code running in your main loop and execute another set of instructions (also known as interrupt handler or interrupt service routine) before returning back to the main loop. For more details on the interrupts, check out these tutorials:

Qwiic Connector

The most convenient feature of the board is the Qwiic connector that allows the SparkFun SAMD51 Thing Plus to seamlessly interface with SparkFun's Qwiic Ecosystem.

Qwiic Connector

What is Qwiic?

The Qwiic system is intended a quick, hassle-free cabling/connector system for I2C devices. Qwiic is actually a play on words between "quick" and I2C or "iic".

Keep your soldering iron at bay.

Cables plug easily between boards making quick work of setting up a new prototype. We currently offer three different lengths of Qwiic cables as well as a breadboard friendly cable to connect any Qwiic enabled board to anything else. Initially you may need to solder headers onto the shield to connect your platform to the Qwiic system but once that’s done it’s plug and go!

Qwiic Cable and Board

Qwiic cables connected to Spectral Sensor Breakout

Minimize your mistakes.

How many times have you swapped the SDA and SCL wires on your breadboard hoping the sensor will start working? The Qwiic connector is polarized so you know you’ll have it wired correctly, every time, from the start.

The PCB connector is part number SM04B-SRSS (Datasheet) or equivalent. The mating connector used on cables is part number SHR04V-S-B or equivalent. This is a common and low cost connector.

JST Connector

1mm pitch, 4-pin JST connector

Expand with ease.

It’s time to leverage the power of the I2C bus! Most Qwiic boards will have two or more connectors on them allowing multiple devices to be connected.

Pull-Up Jumpers

These jumpers can be cut to disconnect the 2.2kΩ pull-up resistors from the I2C bus. You only need to cut this trace if you have a bunch of devices with pull-up resistors because the pull up becommes too strong.

Qwiic jumper
Jumper for pull-up resistors.

How to Modify the Pull-Up Jumper

You will need a knife to modify the jumpers. To modify the jumper, located on the back of the board next to the Qwiic connector, you need to cut the trace between the two pads. Once you have cut the trace, the pull-up resistors will be disconnected. To repair the connection, you just need to solder a jumper between the pads of both jumpers. Be sure to test the jumper with a multimeter to make sure you have a good soldered connection.

Adding External Power

If you need more power for your Qwiic devices, you can attach a separate power supply. However, it is recommended that you cut the 3.3V line of the Qwiic cable to the SparkFun SAMD51 Thing Plus. Leave the GND line alone, as that ground loops your system, providing a consistent reference voltage for your I2C signals.

cutting the 3.3V line
Cutting the 3.3V line of the Qwiic cable to the Qwiic connector (on a Qwiic RedBoard).

By cutting the 3.3V line, this allows you to power all your devices without straining the 3.3V regulator on the board. Since, all voltage regulators are slightly different and don't maintain a perfect 3.3 voltage, the 3.3V AP2112 regulator would be constantly battling the voltage regulator of your separate power supply to regulate its version of 3.3V. For more details on voltage regulators, check out this According to Pete blog post.

Dimensions

The dimensions for the board are approximately 0.9" x 2.3". The breakout pins use a standard 0.1" spacing and the layout is compatible with Feather styled shields. There is a 2-Pin JST PH connector for the option to add Li-Po batteries. The Qwiic connector uses a 4-pin JST SH type connector. There are also 4 mounting points on the board.

SAMD51 Thing Plus Dimensions
Screen shot of SAMD51 Thing Plus board layout in Eagle. (Click image to enlarge.)

For the more details on the board sizing and component placement please refer to the Eagle files provided.

Download Eagle Files (ZIP)

Eagle is a free for educators, makers, and hobbyists (i.e. basically, anything not for commercial purposes). All measurements are accurate, excluding any manufacturing tolerances. (Unfortunately, we do not have this information available; you may need to just measure the board you purchase.)

Hardware Assembly

Connectors

The SAMD51 Thing Plus has 3 primary connectors a micro-B USB connection, a Qwiic connector, and a battery JST connector.

Hardware Connections
Primary hardware connections on the SAMD51 Thing Plus.

Micro-B USB Connector

There are a few ways to use this board. However, most users will be interfacing with the SAMD51 Thing Plus, primarily through the micro-B USB connector to power and program the board. This connection is also used to charge the Li-Po battery, when in use. Need another micro-B USB cable for your drawer?

Qwiic Connector

With the Qwiic connector system, assembling your hardware is simple. All you need to do is connect your Qwiic device to the SAMD51 Thing Plus with a Qwiic cable.

JST Battery Connector

There is a 2-Pin JST PH connector available for single cell Li-Po batteries. The SAMD51 Thing Plus also has a built-in charge controller for charging your single cell Li-Po battery from the USB connection.

Headers & Shields

All the pins for the SparkFun SAMD51 Thing Plus are broken out to 0.1"-spaced pins on the outer edges of the board. When selecting headers, be sure you are aware of the functionality you need. If you have never soldered before or need a quick refresher, check out our Through-Hole Soldering guide.

alt text
Feather Stackable Header Kit soldered to the SAMD51 Thing Plus.

The Feather Stackable Header Kit is a great option as it allows users to stack shields (w/ Feather footprint) or it can be placed on the a breadboard; while, the pins are still accessible from the female/male headers. If you need a refresher on soldering, check out our How to Solder: Through-Hole Soldering tutorial.

alt text
SAMD51 Thing Plus on a breadboard with jumper wire connections and room (above) to add stackable shields.

Arduino Examples

In this section, we will run a few simple sketches to verify and demonstrate the board's functionality.

Using the Arduino IDE

Now it's finally time to upload code to your SAMD51 Thing Plus in the Arduino software. Once you open up the application, you'll be presented with a window that looks a little something like this:

Arduino IDE annotated
Layout of the Arduino IDE.

Before we can send the code over to the SAMD51 Thing Plus, there are a couple of adjustments we need to make.

Select a Board

If you haven't already selected the proper board from the Arduino IDE setup section earlier, we will go over it again. This step is required to tell the Arduino IDE which of the available Arduino boards, we are using. Go up to the Tools menu, hover over Board, and be sure to select the SparkFun SAMD51 Thing Plus from the drop-down list.

SAMD51 Thing Plus board menu entry
Selecting board from Tools menu. Click to enlarge.

Select a Serial Port

Next up we need to tell the Arduino IDE which of our computer's serial ports the SAMD51 Thing Plus is connected to. Navigate back up to the Tools>Port menu. The port menu may magically know which of your ports (if you have more than one) is the SAMD51 Thing Plus board. On a Windows machine, the serial port should come in the form of COM#. On a Mac or Linux machine, the port will look like /dev/cu.usbmodem####.

Selecting the SAMD51 Thing Plus port
Selecting serial port from Tools menu. Click to enlarge.

Once you find it, select it! If you've got more than one port, and you're not sure which of the serial ports is your SAMD51 Thing Plus, unplug it for a moment and check the menu to see which one disappears.

Example 1: Uploading Blink

In this example we will go over the basics of the Arduino IDE and upload a sample code. This is a great way to test the basic functionality of any board to make sure it is working.

Example 1: Blink

Blink Sketch

Code written for the Arduino IDE are referred to as sketches. All code in Arduino is C based. Let us upload a Blink sketch to make sure our new RedBoard setup is totally functional. Go up to the File menu in Arduino, then go to Examples > 01.Basics > Blink to open it up.
Board Selection
Screen shot of Blink sketch selection.

Upload!

With all of those settings adjusted, you're finally ready to upload some code! Click the Upload button (the right-pointing arrow) and allow the IDE some time to compile and upload your code. It should take around 10-20 seconds for the process to complete. When the code has uploaded, you should see something like this in your console window:
Done uploading
Screen shot of upload complete.

And if you look over to the RedBoard, you should see the blue LED turn on for a second, off for a second, on for a second, off for a second...ad infinitum (at least until it loses power).

Blink Example
Expected response from board

If you want to adjust the blink speed, try messing with the "1000" value in the delay(1000); lines. You're well on your way to becoming an Arduino programmer!

Something Wrong?

Uh oh! If you didn't get a "Done Uploading" message, and instead got an error, there are a few things we can double-check.

If you got an avrdude: stk500_getsync(): not in sync: resp=0x00 error in your console window.

Upload error
Screen shot of Error Message in the Console.

Either your serial port or board may be incorrectly set. Again, make sure Arduino/Genuino Uno is the board selection (under the "Tools>Board" menu). The serial port is usually the more common culprit here. Is the Serial Port correctly set (under the "Tools>Serial Port" menu)? Did the drivers successfully install? To double check your RedBoard's serial port, look at the menu when the board is plugged in, then unplug it and look for the missing port. If none of the ports are missing, you may need to go back to driver installation.

Example 2: Qwiic Connector

One of the great features of the RedBoard (Qwiic) is its ability to interface with I2C devices using our Qwiic system. The Qwiic system is a solderless connection system that allows users to seamlessly daisy chain multiple I2C devices with ease.

The Qwiic Distance Sensor

For this example, we will be running a basic sketch using the SparkFun 4m Distance Sensor (VL53L1X). For more examples with this sensor, please refer to the complete hookup guide.

Hardware Assembly

The wiring for this is simple. Use the Qwiic cable and connect the distance sensor to the board. That is it! The connections are polarized, so you don't have to worry about which side or connector you are using.

Hardware assembly for VL53L1X example

Hardware assembly for VL53L1X distance sensor example.

Let's run an example for our distance sensor to see how it behaves.

Install the Arduino Library

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

First, you'll need the Sparkfun VL53L1X Arduino library. You can obtain these libraries through the Arduino Library Manager. Search for Sparkfun VL53L1X Arduino Library to install the latest version. If you prefer downloading the libraries from the GitHub repository and manually installing it, you can grab them here:

DOWNLOAD THE SPARKFUN VL53L1X ARDUINO LIBRARY (ZIP)

Example 1 - Read Distance

To get started with this example, open up File>Examples>SparkFun VL53L1x 4M Laser Distance Sensor>Example1_ReadDistance. In this example, we begin by creating a SFEVL53L1X object called distanceSensor with our wire port, Wire, and then our shutdown and interrupt pins. Then we initialize our sensor object in the setup() loop. The code to do this is shown below.
language:c
#include <Wire.h>
#include "SparkFun_VL53L1X.h"

//Optional interrupt and shutdown pins.
#define SHUTDOWN_PIN 2
#define INTERRUPT_PIN 3

SFEVL53L1X distanceSensor(Wire, SHUTDOWN_PIN, INTERRUPT_PIN);

void setup(void)
{
  Wire.begin();

  Serial.begin(9600);
  Serial.println("VL53L1X Qwiic Test");

  if (distanceSensor.init() == false)
    Serial.println("Sensor online!");

}

Once we've initialized our sensor, we can start grabbing measurements from it. To do this, we send some configuration bytes to our sensor using distanceSensor.startRanging() to initiate the measurement. We then wait for data to become available and when it does, we read it in, convert it from millimeters to feet, and print it out over serial. The void loop() function that does this is shown below.

language:c
void loop(void)
{
  distanceSensor.startRanging(); //Write configuration bytes to initiate measurement
  int distance = distanceSensor.getDistance(); //Get the result of the measurement from the sensor
  distanceSensor.stopRanging();

  Serial.print("Distance(mm): ");
  Serial.print(distance);

  float distanceInches = distance * 0.0393701;
  float distanceFeet = distanceInches / 12.0;

  Serial.print("\tDistance(ft): ");
  Serial.print(distanceFeet, 2);

  Serial.println();
}

Opening your serial monitor to a baud rate of 9600 should show the distance between the sensor and the object it's pointed at in both millimeters and feet. The output should look something like the below image.

Read Distance
Distance readings in mm and ft

Example 2: Hello World

Example 3: Qwiic ADC

Troubleshooting

Please be aware that the SparkFun SAMD drivers are NOT supported on any Windows OS prior to Win 8.

Below, we have also included some troubleshooting tips for issues that you may come across with the new SAMD51 Thing Plus.

  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, I recommend starting with their troubleshooting guide.

If neither of the troubleshooting guides above were able to help, here are some additional tips:

Dual Serial Ports

One global issue to be aware of is that each SAMD51 Board appears to your computer as two USB devices, and your computer will assign two different port numbers to your SAMD51 Board - one for the bootloader, the other for the sketch.

  • Verify that you are selecting the available serial port for the board.
  • If your computer isn't registering the board try double-tapping it into bootloader mode.
  • Once the Arduino IDE is finished programming the board, it should automatically exit the bootloader by resetting the board. (At that point, the board will be on a different serial port, from the one it was programmed on.)

My Board Isn't Working in Arduino:

Every board that we manufacture gets tested. If you didn't buy the board from us or one of our authorized distributors, it could be a knock-off. That being said, let's try a basic test to see if just the board is working. Disconnect everything that you have attached to the board; we just want to test the board.

  1. Inspect the board:
    Check the board to make sure everything looks about right. Use the pictures on the product page to verify component placement or alignment, and bad solder joints, or damage.
  2. Power and check the LEDs:
    Using a known good USB micro-B cable, plug your board in to the computer. Do any of the LEDs turn on (see Hardware Overview)?
    • New boards will come programmed with board in bootloader mode. The pin 13 should be slowly blinking/fading in and out (may look like a solid blue).
  3. Put the board in bootloader mode:
    Bootloader GIF
    Double-tapping the reset button to enter bootloader mode.
    To enter bootloader mode, rapidly double-tap the reset button. On the SAMD51 Thing Plus, the there are a clues to if the board is in bootloader mode:
    • The D13 LED indicator will be a solid blue (may appear to be slowly fading or blinking).
    • Board will show up under a different serial port.
    • The board will appear as a USB mass storage device under the name 51THINGBOOT.
  4. Upload the Blink sketch:
    Try to upload a blink sketch. Why blink? It is simple, known to work (from the example files), and you have an indicator LED.
    • Double check that you have the proper Board and Serial Port selected.
    • For boards that are already running the blink example, I recommend changing the timing parameters to check for a change in the board's response.
  5. Verify Functionality:
    Check that you see the pin 13 LED blinking properly and that the Arduino IDE shows a status of Done uploading.

I Don't See My Board on a Serial/COM Port:

If you don't see your board as an available COM port on the Arduino IDE:

  1. Try to re-open the Arduino IDE.
  2. Check the Device Manager:
    Verify that your computer recognizes the board. See the Driver Verification section of the tutorial.
  3. Check that you are using a USB cable capable of data transfers:
    Your issue might be related to your USB cable; some cables only have the power pins connected for charging. A good way to test this is to plug in a device to your USB cable (like a phone). If it doesn't show up as a device or drive, then try a new USB micro-B cable.
  4. Try forcing the board between the dual serial ports:
    • Bootloader Mode:
      Bootloader GIF
      Double-tapping the reset button to enter bootloader mode.
      To enter bootloader mode, rapidly double-tap the reset button. On the SAMD51 Thing Plus, the there are a clues to if the board is in bootloader mode:
      • The D13 LED indicator will be a solid blue (may appear to be slowly fading or blinking).
      • Board will show up under a different serial port.
      • The board will appear as a USB mass storage device under the name 51THINGBOOT.
    • USB Serial Port:
      The board will remain in bootloader mode until power cycles (happens automatically after uploading code) or the reset button is hit again (once).
  5. Try a different USB port:
    This rarely happens, but it is easy to check. If you are using a USB 3.0 port (you will see a blue "tongue" in the USB jack or bad USB port, try a different USB port. You can also try to test the board on a different computer to double check for a hardware incompatibility (usually with expansion boards).

Errors Uploading to the Board:

There are two types of issues that you will usually see in the console of the Arduino IDE, compile errors or upload errors. The easiest way to see where to start is by clicking the Verify button (check mark); the Arduino IDE will try to compile your code. A failure here is a compile error.

It takes a some experience, but if you enable the verbose output from the Arduino IDE preferences, it may give you more clues to where the issue is.

Screen shots of enabling verbose output

Screen shots of how to enable verbose output. Click to enlarge.
  • Compile Errors:
    With compile errors, there are several things that could be causing issues. However, 99% of the time, it is user error. Usually something wrong with your code or the library you are using. Once in a while you will have a file structure issue if you manually added a file/folder in any of the Arduino folders (still user error).
  • Upload Errors:
    Upload errors get a little more tricky. You will usually just see the Arduino IDE trying to upload to the board multiple times. There are usually several different causes for this, often without specific errors in the console. Here are a few common examples:
    • Wrong Board Selection:
      Double check you board selection options. If you uploaded with the wrong board selection, there is a small chance that you may have overwritten the bootloader on the board or damaged the microcontroller.
    • Not Accessing the Bootloader:
      If a sketch upload is taking longer than usual, or fails entirely, try resetting into the bootloader mode and uploading directly there. If the SAMD51 is in bootloader mode, you may need to re-select your port (see Dual Serial Port section above).
    • Serial Port Interference:
      Closing the serial monitor before uploading may also be more reliable uploading.
    • Bad USB cable or port.

Resources and Going Further

Now that you've successfully got started with your SAMD51 Thing Plus, it's time to incorporate it into your own project! For more information, check out the resources below:


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

SparkFun 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.

What is an Arduino?

What is this 'Arduino' thing anyway?

Installing Arduino IDE

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

Arduino Board Comparison Guides

Hookup Guides for Other SAMD Boards

Choosing an Arduino for Your Project

Examining the diverse world of Arduino boards and understanding the differences between them before choosing one for a project.

Standard Arduino Comparison Guide

Arduino Comparison Guide Uno or Pro Mini? Bluetooth or wireless? When it comes to Arduinos, there are a lot of choices. We've compiled every Arduino development…

SAMD21 Mini/Dev Breakout Hookup Guide

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

RedBoard Turbo Hookup Guide

An introduction to the RedBoard Turbo. Level up your Arduino-skills with the powerful SAMD21 ARM Cortex M0+ processor!
Beginner

Click the buttons above for tutorials relating to the board functionality based on topic difficulty.

Beginner

Serial Communication

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

Analog to Digital Conversion

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

Logic Levels

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

Analog vs. Digital

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

Data Types in Arduino

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

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.

Intermediate

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.

Processor Interrupts with Arduino

What is an interrupt? In a nutshell, there is a method by which a processor can execute its normal program while continuously monitoring for some kind of event, or interrupt. There are two types of interrupts: hardware and software interrupts. For the purposes of this tutorial, we will focus on hardware interrupts.

Adding More SERCOM Ports for SAMD Boards

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

Advanced

Installing an Arduino Bootloader

This tutorial will teach you what a bootloader is and why you would need to install or reinstall it. We will also go over the process of burning a bootloader by flashing a hex file to an Arduino microcontroller.

Integrated Circuits

An introduction to integrated circuits (ICs). Electronics' ubiquitous black chips. Includes a focus on the variety of IC packages.

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!

Looking for project ideas? Check out some of these Qwiic products and tutorials:

Qwiic Human Presence Sensor (AK9753) Hookup Guide

How to get started with your Qwiic enabled AK9753 Human Presence Sensor.

Qwiic Distance Sensor (RFD77402) Hookup Guide

The RFD77402 uses an infrared VCSEL (Vertical Cavity Surface Emitting Laser) TOF (Time of Flight) module capable of millimeter precision distance readings up to 2 meters. It’s also part of SparkFun’s Qwiic system, so you won’t have to do any soldering to figure out how far away things are.

Qwiic Joystick Hookup Guide

Looking for an easy way to implement a joystick to your next Arduino or Raspberry Pi project? This hookup guide will walk you through using the Qwiic Joystick with the Arduino IDE on a RedBoard Qwiic and in Python on a Raspberry Pi.

SparkFun Qwiic AS3935 Lightning Detector Hookup Guide

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

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

Basic Character LCD Hookup Guide

$
0
0

Basic Character LCD Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Printing data to a serial terminal is a great way to see data from a microcontroller. But, what if you want to make your project mobile and see sensor values away from your computer? Liquid crystal displays (LCDs) are a great way to output a string of words or sensor data to a display for visual feedback. In this tutorial, we'll learn about LCDs and how to print a strings of words to a basic character LCD.

Basic 16x2 Character LCD - White on Black 5V

Basic 16x2 Character LCD - White on Black 5V

LCD-00709
$18.95
12

Required Materials

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

SparkFun RedBoard - Programmed with Arduino

SparkFun RedBoard - Programmed with Arduino

DEV-13975
$19.95
42
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
39
Break Away Headers - Straight

Break Away Headers - Straight

PRT-00116
$1.50
20
SparkFun USB Mini-B Cable - 6 Foot

SparkFun USB Mini-B Cable - 6 Foot

CAB-11301
$3.95
2
Basic 16x2 Character LCD - White on Black 5V

Basic 16x2 Character LCD - White on Black 5V

LCD-00709
$18.95
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

While not necessary, we'll be using a breadboard holder to hold the circuit together.

Arduino and Breadboard Holder

Arduino and Breadboard Holder

DEV-11235
$3.95
11
SparkFun Mini Screwdriver

SparkFun Mini Screwdriver

TOL-09146
$0.95
3

Depending on your LCD's specifications, the input voltage may be 3.3V or 5V. For the LCDs listed below, the input voltage for the LCD must be 3.3V. The logic levels will be the same as the input voltage.

Tools

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

Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

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

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2

Suggested Reading

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

Binary

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

What is an Arduino?

What is this 'Arduino' thing anyway?

Installing Arduino IDE

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

Logic Levels

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

How Does an LCD Work?

LCD stands for Liquid Crystal Display. These displays contain a grid of liquid crystal dots, or pixels held between layers of glass etched with transparent electrodes. Liquid crystal molecules are normally twisted, but straighten out when electricity is applied to them. This affects the way light passes through the dot, allowing it to appear either darkened or clear. A HD44780 controller chip built into the display (it's underneath the black blob on the back) receives commands from your a microcontroller, and turns the pixels on and off to form various letters, numbers and symbols. The controller datasheet has a diagram of all the characters stored in the chip. This display also has an LED for backlighting, which is powered usually through a basic character LCD pins 15 and 16.

If you look closely at the characters on the LCD, you will notice that they are actually made up of lots of little squares. These little squares are called pixels. The size of displays is often represented in pixels. Pixels make up a character space, which is the number of pixels in which a character can exist.

Character Made from Pixels of an LCD

Here is a capital letter B as created in pixels. The character space in this example is 6 pixels x 8 pixels.

For more information on the history of LCDs and how they work, check out this video below.

Hardware Overview

A basic character LCD has 16 pins (with the exception of an RGB LCD which has 18 pins), and it is polarized. The pins are numbered from left to right, 1 through 16. The LCD utilizes an extremely common parallel interface LCD driver chip from Hitachi called the HD44780. Thankfully, the Arduino community has developed a library to handle a great deal of the software-to-hardware interface. Below is a list of each of the pins on the LCD.

Pinout Character LCD

Click on image for a closer view.

Input Voltage and Logic Levels

For the scope of this tutorial, we are going to be connecting a 5V Arduino to the 5V basic character LCD. Depending on your LCD's specifications, the input voltage may be 3.3V or 5V. The logic levels will be the same as the input voltage. Just make sure to match the voltages for the microcontroller and LCD.

Hardware Assembly

LCDs usually come without a microcontroller to control the display. To connect, you will need a strip of header pins, a potentiometer to adjust the contrast of the display, breadboard, and wires. Depending on the LCD, you may need a current limiting resistor to to limit the current to the LED backlight. You will need to solder the header pins of your choice to the display in order to plug it into your breadboard. If you have not soldered before, we recommend looking at our soldering tutorial.

How to Solder: Through-Hole Soldering

September 19, 2013

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

While you can use any standard 16x2 alphanumeric LCD, the white on black display supplied with the kit looks übercool. The photographs in this guide are of a standard black on green display so yours may look different. The "16x2" refers to the display having two rows of sixteen characters each — other displays are available which are 8x1 or 20x4.

Soldering Tips

It is pretty straightforward to solder the header pins to the LCD module. Make sure to keep the soldering iron in contact with the joints for no more than about three seconds. There small risk of the damaging the existing components on the board with excess heat. You also need to be careful to keep the soldering iron away from the already soldered components on the board — you're probably not yet ready to do surface mount soldering repair.

Insert Headers to the LCD

Before soldering, perform a "test fit" of parts. A test fit gives you a chance to double check if you've got the parts you need and ensures that they fit together. For this connection, break a row of 16x1 male headers and insert the header pins into the holes on the LCD module as shown in the image below. If you are using an RGB LED, you will need a row of 18x1 male headers.

Testing Header Pins on LCD

Ensure that you don't have one pin too many or too few in your header strip. Also make sure the black plastic strip of the header is positioned on the underside of the printed circuit board (PCB) so that you have plenty of pin length below the PCB to plug into your breadboard or a socket. The longest part of the pins should be below the PCB. The pin header provides connections that carry the data signals for controlling what the display... displays. They also carry power to the small microcontroller behind the black blob on the module and to the LED backlight if your display has one.

Soldering Male Headers

If you've done a test fit then your header should be in place. Ensure the header is aligned as parallel as possible to the edge of the board. Then solder the far left or right pin into place as shown in the image below.

Tacked Header Pin

Because there's not a lot of room it is easiest to feed the solder from behind pin while the soldering iron tip is between the pins, resting on the PCB pad with the side of iron against the side of pin you're soldering. The reason we start with just one pin is because it makes it easier to obtain the correct alignment and fix any mistakes.

If the alignment of the header isn't quite right, carefully reheat the solder joint and move the header slightly. Don't move the header when the solder joint is still in it's liquid state however, or you'll end up with a poor joint.

Once you're happy with the alignment of the header you can solder another pin into place — we recommend soldering the pin at the opposite end of the header to the first pin you soldered. The reason for this is that once the two end pins are in place, the alignment won't change.

Second Pin Soldered in Place

Double check the alignment is still okay and if it's not quite right you can reheat the joint and carefully move the pin. After you've confirmed the alignment, you can solder the remaining pins into place.

All Pins Soldered In Place

Ensure that the solder covers the plated through hole's pad and pins as shown in the image below for the best connection.

Top View of Soldered Header Pins

And now the soldering is complete!

Side View of Soldered Header Pins

Completed LCD

Your display module should now look like the image below. One additional detail to note is that the pin header is usually at the "top" of the display — so keep that in mind if you plan to mount it anywhere. Remember to always test the display out before mounting to a project.

Orientation of Soldered Header Pins

Now it is time to connect your LCD to a microcontroller! For the scope of this tutorial, we'll use an Arduino.

Hardware Hookup

The basic character displays use a parallel interface, which can be either 4 bits or 8 bits wide. We'll use 4 bits, since it requires fewer wires. It will take a total of 8 wires to connect the display to your a microcontroller:

  • two for Vcc and ground
  • two to load the data
  • four for data

You will also need to connect a potentiometer to the display. This is necessary to set the contrast of the display for best visibility. See the following diagram for details.

5V Character LCD Connected to an Arduino

Arduino Examples: LiquidCrystal Library

Note: The library has been tested on an ATmega328P-based Arduino using Arduino IDE v1.8.9. Otherwise, make sure you are using the latest stable version of the Arduino IDE on your desktop. If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you've never connected an FTDI device to your computer before, you may need to install drivers for the USB-to-serial converter. Check out our How to Install FTDI Drivers tutorial for help with the installation.

Normally, you would need to read the HD44780 controller chip's extensive datasheet to determine how to control this display. Fortunately, the Arduino IDE comes with a built-in library called LiquidCrystal, which does all the hard work for you. We'll look at one of the ten examples provided from Arduino.

Open the Arduino IDE, and load the example program: File>Examples>LiquidCrystal>HelloWorld.

Arduino IDE with Built In Examples

Once open, you will need to adjust the pin connections based on your circuit. In this case, we'll need to adjust the pin definitions based on our circuit that we connected earlier. Head to the line where the pins are defined.

language:c
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

Then adjust the pin definitions based on your connections.

language:c
const int rs = 13, en = 12, d4 = 11, d5 = 10, d6 = 9, d7 = 8;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

You can also copy and paste the code below. Just make sure to select the correct board (in this case the Arduino/ Genuino Uno) and the COM port that the Arduino enumerated on. Then upload the code to your Arduino.

language:c
/*LCD-Hello_world.ino

 Modified By: Ho Yun "Bobby" Chan
 SparkFun Electronics
 Date: 5/22/2019
 License: This code is public domain.

 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.

 This sketch prints "Hello World!" to the LCD
 and shows the time since the Arduino was turned on.

  Hardware Hookup:

    lCD VSS pin to GND
    LCD VCC pin to 5V
    10kΩ Potentiometer to LCD VO pin (pin 3)
    LCD RS pin to digital pin 13
    LCD R/W pin to GND
    LCD Enable pin to digital pin 12
    .
    .
    .
    LCD D4 pin to digital pin 11
    LCD D5 pin to digital pin 10
    LCD D6 pin to digital pin 9
    LCD D7 pin to digital pin 8
    LCD-Backlight - Anode to 10KΩ resistor to +5V (optional depending on your LCD)
    LCD Backlight - K to GND

 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe
 modified 7 Nov 2016
 by Arturo Guadalupi

 http://www.arduino.cc/en/Tutorial/LiquidCrystalHelloWorld=

https://learn.sparkfun.com/tutorials/basic-character-lcd-hookup-guide

*/

// include the library code:
#include <LiquidCrystal.h>

//initialize the library by associating any needed LCD interface pin
//with the arduino pin number it is connected to
const int rs = 13, en = 12, d4 = 11, d5 = 10, d6 = 9, d7 = 8;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  //set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  //Print a message to the LCD.
  lcd.print("Hello, world!");
}

void loop() {
  //set the cursor to column 0, line 1
  //(note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

After uploading it to your board, a "hello, world!" should appear on the display. The LCD will also display the time in seconds since the Arduino was reset. You should see something similar to the image below. Depending on how you wrote the code, the letter h might be upper or lower case.

Arduino Outputting a String of Characters and Numbers to the Basic Character LCD via a Parallel Interface

If you see "hello, world!", congratulations! Take a look at the example sketch, and try modifying it to display "hello, your name!" or any other text you'd like. Also, take a look at the other example LiquidCrystal sketches, and the documentation on the Arduino.cc website to see how to write sketches to take advantage of the display. Just make sure to adjust the pin definitions based on how you wired the LCD to your Arduino.

Custom User-Defined Graphics

If you need to make custom characters, there are a few online tools to generate a user-defined graphics. Check out the link below to create your own custom graphic or use any characters made in the pattern library.

For simplicity, we'll just use one of the patterns already generated in the library. Let's create an empty heart. First, you'll need to select your character size. The display that we are using in this example is an 8x5 character space. You'll need to select "Character size: 5 by 8" from the drop down menu so that there is 8 rows and 5 columns of pixels.

Selecting Character Space Size in Custom Character Generator

Then scroll down the webpage and click on the empty heart listed under the Pattern library. You will be presented with values representing the custom character in decimal, hex, and binary.

Using a Pre-Defined Custom Character

We'll use the binary representation of the empty heart. Each value between the comma represents a slice of the custom character space starting from the top of your character space. A pixel is cleared when the value is 0 and darkened when the value is 1.

language:bash
%0,%0,%1010,%10101,%10001,%1010,%100,%0

You will need to copy the values and format it in your code. Since we are using an Arduino to control the basic character display, we'll place the values within an array. We'll name this array emptyHeart[]. To make it easier to read and ensure that the pixel is turned off, we will fill in the most significant bits with 0's to the left of the values so that each slice from the custom character space has a size of 1x5. After formating the values, your array should look like the code below in Arduino.

language:c
byte emptyHeart[8] = {
  B00000,
  B00000,
  B01010,
  B10101,
  B10001,
  B01010,
  B00100,
  B00000
};

Congratulations! You have just created a custom character! Repeat the steps for up to 8x custom characters as necessary.

Example Code

Now that we have created a custom user-defined graphic, let's display it on a screen with a message. The example code below loads three custom characters and displays them on the LCD with a message. Copy the code and paste in the Arduino IDE. Select your board (in this case the Arduino/ Genuino Uno) and COM port. Then upload the code to your Arduino.

language:c
/*LCD-CustomChar.ino

  By: Ho Yun "Bobby" Chan
  SparkFun Electronics
  Date: May 16th, 2019
  License: This code is public domain.

  Description: Demonstrates the use a 16x2 LCD display
  with custom user-defined graphic based on the example 
  used in the Arduino.cc's Reference Library: createChar().
  A message will display with an empty and full heart!

  Hardware Hookup:

    lCD VSS pin to GND
    LCD VCC pin to 5V
    10kΩ Potentiometer to LCD VO pin (pin 3)
    LCD RS pin to digital pin 13
    LCD R/W pin to GND
    LCD Enable pin to digital pin 12
    .
    .
    .
    LCD D4 pin to digital pin 11
    LCD D5 pin to digital pin 10
    LCD D6 pin to digital pin 9
    LCD D7 pin to digital pin 8
    LCD-Backlight - Anode to 10KΩ resistor to +5V (optional depending on your LCD)
    LCD Backlight - K to GND

  For more information about using the creatChar() function,
  make sure to check out the Arduino.cc reference and associated tutorial:

  https://www.arduino.cc/en/Reference/LiquidCrystalCreateChar
  https://learn.sparkfun.com/tutorials/basic-character-lcd-hookup-guide
*/

//Include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 13, en = 12, d4 = 11, d5 = 10, d6 = 9, d7 = 8;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

//Load custom charcter into CGRAM
//Note: Up to 8 characters can be saved

byte smiley[8] = {
  B00000,
  B10001,
  B00000,
  B00000,
  B10001,
  B01110,
  B00000,
};

byte emptyHeart[8] = {
  B00000,
  B00000,
  B01010,
  B10101,
  B10001,
  B01010,
  B00100,
  B00000
};

byte fullHeart[8] = {
  B00000,
  B00000,
  B01010,
  B11111,
  B11111,
  B01110,
  B00100,
  B00000,
};

void setup() {
  //Load a custom character (glyph) for use on the LCD
  lcd.createChar(0, smiley);
  lcd.createChar(1, emptyHeart);
  lcd.createChar(2, fullHeart);

  //Set up the LCD's number of columns and rows:
  lcd.begin(16, 2);

  //Clear the display
  lcd.clear();
}

void loop() {
  //Set the cursor to the 0,0 position (top left corner)
  lcd.setCursor(0, 0);

  //Display a message with the custom characters
  lcd.print("I ");
  lcd.write(byte(1)); //display custom character related associated with num 1
  lcd.print(" SparkFun! ");
  lcd.write(byte(0)); //display custom character related associated with num 0
  delay(1000);

  //Set the cursor to the 0,0 position (top left corner)
  lcd.setCursor(2, 0);

  lcd.write(byte(2)); //display custom character related associated with num 1
   delay(1000);
}

After uploading, a message will display with an empty and full heart!

Basic Character LCD Demo with Custom Character

RGB LED Backlight Control

Previous examples connect the white LED backlight to power. The following example is specifically for those using an LCD with a RGB LED backlight. The only difference between the connection is the LED's backlight on pins 15-18.

Copy and paste the code below. Just make sure to select the correct board (in this case the Arduino/ Genuino Uno) and the COM port that the Arduino enumerated on. Then upload the code to your Arduino.

language:c
/* LCD-RGB_Hello World.ino

  By: Ho Yun "Bobby" Chan
  SparkFun Electronics
  Date: 5/22/2019
  License: This code is public domain.

  Modified example code of Arduino.cc's Hello World.
  https://www.arduino.cc/en/Tutorial/HelloWorld

  Demonstrates the use a 16x2 LCD display with a common cathode
  RGB LED backlight. The LiquidCrystal library works with all
  LCD displays that are compatible with the Hitachi HD44780 driver.
  There are many of them out there, and you can usually tell them
  by the 16-pin/18-pin interface.

  This sketch prints "Hello world!" to the LCD,
  shows the time since the Arduino was last reset, and 
  controls the RGB backlight. The backlight displays
  the primary, secondary, and tertiary colors.

  Hardware Hookup:
    LCD VSS pin to GND
    LCD VCC pin to 5V
    10kΩ Potentiometer to LCD VO pin (pin 3)
    LCD RS pin to digital pin 13
    LCD R/W pin to GND
    LCD Enable pin to digital pin 12
    .
    .
    .
    .
    LCD D4 pin to digital pin 11
    LCD D5 pin to digital pin 10
    LCD D6 pin to digital pin 9
    LCD D7 pin to digital pin 8
    LCD Backlight - K (Common Cathode) to GND
    LCD Backlight - Anode-RED to 330Ω to PWM pin 6
    LCD Backlight - Anode-GREEN to 330Ω to PWM pin 5
    LCD Backlight - Anode-BLUE to 330Ω to PWM pin 3

  Note: You may need to adjust the current limiting resistor
  and PWM value for the LED depending on the voltage used.
  Depending on the mixed color, this may result in a lower
  brightness.

  https://learn.sparkfun.com/tutorials/basic-character-lcd-hookup-guide

*/

//Include the library code:
#include <LiquidCrystal.h>

//LED Backlight
int ledR = 6;//hardware PWM
int ledG = 5;//hardware PWM
int ledB = 3; //hardware PWM
int redIntensity = 255; //value to adjust since red can be brighter than the other colors depending on the resistor value used

//Initialize the library by associating any 
//needed LCD interface pin with the Arduino pin
//number it is connected to
const int rs = 13, en = 12, d4 = 11, d5 = 10, d6 = 9, d7 = 8;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  //Set up the LCD's number of columns and rows:
  lcd.begin(16, 2);

  //Clear the display
  lcd.clear();

  //Test Colors
  sequenceTest();

  lcd.setCursor(0, 0);
  //Print a message to the LCD.
  lcd.print("Hello, world!");
  //Turn on backlight for red
  redON();
  lcd.setCursor(0, 1);
  lcd.print("Red");
  delay(1500);
  lcd.setCursor(0, 1);
  lcd.print("");

}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

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

void allON() {
  analogWrite(ledR, redIntensity);
  analogWrite(ledG, 255);
  analogWrite(ledB, 255);
}

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

void roseON() {
  analogWrite(ledR, redIntensity);
  analogWrite(ledG, 0);
  analogWrite(ledB, 128);
}

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

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

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

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

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

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

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

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

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

void orangeON() {
  analogWrite(ledR, redIntensity);
  analogWrite(ledG, 51);
  analogWrite(ledB, 0);
}

void sequenceTest() {

  lcd.setCursor(0, 0);
  lcd.print("Backlight Color");

  lcd.setCursor(0, 1);          //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);          //set the cursor to the second row, 1st position
  lcd.print("Red");
  redON();//good
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Rose");
  roseON();
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Magenta");
  magentaON();//good
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Violet");
  violetON();
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Blue");
  blueON();//good
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Azure");
  azureON();//good
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Cyan");
  cyanON();//good
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Spring Green");
  springgreenON();//good
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Green");
  greenON();//good
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Chartreuse");
  chartreuseON();
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Yellow");
  yellowON();//good
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("Orange");
  orangeON();//good
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("White");
  allON();
  delay(1500);

  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("");//clear 2nd row
  lcd.setCursor(0, 1);           //set the cursor to the second row, 1st position
  lcd.print("LEDs Off");
  allOFF();
  delay(1500);

  lcd.setCursor(0, 0);           //set the cursor to the second row, 1st position
  lcd.clear();                   //Clear the display
}

After uploading, you will notice the same "Hello, world!" and time since the Arduino was last reset in the first example. The only difference is that the current color of the backlight will be printed as it cycles through each of the primary, secondary, and tertiary colors. You should see something similar to the image below.

Hello World with the RGB LED Backlight

Troubleshooting and FAQ

The Screen is Blank or Flickering

If no message appears, the contrast may need to be adjusted. To do this, turn the potentiometer until "hello, world!" until you can view characters on the screen. Adjust the contrast by twisting the potentiometer. If it’s incorrectly adjusted, you won’t be able to read the text clearly. Also, check the potentiometer and make sure it's connected correctly. If you still don't see anything, double-check your wiring to ensure that the wires are fully connected. Also, check your solder joints to ensure that there is a sufficient connection.

Not Working At All

Double check the circuit's wiring. There are a lot of wires in this circuit, and it's easy to mix up one or two.

Rectangles in First Row and Random Characters

If you see 16x rectangles (like “█”) or random characters on the first row, it may be due to the jumper wires being loose on the breadboard. This is normal and can happen with other LCDs wired in parallel with a microcontroller. Make sure that the wires are fully inserted into the breadboard, then try pressing the reset button and adjusting the contrast using the potentiometer. Also, make sure that the defined pins match your current setup.

Contrast

A display that needs the contrast adjusted. Note the white rectangles.

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. You may need to rework the solder joints for a secure connection.


Can I Connect a Basic Character LCD to the ESP8266 Thing Development Board?

Yes. However, the ESP8266 Thing Dev is 3.3V. You'd have to use two logic level converters (like the four channel bidirectional logic level converter) to convert 6x pins at a minimum if you were using a 5V basic character display. That's a lot of wires. Make sure to avoid using pin D0, D16, Tx, and Rx. There are issues displaying characters using those pins since they are tied to other functions such as the reset or deep sleep. The pin definitions can be defined as the following.

language:c
const int rs = 2, en = 14, d4 = 5, d5 = 4, d6 = 13, d7 = 12;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

The hookup should look similar to the following diagrams.

ESP8266 Thing Dev Connected to 5V Basic Character LCD

ESP8266 Thing Dev Connected to 3.3V Basic Character LCD

Resources and Going Further

Now that you've successfully got your basic character LCD 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 to use the display in javascript, create your own game using custom characters, or display sensor data on your screen.

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!

Endless Runner Game

We make a simple side-scrolling endless runner game using parts from the SparkFun Inventor's Kit v4.0.

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.

Instead of using a parallel interface, you can also try using a serial connection to reduce the amount of wires.

PIC-Based Serial Enabled Character LCD Hookup Guide

The PIC-based serial enabled character LCD backpack is a simple and cost effective solution for interfacing to character Liquid Crystal Displays (LCDs) based on the HD44780 controller. The backpack simplifies the number of wires needed and allows your project to display all kinds of text and numbers.

AVR-Based Serial Enabled LCDs Hookup Guide

The AVR-based Serial Enabled LCDs are a simple and cost effective solution to include in your project. These screens are based on the HD44780 controller, and include ATmega328P with an Arduino compatible bootloader. They accept control commands via Serial, I2C and SPI. In this tutorial, we will show examples of a simple setup and go through each communication option.

Or check out this activity if you are an educator.

SIK LCD Tutorial Activity

July 23, 2016

SIK LCD Tutorial simplifies the wiring and usage of the parallel LCD module that is included in the SIK.

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


LiPo Charger Plus Hookup Guide

$
0
0

LiPo Charger Plus Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun LiPo Charger Plus is the souped-up power option in the SparkFun line of single-cell lithium polymer (LiPo) battery chargers. With this iteration, we've changed the input charge connector to USB-C and provided charge rate selection as well as optional thermal protection. Charge, power, and done LEDs clearly indicate the status of your charging process.

Got a battery? Let's charge!

SparkFun LiPo Charger Plus

SparkFun LiPo Charger Plus

PRT-15217
$9.95

Required Materials

All that is needed to charge a LiPo battery sufficiently is a micro-C USB cable to connect to either a computer USB port or a wall adapter.

USB 2.0 Cable A to C - 3 Foot

USB 2.0 Cable A to C - 3 Foot

CAB-15092
$3.95
USB Wall Charger - 5V, 1A (Black)

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

TOL-11456
$3.95
2
USB 3.1 Cable A to C - 3 Foot

USB 3.1 Cable A to C - 3 Foot

CAB-14743
$4.95
2

A few LiPo batteries with nominal 3.7V from our catalog:

Lithium Ion Battery - 1Ah

Lithium Ion Battery - 1Ah

PRT-13813
$9.95
7
Lithium Ion Battery - 850mAh

Lithium Ion Battery - 850mAh

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

Lithium Ion Battery - 400mAh

PRT-13851
$4.95
9
Lithium Ion Battery - 110mAh

Lithium Ion Battery - 110mAh

PRT-13853
$4.95
2

Suggested Reading

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

Voltage, Current, Resistance, and Ohm's Law

Learn about Ohm's Law, one of the most fundamental equations in all electrical engineering.

Battery Technologies

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

Hardware Overview

For a quick reference, here is an annotated diagram of the parts used on the LiPo Charger Plus:

Highlighted top view of board
NumberDescription
1Charge Input - The input voltage for the MCP73833 charger IC is between 3.75 to 6V. To fully charge the battery, it is recommended to have a voltage around 5V. The charge IC will regulate the voltage down to safely charge the LiPo battery.
2Power LED - When power is supplied this red LED should turn on. The LED is connected to the active low PG (power good) pin, which is active whenever the input to charger is about the UVLO (3.7V) threshold and greater than the battery voltage.
3Charge LED - When a battery is connected and the charge controller is charging the battery, this LED will turn on, and should be off otherwise.
4Done LED - After the battery has reached a full charge, this LED will turn on, and should be off otherwise.
5Charge Rate Select - Programmable current regulation (default: 1kΩ). Selects the maximum amount of current to charge the battery. For a detailed explanation, see the charge rate setting section of this guide.
6Thermistor Input - An internal 50 µA current source provides the bias for most common 10kΩ negative-temperature coefficient thermistors (NTC). The MCP73833 compares the voltage at the THERM pin to factory set thresholds of 1.20V and 0.25V, typically. If using a NTC thermistor, the 10kΩ SMD resistor should be removed.
7Battery Input - A single-cell LiPo battery can be connected to either the JST connector, or PTH pins. If using the PTH pins, pay close attention to the polarity of the battery/battery holder, as connecting a LiPo battery backwards to the charger will destroy the IC.


Status LEDs

The LiPo Charger Plus has three LEDs, a red LED for power, and two status LEDs. Most of the time the charge LED will turn on when the board is charging a battery, and turn off when the board is done charging. The done LED will turn off when the board is charging and turn on when done charging. For a full list of LED status indicators, refer to the table below.

Charge Cycle StateChargeDonePWR
ShutdownOFFOFFOFF
StandbyOFFOFFON
Charge In ProgressONOFFON
Charge CompleteOFFONON
Temperature FaultOFFOFFON
Timer FaultOFFOFFON
System Test ModeONONON


Setting a Different Charge Rate

Lithium batteries should be charged at a rate no higher than 1C (eg. a 400mAH battery should be charged no faster than 400mA). The LiPo Charger Plus has a 1kΩ SMD resistor populated, which sets the charge rate at the maximum 1000mA. If your battery is smaller than 1000mAH, this resistor should be removed and replaced with an appropriate resistor. To determine the correct resistor value, use the formula or lookup table below:



I_REG (mA)R_PROG (kΩ)
10001.00
9001.11
8001.25
7001.43
6001.67
5002.00
4002.50
3003.33
2005.00
10010.0


Over Temperature Protection

The MCP73833 has two forms of thermal protection, one for the charge controller itself and the other for the battery. The charge controller has an internal temperature sensor to maximize the current charge rate up to the programmed charge rate without over heating. When the die temperature of the MCP73833 reaches ~95°C, the charge controller will reduce the charge rate to prevent over heating. Over heating is most likely to occur at the beginning of a charge when the battery's voltage is the lowest. As the difference between the supply voltage and the battery voltage decreases, the die temperature will decrease and allow the charge current to increase up to the programmed charge rate.

Graph of charge current vs junction temperature

Charge Current(Iout) vs Junction Temperature(TJ)

Image pulled from MCP73833 Datasheet

The other temperature sensor is optionally available for the battery. The MCP73833 has an input pin for a thermistor which can be attached to the battery using a high temperature tape. The thermistor that the charge controller is designed to use is a negative-temperature coefficient (NTC), which decreases it's resistance as the temperature increases. If sourcing your own NTC thermistor, look for a NTC thermistor with a resistance of 10kΩ at 25°C. To connect a NTC thermistor, remove the 10kΩ SMD resistor and solder the leads of the NTC to the PTH resistor pads highlighted below.

Highlight of Thermistor Pads

Adding a Heatsink

If the charge rate isn't getting up to the programmed charge rate, the IC is most likely overheating and limiting the current to the battery. One of the easiest ways to solve this is to add a heatsink with our thermal tape. On the bottom of the board is an exposed pad underneath the MCP73833.

Highlight of exposed pad on back of board

To add a heatsink first cut the thermal tape to rough size:

Thermal tape cut to rough size

Peel off one of the protective coverings and attach heatsink to thermal tape:

Heatsink connected to thermal tape

With a hobby knife, follow the perimeter of the heatsink to cut the tape to it's final size:

Cutting thermal tape

Remove the remaining protective covering of the tape and attach the heatsink to the exposed pad. If using a standoff, you may want to attach the standoff first to make sure you have enough clearance between the standoff and the heatsink.

Heatsink attached to board

Troubleshooting

Resources and Going Further

Need more information? Check out some of the links below:

Check out these other power related tutorials from SparkFun:

LiPo USB Charger Hookup Guide

How to charge your LiPo batteries with the USB LiPo charger. Plus how to modify your charger to set the charge current.

FemtoBuck Constant Current LED Driver Hookup Guide V12

The FemtoBuck board is a high-efficiency, single-channel constant-current LED driver.

What is a Battery?

An overview of the inner workings of a battery and how it was invented.

SparkFun 5V/1A LiPo Charger/Booster Hookup Guide

This tutorial shows you how to hook up and use the SparkFun 5V/1A LiPo Charger/Booster circuit.

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

Capacitive Touch Slider Hookup Guide

$
0
0

Capacitive Touch Slider Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Do you want to replace a slider or a button on your art project or science experiment with a more interesting interface? The SparkFun Capacitive Touch Slider - CAP1203 (Qwiic) is a Qwiic and easy way to add capacitive touch to your next project. With the board's built in touch pads, you can immediately start playing with the touch capabilities as three unique touch inputs or as a slider. You can also enable a touch input to act as a power button, customize the sensitivity for your own touch pads, and play with the interrupt alert LED. Since the sensor supports I2C, we've added a Qwiic connector for easy integration into the Qwiic environment. We've also added breakout pins for the capacitive touch inputs, so you can connect to your own touch pads.

SparkFun Capacitive Touch Slider - CAP1203 (Qwiic)

SparkFun Capacitive Touch Slider - CAP1203 (Qwiic)

SEN-15344
$5.95

Required Materials

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

SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

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

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
12
Qwiic Cable - 50mm

Qwiic Cable - 50mm

PRT-14426
$0.95

If you need different sizes of Qwiic cables, we offer a kit that contains many sizes but we also carry them individually.

SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
1
Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - Breadboard Jumper (4-pin)

Qwiic Cable - Breadboard Jumper (4-pin)

PRT-14425
$1.50
Qwiic Cable - 500mm

Qwiic Cable - 500mm

PRT-14429
$1.95

Suggested Reading

If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System
Qwiic Connect System

We would also recommend taking a look at the following tutorials if you aren't familiar with them.

Switch Basics

A tutorial on electronics' most overlooked and underappreciated component: the switch! Here we explain the difference between momentary and maintained switches and what all those acronyms (NO, NC, SPDT, SPST, ...) stand for.

Capacitors

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

I2C

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

How to Work with Jumper Pads and PCB Traces

Handling PCB jumper pads and traces is an essential skill. Learn how to cut a PCB trace, add a solder jumper between pads to reroute connections, and repair a trace with the green wire method if a trace is damaged.

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.

Hardware Overview

Note: If you want to do anything outside of what is covered in this tutorial or the example code, please refer to the CAP1203 Datasheet for exact details on the sensor functionality.

Power

You can provide 3.3V through the polarized Qwiic connectors on the board or through the 3V3 labeled pin on the through-hole header. The Qwiic system is meant to use 3.3V, so be sure you are NOT using another voltage when using the Qwiic system. When you have correctly powered the board, the red power LED will turn on.

Power LED and Breakout Pin
Power LED, Breakout Pin, and Qwiic Connectors

Qwiic Connectors or I2C Pins

There are two Qwiic connectors on the back of the board to easily connect the sensor to I2C. If you prefer the old school method of connecting to I2C, we've also included four breakout pins on the side of the board.

Qwiic Connectors and I2C pins
Qwiic Connectors and I2C Breakout Pins

Interrupt Pin and LED

The interrupt pin is an active low output which is triggered each each time a sensor pad is touched. You can connect to this pin if you want to check when an interrupt occurs. On the front side of the board, the green LED in the bottom right corner also signals when an interrupt occurs.

Interrupt Breakout Pin
Interrupt Breakout Pin

Interrupt LED
Interrupt LED

Capacitive Touch Pads and Pins

On the front of the board, there is an arrow shape which contains three separate capacitive touch pads. In order to know which pad is which, orient the board with the arrow pointing in the right direction. We will reference these capacitive touch pads as the left pad, the middle pad, and the right pad throughout the guide and in the code. We also broke out the capacitive touch sensor lines as plated through-holes on the top of the board. You can use these pins to connect to your own capacitive touch pads. The CS1 pin connects to the left pad, the CS2 pin connects to the middle pad, and the CS3 pin connects to the right pad.

Left Pad Highlighted
Middle Pad Highlighted
Right Pad Highlighted

Left, Middle, and Right Touch Pads

Capacitive Touch Pads Breakout Pins
Capacitive Touch Pad Breakout Pins

Jumpers

There are 3 jumper pads on the back of the board, each labeled with its function. First, on upper left side of the board, there is a two way jumper labeled INT that connects to a 10k pull-up resistor on the interrupt data line. If you cut this jumper, it will disconnect the 10k pull-up resistor from the interrupt data line. Next, on the lower left side of the board, there is a two way jumper labeled LED that connects to the green interrupt LED. If you cut this jumper, it will disconnect the LED from the interrupt line, effectively disabling the green LED's functionality. Lastly, on the lower half of the board, there is a three way jumper labeled I²C that connects two 2.2k pull-up resistors to the I2C data lines. If you have multiple devices on your I2C data lines, then you may consider cutting this jumper. Not sure how to cut a jumper? Read here!

Jumper Pads
Jumper pads for the INT pin pullup, LED disable, and I2C pullup

Hardware Assembly

With the Qwiic connector system, assembling the hardware is easy. For this tutorial, we use the SparkFun RedBoard Qwiic, an associated USB Cable, and a Qwiic cable. Plug your Qwiic cable between the RedBoard Qwiic and the Capacitive Touch Slider. Then, connect the microcontroller via the USB Cable to your computer. And...that's it! You're ready to start uploading code. Otherwise, if your going to be soldering, then connect wires from the power, ground, and I2C data line breakout pins to the microcontroller of your choice. Using the CS1, CS2, and CS3 plated through-hole pins, you can also break out the capacitive touch lines to your own capacitive touch pads.

Qwiic Hardware Assembly
Qwiic Hardware Assembly

Arduino Library

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

We've provided a library to help you easily control and configure your Capacitive Touch Slider. Some of the features include reading when a pad is touched, detecting right and left swipes, enabling a power button, and setting the sensitivity for your own touch pads. If you haven't already, click the button below to get the library or download it manually from the GitHub repository. You can also download the library by searching 'SparkFun Qwiic Capacitive Touch Slider' in the Arduino library manager. We have provided seven different example sketches to help you get started.

Library Functions

The Arduino library is commented and the functions should be self explanatory. However, below is a detailed list of the available library functions.

Note: It is recommended that users begin with the examples in the following section before diving head first into the library functions. The library examples demonstrate how to setup the more basic features of the Capacitive Touch Slider without having to dig through the datasheet. Once users have become familiar with the basic setups and have gone through the datasheet thoroughly, it should be easier to follow the library functions below.

Initialization Settings: We use these to set-up and initialize the board.

.begin() - Initialize the sensor, returns true if correctly set-up

.isConnected() - Checks I2C connection, returns true if correctly connected

Sensitivity Settings: These functions allow you to change the sensitivity settings for your touch pads. Note, the default sensitivity is set to SENSITIVITY_2X in the .begin() function for the SparkFun Capacitive Touch Slider board. We only recommend changing the sensitivity setting if you are breaking out your own touch pads.

.setSensitivity(sensitivity) - Sets the sensitivity multiplier for the touch pads Possible sensitivity argument values:
SENSITIVITY_128X - Most sensitive
SENSITIVITY_64X
SENSITIVITY_32X
SENSITIVITY_16X
SENSITIVITY_8X
SENSITIVITY_4X
SENSITIVITY_2X
SENSITIVITY_1X - Least sensitive

.getSensitivity() - Returns the sensitivity multiplier for the current sensitivity settings, returns as an integer value

Power Button Settings: These functions allow you to enable or disable the power button on a specific pad. The power button requires a longer touch before registering a touch has been detected on the designated pad. Note, when the power button is enabled, the designated pad will only act as the power button.

.setPowerButtonPad(pad) - Sets a button to act as a power button, returns true if correctly set Possible pad argument values:
PAD_LEFT - Left pad and CS1 breakout pin
PAD_MIDDLE - Middle pad and CS2 breakout pin
PAD_RIGHT - Right pad and CS3 breakout pin

.getPowerButtonPad() - Returns which pad is currently set to be the power button, returns as an integer value Return values:
1 - Left pad and CS1 breakout pin
2 - Middle pad and CS2 breakout pin
3 - Right pad and CS3 breakout pin

.setPowerButtonTime(time) - Sets the power button touch time, returns true if correctly set Possible time argument values:
PWR_TIME_280_MS
PWR_TIME_560_MS
PWR_TIME_1120_MS
PWR_TIME_2240_MS

.getPowerButtonTime() - Returns length of time (ms) power button must indicate a touch, returns as an integer value

.setPowerButtonEnabled() - Enables power button functionality
.setPowerButtonDisabled() - Disables power button functionality

isPowerButtonEnabled() - Returns true if power button functionality is currently enabled

Interrupt Settings: These functions allow you to control if the interrupt pin is enabled. When enabled, the green interrupt LED will turn on when any pad detects a touch. Note, the interrupt is enabled as default in the .begin() function.

.setInterruptDisabled() - Disables interrupt pin
.setInterruptEnabled() - Enables interrupt pin

.isInterruptEnabled() - Returns true if interrupt pin is currently enabled

Check if a capacitive touch pad or breakout pin has been touched: These functions allow you to check when a capacitive touch pad or breakout pin has been touched.

.isLeftTouched() - Returns true if left pad or CS1 pin detects a touch
.isMiddleTouched() - Returns true if middle pad or CS2 pin detects a touch
.isRightTouched() - Returns true if right pad or CS3 pin detects a touch
.isTouched() - Returns true if any pad or breakout pin detects a touch
.isPowerButtonTouched() - Returns true if designated power button pad or pin held for alloted time

Check if a swipe has occured: The direction of the swipe is relative to the arrow on the board pointing in the right direction. For the pins, a right swipe is first CS1, then CS2, and finally CS3 and a left swipe is first CS3, then CS2, and finally CS1. Note, these functions pull most available resources. For best swipe recognition, we highly recommend not implementing other functionalities when using these two functions.

.isRightSwipePulled() - Returns true if board detects a right swipe
.isLeftSwipePulled() - Returns true if board detects a left swipe

Example Code

Note: This section is an example of using the Capacitive Touch Slider - CAP1203 (Qwiic) and the RedBoard Qwiic with the Arduino IDE. It is not intended to be a guide for using I2C devices with the Arduino IDE.

Please use the following links and the Internet for a better understanding of I2C and how it works in the Arduino IDE:

Example 1: Basic Reading

The Example01_BasicReading.ino sketch works with the basic functionality of the Capacitive Touch Slider and streams which pad detects a touch. Open up the example to follow along. First, we include the CAP1203 library and initialize an instance of the sensor. Then, in the set-up function, we check to make sure the sensor is correctly connected. Now that the sensor is set-up, we can start checking which pads have been touched in the main loop using the .isLeftTouched(), .isMiddleTouched(), and .isRightTouched() functions. Once you have uploaded the code, you can open your serial terminal to see when a pad has been touched. Make sure the baud rate in your serial terminal is set to 9600 baud, otherwise you won't see the correct output.

Example 1 Output

Example 1 Output

Example 2: Detect Any Touch

The setup for Example02_DetectAnyTouch.ino sketch is similar to Example 1, except it streams when any pad detects a touch using the .isTouched() function.

Example 2 Outputt

Example 2 Output

Example 3: Detect Swipe

The setup for Example03_DetectSwipe.ino sketch is similar to Example 1, except it streams when the board detects a swipe using the .isRightSwipePulled() and .isLeftSwipePulled() functions. The direction of the swipe is relative to the arrow on the board pointing in the right direction. Note, these functions pull most available resources. For best swipe recognition, we highly recommend not implementing other functionalities when using these two functions.

Example 3 Output

Example 3 Output

Example 4: Power Button

The Example04_PowerButton.ino sketch allows you enable or disable the power button feature on a specific pad. The power button requires a longer touch before registering a touch has been detected on the designated pad. Note, when the power button is enabled, the designated pad will only act as the power button. Configuring and enabling the power button feature requires some additional set-up.

In the sketch, we use the .setPowerButtonPad() and .setPowerButtonTime() functions to set which pad will act as the power button and the length of time the designated pad must indicate a touch. We also implement the .getPowerButtonPad() and .getPowerButtonTime() functions to check which pad and time we set with the previous two functions. Then, we enable the power button using the .setPowerButtonEnabled() function, and we check that the power button has been properly enabled using the .isPowerButtonEnabled() function. Finally, we check when the designated power button pad has been held for the allotted time using the .isPowerButtonTouched() function. The serial port prints Power Button when it registers a power button touch.

Example 4 Output

Example 4 Output

Example 5: Detect Current Touch

The Example05_DetectCurrentTouch.ino sketch uses the same functions and set-up as Example 1. However, Example 5 only notifies you about the current touch as opposed to a constant stream of touch data in Example 1. In order to do so, we added a while loop inside of each conditional statement. For example: while (sensor.isLeftTouched() == true).

Example 5 Output

Example 5 Output

Example 6: Disable Interrupt

The Example06_DisableInterrupt.ino sketch allows you to programmatically adjust the interrupt settings. When disabled, the green interrupt LED will no longer turn on when a pad is touched. We use the .setInterruptDisabled() function to disable to interrupt and the .isInterruptEnabled() function to check the current interrupt settings. In the main loop, we then implement the .isTouched() function as in Example 2 to check that our board still registers a touch even though the interrupt LED no longer turns on.

Example 6 Output

Example 6 Output

Example 7: Set Sensitivity

The Example07_SetSensitivity.ino sketch allows you to programmatically adjust the sensitivity settings for your capacitive touch pads. Note, we only recommend changing the sensitivity settings if you are breaking out your own touch pads. The current sensitivity settings are calibrated for the SparkFun Capacitive Touch Slider on board pads. In our example, we use the .setSensitivity() function to change the sensitivity and the .getSensitivity() to check our current sensitivity settings. In the main loop, we then implement the .isTouched() function as in Example 2 to check when the sensor has been touched with the new sensitivity settings.

Example 7 Output

Example 7 Output

Troubleshooting

Don't know if your board is working properly? To check that your board is properly hooked up, start by connecting your Capacitive Touch Slider and uploading the first example sketch to your microcontroller. Then, when you touch one of the pads, as demonstrated in the GIF, the green interrupt LED in the bottom right corner should turn on each time it senses a touch. (Note, if you have not yet uploaded code, the interrupt LED will turn on when you first connect to your microcontroller. The LED will turn off once you have uploaded the Example 1 code.) The red power LED on the back of the board, you can see its reflection on the table in the GIF, will also be on when the board is properly powered.


Interrupt LED GIF Demo

Demo of Interrupt LED

Resources and Going Further

Fore more on the Capacitive Touch Slider - CAP1203 (Qwiic) check out the links below.

Need some inspiration for your next project? Check out some of these capacitive touch tutorials below!

Constant Innovation in Quality Control

In this article, we share our recent advancements in quality control. Along with making our tests more thorough, we have also made them more efficient and robust.

Bare Conductive Musical Painting

Learn how to make a musical painting using the Bare Conductive Touch Board and Conductive Paint.

Getting Started with the Teensy

Basic intro to the Teensy line of products, with soldering and programming suggestions.

AT42QT101X Capacitive Touch Breakout Hookup Guide

Learn how to use the simple SparkFun AT42QT1010 and AT42QT1011 capacitive touch breakout boards.

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

Capacitive Touch Slider (CAP1203) Hookup Guide

$
0
0

Capacitive Touch Slider (CAP1203) Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Do you want to replace a slider or a button on your art project or science experiment with a more interesting interface? The SparkFun Capacitive Touch Slider - CAP1203 (Qwiic) is a Qwiic and easy way to add capacitive touch to your next project. With the board's built in touch pads, you can immediately start playing with the touch capabilities as three unique touch inputs or as a slider. You can also enable a touch input to act as a power button, customize the sensitivity for your own touch pads, and play with the interrupt alert LED. Since the sensor supports I2C, we've added a Qwiic connector for easy integration into the Qwiic environment. We've also added breakout pins for the capacitive touch inputs, so you can connect to your own touch pads.

SparkFun Capacitive Touch Slider - CAP1203 (Qwiic)

SparkFun Capacitive Touch Slider - CAP1203 (Qwiic)

SEN-15344
$5.95

Required Materials

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

SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

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

USB micro-B Cable - 6 Foot

CAB-10215
$4.95
12
Qwiic Cable - 50mm

Qwiic Cable - 50mm

PRT-14426
$0.95

If you need different sizes of Qwiic cables, we offer a kit that contains many sizes but we also carry them individually.

SparkFun Qwiic Cable Kit

SparkFun Qwiic Cable Kit

KIT-15081
$7.95
1
Qwiic Cable - 100mm

Qwiic Cable - 100mm

PRT-14427
$1.50
Qwiic Cable - Breadboard Jumper (4-pin)

Qwiic Cable - Breadboard Jumper (4-pin)

PRT-14425
$1.50
Qwiic Cable - 500mm

Qwiic Cable - 500mm

PRT-14429
$1.95

Suggested Reading

If you aren't familiar with the Qwiic system, we recommend reading here for an overview.

Qwiic Connect System
Qwiic Connect System

We would also recommend taking a look at the following tutorials if you aren't familiar with them.

Switch Basics

A tutorial on electronics' most overlooked and underappreciated component: the switch! Here we explain the difference between momentary and maintained switches and what all those acronyms (NO, NC, SPDT, SPST, ...) stand for.

Capacitors

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

I2C

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

How to Work with Jumper Pads and PCB Traces

Handling PCB jumper pads and traces is an essential skill. Learn how to cut a PCB trace, add a solder jumper between pads to reroute connections, and repair a trace with the green wire method if a trace is damaged.

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.

Hardware Overview

Note: If you want to do anything outside of what is covered in this tutorial or the example code, please refer to the CAP1203 datasheet for exact details on the sensor functionality.

Power

You can provide 3.3V through the polarized Qwiic connectors on the board or through the 3V3 labeled pin on the through-hole header. The Qwiic system is meant to use 3.3V, so be sure you are NOT using another voltage when using the Qwiic system. When you have correctly powered the board, the red power LED will turn on.

Power LED and Breakout Pin

Power LED, Breakout Pin, and Qwiic Connectors

Qwiic Connectors or I2C Pins

There are two Qwiic connectors on the back of the board to easily connect the sensor to I2C. If you prefer the old school method of connecting to I2C, we've also included four breakout pins on the side of the board.

Qwiic Connectors and I2C pins

Qwiic Connectors and I2C Breakout Pins

Interrupt Pin and LED

The interrupt pin is an active low output which is triggered each each time a sensor pad is touched. You can connect to this pin if you want to check when an interrupt occurs. On the front side of the board, the green LED in the bottom right corner also signals when an interrupt occurs.

Interrupt Breakout Pin

Interrupt Breakout Pin

Interrupt LED
Interrupt LED

Capacitive Touch Pads and Pins

On the front of the board, there is an arrow shape which contains three separate capacitive touch pads. In order to know which pad is which, orient the board with the arrow pointing in the right direction. We will reference these capacitive touch pads as the left pad, the middle pad, and the right pad throughout the guide and in the code. We also broke out the capacitive touch sensor lines as plated through-holes on the top of the board. You can use these pins to connect to your own capacitive touch pads. The CS1 pin connects to the left pad, the CS2 pin connects to the middle pad, and the CS3 pin connects to the right pad.

Left Pad Highlighted
Middle Pad Highlighted
Right Pad Highlighted

Left, Middle, and Right Touch Pads

Capacitive Touch Pads Breakout Pins

Capacitive Touch Pad Breakout Pins

Jumpers

There are 3 jumper pads on the back of the board, each labeled with its function. First, on upper left side of the board, there is a two way jumper labeled INT that connects to a 10k&ohm; pull-up resistor on the interrupt data line. If you cut this jumper, it will disconnect the 10kk&ohm; pull-up resistor from the interrupt data line. Next, on the lower left side of the board, there is a two way jumper labeled LED that connects to the green interrupt LED. If you cut this jumper, it will disconnect the LED from the interrupt line, effectively disabling the green LED's functionality. Lastly, on the lower half of the board, there is a three way jumper labeled I²C that connects two 2.2kk&ohm; pull-up resistors to the I2C data lines. If you have multiple devices on your I2C data lines, then you may consider cutting this jumper. Not sure how to cut a jumper? Read here!

Jumper Pads

Jumper pads for the INT pin pull-up, LED disable, and I2C pullup

Hardware Assembly

With the Qwiic connector system, assembling the hardware is easy. For this tutorial, we use the SparkFun RedBoard Qwiic, an associated USB Cable, and a Qwiic cable. Plug your Qwiic cable between the RedBoard Qwiic and the Capacitive Touch Slider. Then, connect the microcontroller via the USB Cable to your computer. And...that's it! You're ready to start uploading code. Otherwise, if you're going to be soldering, then connect wires from the power, ground, and I2C data line breakout pins to the microcontroller of your choice. Using the CS1, CS2, and CS3 plated through-hole pins, you can also break out the capacitive touch lines to your own capacitive touch pads.

Qwiic Hardware Assembly

Qwiic Hardware Assembly

Arduino Library

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

We've provided a library to help you easily control and configure your Capacitive Touch Slider. You can download the library by searching 'SparkFun Qwiic Capacitive Touch Slider' in the Arduino library manager. Some of the features include reading when a pad is touched, detecting right and left swipes, enabling a power button, and setting the sensitivity for your own touch pads. You can also manually install the library by clicking the button below to get the library from it's GitHub repository. We have provided seven different example sketches to help you get started.

Library Functions

The Arduino library is commented and the functions should be self explanatory. However, below is a detailed list of the available library functions.

Note: It is recommended that users begin with the examples in the following section before diving head first into the library functions. The library examples demonstrate how to setup the more basic features of the Capacitive Touch Slider without having to dig through the datasheet. Once users have become familiar with the basic setups and have gone through the datasheet thoroughly, it should be easier to follow the library functions below.

Initialization Settings: We use these to set-up and initialize the board.

.begin() - Initialize the sensor, returns true if correctly set-up

.isConnected() - Checks I2C connection, returns true if correctly connected

Sensitivity Settings: These functions allow you to change the sensitivity settings for your touch pads. Note, the default sensitivity is set to SENSITIVITY_2X in the .begin() function for the SparkFun Capacitive Touch Slider board. We only recommend changing the sensitivity setting if you are breaking out your own touch pads.

.setSensitivity(sensitivity) - Sets the sensitivity multiplier for the touch pads Possible sensitivity argument values:
SENSITIVITY_128X - Most sensitive
SENSITIVITY_64X
SENSITIVITY_32X
SENSITIVITY_16X
SENSITIVITY_8X
SENSITIVITY_4X
SENSITIVITY_2X
SENSITIVITY_1X - Least sensitive

.getSensitivity() - Returns the sensitivity multiplier for the current sensitivity settings, returns as an integer value

Power Button Settings: These functions allow you to enable or disable the power button on a specific pad. The power button requires a longer touch before registering a touch has been detected on the designated pad. Note, when the power button is enabled, the designated pad will only act as the power button.

.setPowerButtonPad(pad) - Sets a button to act as a power button, returns true if correctly set Possible pad argument values:
PAD_LEFT - Left pad and CS1 breakout pin
PAD_MIDDLE - Middle pad and CS2 breakout pin
PAD_RIGHT - Right pad and CS3 breakout pin

.getPowerButtonPad() - Returns which pad is currently set to be the power button, returns as an integer value Return values:
1 - Left pad and CS1 breakout pin
2 - Middle pad and CS2 breakout pin
3 - Right pad and CS3 breakout pin

.setPowerButtonTime(time) - Sets the power button touch time, returns true if correctly set Possible time argument values:
PWR_TIME_280_MS
PWR_TIME_560_MS
PWR_TIME_1120_MS
PWR_TIME_2240_MS

.getPowerButtonTime() - Returns length of time (ms) power button must indicate a touch, returns as an integer value

.setPowerButtonEnabled() - Enables power button functionality
.setPowerButtonDisabled() - Disables power button functionality

isPowerButtonEnabled() - Returns true if power button functionality is currently enabled

Interrupt Settings: These functions allow you to control if the interrupt pin is enabled. When enabled, the green interrupt LED will turn on when any pad detects a touch. Note, the interrupt is enabled as default in the .begin() function.

.setInterruptDisabled() - Disables interrupt pin
.setInterruptEnabled() - Enables interrupt pin

.isInterruptEnabled() - Returns true if interrupt pin is currently enabled

Check if a capacitive touch pad or breakout pin has been touched: These functions allow you to check when a capacitive touch pad or breakout pin has been touched.

.isLeftTouched() - Returns true if left pad or CS1 pin detects a touch
.isMiddleTouched() - Returns true if middle pad or CS2 pin detects a touch
.isRightTouched() - Returns true if right pad or CS3 pin detects a touch
.isTouched() - Returns true if any pad or breakout pin detects a touch
.isPowerButtonTouched() - Returns true if designated power button pad or pin held for alloted time

Check if a swipe has occured: The direction of the swipe is relative to the arrow on the board pointing in the right direction. For the pins, a right swipe is first CS1, then CS2, and finally CS3 and a left swipe is first CS3, then CS2, and finally CS1. Note, these functions pull most available resources. For best swipe recognition, we highly recommend not implementing other functionalities when using these two functions.

.isRightSwipePulled() - Returns true if board detects a right swipe
.isLeftSwipePulled() - Returns true if board detects a left swipe

Example Code

Note: This section is an example of using the Capacitive Touch Slider - CAP1203 (Qwiic) and the RedBoard Qwiic with the Arduino IDE. It is not intended to be a guide for using I2C devices with the Arduino IDE.

Please use the following links and the Internet for a better understanding of I2C and how it works in the Arduino IDE:

Example 1: Basic Reading

The Example01_BasicReading.ino sketch works with the basic functionality of the Capacitive Touch Slider and streams which pad detects a touch. Open up the example to follow along. First, we include the CAP1203 library and initialize an instance of the sensor. Then, in the set-up function, we check to make sure the sensor is correctly connected. Now that the sensor is set-up, we can start checking which pads have been touched in the main loop using the .isLeftTouched(), .isMiddleTouched(), and .isRightTouched() functions. Once you have uploaded the code, you can open your serial terminal to see when a pad has been touched. Make sure the baud rate in your serial terminal is set to 9600 baud, otherwise you won't see the correct output.

Example 1 Output

Example 1 Output

Example 2: Detect Any Touch

The setup for Example02_DetectAnyTouch.ino sketch is similar to Example 1, except it streams when any pad detects a touch using the .isTouched() function.

Example 2 Outputt

Example 2 Output

Example 3: Detect Swipe

The setup for Example03_DetectSwipe.ino sketch is similar to Example 1, except it streams when the board detects a swipe using the .isRightSwipePulled() and .isLeftSwipePulled() functions. The direction of the swipe is relative to the arrow on the board pointing in the right direction. Note, these functions pull most available resources. For best swipe recognition, we highly recommend not implementing other functionalities when using these two functions.

Example 3 Output

Example 3 Output

Example 4: Power Button

The Example04_PowerButton.ino sketch allows you enable or disable the power button feature on a specific pad. The power button requires a longer touch before registering a touch has been detected on the designated pad. Note, when the power button is enabled, the designated pad will only act as the power button. Configuring and enabling the power button feature requires some additional set-up.

In the sketch, we use the .setPowerButtonPad() and .setPowerButtonTime() functions to set which pad will act as the power button and the length of time the designated pad must indicate a touch. We also implement the .getPowerButtonPad() and .getPowerButtonTime() functions to check which pad and time we set with the previous two functions. Then, we enable the power button using the .setPowerButtonEnabled() function, and we check that the power button has been properly enabled using the .isPowerButtonEnabled() function. Finally, we check when the designated power button pad has been held for the allotted time using the .isPowerButtonTouched() function. The serial port prints Power Button when it registers a power button touch.

Example 4 Output

Example 4 Output

Example 5: Detect Current Touch

The Example05_DetectCurrentTouch.ino sketch uses the same functions and set-up as Example 1. However, Example 5 only notifies you about the current touch as opposed to a constant stream of touch data in Example 1. In order to do so, we added a while loop inside of each conditional statement. For example: while (sensor.isLeftTouched() == true).

Example 5 Output

Example 5 Output

Example 6: Disable Interrupt

The Example06_DisableInterrupt.ino sketch allows you to programmatically adjust the interrupt settings. When disabled, the green interrupt LED will no longer turn on when a pad is touched. We use the .setInterruptDisabled() function to disable to interrupt and the .isInterruptEnabled() function to check the current interrupt settings. In the main loop, we then implement the .isTouched() function as in Example 2 to check that our board still registers a touch even though the interrupt LED no longer turns on.

Example 6 Output

Example 6 Output

Example 7: Set Sensitivity

The Example07_SetSensitivity.ino sketch allows you to programmatically adjust the sensitivity settings for your capacitive touch pads. Note, we only recommend changing the sensitivity settings if you are breaking out your own touch pads. The current sensitivity settings are calibrated for the SparkFun Capacitive Touch Slider on board pads. In our example, we use the .setSensitivity() function to change the sensitivity and the .getSensitivity() to check our current sensitivity settings. In the main loop, we then implement the .isTouched() function as in Example 2 to check when the sensor has been touched with the new sensitivity settings.

Example 7 Output

Example 7 Output

Troubleshooting

Don't know if your board is working properly? To check that your board is properly hooked up, start by connecting your Capacitive Touch Slider and uploading the first example sketch to your microcontroller. Then, when you touch one of the pads, as demonstrated in the GIF, the green interrupt LED in the bottom right corner should turn on each time it senses a touch. (Note, if you have not yet uploaded code, the interrupt LED will turn on when you first connect to your microcontroller. The LED will turn off once you have uploaded the Example 1 code.) The red power LED on the back of the board, you can see its reflection on the table in the GIF, will also be on when the board is properly powered.


Interrupt LED GIF Demo

Demo of Interrupt LED

Resources and Going Further

Fore more on the Capacitive Touch Slider - CAP1203 (Qwiic) check out the links below.

Need some inspiration for your next project? Check out some of these capacitive touch tutorials below!

Constant Innovation in Quality Control

In this article, we share our recent advancements in quality control. Along with making our tests more thorough, we have also made them more efficient and robust.

Getting Started with the Teensy

Basic intro to the Teensy line of products, with soldering and programming suggestions.

AT42QT101X Capacitive Touch Breakout Hookup Guide

Learn how to use the simple SparkFun AT42QT1010 and AT42QT1011 capacitive touch breakout boards.

Variable Load Hookup Guide - Revised

This tutorial will show you how to assemble and use SparkFun's Variable Load board. It can be used to test stability of the power supply under various loads, battery lifetime, safety cutoffs, and other design elements of power supplies under test.

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

TPL5110 Nano Power Timer Hookup Guide

$
0
0

TPL5110 Nano Power Timer Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The TPL5110 Nano Power Timer is ideal for applications that require low power, and especially those projects that are running off of a LiPo battery. The Nano Power Timer will turn on your project, most likely a microcontroller, after the set amount of time, continuously. When your microcontroller has completed whatever needs doing, sampling air quality for example, it can then signal back to the Nano Power Timer to turn it off. While the project is off, the Nano Power Timer will only consume 35nA of power until the timer turns the project back on again. In this tutorial, we'll discuss how the time is set with the on board six DIP switch and use a microcontroller to turn it off when a task is finished.

SparkFun Nano Power Timer - TPL5110

SparkFun Nano Power Timer - TPL5110

PRT-15353
$5.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. For example, I chose the RedBoard as a simple demo, but you could use any microcontroller. Add it to your cart, read through the guide, and adjust the cart as necessary.

SparkFun RedBoard Qwiic

SparkFun RedBoard Qwiic

DEV-15123
$19.95
1
Lithium Ion Battery - 400mAh

Lithium Ion Battery - 400mAh

PRT-13851
$4.95
9
Female Headers

Female Headers

PRT-00115
$1.50
7
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$1.95
2

Tools

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

Soldering Iron - 60W (Adjustable Temperature)

Soldering Iron - 60W (Adjustable Temperature)

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

Solder Lead Free - 15-gram Tube

TOL-09163
$3.50
2

Suggested Reading

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

How to Solder: Through-Hole Soldering

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

How to Power a Project

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

Switch Basics

A tutorial on electronics' most overlooked and underappreciated component: the switch! Here we explain the difference between momentary and maintained switches and what all those acronyms (NO, NC, SPDT, SPST, ...) stand for.

Hardware Overview

Power and LiPo Battery

The Nano Power Timer can handle voltages between 1.8V - 5.5V and current up to 1.1 Amps. There are two options when connecting power to the Nano Power Timer. The first and more obvious option is the on board LiPo Battery Connector. The second is the VDD and GND pins on the five pin header underneath the IN label (short for INPUT). The power you provide to the INPUT side will flow out the OUTPUT side to power your microcontroller or project. If your using a LiPo battery, then do not attach another power source to these pins.

TopBottom

The OUT (OUTPUT) power is labeled VDD_OUT and GND. These pins will go to the board or project that you are powering.

TopBottom

Timer and Delay Switch

The Nano Power Timer's main function is to turn your microcontroller on after a set amount of time, continuously. The board has a six DIP switch that controls this time by changing resistance to the timer pin on the IC. To the left of the switch are five letters labeling each switch. On the underside of the board are these letters and the amount of time that is set when the corresponding switch is flipped.

TopBottom

This time is set when the board is powered up, so cycle power after you select your time. Check the table below to find a time suitable for your project.

Timer Switch Resistance
30 s A 16.2 k&ohm;
1 min B 22 k&ohm;
30 min C 93.1 k&ohm;
1 hr D 124 k&ohm;
2 hr E 169 k&ohm;
Custom F Custom

If you're time is not listed then we've left two additional pads for a custom time: one SMD and the other PTH. These two spaces are labeled with F on the product and their corresponding switch is labeled the same. If you decide to use them both at the same time their resistance is in parallel so make sure to calculate accordingly.

alt text

More Timer Options

You are not limited to the times that are represented on the silk. Ignoring the Custom switch option, there are 26 possible combinations of switches aside from the five printed on the board that yield times from three seconds up to 15 minutes. The chart below gives you the combination of ON resistors, their combined resistance, and their approximate time. A few redundant resistances were ommited.

Timer Switch Combo Resistance
2-3 s A+B+C+D+E 7.579 k&ohm;
3-4 s A+B+C+D 7.933 k&ohm;
4 s A+B+C 8.470 k&ohm;
5 s A+B+E 8.844 k&ohm;
6 s A+B 9.329 k&ohm;
10 s A+C+D+E 11.563 k&ohm;
~12 s A+C+D 12.407 k&ohm;
~13 s A+C+E 12.742 k&ohm;
~15 s A+D+E 13.225 k&ohm;
~18 s A+C 13.774 k&ohm;
~19 s B+C+D+E 14.243 k&ohm;
20 s A+D 14.341 k&ohm;
~22 s A+E 14.790 k&ohm;
~25 s B+C+D 15.546 k&ohm;
~28 s B+C+E 16.075 k&ohm;
32 s B+D+E 16.852 k&ohm;
35 s B+C 17.754 k&ohm;
40 s B+D 18.707 k&ohm;
~45 s B+E 19.479 k&ohm;
~5 min C+D+E 40.400 k&ohm;
8 min C+D 52.995 k&ohm;
~12 min C+E 59.694 k&ohm;
15 min D+E 72.033 k&ohm;

Some of these times are approximate, but I have provided a Python script in the resources below to help you calculate what your exact time is. This will differ by small margins for each board due to the tolerance of the resistors.

Additional Timer Options From Datasheet

Below is the list of available times from the datasheet that are not included in the charts above. Of note are the timer options in the millisecond range. You can access these times by taking advantage of the two empty resistor pads on the Nano Power Timer.

Timer Resistance
100 ms 500 &ohm;
200 ms 1000 &ohm;
300 ms 1500 &ohm;
400 ms 2000 &ohm;
500 ms 2500 &ohm;
600 ms 3000 &ohm;
700 ms 3500 &ohm;
800 ms 4000 &ohm;
900 ms 4500 &ohm;
1 s 5.20 k&ohm;
2 s 6.79 k&ohm;
7 s 9.71 k &ohm;
8 s 10.18 k&ohm;
9 s 10.68 k&ohm;
30 s 16.78 k&ohm;
50 s 20.047 k&ohm;
2 min 29.35 k&ohm;
3 min 34.73 k&ohm;
4 min 39.11 k&ohm;
5 min 42.90 k&ohm;
6 min 46.29 k&ohm;
7 min 49.38 k&ohm;
9 min 54.92 k&ohm;
10 min 57.44 k&ohm;
20 min 77.57 k&ohm;
40 min 104.67 k&ohm;
50 min 115.33 k&ohm;
1 hr 30 min 149.39 k&ohm;

Push Button

The push button on the product will manually begin the timer. This allows you to test the timer and your project which should send an OFF signal to the Done pin.

alt text

Header

Next to GND is the DONE pin that tells the product to turn your microcontroller or project off. To do this, your microcontroller or project will need to send a digital signal from LOW to HIGH to this pin. Finally the DRV pin is active high and will start the timer of your project when the pin receives a HIGH signal. This is the same function as the on board push button. Not very many people will want to attach a different button, but if you wanted to, this would be the place.

alt text

How Do I Check the Exact Time?!

I've provided a simple Arduino sketch below to calculate the exact timing of the timer setting. You'll attach the VOUT pin to a digital I/O pin on your microcontroller and the sketch will start its timer when the power is high and end the timer when the power is off.

Hardware Hookup

We're going to power a RedBoard Qwiic with a 3.7V LiPo Battery and set it to a 14 second delay. By default, the board comes with every switch flipped to ON which is 3 second timer. To set the timer to 14 seconds, we'll turn some switches to the ON position and others to the OFF position. I used tweezers because the switches were too small for my hands.

alt text

To get a 14 second delay switches 'A' + 'D' + 'E' must be flipped ON, and the other swtiches flipped OFF. Next solder a 6 pin female header to the Nano Power Timer. After the six pin female header is soldered to the Nano Power Timer, plug in three wires into the female header as follows:

Black Wire GND
Red Wire VDD_OUT
Green Wire DONE

alt text

It should look something like this.

The red, black, and the green wire will go the to the GND pin, 5V pin, and pin 4 respectively on the RedBoard Qwiic. These again refer to the VDD_OUT, GROUND, and DONE pins on the Nano Power Tmer.

alt text

Now attached to the RedBoard

Let's move onto the code.

Simple Example

Note: If this is your first time using Arduino, please review our tutorial on installing the Arduino IDE. If you've never connected an CH340 device to your computer before, you may need to install drivers for the USB-to-serial converter. Check out our section on How to Install CH340 Drivers for help with the installation.

With this example we'll be laying out the very basics of how the Nano Power Timer works. Copy the code and paste in the Arduino IDE. Select your board (in this case, the Arduino/Genuino Uno), COM port, and hit the upload button to upload in the Arduino IDE.

The Nano Power Timer is powered by a LiPo Battery and will turn on a RedBoard Qwiic every 14 seconds. The RedBoard Qwiic will blink it's blue LED, and then send a done signal back to the Nano Power Timer, which will turn off the RedBoard Qwiic.

language:c
/*
  Simple Example Code for the TPL5110 Nano Power Timer Hookup Guide. This code
  simply blinks the pin 13 LED and writes pin 4 (donePin pin) high. This shift from
  LOW to HIGH of the donePin pin, signals to the Nano Power Timer to turn off the
  microcontroller.
  SparkFun Electronics
  Date: May, 2019
  Author: Elias Santistevan
*/

int led = 13; // Pin 13 LED
int donePin = 4; // Done pin - can be any pin.  

void setup(){

  pinMode(led, OUTPUT); 
  pinMode(donePin, OUTPUT); 

}

void loop(){
  // Blink. 
  digitalWrite(led, HIGH); 
  delay(1000); 
  digitalWrite(led, LOW); 
  delay(1000); 

  // We're done!
  // It's important that the donePin is written LOW and THEN HIGH. This shift
  // from low to HIGH is how the Nano Power Timer knows to turn off the
  // microcontroller. 
  digitalWrite(donePin, LOW); 
  digitalWrite(donePin, HIGH); 
  delay(10);
}

After uploading this code, and plugging in the LiPo battery into the Nano Power Timer, the RedBoard Qwiic will blink once, be turned off by the Nano Power Timer, and then will turn on again 12 seconds later (14 second timer - 2 second delay in sketch).

alt text

This Nano Power Timer really shines when you're doing remote projects that are running off of battery and you need to maximize the life of the battery! There's only so much deep sleeping that you can do in code, and nothing will compare to 35nA of power consumed in the off state of the Nano Power Timer. You just need one additional GPIO or some method of sending a digital signal that can go from LOW to HIGH to signal OFF to the Nano Power Timer.

SparkFun USB-C Breakout

SparkFun USB-C Breakout

BOB-15100
$4.50
2
SparkFun microB USB Breakout

SparkFun microB USB Breakout

BOB-12035
$2.50
12
SparkFun Breadboard Power Supply 5V/3.3V

SparkFun Breadboard Power Supply 5V/3.3V

PRT-00114
$10.50
15
DC Barrel Jack Adapter - Female

DC Barrel Jack Adapter - Female

PRT-10288
$2.95
1
Screw Terminals 5mm Pitch (2-Pin)

Screw Terminals 5mm Pitch (2-Pin)

PRT-08432
$0.95
1

Resources and Going Further

Now that you've successfully got your TPL5110 Nano Power Timer 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:

Reaction Timer

Demonstrate mental chronometry with this simple reaction timer!

Sunny Buddy Solar Charger V13 Hookup Guide

How to hookup the Sunny Buddy: a solar-powered, MPPT (peak-power tracking), LiPo battery charger.

SparkFun Inventor's Kit for Photon Experiment Guide

Dive into the world of the Internet of Things with the SparkFun Inventor's Kit for Photon.

Adding a Timed Button to a Project

This tutorial will walk you through making a timed power controller for interactive projects. You will learn how to add an on button that will provide power to your project for an amount of time and then turn off again.

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

SparkFun gator:environment Hookup Guide

$
0
0

SparkFun gator:environment Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Do you have an experiment involving environmental changes?

SparkFun gator:environment - micro:bit Accessory Board

SparkFun gator:environment - micro:bit Accessory Board

SEN-15269
$19.95

The gator:environment is the solution for any environmental experimentation. It utilizes both the CCS811 and BME280 ICs for all of your climate and atmospheric quality readings. The CCS811 is an exceedingly popular sensor, providing readings for equivalent CO2 (or eCO2) in the parts per million (PPM) and equivalent total volatile organic compounds (or eTVOC) in the parts per billion (PPB). While, the BME280 provides a combined humidity, temperature, and barometric pressure readings. This tutorial will show you how to get started using this environmental sensor with the gator:bit (v2) in the micro:bit development environment.

Required Materials

To get started, you'll need a micro:bit to control everything. You can purchase one individually on in a kit.

SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-14542
5
micro:bit Go Bundle

micro:bit Go Bundle

DEV-14336
$16.50
16
micro:bit Board

micro:bit Board

DEV-14208
$14.95
7

To easily use the gator board ecosystem, one of the gator:bit boards will help breakout the necessary pins. You will also need alligator cables to connect the gator:bit to the gator:environment.

SparkFun gator:bit v2.0 - micro:bit Carrier Board

SparkFun gator:bit v2.0 - micro:bit Carrier Board

DEV-15162
$19.95
Alligator Test Leads - Multicolored (10 Pack)

Alligator Test Leads - Multicolored (10 Pack)

PRT-12978
$3.25
4
SparkFun gator:bit

SparkFun gator:bit

DEV-14484
$20.95

You may already have some of these materials, so feel free to modify your cart as necessary.

Suggested Reading

The gator:environment uses two separate sensors a BME280 and CCS811. The operation of the BME280 is fairly straight forward, but the CCS811 is a slightly more complicated metal oxide sensor. You may find the following concepts and tutorials useful with the gator:environment:

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.

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.

CCS811/BME280 (Qwiic) Environmental Combo Breakout Hookup Guide

Sense various environmental conditions such as temperature, humidity, barometric pressure, eCO2 and tVOCs with the CCS811 and BME280 combo breakout board.

If you aren't familiar with the micro:bit, we recommend reading here for an overview.

We would also recommend taking a look at the following tutorials if you aren't familiar with them.

Getting Started with the micro:bit

The BBC micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

How to Load MicroPython on a Microcontroller Board

This tutorial will show you how to load the MicroPython interpreter onto a variety of development boards.

SparkFun gator:bit v2 Hookup Guide

The gator:bit v2 is a breakout board for the BBC micro:bit. The gator:bit exposes almost every pin on the micro:bit to clippable pad with circuit protection. It also has as built-in addressable LEDs and a built-in buzzer.

Hardware Overview

The gator:environment consists of 4 pads for power and data.

ContactsDirectionDescription
GNDN/AGround: Reference voltage and ground loop.
3.3VInPower: Provides 3.3V to board.
SDABi-directionalData: Data and commands are transmitted between the sensor and microcontroller.
SCLInClock: The microcontroller provides the timing needed to communicate on the data line.

Power

The specified operating voltage for the BME280 is between 1.71V - 3.6V and 1.8V - 3.6V for the CCS811. For use with the gator:bit (v2) and micro:bit, you should provide 3.3V through the 3V3 and GND pads to keep the logic levels consistent; the 3.3V input is then regulated to 3.1V for the sensors.

Power Connections and LED
Power connection pads and power indication LED.

Together the sensors will consume 13 mA of current. It takes about 12 mA to power the CCS811 and about 1 mA to power the BME280.

[Check numbers]

BM280

The BME280 is a combined digital humidity, pressure, and temperature sensor that communicates over an I2C bus. For the most part, users will only need to know I2C addresses to prevent address conflicts with other devices or sensors.

BME280 IC
BME280 combined humidity, pressure, and temperature sensor.

Here are some of the characteristics of the BME280 sensor from the datasheet:

CharacteristicRange
Operating Voltage1.71V to 3.6V
Supply Current< 714 µA
Humidity Range: 0 to 100% RH
Resolution: .008% RH
Absolute Accuracy Tolerance: ±3% from 20 - 80%
Temperature Range: -40°C to 85°C
Absolute Accuracy: ±(0.5 - 1.25) °C
Resolution: 0.01 °C
Pressure Range: 300 to 1100 hPa (30,000 - 110,000 Pa or approx. 4.35 - 15.95 Psi)
Absolute Accuracy: ±(1 - 1.7) hPa
Relative Accuracy: ±0.12 hPa
Maximum Resolution: 0.18 Pa
I2C Address0x77 (HEX)

What is Humidity?

Humidity is a measurement of the amount of water vapor in the air. A simple demonstration of humidity is when you breathe on a cold piece of glass, the water vapor from your breath condenses into beads of liquid water. The humidity measurement from the BME280 is reported in terms of relative humidity. Humidity is often associated with various topics in science. For example:

What is Temperature?

Temperature for the most part is the quantification of how hot or cold something is. The BME280 measures the ambient temperature (or temperature of the relative environment). Temperature is reported in different scales or units, the BME280 measures temperature in degrees Celsius. Temperature is an essential unit of measurement that affects all aspects of physical science1. Some applications of the BME280 for temperature are:

1. Note: Sometimes the thermal affects on a system are negligible and therefore, ignored to simplify the model or experiment.

What is Pressure?

The BME280 measures pressure, specifically atmospheric or barometric pressure. Pressure is usually described as the perpendicular force applied to the surface of an object per unit area; in fluid mechanics, it is also referred to as the compressive stress at a particular point. The BME280 reports pressure units in Pascals. Pressure measurements are useful in a variety of applications:

CCS811

The CCS811 is a digital metal oxide (MOX) gas sensor that detects wide range of Volatile Organic Compounds (VOCs). With an integrated microcontroller that implements special algorithms to process the raw measurements, the CCS811 outputs the equivalent total VOC (eTVOC) and equivalent CO2 (eCO2) values over an I2C connection. For the most part users will only need to know I2C addresses to prevent address conflicts with other devices or sensors.

CCS811 IC
CCS811 metal oxide sensor.

Here are some of the characteristics of the CCS811 sensor from the datasheet:

CharacteristicRange
Operating Voltage1.8V to 3.6V
Operational Environment Temperature: -5 to 50°C
Humidity: 10 to 95% RH
Supply Current30 mA (average)
Equivalent Total VOCs (eTVOC)0 - 32768 ppb (parts per billion)
Equivalent CO2 (eCO2)400 - 29206 ppm (parts per million)
I2C Address0x5B (HEX)
Functionality Notes:
  1. The CCS811 implements a highly reliable micro-hotplate for the gas sensor. However, the performance in terms of resistance levels and sensitivities varies in the early stages. Therefore, AMS recommends that you run (or burn-in) this sensor for 48 hours on your first use. After the burn-in conditioning, a run-in period is required after long idle periods. The run-in time for the CCS811 is 20 minutes, before sensor stabilizes and accurate readings are generated.
    (*Essentially, run the board by taking readings for 48 hours the first time you use it to burn-in the sensor. Additionally, after extended periods between uses, you may also need to run the sensor for 20 minutes to stabilize the outputs due to the run-in period.)
  2. To help with the sensor accuracy, the BME280 is also used to provide temperature and humidity compensation. Therefore, any discrepancies between the BME280 readings and the conditions of the ambient air will produce imprecise results. A good example of this is if the board is heated above the temperature of the ambient air; the heating would offset the BME280 and result in inaccurate measurements.
  3. A baseline correction it is maintained on-the-fly in software, which is enabled automatically after initial device operation. There is the capability for manual correction, but it has not been implemented to simplify the sensor operation.

Equivalent TVOC: What are Volatile Organic Compounds?

MOX sensors are a great method for volatile organic compound (VOC) detection. VOCs are organic chemicals, usually with a high vapor pressure or high volatity, due to their low boiling point at room temperature. For indoor air quality (IAQ), these compounds are often attributed to health effects from mild irritation in brief exposures to more serious health risks with compounding long-term exposure.

Here is a list of VOCs detected by the CCS811:

  • Alcohols
  • Aldehydes
  • Ketones
  • Organic Acids
  • Amines
  • Aliphatic and Aromatic Hydrocarbons

For more information about VOC and their effects on IAQ, check out these resources.

Here are some ideas for experiments involving VOCs:

Note: Unfortunately, the standards associating specific chemical compounds and their health effects are wide and varied. Additionally, the number of VOCs are so numerous that it is impossible for a single sensor to detect each compound. Most sensors, like the CCS811, target specific VOCs and then use algorithms to estimate an equivalent total volatile organic compound (eTVOC) values. This sensor is valuable in providing information for the presence of contaminants in indoor air, but it is trend data and not recommended for exact measurements of VOCs.

[Source- Guidelines for CO2 Sensor Selection]

Equivalent CO2: What is Carbon Dioxide?

Carbon Dioxide (CO2) is a trace gas in Earth's atmosphere and it is a naturally occurring due to its solubility and dissolution in water. CO2 is also a common byproduct of combustion, aerobic, and decomposition reactions. It is highly versatile and extensively used in multiple industrial applications.

A common topic about CO2 is its growing abundance in Earth's atmosphere and the affect that has on climate change, as a greenhouse gas. The Scripps Institution of Oceanography at UC San Diego, has maintained continuous measurements of the accumulation of atmospheric carbon dioxide since 1958. A graph based on those measurements, taken from the Mauna Loa Observatory in Hawaii, is referred to as the Kneeling curve (named after Charles David Keeling).

Snapshot of Kneeling curve
Kneeling Curve: The bright red line shows the monthly average or carbon dioxide in parts per million (ppm). The dark red line shows the annual trend, calculated as a 12-month rolling average. [Source: Climate.gov]

Here are resources to some simple experiments involving carbon dioxide:

For more information on carbon dioxide concentration levels in the atmosphere, check out these resources:

Note: Unfortunately, CO2 isn't a VOC and MOX type of sensors can't directly measure CO2, despite being great at VOC detection. However, in an indoor setting, humans are a primary source of VOCs through the process of breathing. The equivalent CO2 (eCO2) values are then estimated based on algorithms that are used to analyze the sensor data to determine the TVOC attributed by the presence of humans. This type of sensor should not be used in applications that directly requires the measurement of CO2; it is an inferred value.

[Source- Guidelines for CO2 Sensor Selection]

I2C Connection

I2C is a communication protocol used to transfer data between master and slave devices. It is a 2-wire connection consisting of SDA (data) and SCL (clock). The protocol is pretty well defined so it can be shared with multiple devices. This is beneficial for daisy chaining multiple devices together on a single bus. The primary thing users will need to watch out for is address conflicts (you can't have devices with the same address).

I2C Connection
I2C connection pads.

Hardware Assembly

Connecting your gator:environment to the gator:bit (v2) is simple. The board can also be daisy-chained with other I2C boards. This can easily be done with alligator cables.

Hardware Assembly
Example of connections used in example. Click to enlarge.
Daisy Chain
Example of daisy chaining multiple I2C gator boards. Click to enlarge.
gator:environmentGND3V3SDASCL
gator:bit (v2)GND3.3V OUTP20 (SDA)P19 (SCL)

Adding the MakeCode Extension

Note: This tutorial assumes you are familiar with MakeCode, the gato:bit (v2), and the micro:bit board.

The easiest way to get started using the gator:environment is to use Microsoft MakeCode, a web-based block editor. This tutorial assumes you are familiar with the with MakeCode, the gato:bit (v2), and the micro:bit development board. If this is your first time check out this guides linked in the suggested reading section (above).

Installing Extensions

To get started with using MakeCode with the miccro:bit, head over to the MakeCode for micro:bit website by Microsoft. Then, click the New Project button to start a new project and open the Editor. (*Yes, all you only need to get start coding is a computer with internet access, an up-to-date web browser, and an available USB port!)

MakeCode Website
Click the New Project button to start a new project and open the Editor. Click on image to enlarge.

Once you have the editor up, click on the the Advanced block in the block library to reveal the drop down menu.

Editor
Click on the the Advanced block in the block library to reveal the drop down menu. Click on image to enlarge.

Finally, click on the Extensions block. This should bring up the extensions page. (*Alternatively, you could also click on the extensions link from the settings menu.)

Advanced Block
Click on the the Extensions block to open the extensions page. Click on image to enlarge.

There are two methods for finding the gator:environment extension:

  • Search for the name used on the extension3.
  • Use the link to the GitHub repository for the pxt-package as the search term.

Extensions Page
Use the search bar to find the extension you want to install. Click on image to enlarge.
Note: Unfortunately, it does take time to get an extension approved by the micro:bit Educational Foundation before it can be searchable by name. Part of the requirements for the approval process involves a live product page. Therefore, at the time of the launch of this product, the extension has not been approved yet and the only method of adding the extension is to use the link to the GitHub repository of the pxt-package. We will update this tutorial as soon as the extension has been approved.

Search for the PXT-Package

Search for the gator:environment extension using the GitHub repository link to the pxt-package:

https://github.com/sparkfun/pxt-gator-environment

Search for Extension
Search for Extension. Then, click on the box to add it to the block library. Click on image to enlarge.

Then, click on the box for the extension to add it to the block library. The gator:environment extension should now appear in the block library.

Extension in Block Library
Extension in the block library; click on the block to open menu options. Click on image to enlarge.

To verify that you have added the extension, click on the gator:environment block to make sure that your drop down menu options match the image below.

Menu Options
Available blocks for the gator:environment extension. Click on image to enlarge.

MakeCode Examples

Now that you have added the gator:environment extension to the Editor, lets start with some example code. Plug the micro:bit into your computer using an USB micro-B cable after you have assembled your hardware with the instructions from the previous section. The micro:bit should appear on your computer as a removable storage device.

USB Drive
The micro:bit showing up as a USB drive on a Windows computer. Click to enlarge.

To upload new code, this is where you will be copying the downloaded .hex file to later.

Block Functions

initialize gator:environment sensor
This block should be pretty self explanatory, it sets the sensor up to be used. You should use this within the on start block.

get _____ value
This is a value block as indicated by the block's shape. There is a drop down menu with selectable options for the output value of the block. Below is a description of the available menu options:

  • degreeC- Reports temperature reading from BME280 in Celsius (°C).
  • degreeF- Reports temperature reading from BME280 in Fahrenheit (°F).
  • humidity- Reports humidity reading from BME280 in relative humidity (RH%).
  • pressure- Reports pressure reading from BME280 in Pascals (Pa).
  • eCO2- Reports equivalent CO2 reading from CCS811 in parts per million (ppm).
  • TVOC- Reports equivalent TVOC reading from CCS811 in parts per billion (ppb).

Basic Read

Below, is a simple example of how to take simple measurements from the sensor. To use this example, there are multiple options for accessing the .hex file:

  • Replicate the block functions from the display below to copy the example project. Then download the .hex file.
  • Expand the display widow to pull up the example project. Then download the .hex file.
  • Use this link to pull up the example project. Then download the .hex file.
  • Download the .hex file from the button below or the link on the bottom of the display.

The output is redirected over the serial port to avoid conflicts on pins P0 and P1, which are also used for serial communication. To read the sensor values, pull up your favorite serial terminal emulator. Then, connect to the serial port that the micro:bit is on; the default baud rate is 115200 bps. Below, is an example of the sensor output for the example code.

Sample Readings
Example of readings from the sensor.

Troubleshooting Tips

Here are a few tips for troubleshooting this device.

Sensor Heating

The CCS811 is a MOX sensor that uses a hotplate to detect the VOCs. Additionally, the CCS811 relies on the BME280 for ambient air temperature and humidity to compensate the MOX readings. The heat generated from the CCS811 should be isolated from the BME280 to prevent the heat from affecting the BME280 and thus affecting the compensation values. However, this doesn't take into account any external heating which would also affect the temperature and humidity for compensation of the CCS811.

Equivalent CO2 and TVOC

As mentioned in the Hardware Overview section, the CO2 and TVOC values are equivalent; they are interpreted values. If you are trying to measure CO2 directly, the CCS811 sensor will not be able to detect it. Additionally, the CCS811 only measures specific VOCs.

If you still have questions or issues with this product, please create a post on our forum under the Gator Products topic.

Additionally, if you are an educator and you have class or application based questions, please create a post on our forum under the Educational Products topic.

Resources and Going Further

For more product information, check out the resources below:

Interested in the micro:bit? Check out some of these other micro:bit products:

SparkFun Inventor's Kit for micro:bit Lab Pack

SparkFun Inventor's Kit for micro:bit Lab Pack

LAB-15229
$450.00
SparkFun gator:bit v2.0 - micro:bit Carrier Board

SparkFun gator:bit v2.0 - micro:bit Carrier Board

DEV-15162
$19.95
SparkFun Inventor's Kit for micro:bit

SparkFun Inventor's Kit for micro:bit

KIT-15228
$49.95
micro:bit Educator Lab Pack

micro:bit Educator Lab Pack

LAB-15230
$299.95

Need some inspiration for your next project? Check out some of these other micro:bit product tutorials:

SparkFun Inventor's Kit for micro:bit Experiment Guide

This guide contains all the information you will need to explore the twelve circuits of the SparkFun Inventors Kit for micro:bit.

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.

How to Load MicroPython on a Microcontroller Board

This tutorial will show you how to load the MicroPython interpreter onto a variety of development boards.
New!

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.

For more information on the CCS811 or BME280, check out the resources below:

SparkFun BME280 Breakout Hookup Guide

A guide for connecting the BEM280 sensor to a microcontroller, and for using the Sparkfun Arduino library.

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.

CCS811 Air Quality Breakout Hookup Guide

This tutorial shows you how to get data from a CCS811 breakout board with the I2C interface.

CCS811/BME280 (Qwiic) Environmental Combo Breakout Hookup Guide

Sense various environmental conditions such as temperature, humidity, barometric pressure, eCO2 and tVOCs with the CCS811 and BME280 combo breakout board.

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>