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

The Great Big Guide to Paper Circuits

$
0
0

The Great Big Guide to Paper Circuits a learn.sparkfun.com tutorial

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

Introduction

Paper circuits are becoming more and more popular in the hobby electronics world. The easy availability of craft-like materials and increasing abundance of new products has created a really unique ecosystem for crafters looking to make the leap to electronics projects. This guide is an overview of materials and techniques available to paper circuit crafters.

What is a Paper Circuit?

A paper circuit is a functioning electronic circuit built on a paper surface instead of a PCB. Projects can range from greeting cards, to origami, to traditional art such as paintings or drawings. What makes them unique is the use of traditional fine art techniques to create a circuit that is combines aesthetics and functionality.

Suggested Reading

Before we begin crafting, here few concepts you should be familiar with:

Creating Traces: Overview

A trace is a path that takes the place of wiring, most commonly seen on a printed circuit board. In paper circuits we’ll use conductive materials as a substitute for wires on the paper’s surface to connect components. In this tutorial we’ll discuss three types of traces: paint, tape, and ink.

alt text

The green lines on this PCB are the traces connecting parts of the board.

Conductive Tape Traces

Conductive tape is one of the easiest ways to get started crafting a paper circuit. Just peel off the paper backing and press down where you want your circuit to go! Copper tape is also solderable, allowing strong connections between components and traces that you won’t get with paint and inking methods.

alt text

Prototyping with copper tape and a SparkFun template

Difficulty: Beginner
Cost: Varies - copper tape ~$.06/ft, fabric tape ~$.79/ft
Mess Level: Minimal

Pros:

  • No dry time.
  • Solderable (copper tape only).
  • Easier to find locally - copper tape is also used as a snail/slug repellent and sold in hardware stores. It is also used in stained glass making and may be available in local craft or hobby stores. Not all tapes are made alike though - these ones may be more difficult to work with and the adhesive is probably not conductive.

Cons:

  • Copper tape can give you a nasty paper cut, please be careful!
  • Harder to create smooth lines or shapes. You can cut the tape to a thinner width to help with this.
  • Conductive fabric tape can be very expensive.

Copper Tape

Copper Tape - 5mm (50ft)

PRT-10561
$2.95
3
Copper Tape - 2" (50ft)

PRT-11081
$14.95
3

The most common conductive tape for paper circuits is made of a thin sheet of copper with an adhesive on the bottom that comes on a roll. Manufacturers create the tape in a few different sizes, we like 5mm width tape because it is easy to work with on a smaller crafting scale.

Ni/Cu/Co 1" Wide Fabric Tape

alt text

Image from LessEMF.com

Less common than copper tape is a conductive fabric tape made of nickel, copper and cobalt. This tape will stand up to bending and flexing and is a great option for projects that have folds (such as cards that require traces to cross the center crease).

Instructions:

  • Peel and stick where the traces should go, making sure to leave gaps in the tape where components will sit. For the most reliable circuit, try to use one continuous piece of tape between components. Use folding techniques around corners or solder pieces together as needed.
  • For copper tape - use clear tape over bent leads to hold them down to the trace. Soldering is a more secure option. For fabric tape we recommend a conductive glue or sewing the connection with conductive thread.

alt text

Note how the copper tape is cut to leave room for the LED.

Examples:

alt text

This blushing robot card from Chibitronics uses thin copper tape to spell the message inside and create the circuit for the LED on the front of the card.

Jie Qi’s Circuit Sketchbook uses conductive fabric tape in the book’s binding and copper tape on the inside cover.

Additional Resources:

Conductive Paint Traces

Conductive paints are a great way to create artistic pieces with electronics. Use a brush or a squeeze bottle to create traces that curve and swirl to connect components. Conductive paints can also be used to ‘glue’ components to a trace. This method can be the most frustrating to use because of the mess factor and dry time. We recommend patience and practice when beginning to work with these materials.

Difficulty: Beginner - Intermediate (depending on complexity). Can be frustrating to get smooth lines.
Cost: Varies. Most conductive paints start at ~$10.
Mess Level: Moderate

alt text

Painting with Bare Conductive Paint and a paintbrush. Image via Instructables.com.

Pros:

  • Use it like any other water-based paint.
  • Can cover with other paint mediums (such as acrylic) after drying to create a seamless piece of art.
  • Easy to layer more paint on top of an existing trace to troubleshoot or fix an unreliable connection.

Cons:

  • Not conductive until fully dry. Depending on the thickness of your painting and the type of paint, may need to dry overnight. A hair dryer or heat gun will speed this along.
  • May take some practice to get consistent lines/traces.
  • Copper based paints will oxidize quickly and can have a short shelf life.
  • Prone to cracking when under strain. Best on flat surfaces. Painted traces over folds or on bendable projects will mostly likely fail with repeated movement.

Bare Conductive Electric Paint

Bare Conductive - Electric Paint (50ml)

COM-10994
$24.95
Bare Conductive - Electric Paint Pen (10ml)

COM-11521
$9.95

Bare Conductive’s Electric Paint is a nontoxic, solvent free and water soluble carbon-based paint. Available in a squeeze tube for finer lines or pot for brush and stencil use.

CuPro-Cote Paint™ from LessEMF

alt text

CuPro-Coate Paint is water based paint containing copper, similar to latex paint. Comes in 4oz through gallon containers. Due to short shelf life/working time once opened, we recommend the 4oz size.

Instructions:

  • When planning your circuit design, first sketch out where the traces will go. Drawing the path with a pencil or marker before painting will make the process much easier.

  • Glue down any components you will be using onto your paper. Use tweezers for precise placement of smaller components.

  • Using a paintbrush or squeeze bottle, carefully apply the paint along traces and over the wires or pads of the components in your circuit. Let dry completely before testing.

alt text

Artist carefully following her lines with conductive paint during a paintable electronics workshop held at MIT.

Examples:

Electronic Popables is an interactive pop up book created using conductive paints and electronics

alt text

Paper Piano created by Hannah Perner-Wilson

Additional Resources:

Conductive Ink Traces

Conductive inks are now available in pre-filled pens, making it easier than ever to create traces by simply drawing them. Most conductive ink pens also dry faster than conductive paints. This method may be the easiest to apply, but attaching components can be more frustrating.

Difficulty: Beginner to Intermediate (depending on components you are attaching to the ink).
Cost: Higher - most pens start ~$20
Mess Level: Minimal

alt text

Drawing with a Circuit Scribe pen. Image via Circuit Scribe’s Kickstarter.

Pros:

  • Dries faster than conductive paints.
  • Precise lines.
  • Intuitive use.

Cons:

  • Can be difficult to attach components to (see Making Connections section for techniques).
  • Paper selection matters - inks will not adhere to some types of paper. Photo paper works best.
  • May be easily mistaken for regular pens or markers and accidentally wasted on non-electronic projects.

Circuit Scribe

Circuit Scribe Lite Kit

COM-13184
$24.95
Circuit Scribe Conductive Ink Pen

COM-13254
$19.95
Circuit Scribe Maker Kit

COM-13255
$79.95

Circuit Scribe is a non-toxic, silver conductive ink pen that writes similarly to a gel pen. It is great for creating precise lines and drawings to showcase (and light up) your circuit.

AgIC Circuit Marker

alt text

AgIC is another silver-based ink that comes in marker form. It only works on EPSON Glossy Photo Paper, so you will need to plan your projects accordingly.

Instructions:

  • Plan your circuit using a pencil (and stencil if it comes with your conductive ink kit). The ink does not adhere well to printer toner, if you are designing your circuit on a computer, make sure to leave outlines to fill in rather than lines to draw directly over.
  • Carefully trace your lines with the conductive ink pen, making sure to keep a continuous path between components. Leave larger circles/pads where components will connect to the traces.
  • Use tape, conductive glue, or circuit stickers on top of ink lines to attach components.

Examples:

alt text

Paperduino 2.0 - an entire Arduino made with Circuit Scribe ink and components. Image via Instructables.

alt text

Interactive art using Circuit Scribe modules and ink, crafted by SparkFun’s Education Team.

Additional Resources:

Choosing Components

Now that we’ve explored options for creating traces, let’s talk about the components we can use with our circuits. Not all components play nice with paper circuit trace materials. For example, if you’d like to solder connections, copper tape would be a better choice than a conductive ink. Here are a few of our suggestions of components to use in your projects.

Through-Hole Components

alt text

Through-hole components with long leads (such as LEDs) can be bent with pliers into a shape that will sit flat on paper and provide more surface area to connect with the traces. Components with shorter legs (like the ATtiny85) can can be carefully bent flat with fingers or pliers.

Use With:

  • Bare Conductive Electric Paint - use the paint as a cold solder joint. Here’s a tutorial covering that process.
  • Copper tape - use clear tape over the leads to quickly attach components, or solder directly to the copper tape.
  • Conductive fabric tape - sew over leads with conductive thread or use conductive glue to attach.

SMD Components

alt text

While a little trickier to work with, surface-mount device (SMD) components are low profile and great small or flat projects such as greeting cards. You will need tweezers to place these components and a good eye to see the labels on the part itself. SMD components can be soldered to copper tape, connected by painting the pads with conductive paint, or taped onto copper tape. This tutorial from The Exploratorium’s Tinkering Studio shows two methods for attaching SMD LEDs - soldering and clear tape.

Use With:

  • Copper tape - solder or attach with conductive glue. Some components can also be taped over to hold them to the copper.
  • Conductive paints - use superglue to attach to paper, then paint over the pads of the components to connect. Here’s a great tutorial from High-Low Tech that walks through the process.
  • Conductive inks - use superglue to attach to paper, being careful not to get between the ink pad and the pads of the component. Connect to ink with conductive glue or z-axis tape. This method is used in Circuit Scribe’s Paperduino 2.0 project.

LilyPad Components

alt text

Originally made for e-textile applications, LilyPad components can work well with paper circuits because of their low profile and large conductive pads. LilyPad components work best when soldered to copper tape, but can also be attached using z-axis tape or by placing clear tape over the pads to hold them to traces. Note - if using the clear tape method, only the Button and Switch boards have large enough pads to make good contact.

Use With:

  • Copper tape - soldering works best, but conductive tapes, glues, and clear tape may be suitable options.
  • Fabric tape - sewing is ideal, or z-axis tape.

Chibitronics Circuit Stickers

alt text

Chibitronics stickers have a conductive adhesive on them which make them ideal for paper circuit projects. They are compatible with almost all paper circuit traces, but can be more expensive than using off the shelf components.

Use With:

  • Copper tape
  • Conductive fabric tape
  • Conductive paint

Circuit Scribe Modules

alt text

Circuit Scribe modules work differently than all the other components we’ve shown so far - they are magnetic. To attach to your traces, you will need a metal sheet or surface behind your paper. This is a temporary connection instead of the more permanent connections shown in this tutorial. While their size isn’t ideal for small projects like greeting cards, it can be fun to create wall hangings or reconfigurable artwork with the modules.

Use With:

  • Copper tape
  • Conductive fabric tape
  • Conductive inks

Making Connections

Now that we know how to create traces and have chosen components for our project, it’s time to connect them together. Here are a variety techniques for creating an electrical connection between the components and traces.

Tape Method

Clear tape is an easy way to start attaching components to paper circuits, though it is not as reliable as other methods. Use tape to carefully press over component leads or pads and press down onto copper tape. For SMD components, you can tape over the entire part.

alt text

Taping over SMD LED. Image via Jie Qi’s flickr feed.

Use With:

  • Copper tape
  • Through-hole or SMD components

Z Axis Tape

alt text

Z-Axis tape is an easy-to-use, pressure sensitive double-sided tape designed for connecting, bonding and grounding flex circuits and PCBs. We can use small sections of tape to attach components to conductive traces.

Use With:

  • Copper tape
  • Components with larger surface area such as tabs (bend wires into spirals or squares to give an easier surface for the adhesive to grab onto).
  • Conductive ink in large areas - draw pads for components and tape to attach to.

Conductive Paint

alt text

Image from Bare Conductive’s How to Cold Solder Tutorial.

Conductive paints can be used as a glue/cold solder joint to attach components to traces. Push components into wet paint to connect and let dry completely before powering.

Use With:

  • Conductive paint traces - attach components while the original trace is still wet for the best connection.
  • Non-flexible surfaces - the paint can crack or break under repeated stress. Push component legs through the paper before painting for some strain relief.
  • Through-hole and SMD components

Conductive Glue/Epoxy

alt text

An example of conductive epoxy from Atom Adhesives.

Conductive glue or epoxy is another option for connecting components. These products are one of the more expensive ways of attaching components to your paper circuit projects and can be difficult to work with. Often they need a long dry time or to be heat set. Try to find a syringe of epoxy to cut down on mess and help with precision placement. Make sure to read through the MSDS and follow all package directions when using these types of glues.

Use With:

  • Copper tape
  • Conductive inks
  • Through-hole and SMD components
  • LilyPad components

Soldering

Soldering is one of the stronger connections you can make with paper circuits, the only drawback is that it will only work on copper tape - you cannot solder to conductive paints, inks, or most fabrics. If you need help learning how to solder, check out our tutorial.

alt text

Examples of soldering components to copper tape from left to right:
SMD LED from the Tinkering Studio, LilyPad LED from SparkFun, and 3mm LED from High Low Tech.

Use With:

  • Copper tape
  • Through-hole and SMD components
  • LilyPad components
  • Circuit Stickers

Powering Your Project

Paper circuit projects can be easily powered with a 3V coin cell battery. We recommend a 20mm or 12mm diameter battery for small projects such as greeting cards.

Coin Cell Battery - 20mm (CR2032)

PRT-00338
$1.95
Coin Cell Battery - 12mm (CR1225)

PRT-00337
$1.95

Most common coin cell batteries look like the ones above - the top and sides of the battery are positive and a textured bottom is negative. This can prove tricky for attaching to our traces, so we’ll go over a few techniques to try.

Safety Note: Never solder directly to a coin cell battery! To attach a battery, choose a battery holder or battery with tabs specifically for soldering.

Create Your Own Battery Holder

Making a battery holder with the materials you have on hand is quick and easy! Here are a few different methods for crafting your own battery holder.

Copper Tape Holder:

alt text

alt text

alt text

We at SparkFun use this copper tape technique in all of our pop up card tutorials.

Paper and Copper Tape Holder:

alt text

Image via Chibitronics.

Chibitronics has a tutorial on using copper tape and a piece of paper to make a battery pouch.

Paper and Conductive Paint Holder:

alt text

Image via Bare Conductive

Bare Conductive has a few different paper battery holder tutorials:

Battery Holder Modules

Battery holder modules can be soldered onto copper tape or glued with conductive glue or paint. Always remember to remove the battery from the holder before soldering.

LilyPad Coin Cell Battery Holder - Switched - 20mm

DEV-11285
$4.95
5
Coin Cell Battery Holder - 20mm (Sewable)

DEV-08822
$1.25
3

Tabbed Batteries

You can also purchase batteries with solder tabs - these can then be soldered, glued with conductive glue, or sometimes even pressed in place with clear tape to attach to a circuit. When shopping for a tabbed battery, try to find one with insulation around the sides to avoid accidental shorts.

alt text

Some examples of tabbed batteries.

Many paper circuit-specific components such as LED stickers, boards, or modules have built-in resistors. If creating your own paper circuit components with off the shelf LEDs, you may need to add resistors to your circuit to account for different voltage requirements.

Resources and Going Further

alt text

Wow, we covered a lot of concepts in this tutorial! If you are unsure where to start, try experimenting with small swatches of scrap paper and exploring which technique works best for your project ideas. If you are looking for some more guided projects, chack out some of our resources and tutorials:


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


Origami Paper Circuits

$
0
0

Origami Paper Circuits a learn.sparkfun.com tutorial

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

Getting Started

We love paper circuits! They’re fun, they’re easy to teach, and there are so many different ways you can create paper circuits. In this tutorial, we will show you how to incorporate paper circuits into Origami.

alt text

Required Materials

For this tutorial, we will be using origami paper. Regular paper can also be used, but make sure that it can be folded several times and bent without ripping, but also be thin enough that light can shine through it.

For the electronic parts, I have chosen to use copper tape and LED stickers, but you could easily use regular LEDs, Lilypad LEDs, or any number of other LEDs and some adhesive and resistors. As for the connections, Bare Conductive paint, Circuit Scripe pen, or regular wires could be used instead of copper tape. I chose copper tape and LED stickers because they are already adhesive, they work well with paper, can stick to the origami paper I have, and I can solder to the copper tape for better connections if needed. When choosing your components make sure to check that everything can work together without issue. For example, Bare Conductive paint and the Circuit Scribe pen ink DO NOT work on glossy origami paper, so if you want to use them think about going with a different kind of paper.

Here is a list of exactly what I used for my origami flowers:

Note that origami paper (or some other kind of paper) is also needed. Also worth noting is that two power options are listed int he wish list, a battery and a wall adapter. You will only need one of these to power your project.

Here are the tools I used:

  • (optional) Soldering iron
  • (optional) Solder
  • Krazy glue (may be needed depending on the flower you chose)
  • Invisible tape (may be needed depending on the flower you chose, or if you don’t want to solder)

Suggested Reading

If this is your first time working with paper electronics, or you want more information about all your options, and each of their pros and cons, take a look at The Great Big Guide to Paper Circuits.

Some other tutorials that may come in handy are:

Choosing a Flower

There are lots of origami flowers from which to choose. There are a few things to keep in mind when choosing one, each discussed below.

  1. Do you want to be able to see the LEDs or not: With an open flower such as this:

    alt text

    Origami Kusudama Flower

    You can see the LEDs inside, which for most folks isn’t a problem. However, for those who don’t want the LEDs to show, you will want to look for a flower design that doesn’t open and has at least one layer for you to put the LEDs behind:

    alt text

    Origami Kawasaki Rose

  2. When looking at the design of the flower, you are going to have to think about if there is a surface near the middle where you can put an LED. This is where things can get interesting, and you might have to get creative. I try and make as much of the flower as I can before it is all closed up/finished/glued together, and then I put in the LEDs right before finishing it. Sometimes there isn’t a good place to put an LED. In that case, you can kinda “cheat” and insert a piece of paper with the LEDs connected into the center, and tape it in place. This worked well for this lotus flower:

alt text

Inside of a origami Lotus flower before its final folds

alt text

Finished origami Lotus flower

Find a flower you like, get creative with it, and fold it up.

Here are the flowers I worked with and how to fold them:

  • Here is a great tutorial video on how to make the five petal Kusudama Flower, done by Origami Instructions
  • This video is a wonder tutorial for the Lotus flower done by ProudPaperOfficial
  • and here is a video for the origami Rose by Carolzjh1 的频道. There are many variations on this kind of origami rose, so you might want to look around and find the one that you feels is prettiest and/or easiest for you to make.

To rate these from easiest to hardest, the five petal Kusudama flower is the easiest, using five full square sheets of paper that are glued shut and glued together. Medium difficulty would be the Lotus flower, which takes 12 half sheets of paper (6 full square sheets needed) rubber-banded together before the final folds. Lastly, the most difficult is the Rose (or Kawasaki Rose if you want to get really specific). This only uses one sheet of square paper, and all the folds are made before hand and squashed together. No tape, glue, or rubber bands are used for the rose, so if this is the flower you want to use, be prepared to watch the video a few times and to make a few mistakes before you get the technique down.

Adding LEDs

Conductive tape is one of the easiest ways to get started crafting a paper circuit. Just peel off the paper backing, and press down where you want your circuit to go! Copper tape is also solderable, allowing strong connections between components and traces that you won’t get with paint and inking methods. (Again you might want to take a look at our more in depth Great Big Guide to Paper Circuits to help you understand all your choices and pick the right parts for your specific project.)

If you are just looking to use the flowers and components that I did, then here is an explanation of how I integrated the LED stickers and copper tape for each of the three flowers previously mentioned.

For the five petal flower, first I cut off the bottom corner of the petal so the wires have somewhere to go to the LED. Then I inserted the LEDs before using any glue but after I had done all of the folding:

alt text

Inside of one of the Kusudama Flower pedals before using any glue

For the lotus flower, I connected all the folded pieces with the rubber band and then added a paper with the LED before folding the petals up

alt text

Inside of origami Lotus with LED sticker on a separate piece of paper connected by the rubber band

For the rose, I folded everything and then unfolded the last step and placed an LED on one of the four prongs

alt text

Inside of origami rose before the last fold

Finishing Touches

For the last step, you can solder wires to the copper tape. Warning: you might want to set your soldering iron to a much lower temp so that it doesn’t burn off the adhesive on the back of the copper tape. If you do not have access to a soldering iron, you can connect the wires to the tape with scotch or other clear tape. Note that this type of connect will be flimsy and may conduct poorly.

alt text

Solder wires straight to the copper tape

Make sure if you are using the same color wires for both 5V and Ground, as I did in the photo above, that you mark one of the wires so that you can tell them apart when you close up the flower.

Make sure that the 5V and Ground copper wires never touch at any point. Since the copper wires are conductive on the surface, if they touch at any point, you will short your circuit and probably burn up your LED.

Once you have double checked your connections and made sure there aren’t any shorts, connect your wire to Ground and 5V. I have twisted mine to make them the stems of my flowers, or you could go further with magnets and metal sheets like my origami flower art installation and make something bigger.

Some of the LEDs I used were colored, and some where white. I suggest you try both out and see which color you like better, if using colored paper, or, if you just want to use white paper with a surprise color inside, that’s fun too!

alt text

And there you have it! Lovely light up flowers!

alt text

Bouquet that is fun in the light…

alt text

..and in the dark!

Resources and Going Further

Want to integrate electronics into more projects? Check out some of our other crafty tutorials:

ELasto-Nightlight

Fear the dark no longer with this ELastoLite nightlight.

Twinkling Trick or Treat Bag

Make a light up goodie bag with conductive thread, LEDs, and the LilyTwinkle!

E-Textile Art Pin

Create a quick and easy piece of e-textile art using a LilyPad LED, battery holder, conductive thread, and coin cell battery.
New!

Sound Page Guide

How to use the Lilypad MP3 Player and some Bare Conductive Paint to make a fandom silhouette sound trigger page.

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

Experiment Guide for RedBot with Shadow Chassis

$
0
0

Experiment Guide for RedBot with Shadow Chassis a learn.sparkfun.com tutorial

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

Introduction

The SparkFun RedBot is a great way to get your feet wet in the world of robotics. However, once you have assembled your RedBot, you may be at a loss as to where to go from there. This guide will go through nine different experiments, ranging from learning how to drive your RedBot to using an accelerometer to trigger your RedBot to move. Once you’ve mastered each experiment, you can take what you’ve learned in this guide and apply it to creating your own robot platform.

RedBot Kit vs. SIK for RedBot

This tutorial will cover how to use everything in the SparkFun RedBot Kit and the SparkFun Inventor’s Kit for RedBot (SIK for RedBot).

The SIK for RedBot contains a few extra parts in addition to the RedBot Kit that are covered in this tutorial. Sections pertaining to these extra parts will be marked with (SIK).

RedBot Kit

If you have the RedBot Kit, you can skip the steps marked with (SIK).

Completed RedBot Kit

Alternatively, you can pick up additional sensors to install on your RedBot. These parts include the Wheel Encoder Kit, RedBot Buzzer, and twoRedBot Mechanical Bumpers. Follow the sections in this guide that cover any of the extra sensors you might have.

SIK for RedBot

If you have the SIK for RedBot, you can follow all the sections in this guide, including those marked with (SIK).

Completed SIK for RedBot

Experiment List:

Here is a breakdown of each experiment presented in this tutorial. Click on the link to jump to that section, or continue reading to learn more about the hardware and library before starting on Experiment 1.

  1. Software Install and Basic Test
  2. Drive Forward
  3. Turning
  4. Push to Start & Making Sounds
  5. Bumpers
  6. Line Following with IR Sensors
  7. Encoder
  8. Accelerometer
  9. Remote Control

Extra Supplies Needed

Suggested Reading

If you still need to assemble your RedBot, visit our RedBot Assembly Guide for detailed instructions. Please note that are a couple of versions of the assembly guide. For an older version of the RedBot Kit, please see this assembly guide.

Already put together the RedBot? Great! It’s a good idea to double-check the wiring. If you hooked up the RedBot differently, you can either change the example code to reflect your changes or rewire your bot as per the assembly guide.

Before you go any further, you should probably make certain that you’re familiar with these other topics:

  • What is an Arduino? - Since the RedBot is based off the Arduino platform, it’s a good idea to understand what that means.
  • Installing the Arduino IDE - If you don’t have the Arduino software installed, this guide will help you out.
  • Installing an Arduino Library - To get the most out of the RedBot, you’ll want to install our RedBot library. This tutorial will show you how to install any library.
  • Accelerometer basics - One of the core sensors for the RedBot is an accelerometer. To find out more about accelerometers, check out this guide.
  • Analog to digital conversion - Many useful sensors for the RedBot will be analog. This guide will help you interface with them and make the most of the data you get back.
  • Pulse width modulation (PWM) - The RedBot includes two headers with PWM signals, and uses PWM to control the speed of the motors. It’s probably a good idea to be familiar with the concept.
  • I2C - The RedBot Accelerometer, which ships with the RedBot kit, uses I2C to communicate with the RedBot. While the accelerometer is accessible through the library with no knowledge of I2C required, if you want to get more out of it, you can check out this tutorial.

Hardware

RedBot Mainboard

The RedBot mainboard, labeled for convenient reference

The RedBot Mainboard was designed to be as versatile as possible. It has banks of 3-pin I/O break-outs for easily connecting up LEDs, Sensors, or motors. It also has an integrated H-Bridge Driver chip. We have developed an integrated library for the RedBot, if you want to drive the motors manually. Here are the pin outs for the Motor Driver:

LEFT MOTOR:

  • Control 1 - Pin 2
  • Control 2 - Pin 4
  • Motor PWM (Speed) - Pin 5

RIGHT MOTOR:

  • Control 1 - Pin 7
  • Control 2 - Pin 8
  • Motor PWM (Speed) - Pin 6

Here’s a quick tour of the hardware that’s on the board:

  1. Analog/digital headers - These three headers provide one I/O pin, which can be used for analog input as well as digital input or output, as well as 5V power and ground. In addition, the header with A4 and A5 can be used for connecting I2C devices; the RedBot Accelerometer is designed to solder directly to this header, making connecting an accelerometer a snap.

  2. Analog input header - This header provides an additional two analog input pins. These pins can’t be used for digital signals, however.

  3. Analog output/digital header - These two headers provide four pins which can be used for either PWM output or regular digital I/O. Note that the power supply for these headers is connected directly to the battery, providing extra umph for servo motors, but devices expecting 5V should not be connected directly to them!

  4. Wireless Socket - The RedBot has a socket for an XBee module, providing easy wireless interfacing.

  5. XBee Mode Switch A switch allows you to select whether the XBee communicates via the standard serial I/O pins (0 and 1, accessible through the built in Serial command set) or via pins 14 and 15 (A0 and A1), using the SoftwareSerial library. Using the software mode will consume two of your analog inputs, however.

  6. 5V / GND Headers - Headers are available to allow the user to tap off the 5V and ground signals.

  7. Power Switch - A power switch puts the board into a very low power consumption mode (microamps or less) allowing you to turn the board off without pulling the power connection.

  8. Motor Disable Switch - A motor disable switch allows you to turn off the motor driver so you can program the board without having it drive all over.

  9. Motor Headers - Headers are available to easily connect up the right and left side motors. The motor control is powered by the TB6612FNG Motor Driver.

  10. Power Input Header - A header has also been provided to allow you to access the input supply, either for purposes of driving additional circuitry or to allow more flexibility than the standard barrel jack does for power sources.

  11. DEBUG LED (pin 13) - An LED is connected to pin 13 to allow basic sanity checks that code is loading and running on the board.

  12. Power LED - A power LED will remain lit whenever the power switch is active.

Shadow Chassis

RedBot Chassis Complete Build

The Shadow Chassis is an economical robot platform with a lot of versatility. It features two gearmotors with 65mm wheels and a caster. The chassis pieces are made of ABS plastic with a wide variety of mounting holes for sensors, controllers, power, etc. Instructions for assembling the chassis can be found here.

RedBot Line Follower Sensor

Line sensor

The Line Follower sensor is an add-on for your RedBot that gives your robot the ability to detect lines or nearby objects. The sensor works by detecting reflected light coming from its own infrared LED. By measuring the amount of reflected infrared light, it can detect transitions from light to dark (lines) or even objects directly in front of it.

The sensor has a 3-pin header which connects directly to the RedBot Mainboard via female to female jumper wires. Use the included RedBot library to detect lines or objects. A mounting slot lets you easily connect one or more of these to the front or back of your robot chassis.

RedBot Accelerometer

Accelerometer

The Accelerometer sensor is an add-on for your RedBot that provides bump and motion detection. The sensor works by measuring acceleration forces on the x, y, and z axis. By measuring the amount of acceleration (or lack there of) your robot can get a better understanding of its movements.

The sensor has a 2x3 unpopulated footprint which connects directly to the RedBot Mainboard via a female header. You can also solder the sensor directly to the headers on the Mainboard if you wish.

RedBot Whisker Bumper

Bumper board

The Whisker Bumper is a very simple sensor comprised of a piece of music wire that closes a contact when bent and a circuit board to interface it to the RedBot. We ship the music wire straight, so you’ll have to bend it to suit your application.

RedBot Buzzer Board

Buzzer

What’s the fun of a robot that doesn’t make beep-beep noises? We’ve made the RedBot Buzzer board to fit nicely on any header on the board, so you can integrate noise with your robot either just for fun or as a nice remote feedback function.

There’s no special library support needed; just use the tone() family of commands already built into Arduino. One note: you can’t use the Buzzer board on pins A6 and A7, as they are analog input-only pins.

RedBot Library Quick Reference

We have written our own library to simplify the programming and interface to the RedBot motors, encoders, sensors, and other peripherals. Here is a quick summary / overview of the RedBot Library, classes, methods, and variables.

RedBotMotors class

RedBotMotors motors;– this creates an instance of the RedBotMotors class. This can only be instantiated once in your code. This allows you to control the motors with simple methods such as:

  • .drive(motorPower)– this method drives the right side CW and the left side CCW for positive values of motorPower (i.e. drives the RedBot forward), and it does the reverse for negative values of motorPower.
  • .pivot(motorPower)– this method spins the entire RedBot CW for positive values of motorPower and CCW for negative values of motorPower.
  • .coast()– stops the motors and allows the RedBot to coast to a stop.
  • .brake()– applies the brakes using the H-Bridge by shorting out both of the motors. Forces the motors to come to an abrupt stop.
  • .leftMotor(motorPower)– controls the leftMotor independantly. Positive values of motorPower spin the motor CW, and negative values spin the motor CCW.
  • .leftBrake(motorPower)– applies the brakes the leftMotor.
  • .leftCoast(motorPower)– stops the leftMotor allowing it to coast to a stop.
  • .rightMotor(motorPower)– controls the rightMotor independantly. Positive values of motorPower spin the motor CW, and negative values spin the motor CCW.
  • .rightBrake(motorPower)– applies the brakes the rightMotor.
  • .rightCoast(motorPower)– stops the rightMotor allowing it to coast to a stop.

Advanced

If you wish to control the motors independently, the following are the control pins for the left and right motors:

leftMotor_controlPin1 = 2
leftMotor_controlPin2 = 4
leftMotor_motorPwrPin = 5

rightMotor_controlPin1 = 7
rightMotor_controlPin2 = 8
rightMotor_motorPwrPin = 6

The RedBot uses the Toshiba TB6612FNG H-Bridge Motor Driver. The full datasheet is available here.

RedBotEncoder class

RedBotEncoder encoder(leftEncoder, rightEncoder);– this creates a RedBotEncoder object with the left encoder connected to pin leftEncoder and the right encoder connected to pin rightEncoder. This can only be instantiated once in your code.

  • .clearEnc(LEFT\RIGHT\BOTH)– clears the counter variable for either the LEFT, RIGHT, or BOTH encoders. The labels LEFT, RIGHT, and BOTH are specific types defined in this class.

  • .getTicks(LEFT\RIGHT)– returns a long integer value representing the number of encoder ticks (counts) for either the LEFT or the RIGHT encoder.

RedBotButton class

RedBotButton button();– Creates an instance of the RedBotButton class on the RedBot. Because the button is hardwired on the RedBot board to pin 12, this initialization is handled inside the library code. This can only be instantiated once in your code.

  • .read()– returns a boolean value representing the status of the button.

RedBotSensor class

RedBotSensor sensorA(pinNum);– this creates a RedBotSensor object connected to the port (pin) on the RedBot Mainboard. This is primarily used for the line-following sensors, but can be used with any analog sensor. This class can only be instantiated for as many sensors as you have on your RedBot.

  • .read()– returns an integer value scales from 0 to 255 for the analog voltage read by the sensor. 0 represents 0V and 255 represents 5V.

  • .setBGLevel()– reads the value of the sensor in it’s ‘nominal’ position. This value is stored as the ‘background’ level.

  • .setDetectLevel()– reads the value of the sensor in it’s ‘detect’ position. This value is stored as the threshold for a ‘detect’ level.

  • .check()– returns a boolean value that TRUE if the measured sensor value is greater than ¼ of the difference between the background and the detect levels. Note: This method only works if you have set both the BGLevel and the DetectLevel.

RedBotBumper class

RedBotBumper bumperA(pinNum);– Creates an instance of RedBotBumper object connected to the port (pin) on the RedBot Mainboard. While the RedBotBumper is designed for use with the whisker / bumper switches on the RedBot, it can be used with any digital sensor or switch. This class can only be instantiated for as many digital sensors (bumpers) as you have on your RedBot.

  • .read()– returns a boolean value for the state of the bumper. It returns TRUE when the bumper switch is closed or connected to GND.

RedBotAccel class

RedBotAccel accel();– Creates an instance of the RedBotAccel object. The RedBot accelerometer uses I2C for communication. Because of this, it needs to be connected to A4/A5 on the RedBot Mainboard. This can only be instantiated once in your code.

  • .read()– this reads the current values of the accelerometer and stores it into local variables in the library. It does not return any values.

  • .x– is the raw X-axis accelerometer value read using the .read() method. In general, these values vary from -16000 to +16000. The X-axis is aligned with the FWD/REV direction of the RedBot.

  • .y– is the raw Y-axis accelerometer value read using the .read() method. In general, these values vary from -16000 to +16000. The Y-axis is aligned with the lateral or RIGHT/LEFT direction of the RedBot.

  • .z– is the raw Z-axis accelerometer value read using the .read() method. In general, these values vary from -16000 to +16000. The Y-axis is aligned with the UP/DOWN direction of the RedBot.

  • .angleXZ– is a floating point value for the calculated angle between the X and Z axes of the accelerometer. It calculates the arc tangent between the raw X and raw Z values. On the RedBot, this is the forward / backward tilt.

  • .angleYZ– is a floating point value for the calculated angle between the Y and Z axes of the accelerometer. It calculates the arc tangent between the raw Y and raw Z values. On the RedBot, this is the side to side tilt.

  • .angleXY– is a floating point value for the calculated angle between the X and Y axes of the accelerometer. It calculates the arc tangent between the raw X and raw Y values.

RedBotSoftwareSerial class

RedBotSoftwareSerial xBeeRadio();– Creates an instance of the RedBotSoftwareSerial object. This library uses a lot of code from the standard Arduino SoftwareSerial library. The RedBot Mainboard uses pins A0 (14) and A1 (15) for TX and RX when switched to SW_SERIAL.

  • .begin(baudRate)– opens up the serial communication on the SW_SERIAL TX and RX lines of the RedBot Mainboard at the baudRate. Acceptable baud rates include: 300, 1200, 2400, 4800, 9600, 19200, 28800, 38400, 57600, 115200.

  • .write()– writes a single bye of data to the software serial port.

  • .read()– returns a single byte from the software serial port.
  • .available()– returns an integer value representing the number of bytes (characters) available for reading from a software serial port.

Experiment 1: Software Install and Basic Test

Install Arduino IDE

In order to get your RedBot up and running, you’ll first need to download the newest version of the Arduino software from www.arduino.cc. This software, known as the Arduino IDE (Integrated Development Environment), will allow you to program the board to do exactly what you want. It’s like a word processor for writing programs. Please visit our Installing Arduino IDE tutorial for step-by-step directions on installing the Arduino IDE.

Connect your RedBot to your computer

Use a USB miniB cable to connect the RedBot to one of your computer’s USB inputs. Make sure you have the four AA batteries in the battery holder.

Plug in USB cable

Install FTDI drivers

Depending on your computer’s operating system, you will need to follow specific instructions. Please go to How to Install FTDI Drivers for specific instructions on how to install the FTDI drivers onto your RedBot.

Install the RedBot library

A library in Arduino is a set of files containing pre-written code that simplifies instructions and commands to perform certain tasks. We have written a specific library for the RedBot. Make sure you install the RedBot library. You will need it for all the example code. Click the button below to download it.

RedBot Library

Unzip the downloaded file. Copy/Move the RedBot folder to the libraries folder into your Arduino Documents folder. If you need a refresher on how to install an Arduino library, please see our library tutorial.

Example Code

Included in the library are a set of examples for the 9 RedBot Experiments. Click on File > Examples > RedBot > RedBot_Experiments, you should see a list of the 9 Examples we have created.

RedBot exerpiment examples

If you need to find the example code separately, click the button below

RedBot Kit Example Experiments

You can also find the RedBot Kit Experiments example code on the RedBot Github page. To download all the code, click the “Download ZIP” button on the right-hand side of the page.

Open the Arduino IDE and select board:

Open the Arduino IDE software on your computer. This step is to set your IDE to identify your RedBot. You will want to select the board, Arduino Uno. To do this, go to Tools > Board > Arduino Uno.

Select board

Select your Serial Port

Window users: Select the serial port for the RedBot from the Tools > Port menu. This is likely to be COM3 or higher (COM1 and COM2 are usually reserved for other internal devices). To check, disconnect your RedBot and re-open the menu; the entry that disappears is the one for the RedBot. Reconnect the board, and select that serial port.

Find serial port in Arduino

Mac users: Select the serial device of the RedBot from the Tools > Serial Port menu. On the Mac, this should be something with /dev/tty.usbmodem or /dev/tty.usbserial in it. To find out, you can disconnect your RedBot and re-open the menu; the entry that disappears should be the RedBot. Reconnect the board and select that serial port.

Select serial port in OS X

Note: If the Serial Port is not showing up, go back and re-install the FTDI drivers for your machine or try re-starting Arduino.

Experiment 1: Basic Test – Hello World!

Time to make sure the electronics work! The “Hello World” of physical computing is generally a simple blink. On your RedBot Mainboard, there is a debug LED on pin 13. It’s labeled on the board D13 LED.

We are going upload a simple program to the board to make sure everything is up and running.

Go to File > Examples > RedBot_Experiments > Exp1_BasicTest or copy and paste the example code below:

What You Should See

Make sure the battery pack is plugged into the Mainboard, and turn the POWER switch to ON.

Turn the POWER to ON

Click Upload in the Arduino IDE. The code will be compiled and converted into machine langage 1’s and 0’s. You should see two LEDs (TX and RX) blink rapidly back and forth - these indicate data being transmitted and received between the RedBot and your computer. After this is complete, you should see the D13 LED on the RedBot Mainboard LED on and off.

D13 LED flashing

Learn More: LEDs

LEDs – short for light-emitting diodes – are the heart of every good, blinky electronics project. They are perfect for power indicators, debugging, or just adding a little zazz to your project.

LEDs have all sorts of light-related uses. You’re no-doubt used to seeing them in public displays (clocks, traffic lights, and signs) or as energy-efficient light-sources (flashlights, grocery store lighting, and accents), but they also have less obvious uses like infrared remote controls and computer mice.

In fact, recently the Nobel Prize in Physics was recently awarded to Isamu Akasaki, Hiroshi Amano and Shuji Nakamura for the invention of the Blue LED, which allows us to create white light with LEDs!

Code To Note

The RedBot has an LED connected to pin 13. Control of pin 13 can be accessed through the digitalWrite([pin], [HIGH\LOW]) command.

digitalWrite(13, HIGH) puts 5V on pin 13. In this case, this turns the LED on.

digitalWrite(13, LOW) puts 0V on pin 13, and turns the LED off.

The Arduino microcontroller runs at 16 MHz. This means it performs 16 Million operations per second. The digitalWrite() command takes less than 4 uS to execute. In order for us to see the LED turn on, we need to pause or delay the program flow. We do this with the command delay([time_ms]).

In our example, delay(500); 500 indicates the number of milliseconds the program is delayed for.

Going Further

Experiment around with the delay() function to change the rate of the blink. What is the fastest blink that you can still see? 10 ms? 20 ms?

Can you change the blink pattern to resemble a heart-beat? (Hint: You might need to add a second blink sequence to your loop.)

Troubleshooting

My code won’t upload!

  • Make sure your USB cable is plugged into both the robot and the computer you’re using to write code.
  • Make sure the “POWER” switch is switched to “ON.”
  • Double check that you have the right serial port selected under the “Tools” menu. The easiest way to check is to see which item disappears from the menu when you unplug the USB cable, and select that one when you plug the board back in.
  • If you have an Xbee module plugged in, make sure the Serial Select switch at the top edge of the board is switched to “XBEE SW SERIAL.”
  • Check that you have the right board selected under the “Tools” menu. The RedBot is Arduino Uno-compatible, so select “Arduino Uno” from the list.

My motors aren’t turning!

  • This sketch does not turn on the motors; it just blinks. So, the motors should not be spinning.

Experiment 2: Drive Forward

Let’s get your RedBot moving! Let’s start by writing a few lines of code to make your robot drive forward and stop.

To help us out, we are going to utilize parts of the RedBot library. To do this, we need to add a line at the top of our code #include <RedBot.h>. (Remember, Arduino code is case sensitive. This must be typed in exactly the way it’s shown here – otherwise it won’t work.) This “#include” statement will allow us to create a RedBotMotors object that has methods (functions or behaviors) for driving and controlling the RedBot.

RedBotMotors motors;

This line creates an object called motors that allows us to control the right and left motors and drive the robot. See more details below in the Code to Note section.

Before uploading this example code, make sure that the RedBot is in a safe position. The program will start immediately after uploading, and it might drive off your desk, knock over your drink, or stomp through your lunch. We suggest standing the RedBot upright on the flat edge of the rear end so that the wheels are off the table.

Note: When uploading, the power must be on, the motors must be connected, and the board must be powered by a battery. Also, the motor switch should be set to RUN.

Upload this code onto the RedBot.

Go to File > Examples > RedBot_Experiments > Exp2_DriveForward or copy and paste the example code below:

What You Should See

Flip the switch labeled “MOTOR” to “RUN”.

Flipping switch to RUN

Upload the code, and you should see both motors on at full speed for two seconds, and stop. The right motor should spin clockwise (CW) and the left motor should spin counter clockwise (CCW).

Unplug the USB cable from your RedBot and set the RedBot on the floor. Hit the reset button to manually restart your program and watch your RedBot go!

How far did your RedBot move? How long does it drive for? (Can you verify this with a stopwatch?) Be sure to run a few trials. What is the average speed of your robot?

Learn More: Motors

Curious on how motors work? Visit our Motors and Selecting the Right One to learn more about different types of motors and how they work!

Code To Note

Adding the #include <RedBot.h> to the top of your code gives us access to a number of classes, functions, objects, and methods that make controlling the RedBot much easier. The RedBot library has custom routines for creating objects such as:

  • RedBotMotors– motor drive class
  • RedBotAccel– accelerometer sensors
  • RedBotBumper– whisker switch bumpers
  • RedBotEncoder– wheel encoder control
  • RedBotSensor– general purpose sensors
  • RedBotSoftwareSerial– SoftwareSerial for Xbee control

Our focus here is going to be only on the RedBotMotors class. The RedBotMotors class has a number of methods for controlling the motors. In programming, methods are behaviors or questions you ask of an object.

language:c
RedBotMotors motors; // Instantiate the motor control object.

Recall that this line declares an object called motors using the RedBotMotors class. This is sometimes called “instantiating” an object. Now, we can use any of the methods that are a part of this class. To use (or “call”) a method, the command will start with motors. followed by the name of the method. Let’s look at a few examples:

Driving Forward / Reverse

motors.drive([motorPower]) turns both motors. This method takes one input parameter, [motorPower]. [motorPower] can be any integer value from -255 to +255. Values > 0 will cause the robot to drive forward – spinning the right motor clockwise (CW) and the left motor counter-clockwise (CCW) – driving the robot forward. Values < 0 will do the opposite causing the robot to drive in reverse.

language:c
motors.drive(255);  // drives forward at full power.  motors.drive(-255); // drives reverse at full power.

Sometimes running the motors at full power causes the wheels to spin-out. If you notice traction issues, you may want to try playing around with slower speeds.

Stopping

motors.stop() turns off power to both motors and coasts to a stop.

language:c
motors.stop();   // sets the motor speeds to 0 and coasts to a stop.

Sometimes, you might want a more precise stop. the RedBotMotors class also has a brake() method that forces the motors to come to a more abrupt stop.

Try replacing the motors.stop() with motors.brake() in your example code. Measure the distance your robot travels. How much farther does it travel when it “coasts” compared to “braking”?

language:c
motors.brake();       // Stops both motors and applies "brakes" by shorting out the motors

When might you use stop() and when might you want to use brake()?

Going Further

Now that you have control of driving the robot, see if you can get your robot to drive forward for 1 second, stop, and reverse for 1 second. Repeat your test a few times. Does your robot always return to where it started?

How far from your starting point does it return to? What factors might cause it not to come back to it’s starting point?

How might this be useful for robotics applications?

Experiment / Activity

  • Adjust the [motorPower] for your robot so that it drives about 2 - 3 feet in 2 seconds. Approximate this. Write down the motorPower here: ______

We’ll use this motorPower later.

  • Run a minimum of 5 trials with your robot and measure how far your robot travels in 2 seconds.
  • Calculate the average speed of your robot (in inches per second) using the equation: avgSpeed = distance / time.

Writing your own custom sub-routine \ function - driveDistance()

We’ve already seen two functions used in every Arduino sketch – setup() and loop(). Arduino contains a wealth of built-in functions that are useful for all kinds of things. Visit the Arduino site for a list. In addition to these, you can also easily create your own functions. First, we need to declare & define the function.

When you write your own functions, you make your code neat and easy to re-use. Visit the Arduino FunctionDeclaration page for more information about functions. Every function declaration has the following format:

Arduino function

The return type is void if the function does not return a value or any information. In this case, driveDistance() will simply execute some commands. The functionName will be used in your code to call or reference your function, and the parameters are values or information that you will pass into the function.

In this example, this function will use the the average speed you calculated above to make motion planning easier. It computes the delay used for the driveTime based on a given distance by re-arranging the equation above to: time = distance / avgSpeed

Copy and paste this block of code to the end of your program – after the void loop(){}

language:c
void driveDistance(int distance)
{
// this function takes a distance input parameter and the avgSpeed of your
// RedBot to compute a delayTime for driving forward.
    int avgSpeed = 16;  // average speed in inches per second.

    long driveTime;
    driveTime = (long) 1000 * distance / avgSpeed;
    motors.drive(200);  // make sure you're using the same motorPower as your tests.
    delay(driveTime);
    motors.brake();
}

Now, replace your own drive code with a function call driveDistance(12); Upload and test. Your RedBot should have driven 12 inches. How far did it go? If it drove too far, then adjust the variable avgSpeed until your RedBot is within ½ an inch of 12 inches. Change the driveDistance(12); to driveDistance(24); and test this again. How far did your RedBot go?

Sample Data Table

Create a data table like this to track your results.

motorPower = ______

avgSpeed = ______

RedBot speed trials

Troubleshooting

Compile Error – ‘RedBotMotors’ does not name a type

language:c
Exp2_DriveForward:18: error: 'RedBotMotors' does not name a type
Exp2_DriveForward.ino: In function 'void setup()':
Exp2_DriveForward:23: error: 'motors' was not declared in this scope

This indicates that the RedBot library is not properly included into your sketch. This is usually a result of one of two things:

  • #include <RedBot.h>– this line must be at the top of your code, and RedBot.h must be spelled and capitalized exactly as it is shown here.
  • The RedBot library is not in the Arduino libraries folder. Go back to Experiment 1 and make sure that you have properly installed the RedBot library.

My motors aren’t turning!

  • Check the “MOTOR” switch on the board and make sure that it’s switched over to RUN.
  • Do you have external power connected? The RedBot’s motors need more power than a USB plug can supply, so they won’t run unless a power supply is connected to the barrel jack on the board.
  • Make sure that the motors are correctly connected; it may be that you have connected one wire from each board to each power header, or that the wires are plugged into the wrong locations. Match the wire colors to the labels on the board.

My RedBot moves, but spins in a circle!

  • If the right side and the left side both spin in the same direction (i.e. CCW or CW), then your RedBot will pivot in place. During assembly, it’s important that the motors be mounted on the chassis properly: with the red wire farthest from the underside of the chassis. If you assembled the robot the other way, you can either dis-assemble and flip the motors or flip the wires in the motor headers.

  • Flipping the wires is usually the easiest fix. Identify which motor is spinning in the wrong direction, and flip the red wire with the black one.

My RedBot is not driving straight! It drives in a curve!

  • This is a pretty common thing for the RedBot, and for all robots with independent drive wheels. There are lots of reasons for it, but it’s something that simply must be dealt with.
    • First – check to make sure that there is nothing rubbing on either the wheels or on the magnetic motor encoder. Move the wheels out so that they are not rubbing, but still tightly seated into the motor. Any added friction on one side will cause one side to drive faster than the other (resulting it the RedBot pulling to one side.)
    • Second – Driving straight requires equal power on both wheels. This requires equal amounts of traction on both wheels. Running the motors up at full power sometimes causes the wheels to “spin out” and lose traction. Try reducing the motorPower to something lower than 255.
    • Third – use an encoder to ensure that both wheels turn the same distance each time. “What’s an encoder?” Shucks – we’ll cover encoders later on in Experiment 8.

Experiment 3: Turning

In this experiment, we will look at how to fine-tune the control of the RedBot by controlling the right motor and the left motor separately. We will introduce a few new methods of the RedBotMotor class that will allow us to control the motors separately.

In this experiment, we will break-down the commands for the RedBot to drive forward, turn 90 degrees, drive forward again, and then stop.

Make sure RedBot is in safe location, or standing on the flat back edge of the chassis. This code requires only the most basic setup: the motors must be connected, and the board must be receiving power from the battery pack.

Let’s load this experiment onto the RedBot. Go to File > Examples > RedBot_Experiments > Exp3_Turning or copy and paste the example code below:

What You Should See

After you upload this example code, you should see the wheels spin for a bit, change directions, and then stop. Unplug the USB cable from your RedBot and set the RedBot on the floor. Hit the reset button to manually restart your program. Watch your RedBot go!

On a nice flat surface, your RedBot should drive forward (in a straight line), turn 90 degrees to the right, and then drive forward again. If your RedBot isn’t turning 90 degrees, there are two things you can adjust.

  • Try changing the turning time by changing the delay(500); The default example is set for 500 ms.

  • You can also try changing the motorPower during the pivot. Once you have your RedBot making a nice 90 degree turn.

Remember that turning with this system relies on an equal amount of traction on both wheels. Again, if the wheels are slipping or spinning out, you may need to slow down the speed.

Learn More: Turning

The way we turn with a two-wheel differential system is by spinning the right side at a different speed as the left side. In order to pivot to the right, we spin both the right and the left motors in opposite directions. This results in a nice tight turn.

Pivot right

Notice however, that to drive straight, the right side is usually spinning in the same direction as the left side.

Drive in a straight line

While making the motor change directions may result in a tight turn, it is slow. Another way of turning to the right is by only driving the left motor and keeping the other side stopped. This gives us a turn radius pivoting about the non-driven wheel. While the turn may not be as tight, the momentum of the robot is kept going forward.

Turn right

Code To Note

Clockwise or Counter-Clockwise

In the last example, to drive the RedBot forward, we used a single command motors.drive([speed]); Positive speeds cause the RedBot to go forward by spinning the right side clockwise and the left side counter-clockwise.

To control the individual motors, the RedBotMotors class has two methods that are used in this example.

  motors.rightMotor([motorPower]);  // controls the right motor
  motors.leftMotor([motorPower]);   // controls the left motor

Similar to the .drive([motorPower]) method, [motorPower] values can vary from -255 to +255. Positive values spin the motor in the clockwise direction and Negative values spin the motor in the counterclockwise direction.

The RedBot is pretty nimble, so we want to use a lower motorPowers for pivoting. In our example, we set the motorPower to 100 and the delay time to 0.5 seconds. Play around with this until you’re able to get your robot to turn a nice 90 degree turn consistently.

Too abrupt of a turn? How can I turn more gradually? Play around with varying the power to the right side vs. the left side.

setup() vs. loop()

Up until this point, we have always had our code in the setup() portion of the code. Any code that we place in between the curly braces { and } after the setup() runs just once. This is convenient for testing single instructions or routines. But, what if we want our RedBot to repeat a pattern - like doing a figure-8? or a dance?

Any code that we place in the loop() repeats over and over. We have a simple example of a figure-8 pattern. The two forward slashes \\ in front of this code comments the code out from being run. To see un-comment these lines of code, simply remove the two \\.

The RedBot is instructed to turn right and then turn left. Notice that to soften the turn, the motors never change direction. The left motor continues to rotate counter clockwise and the right motor rotates clockwise. The difference in speeds causes the robot to turn.

//  motors.leftMotor(-200);  // Left motor CCW at 200
//  motors.rightMotor(80);   // Right motor CW at 80
//  delay(2000);
//  motors.leftMotor(-80);    // Left motor CCW at 80
//  motors.rightMotor(200);   // Right motor CW at 200
//  delay(2000);

You may need to adjust the speeds and the delay() times to get a good figure-8 pattern.

Going Further

Box step?

Now that you have fine-tuned a 90 degree turn, repeat this four times to see if you can get your RedBot to trace out a box. If you have whiteboard sheets, you can tape a dry-erase marker to the back of the RedBot to trace out your path.

Dance party

Adjust the figure-8 pattern until your RedBot is tracing out figure-8s on the floor. Now, plan out your own dance routine for your robot. See if you can choreograph it to music!

Experiment / Activity

  • Take the motorPower that you used above and the turningTime to calculate the “turningSpeed” of your RedBot. We define turningSpeed = angle / time. In this case, it should be 90 degrees divided by the turningTime you used above. Write down your turningSpeed.

  • turningSpeed = _______

Writing your own custom sub-routine \ function.

Similar to what we did in the DriveForward activity, we will write a sub-routine called turnAngle(). This function will use the the average turningSpeed you calculated above to make motion planning easier.

Copy and paste this block of code to the end of your program – after the void loop(){}

language:c
void turnAngle(int angle)
{
  int turningSpeed = 180; // degreees / second

  long turningTime;
  turningTime = (long) 1000 * angle / turningSpeed;

  motors.rightMotor(-100); // Turn CCW at motorPower of 100
  motors.leftMotor(-100);  // Turn CCW at motorPower of 100
  delay(turningTime);      // turning Time
  motors.brake();     // brake() motors
}

Now, replace your turning code with a function call turnAngle(90); Upload and test. Your RedBot should still be turning 90 degrees. If it’s turning too far or not far enough, then adjust the variable turningSpeed until your RedBot is turning a good 90 degrees. Use this with the driveDistance() function from before to trace out a triangle, a square, and a pentagon.

Troubleshooting

My wheels don’t turn but I hear a high-pitched noise.

The motors may not have enough torque at such a low speed. Try driving the motors at a higher speed, or reducing the weight on the RedBot.

Everytime I plug the USB cable in, the RedBot acts funny for a few seconds! What’s happening?

The RedBot will try to run its code every time it is reset. When you plug something into a computer the computer has to identify what it is. During this period, the computer resets the RedBot controller board multiple times. No harm will come to your RedBot. If it distracts you, switch the motor switch from RUN to STOP and the motors will be disabled.

Experiment 4: Push to Start & Making Sounds (SIK)

Read on if you have the SIK for RedBot or are using the RedBot Buzzer. If not, skip to the next section.

In our past experiments, our RedBot starts running right away after we upload code. Here, we will show an example of how to use the user push button to start our program – and, to make things fun – we’re going to add some noises? After all, what’s a robot without some beep-boop sounds!

Let’s load this experiment onto the RedBot. Go to File > Examples > RedBot_Experiments > Exp4_MakingSounds or copy and paste the example code below:

What You Should See (and Hear)

Your Redbot should make a beep-beep sound and then start spinning the wheels when you press the D12 button next to the USB connector.

Push D12 on the RedBot Mainboard

Code to Note

tone([pin], [freq]) plays a sound of the given frequency on the pin. Since the buzzerPin is set to 9, we can use these commands to play different tones on the buzzer. Rather than just using a blinking LED as an indicator, we can program our RedBot to make sounds at different times to help us know what the robot is doing. This is a way to debug problems just by the sound the robot makes!

language:c
tone(buzzerPin, 1000);  // plays a note of 1 kHz (1000 Hz).

noTone() stops playing a tone on a specific pin.

language:c
noTone(buzzer);  // stops playing the note.

Learn More: Sound

Sound is a longitudinal wave that is caused by vibrations (compressions and expansions) in the air. The Arduino causes sounds by creating a square-wave of a given frequency on the pin. The buzzer reacts to the square-wave by moving the air back and forth creating sound. Because a square-wave is not a pure tone, you will may also hear other harmonics of the base frequency.

A list of notes and their related frequencies can be found here. Can you compose a simple scale? (Hint: The C-Major scale is the easiest, it doesn’t have any sharps or flats.) Human hearing is generally limited between 20 Hz and 20,000 Hz. Can you find where your hearing cuts out? Note: the piezo-buzzer is not capable of producing high fidelity sounds at the low end of the frequency spectrum.

Going Further

Is it hard to remember which frequency corresponds to which note? Download the Music sketch.

RedBot Music Sketch

Unzip it, open it with Arduino, and upload it to your RedBot.

This experiment will play the beginning of “Twinkle Twinkle Little Star” when you press the D12 button. If you look at the code, we use a couple tricks to make things easier.

You will see an extra file in this example called notes.h. This file is a “header” file that is often used to contain extra constants, variables, and sub-routines that are used in your code. notes.h has a list of #define statements that replace noteC4 with 262 (much like a variable, but more efficient).

It also has the length of the notes defined in terms of milliseconds. These are denoted as: WN - whole note, HN - half note, QN - quarter note, EN - eighth note, SN - sixteenth note.

The second trick is a custom function called playNote([note], [duration]). This custom function plays the note using the tone() command and adds a delay(). This simplifies playing notes to just one line of code. For example, to play a middle C for a quarter note, we can type: playNote(noteC4, QN);

What song can you compose? Camptown Races? Amazing Grace? or When the Saints go Marching? Pick a piece to compose as your “theme” song for your RedBot!

Troubleshooting

I don’t hear anything

  • If you look at the code, the example program waits for a button press on D12 before doing anything. Press the button and listen.
  • Make sure that the buzzer is plugged into the Servo header labeled #9.

Experiment 5: Bumpers (SIK)

Read on if you have the SIK for RedBot or are using the Mechanical Bumpers. If not, skip to the next section.

Now let’s experiment with the whisker bumpers. These super simple switches let you detect a collision before it happens; the whisker will feel a bump just before your robot crashes into it.

One of the most useful elements of the Arduino is its ability to send messages back to a computer over a USB connection. This is accomplished with the “Serial” library, and it allows you to, among other things, report fairly complicated debugging information (reading back variable values, setting multiple different messages to occur under different circumstances, etc).

We’re also going to introduce the concept of “conditional” code - code that only executes when some condition is true. Conditionals are the key to making robots do interesting things; here, we’re going to use the simplest conditional: the if() statement.

Let’s load this experiment onto the RedBot. Go to File > Examples > RedBot_Experiments > Exp5_Bumpers or copy and paste the example code below:

What You Should See

In this experiment, the RedBot should start driving forward until one of the bumpers is hit. When the right side is bumped, the RedBot should reverse and turn the left. When the left side is bumped, the RedBot should reverse and turn right.

Manipulate the timing and the motorPower settings so that your RedBot backs up 12 inches and turns a full 90 degrees after each bump.

Code to Note

Above the setup() and loop(), we declare and initialize two bumper objects using the RedBotBumper class. The initialize statement takes a single parameter indicating which pin the whisker is connected to.

language:c
RedBotBumper lBumper = RedBotBumper(3);  // initializes bumper object on pin 3
RedBotBumper rBumper = RedBotBumper(11); // initializes bumper object on pin 11

The initialize statement automatically sets up the pin with an internal pull-up resistor. This forces the default / nominal state of the input to be HIGH. Not sure what a pull-up resistor is? Check out our Pull-up Resistors tutorial!

lBumper.read() and rBumper.read() returns the state of the bumper. When the RedBot is bumped, the whisker makes contact with a screw bolt that is connected to GND. Therefore, a bump is detected as LOW. We introduce the use of state variables in this example. We read in the state of each bumper and store these in two variables called lBumperState and rBumperState.

language:c
lBumperState = lBumper.read();  // default INPUT state is HIGH, it is LOW when bumped
rBumperState = rBumper.read();  // default INPUT state is HIGH, it is LOW when bumped

Learn More: if() Statements

Want to know how to use logic like a Vulcan? One of the things that makes the RedBot so useful is that it can make complex decisions based on the input it’s getting. For example, you could make a thermostat that turns on a heater if it gets too cold, or a fan if it gets too hot, waters your plants if they get too dry, etc.

Conditional Statements

In order to make these decisions, the Arduino environment provides a set of logic operations that let you make decisions based on conditions or comparisons. Conditional statements should be grouped together using parentheses - e.g. (A == B). These “test” statements or comparisons include:

SymbolNameDescription
==IS EQUAL TO?A == B is true if A and B are the SAME.
!=IS NOT EQUAL TO?(A != B) is true if A and B are NOT THE SAME.
>GREATER THAN(A > B) is true if A is greater than B.
<LESS THAN(A< B) is true if A is less than B.
>= GREATER THAN
OR EQUAL TO
(A >= B) is true if A is greater than or equal to B.
<= LESS THAN
OR EQUAL TO
(A <= B) is true if A is less than or equal to B.

Compound Conditional Statements

Often you might want to string together multiple conditional statements together. The Arduino environment allows us to “chain together” or combine multiple conditional statements with a few symbols. You can combine these symbols to build complex if() statements.

SymbolNameDescription
&&AND(condition X) && (condition Y) is true only if BOTH (condition X) and (condition Y) are true.
||OR(condition X) || (condition Y) is true if condition X is TRUE or condition Y is TRUE or BOTH are TRUE. These are sometimes called "pipes."
!NOT or INVERSE!(condition X) is true if (condition X) is false. !(condition X) is false if (condition X) is true.

For example:

language:c
if ((mode == 1) && ((temperature < threshold) || (override == true)))
{
    digitalWrite(heaterPin, HIGH);
}

…will turn on a heater if the mode varaible is equal to 1 (heating mode) “AND” the temperature is below the threshold, OR if the override variable is set to true. Notice the order of operations are controlled with the parentheses () in these compound conditional statements. Using these logic operators, you can program your RedBoard to make intelligent decisions and take control of the world around it!

Going Further

The current example has the RedBot backing up and turning if either the right or the left bumpers are hit. What should the RedBot do if both bumpers are pressed at the same time? Change the code so that the RedBot backs up and rotates a full 180 degrees when both left and right bumpers are hit.

Troubleshooting

The whiskers aren't triggering anything!

  • Check and be sure that they make good contact with the screws when the whisker bumps into something.
  • Make sure that you've got them plugged into the right pins on the mainboard, and that the other ends plug onto OUT and GND on the sensor board.

Experiment 6: Line Following with IR Sensors

In this experiment, the RedBot will use IR Reflectance sensors to detect characteristics about the surface below the RedBot. The IR Reflectance sensor works by emitting a beam of infrared (IR) light down toward the surface below and measuring the reflected signal. On the IR Reflectance sensor, you will notice two small rectangular shapes. One is the IR transmitter and the other is the detector.

IR reflectance sensor

The IR Reflectance sensors work best when they are close to the surface below the RedBot. The sensor should be about 1/8" above the table. This is an optimal distance for the IR transmitter to illuminate the surface below and measure the reflected light. (Note: Human eyes are non sensitive to IR light, but if you use a CCD camera – like the one in your phone – you can see a small light shining out of the front element)

IR light in camera

Here, you can see a faint pink glow from the IR LED. This is picked up on most digital cameras and cell phones.

Experiment 6.1 – Simple IRSensor Read

This example simply reads and prints the value of the three IR Sensors. Test out different scenarios to characterize the behavior of the IR sensor.

Upload this example code to the RedBot. Go to File > Examples > RedBot_Experiments > Exp6_LineFollowing_IRSensors or copy and paste the example code below. After the code has successfully uploaded, open up the Serial Monitor to view the readings from the sensors.

After uploading this example, leaving the RedBot connected to your computer, set it down on a piece of paper with a dark line (at least ½" wide). You may use a Sharpie Marker, electrical tape, or dark paint. Open up the Serial Monitor (Tools > Serial Monitor) to see the data and sensor readings by the RedBot.

Readings from IR sensor

Sensor Characterization Exercise

The IR Reflectance sensors operate in a pretty short range. They are optimal between 1/8" and 3/16" from the surface. Test this out with your own RedBot.

  • Set the robot flat on your desk. What are the nominal values of the three sensors?
  • Set the robot down on a piece of white paper. What are the values of the sensors now?
  • Making some marks on your paper with different materials: electrical tape, paint, markers, pencils, etc.
  • With the robot still sitting on your desk, turn out the lights or throw a blanket over it. What happens to the values of the sensor readings? What do you think is causing this?
  • Slowly roll the robot towards the edge of a table. Watch the value as the sensor moves off the edge of the table. What is the sensor value when it rolls off the table?

We can now use these values to program our robot to do things like stay on a table or follow a dark line.

What You Should See

The RedBot won’t do anything on its own with this example. It does, however, report back the sensor readings to the Serial Monitor in Arduino. Click on the Magnifying glass in the upper-right corner to open the Serial Monitor, and watch the values of the line followers change in different situations.

Learn More: Infrared

The IR Reflectance sensor is essentially an IR LED and an IR detector. It works by transmitting a beam of IR light downward toward the surface. If the detector is over a white surface, the reflected light is received by the detector and outputs a LOW signal. When the sensor is over a black surface where the light is absorbed or not reflected, the IR detector outputs a HIGH signal. The IR Sensor module provides an analog value from 0 - 1023 inversely dependent to the amount of reflected IR light.

The analog values read into the Arduino environment vary from 0 to 1023 because Arduino uses a 10-bit Analog-to-Digital Converter (ADC). A value of 0 corresponds to 0 Volts, and 1023 corresponds to 5V read in by the sensor.

Code to Note

To setup communication between the RedBot and your computer, we need to use the Serial object in Arduino. In the setup(), you will see a command: Serial.begin(9600); This initializes the Serial object and determines the data rate (speed) that data will be transmitted and received between the RedBot and the computer. 9600 refers to a baud rate or the number of bis per second. 9600 is a good moderate data rate for most applications. However, other speeds, including 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, and 115200, are supported in Arduino.

language:c
Serial.begin(9600);

To send data from the RedBot to your computer, we have two commands: Serial.print(""); and Serial.println(""); The first command, Serial.print(""); simply prints the text in “ ” or data (in the form of a number or variable) to the Serial bus – this shows up in the Serial monitor. The second command, Serial.println(""); does the same, but adds a carriage-return/line-feed (CRLF) character, moving the cursor to the next line.

language:c
Serial.print("IR Sensor Readings: ");

Serial.println(); // Sends a CRLF character -- moves cursor to next line.

Printing Special Characters

There are a few special characters that can be printed out. These follow all of the standard conventions used in C and C++. A few handy ones include:

CodeDescription
\tTAB character
\"Double quotation mark
\'Single quotation mark
\nCRLF - moves to next line

RedBot Library

Library support for the line sensor is included in the main RedBot library. The line following sensors will be attached to pins A3, A6, and A7. We will create three objects for each of the three sensors with the following lines of code:

language:c
RedBotSensor IRSensor1 = RedBotSensor(A3);  // initialize a sensor object on A3
RedBotSensor IRSensor2 = RedBotSensor(A6);  // initialize a sensor object on A6
RedBotSensor IRSensor3 = RedBotSensor(A7);  // initialize a sensor object on A7

The RedBotSensor class has only one method of interest to us. It is xxxxxx.read(); This method returns a value from 0 to 1023 based on the input voltage of the sensor. Remember that the xxxxxx represents the name of the object – In this case, IRSensor1, IRSensor2, or IRSensor3.

language:c
Serial.print(IRSensor1.read()); // prints out the sensor value of IRSensor1 to the Serial Monitor

Going Further

Modify the code to make the RedBot drive around and stop before it crosses a black line.

Use the xxxxxx.read() method to check the values and then write some code that will stop the robot if the level of one of the sensors changes more than a certain amount.

You will need to use an if() statement. Go back to Experiment 5 – Bumpers to remind yourself how to make comparisons and conditional statements within an if() statement.

Let’s take a look at a few basic scenarios.

  • The center moves off the line and the left sensor is now on the line. Adjust the power to turn / veer left until the center is back on the line.

  • The center moves off the line and the right sensor is now on the line. Adjust the power to turn / veer right until the center is back on the line.

  • The RedBot approaches a left turn, the center AND the left are BOTH on the line. Turn 90 degrees to the left.

  • The RedBot approaches a right turn, the center AND the right are BOTH on the line. Turn 90 degrees to the right.

Play around with these basic ideas to see if you can program your RedBot to:

  • A) Follow a straight line.

  • B) Follow a straight line and turn Left or Right.

  • C) Follow a maze traced out with electrical tape.

Troubleshooting

Nothing is printing in the serial monitor!

  • Check to make sure the baud rate is set properly in the serial monitor. There’s a drop-down menu in the lower right corner, and by default, this sketch wants the baud rate at 9600.

I don’t see any change in my sensor values, no matter what I do!

  • Double-check your connections.
  • Try swapping out the sensor board with one of the others.

Experiment 6.2 – Line Following Example

Example of line following

Here is a quick example of using the line following sensors to follow a dark line on a white background. The algorithm is fairly straight forward. If the center sensor is on the line, the RedBot drives straight (left & right motors are at the same speed). If the right sensor is on the line, we adjust by turning the RedBot to the right (driving the left a little faster and the right a little slower). Similarly, if the left sensor is on the line, the RedBot adjusts by turning to the left (driving the right a little faster and the left a little slower).

This example really only works when the RedBot is moving slowly, and it doesn’t always handle sharp turns well. What can you do to make this example work better?

Experiment 7: Encoder (SIK)

Read on if you have the SIK for RedBot or are using the Wheel Encoder Kit. If not, skip to the next section.

Knowing where your robot is can be very important. The RedBot supports the use of an encoder to track the number of revolutions each wheel has made, so you can tell not only how far each wheel has traveled but how fast the wheels are turning. Included in the SIK for RedBot is a magnetic hall effect sensor and an 8-pole magnetic disk (looks like a washer – but, it’s magnetic!).

This experiment is broken down into three parts: (1) Reading the encoders, (2) Driving a specific distance, and (3) Driving straight.

This first code example is pretty short, but with it we will introduce a how to interface and read the encoder inputs. Go to File > Examples > RedBot_Experiments > Exp7_1_RotaryEncoder or copy and paste the example code below and open up the Serial Monitor.

Experiment 7.1 - Exploring the Encoder

What You Should See

If you open up the Serial Monitor you should see a window like this:

Arduino Serial Monitor

Turn each wheel one complete revolution, and watch what happens. What happens if you reverse directions?

You should see the numbers go up – whether the wheel is turning clock-wise or counter clock-wise. The encoder simply counts the number of times the magnetic poles (N-S) change. The magnet has 8 poles (4 pairs of N-S), so you see 4 counts for every one turn of the magnet. So, why are we seeing more than just 4 counts? Because the motor is connected to a 48:1 gear box, one turn of the wheel is equal to 48 turns of the motor. 48 x (4 magnetic N-S pairs) = 192. Did you see about 192 counts?

Press the reset button to re-start the count at zero. Try it again.

Finally – with the Serial Monitor window still open, push the D12 button on the RedBot. You should see the motors start spinning. You will also see the encoder counts track with the wheels. It should stop after 5 full rotations or at a count of about 960.

Code to Note

RedBotEncoder is another class in the RedBot library. This line initializes the encoder object with the left encoder connected to pin A2 and the right encoder connected to pin 10.

language:c
RedBotEncoder encoder = RedBotEncoder(A2, 10);  // initializes encoder on pins A2 and 10

One of the useful methods in the RedBotEncoder class is encoder.clearEnc([LEFT/RIGHT/BOTH]); This method clears the internal encoder counters for either the LEFT, RIGHT, or BOTH. This is useful for resetting the encoder count just before you start moving.

language:c
encoder.clearEnc(BOTH);  // Reset the counters.

To read the encoder count - also called “ticks” - we use the method encoder.getTicks[LEFT/RIGHT]); This returns a value representing the number of ticks or encoder counts. Because this number can be very large, we use a long variable type for it.

language:c
// store the encoder counts to a variable.
lCount = encoder.getTicks(LEFT);    // read the left motor encoder
rCount = encoder.getTicks(RIGHT);   // read the right motor encoder

Things to try

Looking at the code, we use the motors.brake(); method. Change this to motors.coast(). With motors.coast() the wheels coast and gradually come to a stop. How many more ticks or counts does a coast take compared to a brake()?

Experiment 7.2 - Driving a distance

In this example, we will use the encoder values and the circumference of the wheel to determine how far the RedBot moves.

The standard RedBot chassis has 65 mm (2.56 inch) diameter wheels. The circumference of a circle is equal to π × D, or in this case, approximately 8.04 inches. And using the encoders, one circumference of the wheel (one full rotation) is also equal to 192 ticks of the encoder.

We will use all of this to write a function called driveDistance() that takes two parameters – distance and motorPower to precisely move our robot. We can calculate the exact number of ticks (encoder counts) it will take to move a specific distance.

Go to File > Examples > RedBot_Experiments > Exp7_2_DriveDistance or copy and paste the example code below and open up the Serial Monitor.

What You Should See

In this example, when you push the D12 button, the RedBot should drive forward 12 inches and stop. If you have the Serial monitor open, you will see this debug information.

Debug information

In the code, given a desired distance, it calculates the number of wheel rotations needed and the target number of encoder ticks (counts). As the wheels spin, it reports back the current count until it reaches its target.

Place the RedBot on a table or flat surface. Push the D12 button. How far did the RedBot move? Repeat this a few times. How far off is your RedBot? Try changing speeds. Is the RedBot more or less accurate when you change the motorPower?

Code to Note

In this example, we created a custom function called driveDistance(); It takes two input parameters – distance and motorPower. If you look at the code, you will see where it calculates the number of revolutions (numRev = distance / wheelCirc;) and where it calculates the target encoder count (targetCount = numRev * countsPerRev;).

language:c
void driveDistance(float distance, int motorPower)
    {
        ...
    }

In this function, we use a while() loop. In this case, the while() loop will repeat over and over so long as rCount is less than targetCount. Inside the loop, we read both the left and the right encoder values, and print these out to the Serial Monitor.

while (rCount < targetCount)
    {
       ...
    }

Did you notice that the right motor doesn’t spin the same speed as the left motor? Sometimes this happens with DC motors. In our next example, we will use the encoders to help us keep the RedBot driving straight.

Things to try

On the line of code that reads driveDistance(12, 150);, try changing the distance to something shorter or longer. Take a tape measure and see how accurate the RedBot is. Try changing the speed. How does the speed affect the accuracy of your driveDistance()?

Finally, you notice that in the while() loop we are only comparing the right encoder count, rCount. We assume that both the left and the right are pretty close – but, try changing the rCount to lCount. How does this affect the behavior of your RedBot? Does it drive farther or shorter? Why?

Experiment 7.3 - Driving a “straight” distance

We have all of this information about how far each of the wheels are moving. We can now drive a precise distance at any speed, but our RedBot still curves a bit to one side or the other. Let’s see if we can use the rCount and lCount information to steer our RedBot straight. Copy and paste the following code into the Arduino window.

/***********************************************************************
 * Exp7_3_DriveStraight -- RedBot Experiment 7.3
 *
 * Knowing where your robot is can be very important. The RedBot supports
 * the use of an encoder to track the number of revolutions each wheels has
 * made, so you can tell not only how far each wheel has traveled but how
 * fast the wheels are turning.
 *
 * This sketch was written by SparkFun Electronics, with lots of help from
 * the Arduino community. This code is completely free for any use.
 *
 * 8 Oct 2013 M. Hord
 * Revised, 31 Oct 2014 B. Huang
 ***********************************************************************/
#include <RedBot.h>
RedBotMotors motors;

RedBotEncoder encoder = RedBotEncoder(A2, 10);
int buttonPin = 12;
int countsPerRev = 192;   // 4 pairs of N-S x 48:1 gearbox = 192 ticks per wheel rev

float wheelDiam = 2.56;  // diam = 65mm / 25.4 mm/in
float wheelCirc = PI*wheelDiam;  // Redbot wheel circumference = pi*D

void setup()
{
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(void)
{
  // set the power for left & right motors on button press
  if (digitalRead(buttonPin) == LOW)
  {
    driveStraight(12, 150);
  }
}

void driveStraight(float distance, int motorPower)
{
  long lCount = 0;
  long rCount = 0;
  long targetCount;
  float numRev;

  // variables for tracking the left and right encoder counts
  long prevlCount, prevrCount;

  long lDiff, rDiff;  // diff between current encoder count and previous count

  // variables for setting left and right motor power
  int leftPower = motorPower;
  int rightPower = motorPower;

  // variable used to offset motor power on right vs left to keep straight.
  int offset = 5;  // offset amount to compensate Right vs. Left drive

  numRev = distance / wheelCirc;  // calculate the target # of rotations
  targetCount = numRev * countsPerRev;    // calculate the target count

  // debug
  Serial.print("driveStraight() ");
  Serial.print(distance);
  Serial.print(" inches at ");
  Serial.print(motorPower);
  Serial.println(" power.");

  Serial.print("Target: ");
  Serial.print(numRev, 3);
  Serial.println(" revolutions.");
  Serial.println();

  // print out header
  Serial.print("Left\t");   // "Left" and tab
  Serial.print("Right\t");  // "Right" and tab
  Serial.println("Target count");
  Serial.println("============================");

  encoder.clearEnc(BOTH);    // clear the encoder count
  delay(100);  // short delay before starting the motors.

  motors.drive(motorPower);  // start motors

  while (rCount < targetCount)
  {
    // while the right encoder is less than the target count -- debug print
    // the encoder values and wait -- this is a holding loop.
    lCount = encoder.getTicks(LEFT);
    rCount = encoder.getTicks(RIGHT);
    Serial.print(lCount);
    Serial.print("\t");
    Serial.print(rCount);
    Serial.print("\t");
    Serial.println(targetCount);

    motors.leftDrive(leftPower);
    motors.rightDrive(rightPower);

    // calculate the rotation "speed" as a difference in the count from previous cycle.
    lDiff = (lCount - prevlCount);
    rDiff = (rCount - prevrCount);

    // store the current count as the "previous" count for the next cycle.
    prevlCount = lCount;
    prevrCount = rCount;

    // if left is faster than the right, slow down the left / speed up right
    if (lDiff > rDiff)
    {
      leftPower = leftPower - offset;
      rightPower = rightPower + offset;
    }
    // if right is faster than the left, speed up the left / slow down right
    else if (lDiff < rDiff)
    {
      leftPower = leftPower + offset;
      rightPower = rightPower - offset;
    }
    delay(50);  // short delay to give motors a chance to respond.
  }
  // now apply "brakes" to stop the motors.
  motors.brake();
}

Code to Note

In this code, we use the motors.leftDrive() and motors.rightDrive() to independently drive each side. In the while() loop, we calculate a “speed” based on the difference in the current encoder count compared to the last cycle.

If the left difference lDiff is greater than the right difference rDiff, we reduce the leftPower and increase the rightPower. And, if lDiff is less than rDiff, we increaes the leftPower and reduce the rightPower. This is a simple feedback loop that will help keep the RedBot driving straight.

Things to try

Take a look at the last experiment 7.3. There is a function called driveStraight that checks the difference in the lCount and the difference in the rCount from the previous encoder reading. It uses this to add or subtract a power offset to the right or left motors. On the line that reads: int offset = 5; Change the offset to a bigger number. How does this change the behavior of your RedBot.

Going Further

You have learned a lot so far! Encoders are great feedback sensors for robotics. In our earlier examples, when we used delay() and dead reckoning to drive a specific distance, we relied on the batteries maintaining a constant voltage and the motors to behave predictably each time. With encoders, we know exactly how far each wheel rotates.

For a challenge, write your own turn() function that uses the encoders to help the RedBot turn a 90 degree angle. With the encoders, your results should be pretty consistent each time.

Learn More: RedBot Sensor - Encoder

The wheel encoder on the RedBot is a Hall Effect Sensor that detects changes in magnetic fields. As the round magnetic disk mounted to the back of the drive motors rotates, it moves it’s N/S poles past the sensor. Each transition from N/S is marked as a count. The disk is an 8-pole magnet (4 north-south pairs) and results in 4 ticks or counts for each revolution of the motor.

The motor is mounted inside a 48:1 gearbox. This means that the motor will spin 48 times for one full rotation of the wheel (48 x 4 = 192 counts).

Since the wheel is about 2.5 inches (65mm) in diameter, that corresponds to about eight inches or 200mm traveled per full revolution. So, 192 counts of the encoder is equal to about 8 inches of linear travel.

Now, to forestall angry messages about conversions and precision of measurement (for instance, if you ask Google how many mm are in 2.5 inches, it’ll tell you 63.5, not 65, and the circumference of a 2.5 in diameter is certainly not exactly eight inches), I invite you to consider this your first lesson in precision and tolerance. Given all the tolerances involved in this system, eight inches/200mm per revolution is almost certainly a “good enough” answer, and if you need better than that, you’ll need a more expensive robotics platform.

Troubleshooting

The encoder counts aren’t incrementing!

  • Double check the wiring. Make sure that the encoders are plugged into ports A2 and 10 on the RedBot Mainboard.
  • Make sure that the magnetic disk is still in place. If it falls off, a little super glue or epoxy will do the trick.
  • Make sure that the encoder sensor is bent and next to the magnetic disk.

Experiment 8: Accelerometer

The RedBot Kit comes with an accelerometer board that can be used to detect bumps or to tell whether the robot is on an incline. This example will use the accelerometer as an input to “wind up” the robot.

Experiment 8.1 - Exploring the Accelerometer

Let’s load this experiment onto the RedBot. Go to File > Examples > Exp8_1_AccelerometerRead or copy and paste the example code below.

What You Should See

This simple sketch introduces us to the RedBotAccelerometer class object. The RedBotAccelerometer class has a .read() method that reads the current X, Y, and Z accelerometer readings and calculates the X-Z, Y-Z, and X-Z angles. Upload this sketch to your RedBot, open up the Serial Monitor, and rotate/tilt the RedBot around to see how the values change.

Reading the accelerometer

What is the maximum values that you see for any one axis?

Code to Note

RedBotAccel is another class in the RedBot library. This line initializes the accelerometer object. The Accelerometer sensor uses a protocol called I2C. For this, the sensor must be connected to pins A4 & A5 on the RedBot Mainboard. This is why the accelerometer must be plugged into the front-right corner of the RedBot.

language:c
RedBotAccel accelerometer;

The RedBotAccel class has one method (function) that we need to use. It is the .read() method. This sends the commands to the sensor to read the X, Y, and Z axis accelerations and calculate the X-Z, Y-Z, and X-Y angles. The accelerometer works by measuring the vector force of gravity on a small mass in the X, Y, and Z directions. By using the component values of each vector, you can determine the orientation of the RedBot with respect to Earth’s gravitational pull.

language:c
accelerometer.read(); // updates the x, y, and z axis readings on the accelerometer

After we have called the .read() method, the accelerometer values are stored in public variables that are part of the class. These variables are: x, y, z, angleXZ, angleYZ, and angleXY. The variables x, y, and z return an integer that represents the raw accelerometer values. The variables angleXZ, angleYZ, and angleXY return a floating point number representing the angle in each of these planes:

language:c
int xAccel = accelerometer.x;
int yAccel = accelerometer.y;
int zAccel = accelerometer.z;

float XZ = accelerometer.angleXZ;
float YZ = accelerometer.angleYZ;
float XY = accelerometer.angleXY;

The raw x, y, and z readings indicate acceleration along each of these axes. You can see the markings on the sensor indicating the direction. X points in the forward direction, Y points to the left, and Z is straight up. The absolute reading should vary between something close to 16,000 to -16,000, and when the robot is neutral or flat, the reading will be near zero (+/- perhaps 500 counts, depending on how level it is).

Things to Try

Can you figure out what mathematical function is used to calculate the angle in each plane – XZ, YZ, and XY? (Hint: Think back to you triangles and trig identities).

Experiment 8.2 - Wind-up

This is a fun demo that uses the accelerometer reading to detect the tilt / incline of the Redbot. As you tilt the RedBot, the wheels should start to spin. This mimics a “wind-up” toy action. Set it down on the floor and watch it drive slowly to a stop.

Go to File > Examples > RedBot_Experiments > Exp8_2_WindUp or copy and paste the example code below:

What You Should See

If your Redbot is sitting up-right, you should see the Redbot motors start spinning. As you change the incline or tilt of the position of the Redbot, it will change speed. Set the robot on the floor, and it should slow to a stop.

Code to Note

In robotics and electronics, we often have the need to scale our inputs to a different range of values. In Arduino, there is a nifty function called map() that does this for us. map() uses 5 parameters or inputs. map(value, fromLOW, fromHIGH, toLOW, toHIGH). Basically, it scales a value that is in a range of between fromLOW to fromHIGH to a new range that is toLOW to toHIGH. In this example, we are scaling the angle from 0 to 90 degrees to an output value of 0 to 255 for the motorPower.

language:c
motorSpeed = map(XZ, 0, 90, 0, 255);

Things to Try

What other things can we do with the accelerometer? How about a tilt sensor that lights up different LEDs to indicate what direction the RedBot is tilted? How about a sound maker that varies the pitch of the sound based on the angle of the RedBot? You have access to the three independent vectors (X, Y, & Z) and the three relative angles in the X-Z, Y-Z, and X-Y planes. Come up with something fun to do based on the accelerometer readings!

Learn More: Accelerometer

The accelerometer sensor is an add-on for your RedBot that provides bump and motion detection. The sensor works by measuring acceleration forces on the x, y, and z axis. By measuring the amount of acceleration (or lack thereof) your robot can get a better understanding of its movements.

To learn more about accelerometers, please check out our Accelerometer Basics tutorial.

Going Further

Use the accelerometer to start a program. Shut down when things have gone wrong (turned over). After doing that, try to combine what you have learned to make the RedBot start driving around a line when the accelerometer is bumped.

Troubleshooting

The accelerometer values in the Serial window aren’t changing!

Experiment 9: Remote Control

At the heart of almost every robotics project is remote control. Up to this point, we have only looked at autonomous or pre-programmed control of the RedBot. Using a few simple commands, we will setup the RedBot to respond to Serial data that is transmitted from your computer.

Let’s load this experiment onto the RedBot. Go to File > Examples > Exp9_SerialDrive or copy and paste the example code below:

What You Should See

After uploading this sketch, open up the Serial Monitor.

Remote control with the RedBot

In the code, we print out a few lines in the setup() using the Serial.println() command. These are used as user-interface prompts. Type in one or two numbers into the input window and click [Send]. The motors should start spinning. The values that you send to the RedBot will drive the left and the right motors, respectively. What happens when you type in a negative value? How would you stop the motors?

Code to Note

language:c
Serial.begin(9600);

This first command in the setup() starts the Serial communication between the RedBot and your computer. The “9600” specifies the baud rate or speed that you can communicate. Did you notice that the RedBot response lagged a little from when you sent it commands to change speeds? Try changing the baud rate to 57600. Note that when you change the baud rate, you need to re-upload your code and change the speed on the Serial Monitor.

Changing the baud rate

If you forget to change the baud rate in the Serial Monitor, all you’ll see is gobbly-gook. Make sure the baud rate in the Serial Monitor matches what you have in your Serial.begin() in your code.

Wrong baud

language:c
if(Serial.available() > 0)
{
}

In the loop() part of the code, we start with a simple if() conditional statement. Serial.available() returns the number of bytes waiting to be read in. Remember that this is on the RedBot. So, when we type in “-150 150” [Send], there are 8 characters worth of data being sent to the RedBot.

language:c
  leftPower = Serial.parseInt();  // read in the next numeric value
  leftPower = constrain(leftPower, -255, 255);  // constrain the data to -255 to +255

  rightPower = Serial.parseInt();   // read in the next numeric value
  rightPower = constrain(rightPower, -255, 255);  // constrain the data to -255 to +255

Next, we use a nifty function of the Serial object called .parseInt(). This function reads in the next numeric value and converts this to a number. Note that when we pass data back and forth on the Serial Monitor, we generally pass data as ASCII characters. Because these are not actually number values, we need to use this function to read in the data and convert them.

You can use this same method to send any number of data items. For this example, we’re just sending two pieces of data (leftMotor power and rightMotor power). You can use this to signal turning on LEDs, making sounds, or moving motors.

Learn More: Serial

The Serial object in Arduino has many other methods, functions, and features. Serial communication is one of the simplest methods to send data, instructions, and commands between the RedBot and your computer. If you look closely at the RedBot, you should see two lights blinking back and forth whenever data is being sent or received.

One LED represents data being received (RX) and the other represents data being transmitted (TX). For the Arduino, all of this communication happens over two wires (one for RX and one for TX). We can send data at speeds up to 115200 baud (that’s 115200 bytes per second!).

In today’s world of GB/s data rates, this may not seem like that much, but this is remarkably fast given that it’s just being sent over two very thin wires.

Going Further

Want to go wireless? Well – you’ll need a few things to get started. First, you’ll need two XBee Series 1 and an XBee Explorer USB.

The XBee radio modules are ready to go with their default settings. The radios are on a generic network address (3332) and are broadcasting out to any and all radios that are on this network. Note: The default settings will not work in a classroom setting or where there may be more than one set of wireless RedBots.

To start, plug one XBee into the XBee Explorer USB. It is very important to make sure that the pins all line up and the XBee matches the white pentagonal outline on the XBee Explorer. Using a USB cable, connect this to your computer. Your computer may “find a new device” and attempt to install drivers. Allow your computer to complete this process before moving on.

Plug the other XBee into your RedBot. Again, make sure that the pins line up and the XBee matches the white pentagonal outline. Also, check to make sure that the switch next to the XBee header is set to XBEE HW SERIAL.

The RedBot should now be connected to your computer wirelessly: through the two XBees. The XBee Explorer will identify as a different Serial Port on your computer. Go to the Tools > Serial Port menu and change this to the Serial Port for the XBee.

Select Port for XBee

Now, open up the Serial Monitor. Push the [Reset] button on the RedBot, and you should see text come across. Type in a couple numbers and see if your RedBot starts moving. With the default XBee configuration, you can only communicate at 9600 baud.

Controlling the RedBot wirelessly

Notice that this uses a different COM Port.

If you want to use a different baud rate, or you want to run multiple RedBots in a single classroom, you will need to re-configure each of the XBee radios. For this, you can use a program like XCTU. XCTU is a configuration tool made by Digi, the manufacturer of the XBee Wireless modules.

For more information on XBees or wireless projects check out our tutorial on learn.sparkfun.com:

Exploring XBees and XCTU

June 5, 2014

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

Resources and Going Further

Get moving!

Hopefully, this guide has given you enough information to get started with the RedBot!

Once you’ve mastered the art of line following robots, try you hand at other types of robots.

Resources

GitHub repositories:

Beyond the Tutorial

Here are some guides and projects to get you going with other ideas:

Building the HUB-ee Buggy

Let's build the HUB-ee Buggy: A simple robot based on the HUB-ee wheel system!

MMA8452Q Accelerometer Breakout Hookup Guide

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

Alternative Arduino Interfaces

We admit the Arduino IDE isn't for everyone. Here are some other options for programming your Arduino boards, including web interfaces and graphical programming languages.

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

Assembly Guide for RedBot with Shadow Chassis

$
0
0

Assembly Guide for RedBot with Shadow Chassis a learn.sparkfun.com tutorial

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

Introduction

The RedBot is robotic development platform capable of teaching basic robotics and sensor integration! Based on the SparkFun RedBoard and programmable in the Arduino environment, the RedBot has all the I/O you need to make a small robot in no time at all. This guide covers the new Shadow Chassis for the RedBot.

Completed RedBot SIK

NOTE: We recommend that you read all of the directions first, before building your RedBot.

RedBot Kit vs. SIK for RedBot

This tutorial will cover how to install all the parts in the SparkFun RedBot Kit and the SparkFun Inventor’s Kit for RedBot (SIK for RedBot).

The SIK for RedBot contains a few extra parts in addition to the RedBot Kit that are covered in this guide. Please ignore any instances of the extra sensors if you do not need to assemble them. Sections pertaining to these extra parts will be marked with (SIK). This is some kind of warning.

RedBot Kit

If you have the RedBot Kit, you can skip the steps marked with (SIK).

RedBot Kit

Alternatively, you can pick up additional sensors to install on your RedBot. These parts include the Wheel Encoder Kit, RedBot Buzzer, and twoRedBot Mechanical Bumpers. Follow the sections in this guide that covers any of the extra sensors you might have.

SIK for RedBot

If you have the SIK for RedBot, you can follow all the sections in this guide, including those marked with (SIK).

Completed RedBot SIK

Materials

The RedBot kit contains the following pieces. SIK-only parts are noted with an asterisk (*).

RedBot Kit parts

PartQty
ABottom Chassis Plate1
BTop Chassis Plate1
CFront Motor Mount2
DRear Motor Mount2
ESide Strut4
FEncoder Mount2
GMainboard Mount2
HBattery Pack Clip1
ILine Follower Mount1
JLine Follower Mount Plate1
KMotor2
LWheel2
MNub Caster1
N*Encoder Magnet Plate (SIK)2
O*Encoder Hall Effect Sensor (SIK)2
PRedBot Mainboard1
QLine Follower Board3
RAccelerometer Board1
S*Buzzer Board (SIK)1
T*Bumper Board (SIK)2
U*Bumper Whisker (SIK)2
V*#4-40 x 3/8" Screw (SIK)6
W*#4-40 Nylon Standoff (SIK)2
X*#4-40 Hex Nut (SIK)2
Y3-Wire Jumper Cable (SIK)3 (5*)
ZBattery Holder1
AA*AA Batteries (SIK)4
AB*Screwdriver (SIK) (Not Shown)1
* Indicates parts included in the SIK for RedBot

IMPORTANT: If you have the RedBot Kit, you will need 4x AA batteries.

Recommended Tools

None! The RedBot Kit does not require any additional tools. The SIK for RedBot comes with a screwdriver, which you will need to mount the Bumper Boards. If you bought the Bumper Boards separately, you will need a Phillips screwdriver.

WARNING: Do not attempt to remove chassis parts by squeezing them with pliers. You will break them, and the robot will be sad.

You're going to have a bad time

A Note About Directions

When we talk about the “front,” “left,” “right,” and “back” of the RedBot, we are referring to specific sides of the robot when viewed from above.

Directions on the RedBot

Notice that we consider the Mainboard to be on the “back” of the RedBot and the Bumper Whiskers and Line Follower Boards to be in the “front.”

1. Wheel Encoders (SIK)

Read on if you have the SIK for RedBot or are using the Wheel Encoder Kit. If not, skip to the next section.

The Wheel Encoder Kit is a simple add-on to any wheeled robot that can help measure the speed or distance the chassis travels.

Locate the Following:

1x Bottom Chassis Plate (A)2x Encoder Mount (F)2x Motor (K)
Bottom Chassis PlateEncoder MountMotor
2x Encoder Magnet Plate (N)2x Encoder Hall Effect Sensor (O)
Encoder Magnet PlateEncoder Hall Effect Sensor

Add the Magnets

Slide the Encoder Magnet Plates (N) onto the metal shaft on the back of the Motors (K). Note that magnet side (silver) should face away from the motor.

Magnet plate

Attach the Hall Effect Sensors

Left Encoder

Take one of the Encoder Mounts (F) and hold it so that the protruding slot is on the left. Push one of the encoder sensors through the first slot on the right. Note that the front of the sensor (marked “A 20L”) is facing to the left.

Adding hall effect sensor

Loop the sensor and push it through the second (middle) slot. The “A 20L” marking should now be facing to the right.

Looping left encoder

Once more, push the sensor through the protruding slot on the left. Carefully pull the wires so there is no more slack in the mount. Make sure the whole sensor can be seen coming out of the final slot and the markings “A 20L” is pointing away from the mount (to the left in the picture).

Hall effect sensor in mount

Snap the assembled encoder mount into the back-left vertical slot of the Bottom Chassis Plate (A).

Left hall effect sensor in place

Right Encoder

The right encoder is a mirrored assembly of the left encoder.

Take the other Encoder Mount (F) and hold it so that the protruding slot is on the right. Push the other encoder sensor through the first slot on the left. Note that the front of the sensor (marked “A 20L”) is facing to the right.

Assembling right encoder

Loop the sensor and push it through the second (middle) slot. The “A 20L” marking should now be facing to the left.

Through the middle slot

Once more, push the sensor through the protruding slot on the right. Carefully pull the wires so there is no more slack in the mount. Make sure the whole sensor can be seen coming out of the final slot and the markings “A 20L” is pointing away from the mount (to the right in the picture).

Assembled right hall effect sensor

Snap the assembled encoder mount into the back-left vertical slot of the Bottom Chassis Plate (A). Note that the hall effect sensors are facing to the outside of the chassis.

Hall effect sensors on chassis

2. Motors and Wheels

The motors add some motion to the RedBot by turning the nice, rubbery wheels.

NOTE: If you completed the previous Wheel Encoder (SIK) step, your motors will each have an encoder magnet plate attached to their rear shaft. However, they are not necessary to complete this step.

Locate the Following:

2x Front Motor Mount (C)2x Rear Motor Mount (D)2x Motor (K)
Front motor mountRear motor mountMotor
2x Wheel (L)
Wheel

Attach Rear Motor Mounts

Hold the wires close to the middle of the Motor (K), and carefully slide a Rear Motor Mount (D) over the top of the motor.

Attaching rear motor mounts

Twist the Rear Motor Mount so that it snaps in place on the motor and the wires are centered in the grove of the motor mount.

Twist rear motor mount into place

Repeat the process for the second motor.

Both rear motor mounts on the motors

Attach the Front Motor Mounts

Slide a Front Motor Mount (C) onto the protruding eyelet on the front of a Motor (K). Ensure the rounded sides of the motor mounts are facing the same way.

Front motor mount

Repeat the process for the second motor.

Attach all the mounts!

Add the Motor Assemblies

Snap one of the motor assemblies into the left 2 horizontal slots of the Bottom Chassis Plate (A). Make sure that the rounded edges of the motor mounts and the wires are facing the inside of the RedBot.

Left motor attached

Snap the other motor assembly into the right 2 horizontal slots of the Bottom Chassis Plate (A). Make sure that the rounded edges of the motor mounts and the wires are facing the inside of the RedBot.

All the motors attached

Attach the Wheels

Slide one Wheel (L) onto the plastic shaft of a motor (K). Make sure to line up the inside notches of the wheel to the motor shaft notches.

Alide on a wheel

Repeat with the other wheel.

Ready to roll

3. Line Follower

In this section, you will be putting standoffs on the RedBot Sensor - Line Followers. Then you will add the sensors to your chassis.

Locate the Following:

1x Line Follower Mount (I)1x Line Follower Mount Plate (J)3x Line Follower Board (Q)
Line follower mount mountFront motor mount plateLine follower board
3x 3-Wire Jumper Cable (Y)
Jumper cable>

Construct the Line Follower Assembly

Attach the 3 Line Follower Boards (Q) to the Line Follower Mount (I) such that the rectangular pegs in the Line Follower Mount poke through the mounting holes in the Line Follower Boards. Make sure the sensors are facing away from the clip of the mount.

Line follower boards on mount

Place the Line Follower Mount Plate (J) on top of the Line Follower Mount (I) so that the center clip of the Line Follower Mount is poking through the center slot of the Line Follower Mount Plate.

Plate on top of line follower boards

Attach the Cables

You will need to connect a 3-Wire Jumper Cable (Y) to each of the Line Follower Boards (Q). Note the color of the wire attached to each pin.

Line Follower Connections:

Jumper Wire ColorRedBot Sensor - Line Follower
BlackGND
RedVCC
WhiteOUT

Attach all 3 cables to the 3 Line Follower Boards.

Attach cables to line follower boards

Add the Line Follower Assembly

Snap the line follower assembly into bottom of the front horizontal slot of the RedBot. Route the cables through the large hole in the bottom plate.

Line follower boards added to chassis

4. Mechanical Bumpers (SIK)

Read on if you have the SIK for RedBot or are using the Mechanical Bumpers. If not, skip to the next section.

You will need to prepare the music wire by bending the wire itself. Then, you will add standoffs and screws to your mechanical bumpers, followed by adding the mechanical bumpers to the RedBot chassis.

Locate the Following:

1x Top Chassis Plate (B)2x Bumper Board (T)2x Bumper Whisker (U)
Top chassis plateBumper boardLine follower mount mount
6x #4-40 x 3/8" Screw (V)2x #4-40 Nylon Standoff (W)2x #4-40 Hex Nut (X)
ScrewStandoffNut
2x 3-Wire Jumper Cable (Y)1x Phillips Screwdriver (AB)
Jumper cableScrewdriver

Prepare the Mechanical Bumpers

Using a Phillips screwdriver (AB), screw a #4-40 x 3/8" screw (V) and #4-40 hex nut (X) to one of the two large mechanical bumper holes.

Screw and nut in one side of bumper

Time to bend the whisker! It is easy to bend the whisker with needle nose pliers. However, there is a trick to bend the whisker using the mechanical bumper PCB itself. First, stick one of the whiskers (U) through one of the smaller side holes. It only needs to stick out a little bit.

Wire through hole

Bend the whisker 90 degrees.

Benting the wire

Bend the whisker 90 degrees again.

Benting the wire even more

Now that the whisker is bent, take the wire out of the PCB hole. Add a #4-40 x 3/8" Screw (V) from the bottom, and loop the bent whisker around the screw. It is very important that you do not let the whisker touch the other side’s #4-40 hex nut or screw, since that is what triggers the sensor. Leave a little space between the wire and other side’s nut.

Wire looped around screw

Twist a #4-40 nylon standoff on top of the screw to secure the wire.

Adding standoff

Double check that the wire does not touch the other side’s #4-40 hex nut and #4-40 x 3/8" screw.

Do not let the wire and the nut touch

Do this for the other mechanical bumper. Take note of which side your #4-40 x ¾" standoff is on for the first mechanical bumper. Do the opposite for the other bumper. Double check that there is one mechanical bumper that has a #4-40 x ¾" standoff on the right side of the “RedBot Bumper” silkscreen and one that has a #4-40 x ¾" standoff on the left side.

Do the opposite for the other music bumper

Add the Bumpers

Locate the horizontal slot on the front of the Top Chassis Plate (B).

Front slot

Using two #4-40 x 3/8" Screws (V), tighten down the bumper assemblies with the two wires pointing in opposite directions on the bottom side of the top chassis plate. The mechanical bumpers' header pins should be pointing toward the chassis piece.

Screwing in bumper boards

Attach the Cables

You will need to connect a 3-Wire Jumper Cable (Y) to each of the Bumper Boards (T). Note the color of the wire attached to each pin.

Bumper Connections:

Jumper Wire ColorRedBot Sensor - Line Follower
BlackGND
RedVCC
WhiteOUT

Attach both cables to the 2 Bumper Boards.

Cables attached to bumper boards

Route the cables through the left and right oval cutouts, respectively.

Cables through cutouts

5. Chassis

With the motors and a few sensors attached, we can assemble the main body of the robot.

Locate the Following:

4x Side Strut (E)1x Nub Caster (M)
Side strutNub caster

You will also need the Top Chassis Plate and Bottom Chassis Plate assemblies, which have any additional parts and sensors you attached in previous steps.

Attach the Nub Caster

Snap the Nub Caster (M) into the slot on the back of the Bottom Chassis Plate assembly. Make sure the Nub Caster is on the side opposite the motors (the bottom side).

Adding the ball caster

Add the Side Struts

Snap the four Side Struts (E) into the diagonal slots on the four corners of the Bottom Chassis Plate assembly.

Adding the side struts

Route the Cables

Position the Top Chassis Plate assembly over the Bottom Chassis Plate assembly. Route the wires and cables through the left and right oval slots in the Top Chassis Plate assembly as shown. Note that SIK-only cables are listed with an asterisk (*).

Cable Routing:

Cable ConnectionOval Side
Left Bumper Sensor*Left
Right Bumper Sensor*Right
Left Line FollowerLeft
Middle Line FollowerRight
Right Line FollowerRight
Left Motor wires (red and black)Left
Right Motor wires (red and black)Right
Left Wheel Encoder*Left
Right Wheel Encoder*Right
* Indicates parts included in the SIK for RedBot

Cables through cutouts

Attach Top Chassis Plate Assembly

Carefully snap the Top Chassis Plate assembly onto the side struts and motor mounts. If you have the Bumpers installed, make sure the boards are between the top and bottom plates.

Snap top plate to side struts

6. Mainboard

In this section, you will add brains of the robot: the RedBot Mainbooard.

Locate the Following:

2x Mainboard Mount (G)1x RedBot Mainboard (P)
Mainboard mountRedBot Mainboard>

You will also need the full chassis assembly, which contains any additional parts and sensors you attached in previous steps.

Attach the Mainboard Mounts

Snap the two Mainboard Mounts (G) into the vertical slots in the back of the top chassis plate.

Add mainboard mounts

Add the Mainboard

Snap the Mainboard (P) into the lowest of the notches on the Mainboard Mounts (G). Make sure the power jack is facing the left side of the robot.

Add the mainboard

Connecting the Cables

It is time to connect the jumper wires; it’s really important that the connections are right.

Pin Out

You can follow along with the pin out tables or scroll down for a Fritzing diagram. If you have the RedBot Kit, you do not need to connect the sensors from the SIK. Sensors for the SIK will be marked with (SIK).

Please note: When you have the RedBot upright and the front of the chassis facing away from you, “left” sensors/motors will be on the left side and “right” sensors/motors will be on the right side.

RedBot directions

Left Line Follower:

RedBot Mainboard PinsJumper WiresLeft Line Follower Board
A33-Wire Jumper Cable - WhiteOUT
5V3-Wire Jumper Cable - RedVCC
GND3-Wire Jumper Cable - BlackGND

Middle Line Follower:

RedBot Mainboard PinsJumper WiresMiddle Line Follower Board
A63-Wire Jumper Cable - WhiteOUT
5V3-Wire Jumper Cable - RedVCC
GND3-Wire Jumper Cable - BlackGND

Right Line Follower:

RedBot Mainboard PinsJumper WiresRight Line Follower Board
A73-Wire Jumper Cable - WhiteOUT
5V3-Wire Jumper Cable - RedVCC
GND3-Wire Jumper Cable - BlackGND

Left Mechanical Bumper (SIK):

RedBot Mainboard PinsJumper WiresLeft Bumper Board
33-Wire Jumper Cable - WhiteOUT
POW3-Wire Jumper Cable - Red5V
GND3-Wire Jumper Cable - BlackGND

Right Mechanical Bumper (SIK):

RedBot Mainboard PinsJumper WiresRight Bumper Board
113-Wire Jumper Cable - WhiteOUT
POW3-Wire Jumper Cable - Red5V
GND3-Wire Jumper Cable - BlackGND

Left Motor:

RedBot Mainboard PinsLeft Motor Jumper Wires
LEFT MOTOR - REDSoldered on Motor Jumper Wire - RED
LEFT MOTOR - BLACKSoldered on Motor Jumper Wire - BLACK

Right Motor:

RedBot Mainboard PinsRight Motor Jumper Wires
RIGHT MOTOR - REDSoldered on Motor Jumper Wire - RED
RIGHT MOTOR - BLACKSoldered on Motor Jumper Wire - BLACK

Left Wheel Encoder (SIK):

RedBot Mainboard PinsJumper WiresLeft Wheel Encoder
A23-Wire Jumper Cable - WhiteOUT
POW3-Wire Jumper Cable - Red5V
GND3-Wire Jumper Cable - BlackGND

Right Wheel Encoder (SIK):

RedBot Mainboard PinsJumper WiresRight Wheel Encoder
103-Wire Jumper Cable - WhiteOUT
POW3-Wire Jumper Cable - Red5V
GND3-Wire Jumper Cable - BlackGND

Fritzing Diagram

How to connect the RedBot Mainboard

Look at all those connections! Having a hard time seeing the image? Click on the Fritzing image to see a bigger diagram.

7. Accelerometer

Time to add the RedBot accelerometer! If you do not have headers on your accelerometer already (older revisions of the RedBot accelerometer did not have headers), we recommend soldering on female headers to your accelerometer to fit on top of the RedBot Mainboard’s headers.

Locate the Following:

1x Accelerometer Board (R)
RedBot Accelerometer

Add the RedBot Accelerometer

Locate the SENSOR port with “A4” and “A5” marked on the RedBot Mainboard. Line up the “A4” pin on the accelerometer to the “A4” male header pin on the RedBot Mainboard, and attach the Accelerometer Board (R).

Adding the accelerometer to the RedBot

8. Buzzer (SIK)

Read on if you have the SIK for RedBot or are using the RedBot Buzzer. If not, skip to the next section.

Adding the RedBot Buzzer is nice and easy!

Locate the Following:

1x Buzzer Board (S)
RedBot Buzzer

Add the RedBot Buzzer

Locate the SERVO port with “9” marked on the RedBot Mainboard. With the buzzer and female header side of the Buzzer Board (S) facing to the left, place the Buzzer Board on top of the “9”, “POW”, and “GND” male header pins.

Adding the buzzer to the RedBot

9. Batteries

We need to give some power to the RedBot. If you do not have the SIK for RedBot, you will need to provide your own AA batteries.

Locate the Following:

1x Battery Pack Clip (H)1x Battery Holder (Z)4x AA Batteries* (AA)
Battery pack clipBattery packBattery
* Provided in the SIK for RedBot

Insert Batteries

Insert the AA batteries into the Battery Holder (Z). Makes sure the batteries are facing the correct direction, as per the markings inside of the Battery Holder.

Insert AA batteries

Attach Battery Pack

Insert the Battery Holder (Z) with batteries into the back cavity of the RedBot. Have the barrel jack cable facing to the left of the robot.

Instert battery pack

Insert the Battery Pack Clip (H) on top of the battery pack.

Insert battery pack clip

Twist the clip so that it rests on top of the battery pack.

Attach battery pack clip

Push the clip down into the vertical slots in the Bottom Chassis Plate so it snaps in place.

Snapping battery pack clip into the RedBot

Route the barrel jack cable out of the left side of the RedBot and up to the Mainboard. Plug it into the barrel jack adapter labeled V_IN.

Plug in the batteries

Changing the Batteries

If you find that you need to replace the batteries in the RedBot, the process is simple. Unplug the battery pack from the Mainboard.

Unplug batteries

Turn the RedBot over and push on the Battery Holder through the hole in the Bottom Chassis Plate. This will cause the Battery Pack Clip to unsnap from the Bottom Chassis Plate.

Push on battery pack to unsnap it

Slide the Battery Pack and Clip out from the back of the RedBot.

Remove battery pack and clip

Change the batteries, and follow the steps in Attach Battery Pack section above to put the Battery Pack back in the RedBot.

Resources and Going Further

What a rock star! With all that building, we bet you are ready to start cruising. We recommend continuing to the Experiment Guide for RedBot with Shadow Chassis to learn how to program your new robot friend.

New!

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 familiar with our SparkFun Inventors Kit and want to take their robotics knowledge to the next level.

Upgrades

You might have noticed some odd-looking hole patterns in the top plate and side struts. The RedBot’s chassis is manufactured to accept Actobotics parts. Feel free to add other mounts, gimbals, servos, and claws!

Actobotics upgrades!

Resources

GitHub repositories:


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

SD Cards and Writing Images

$
0
0

SD Cards and Writing Images a learn.sparkfun.com tutorial

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

Introduction

This tutoril is designed to give you a basic understanding of SD Cards and how to write different images to the SD card of your choice.

SD cards, short for Secure Digital, are everywhere you look now, from digital cameras, to phones and tablets, and even Single Board Computers (SBCs). In many cases your SBC won’t come with Linux or any other operating system on it. It is up to you to provide the OS on an SD card. With the exception of Noobs for Raspberry Pi, this is usually not a drag and drop procedure.

In this tutorial, we are going to talk about different types of SD cards and readers, formatting your card to erase any data that may be lurking around, installing your image, and then how to use any left over space on the card.

alt text

Single Board Computers, such as the Raspberry Pi, use SD and microSD cards to house various operating systems. Pictured here: a microSD card with full-size adapter.

Required Materials

To follow along with this tutorial, you will need an SD card, and a card reader (see related sections for more information on different types). You will also need a computer and an Internet connection (if you don’t have all the software and your image already on your computer). Last, you’ll want your SBC or whatever device into which you are installing your card.

Recommended Reading

There is no one best place to start when it comes to single board computers. However, you may find these links useful in your SBC adventure.

SD Cards

SD Cards can be found most everywhere, online, at your local store. But whats sets one apart from the rest? What makes a good SD card? Besides manufacture, the main differences between cards are physical size, capacity/standards, and speed. Here is a brief overview of each of those elements.

Size

SD cards come in two main sizes. Full sized SD cards are used in digital cameras all over the globe, and microSD (often called µSD or uSD) cards are used in cellphones and tablets, amongst others. Electrically they are the same thing, though. Ever notice the cheap plastic adapters that come with some microSD cards? They are nothing more than a plastic shell with connectors to pass through the microSD connectors to the full size connectors. Installing images on them is the same, just make sure you have the right card (and adapter, if needed) for your device and reader.

Standards

There are actually 4 different standards of SD card, with each new version came higher capacity and often higher speeds. The 4 versions are: Standard or SD (up to 4GB), High Capacity or SDHC (up to 32GB and formatted as FAT32), Extended High Capacity or SDXC (up to 2TB and formatted as exFAT), and SDIO (has support for I/O). Any of these should work but be careful with SDXC cards; because of licensing issues, not all devices can support exFAT.

Speed

Most cards will also list a class or speed on them to distinguish how fast they can read and write. Class 2,4,6,8 and 10 are 2MB/s, 4MB/s, 6MB/s, 8MB/s, and 10MB/s, respectively. UHS Class 1 and UHS Class 3 are 10MB/s and 30MB/s, respectively. For the most part, these numbers are irrelevant; just keep in mind that there are different speeds so if things are running slower than you’d like, check the card.

For this tutorial, any of these cards will work with. However, make sure you have the correct physical size for your device, and the the card has a high enough capacity to hold the image you want to use. This 8GB card should work for just about everything since it has an SD adapter as well as a card reader.

SD cards, uSD cards, uSD adapters, and Wifi enabled SD card

SD cards, uSD cards, uSD adapters, and Wifi enabled SD card

Card Readers

You can find almost as many SD card readers as SD cards but there really aren’t that many differences.

Your local computer store, or even conveinence store will most likely have at least one USB adapters. If your computer doesn’t have one there are plenty of choices available for adapters, for the most part these will connect to your computer over USB. Some will do just uSD, uSD and SD or, a whole bunch of different card types. Any of these should work fine for our examples.

Most laptops and even some desktops now have direct slots in them to read and write SD cards. Often these are directly connected to the USB port inside your machine, making them the same as the USB adapters, but not always. These should work just fine for our examples, but if you are having problems try a USB adapter.

Most cameras now use SD cards and can be plugged into your computer via a USB cable. For the most part the data is going through the camera and not being read directly from the computer. For that reason this will not work for our examples, this is true for phones and other devices as well. Basically if your device has a name other than “SD adapter” it probably won’t work.

For this tutorial you will need either an SD slot in your computer or a USB adapter. Make sure it fits the size card you have or you have the appropriate adapter. This 8GB card should work for just about everything since it has an SD adapter as well as a card reader.

A few different SD and uSD card readers

A few different SD and uSD card readers

Formatting your card

We are going to start with formatting your SD card. This step is not strictly necessary, but it does help clean off your card. In some cases if something has gone wrong this will help clean up the mess instead of bring the mess with you.

Always be careful when doing this, it will erase everything on your card, so make sure you are OK losing everything on the card. Also, make sure you select the correct drive! Alternately the tools used to change partition size will also format any card or partition. If your card has been partitioned because it already has an image on it, see the last section on resizing and deleting partitions.

Windows

The SD Association has a formatter that is designed to work with both Windows and Mac that they recommend, you can try it or use the following directions - SD Card Formatter

  • Open “My Computer”
  • Right click on the drive with the SD card
  • Select “Format”

alt text

  • Select your file system (FAT32 works fine)
  • Feel free to name your card in “Volume Label”
  • Quick Format is not quite as thorough but a bit quicker, either option is fine
  • Select “Start”

alt text

Mac

The SD Association has a formatter that is designed to work with both Windows and Mac that they recommend, you can try it or use the following directions - SD Card Formatter

  • Open the Disk Utility (Applications -> Utilities ->Disk Utility)
  • Select the SD Card
  • Select the “Erase” tab
  • Select your file system - MSDOS(FAT)
  • Feel free to name your card in the “Name” field
  • Select “Erase”

alt text

Linux

  • Run Gparted (you may need to install it first using sudo apt-get install gparted)
  • Select the correct device from the drop down menu on the top right
  • Select Partition → Format to → fat32
  • Click Apply

alt text

Downloading and Installing the Image

Finally, this is what we’ve been waiting for. So, why can’t you just copy the file onto the card? When you look at the SD card you actually don’t see all the bits on the card, you just see the main storage area. There are other parts that allow the card the card to be bootable, and this is what needs to be written. While you can do that by hand and then add all the files you need, generally your files are released as an image that has all the information in it. This way you can make the disk bootable and add the files all in one easy step. Just like formatting your SD card, this will erase everything on it. Make sure you want to do this and you select the correct disk.

Downloading the image

Start by downloading the image you want to use, and don’t forget to extract your image so you have a *.img file. Here are some files for a few common boards; notice there are often different downloads available. You will find different Linux distributions, Android images, and even different images depending on the display you want to use. Pick the one that best works for your application, and remember, you can always go back and pick a different one.

  • Raspberry Pi (Noobs install is done differently follow the directions on the Raspberry page) - Downloads
  • PCDuino 3 - Downloads
  • Acadia - Downloads

Windows

  • Download and unzip Win32DiskImager
  • Run Win32DiskImager.exe (you may need to run as Adminstrator)
  • Select the drive of your SD card
  • Click the folder icon and select the image you downloaded
  • Click “Write” and wait until it is done

alt text

Mac

  • Run diskutil list to display all disks, find the correct disk
  • Run diskutil unmountDisk /dev/disk4 to unmount the disk (replace disk4 with the correct disk)
  • Run sudo dd bs=1M if=your/file/here.img of=/dev/disk4 (again replace disk4 with the correct disk, and add the correct path to your image)
  • Wait until it is done

alt text

Linux

  • Run df-h to see what devies are mounted on your system, you may want to do this without the card in and then with the card in.
  • Take a look at the card name on the left column. There will most likely be a number at the end, this in the partition number. In the example below my card /dev/sdd has 1 partition (/dev/sdd5). You may also have more than 1 partition on your card, keep that in mind if you do.
  • Unmount any partitions you see using the command umount /dev/sdd5 where /dev/sdd5 is the partition on your card.
  • Next run the following command to actually write to the card, keep in mind you will need to know where your image is and you will want to use the path to the card without any partition numbers on the end. You may or may not need to run this as “sudo” depending on your permissions dd if=2015-05-05-raspbian-wheezy.img of=/dev/sdd (make sure to use the correct path to your file and your SD card)
  • Wait… this will take a few minutes, there is no status bar, but even on a live Linux distro this only took a couple of minutes.
  • Run sync (this will flush the write cache, and other fancy things)

alt text

Resizing the partition

At this point you should have a working bootable SD card, feel free to stop here. Sometimes though you go grab that 16GB card you have lying around, burn a 1GB image and then think, well that’s silly, I’ve lost 15GB of space! Now we are going to change partition sizes around so that the remainder of your card shows up as a separate partition that you can still use for storage. Before we start you may want to boot your card and take a look around, many distrobutions have a built in utility to do this. You can also use these programs to resize the partition if you’d rather.

Keep in mind that Windows can only read the first partition, so you will not be able to use this as general storage if you use a Windows device. But you can use it as storage on your Linux based Single Board Computer (SBC).

This is also a good way to get your SD card back to the original full sized partition if you no longer want to use it on your SBC. You wil need to delete all partitions, then make a new one and format it.

Most of these programs actually have very similar layout and directions, and there will be plenty of other options available online as well.

All Windows

  • Newer versions of Windows have a partition manager built in (see below), but for older versions of Windows or a more full featured partion manager try EaseUS Partition Manager
  • Download EaseUS Partition Manager
  • Unzip, and run the program
  • Select the Disk in the upper part of the window
  • You should see a graphical representation of the partitions in the bottom half
  • Depending on the image you installed, you may have various options. Any unallocated space can be turned into a new partition and formatted. You can also take the last partition and resize it so it takes up the rest of the card.

alt text

  • Make sure you apply your changes (check mark in the toolbar on top). This applies all changes you make to the card.

Windows Vista,7,8

  • Open Control Panel
  • Type Partition into the search box
  • Select the option “Create and format hard disk partitions”
  • Select the Disk in the upper part of the window
  • You should see a graphical representation of the partitions in the bottom half
  • Depending on the image you installed, you may have various options. Any unallocated space can be turned into a new partition and formatted. You can also take the last partition and resize it so it takes up the rest of the card.
  • Make sure you apply your changes (check mark in the toolbar on top), this applies all changes you make to the card

Mac

  • Depending on whether your image uses a Windows based file system or not, this may or may not work. If you are having problems try these alternatives.
  • Open the Disk Utility (Applications -> Utilities)
  • Select the SD Card
  • Select the “Partition” tab
  • Click the “+” in the bottom left corner to add a partition
  • Select the partition and drag the bottom right corner to resizse
  • Click Apply

Linux

  • Run Gparted (you may need to install it first using sudo apt-get install gparted)
  • Select the correct device from the drop down menu on the top right
  • Depending on the image you installed you may have various options. Any unallocated space can be turned into a new partition and formatted. You can also take the past partition and resize it so it takes up the rest of the card.
  • Make sure you apply your changes. This applies all changes you make to the card.

alt text

alt text

Resources and Going Further

Now that you know how to install an image on an SD card, it’s time to egt out there and create some great SBC projects. Need some inspiration? Check out thses other related tutorials from SparkFun.

Check out these other SD card-related projects as well.


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

How to Sell Your Widget on SparkFun

$
0
0

How to Sell Your Widget on SparkFun a learn.sparkfun.com tutorial

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

Choose Your Adventure

Have an awesome electronic widget that you want to get to market? Great! We are always listening to new ideas from our customers and the community. We get many inquires on this topic, so read this tutorial carefully to keep your product pitch from getting lost in the shuffle.


We’re lucky, here at SparkFun, to have an amazingly creative and talented group of customers. Not only can they identify gaps in the catalogs of electronics suppliers, they can create a gizmo that fills that hole. But, going beyond a prototype or even a limited-quantity production run, often the hardest task in getting your world-alterring product out there is producing, marketing, and/or selling it to the masses. That’s where we come into the picture. We recognize that there comes a certain benefit to having your product in our catalog and we want to give you the best chance to have that. However, the partnership needs to make sense for both parties (maybe more parties) involved.

We strive to keep the SparkFun catalog of products curated. A selection of products that help get your project completed that we would use ourselves. So regretfully we cannot take all products brought to us. Below we have outlined what we look for, how we can possibly work together, and the steps to take in order to properly submit your product for evaluation.

SparkFun aims to sell parts and boards pertinent to DIY electronics. This may touch on areas relating to education, prototyping, and product design. Among the reasons for stocking certain products, we look for things that are helpful, cutting edge, useful in a broad spectrum, and appealing the community. We want products that make things easy for the user, but at the same time, do not constrain the possible uses for the product.

(An older image of) the SparkFun Team

Over the years SparkFun has helped to bring dozens of unique widgets and useful electronic shortcuts – dreamt-up and designed by our customers – to the throngs of electronics hobbyists, artists and students. A few examples include:

We’ve gone through this process enough to know how to guide any product through it. The goal of this tutorial is to walk you through two of the most common routes previous collaborators have followed in getting their widgets sold on SparkFun. Which route you choose mostly depends on who is manufacturing your product. Time to choose your adventure:

Option 1: You Manufacture, SparkFun Buys and Resells

Have you already set up a manufacturing process for your design? Whether you’re cooking the boards in your basement reflow toaster, or working with an established assembly house, we might be interested in reselling it. What really matters is that you have a solid, tested design, a manufacturing process set up for it, and a market starving to buy it.

Hundreds of products in the SparkFun catalog go through this process, including pcDuino3 and BITalino - BioMedical Development Kit. It’s the fastest route to our storefront, if that’s what interests you the most.

Check out this half of the tutorial to find out more about how to pitch your product.

Option 2: SparkFun Manufactures, and Pays You a Royalty Per Sale

Have you prototyped your design, and proven that it works, but gotten stuck trying to produce and sell it? Well it just so happens that we have pick-and-place machines, reflow ovens, and a all-star production team that can help with manufacturing. Plus, our engineers can help polish the design along the way.

The best part about this option is you still get paid. Instead of buying the products up-front, we pay you a percentage-based royalty per product sold.

We do have limited production and design resources, so there’s no guarantee that we can take your product on. But if it’s unique enough, and fits within our manufacturing abilities, we’re certainly interested in working with you to help productize your widget.

Products like the MaKey MaKey, WAV Trigger, and EasyDriver have all gone through this process, and are now some of the highest-selling, most important products in our catalog. Check out this section of the tutorial to learn more about how to pitch your design.


So, it all begins by figuring out who’s producing the widget. Read on to learn more about each option. At the end is a form you can use to submit your project/product/idea for review. Please read the entire tutorial before submitting as there is very pertinent information involved.

Option 1: You Manufacture, SparkFun Resells

This option is great for those who already have the resources to support manufacturing. In this relationship, SparkFun assumes the responsibilities of storefront management, inventory storage, shipping, and customer service. You, on the other hand, deal with manufacturing and assume all the risks inherent to that. This allows you to have more control over your product (revisions, pricing, documentation, etc).

A great example of this relationship in action is the pcDuino.

pcDuino 3

The pcDuino is designed and manufactured by our friends at LinkSprite. They support a community, publish the documentation, and handle all manufacturing, but aren’t as interested in hosting a storefront. So we resell it! As a bonus, the end-customer can save on shipping (or get it for free) when resistors, batteries, switches, and other components are inevitably added to the order.

Division of Responsibilities

Here’s an overview of who does what in this relationship:

Venn diagram of responsibilities

SparkFun’s Responsibilities

To help store, sell, ship, and market your product, we have a great group of talented employees canvassing a wide variety of skills. Here are the roles we’ll take sole ownership of in the relationship:

  • Purchasing Your Product– To begin, our purchasers can work with you to work out prices, payment methods, and inbound shipping requirements. We’ll need a decent distributor margin to give us room for our distributor and education pricing. We’ll work out those details in an email.
  • Storing Your Product– Once we bring the product in, we’ve got a warehouse equipped to store it until it sells.
  • Managing Storefront– We’ll post up a product page with all of the relevant descriptions and documentation-links to the product.
  • Shipping Your Product– Once the order comes in, we’ll grab it from the inventory shelves and ship it away.
  • Customer Service– If there are any problems before or after an order, our customer service team can help sort it out.
  • (First Level) Tech Support– Our crack technical support team can field initial tech questions (via email, chat, or phone calls), but we may have to refer the tough ones to you.

Your Responsibilities

  • Manufacturing– In this relationship, you’ll manage all of the part sourcing, manufacturing, and assembly responsibilities. That includes testing the product for complete functionality.
  • Keeping Supply Up with Demand– Some of the greatest products are sunk because they can’t stay in stock. We want to keep your product in stock as much as possible, so we’ll work with you ahead of time to understand the lead times of your product.
  • Documentation– Products that are well-supported, by datasheets, user’s manuals, and tutorials, really stick out to us. This is a load we’re willing to share (see below), but the most attractive products to us are those with the proper documentation to support them.
  • Replacements– No test procedure is perfect. Even the most battle-tested products may have a hidden flaw, and our customers will find it. If a defective product is discovered, we’ll lean on you to help replace it. (But the first defense is tech support. See below.)
  • Sticking Around– Whether your product needs future firmware updates or customer support, we need to be able to stay in contact with you for the long term.

Shared Responsibilities

This is still a team effort. You’ve got a product that you love and want to see in the hands of as many users as possible. And we want to help get the word out and move some product! Here are some duties we might share in our quest:

  • Marketing– We both want to see your product sell. We’ll pitch in on getting the word out, but we’ll need your help too.
  • Documentation/Tutorials– Generally we’re looking for products that are already well-supported through tutorials, datasheets, and user’s guides. We’re always excited about playing with new toys and documenting our experience, though – so we can help out with tutorials here and there.
  • Technical support– We can handle first level calls and emails. For the real brain-stumpers, we’ll refer customer questions to you, the all-knowing-product-creator.

Crowdfunded? Crowdfunding?

Many products in our catalog were born out of a crowdfunding website, like Kickstarter or Indiegogo. We’re happy to work with you, if your product is on this path, but there are a few caveats.

If you aim to approach us with a crowdfunded product, it’s best to do so after it’s been funded, or at least while it’s on a trajectory to be funded. But, most important of all, we need to know ahead of time how far out your product is from shipping. Obviously this is a sticking point for a lot of crowdfunded projects.

If your product failed to meet its crowdfunding goal, we might be able to work together to still make it a reality. Check out the next page to see how we can collaborate to produce your widget.

Option 2: SparkFun Manufactures, You Get a Royalty

This option is great for those looking to steer clear of the hassles of organizing manufacturing and generally running a business. We’ll keep in contact with you about further revisions or changes to your design, but we deal with the manufacturing risks. We buy the parts and the PCBs to build your widget. We monitor demand and order stock to meet it. Doing this we can often significantly reduce the cost of the BOM (bill of materials), and produce a reliable, steady supply of your widget.

An example of this relationship is the WAV Trigger. The hardware and firmware was spearheaded by Jamie Robertson with one of our engineers guiding the design to help leverage the SparkFun manufacturing process.

WAV trigger

We generally prefer Open Source Hardware designs for this relationship. Almost always those designs will be published under the creative commons license, so please take a look and decide if this is ideal for you.

Division of Responsibilities

Our load is much heavier in this relationship, but we still need some help from you. Here’s an example of what we’ll be doing, what we expect from you, and what duties we’ll share in:

SparkFun’s Responsibilities

  • Part Sourcing, Manufacturing, and Testing– We’ll handle everything that goes into manufacturing and assembling your product. From ordering PCBs, resistors, IC’s and other components, to stuffing the boards, and testing for complete functionality. These are company skills in which we place a lot of pride.
  • Managing the Storefront, and Shipping Orders– Just as any other product, your widget will get its own product page, and can be ordered via our online retail system.
  • Paying You a Percentage Royalty Per Product Sold– Before the product goes live, we’ll find an agreeable percentage royalty to pay you per product sold. Then sit back as we send you quarterly checks.
  • Customer Service and Technical Support– Our customer service team will tackle all of the customer’s order-specific questions. Our ace technical support crew will be trained up on your widget, and help answer any technical questions. Should it be necessary, we’ll handle replacements or returns.

Your Responsibilities

  • Initial Design (Prototype)– Come to us with as much information and tested hardware as you can. Usually we like to see at least an initial round of prototyped PCBs. We can work together from there to bring your product fully into the fold.
  • Keeping in Contact– We expect your product to be around for a while, and as long as it’s around we need you to be there too. For the product’s lifetime, we’ll need you to stay in contact for any questions or revisions that might come up.

Shared Responsibilities

  • Designing for (SparkFun) Manufacturing– More on this in the next section. We’ll assign one of our talented engineers to help create a SparkFun manufacturing-friendly design based as closely-as-possible on your original design.
  • Documentation– At the bare minimum we’ll want to release a hookup guide alongside your product. We can work together to help make this happen. We’re happy to help publish and create more content as required.
  • Getting the Word Out– Our marketing team will help let the world know about your product. We hope you will too!

Collaborative Design Process

Since we’ll be the ones manufacturing the board, there are certain design-for-manufacturability adjustments we usually like to make in order to keep costs down and production times minimal. These changes include:

  • “Scrubbing” the Bill-of-Materials (BOM)– We’ll look for minor BOM adjustments that allow us to use parts we already have in production stock rather than sourcing a new component. For example, we may want to swap out your TC1185 voltage regulator with a nearly-compatible (already in house) MIC5205. Or (assuming it doesn’t break anything) try to use a 2.2kΩ resistor instead of the 2.1kΩ you’ve spec'ed out.
  • PCB Layout Adjustments– We’ll want to use part footprints from our EAGLE libraries, and we may want to tweak some component placements to give the pick-and-place machines some breathing room.
  • Test Procedure Considerations– Every one of our boards is tested for complete functionality, in one way or another. On some designs this means adding test points, on others it means working in some test code under the hood of your firmware.

To help implement these DFM adjustments, one of our talented engineers will be assigned to work with you on bringing it in house. No matter what, we’ll work and communicate with you along the way to make sure our changes don’t alter your vision of your product.

As a result of the “design scrub”, this option takes longer than the previously mentioned route. We’ll go through at least one prototype round of the design to iron out any production issues, and just make sure the thing works as intended. If you want to get a head start, and make things go a little more smoothly, try design your product to follow as many of our design rules as possible. Check out the next page for more details on that!

Designing for (SparkFun) Manfuacture

The schematic and PCB designs are the heart of most SparkFun products. Over the last 10+ years, we’ve designed hundreds of unique PCBs, and produced millions of widgets, so we know what adjustments to the design will make our production process flow as smoothly as possible.

Those adjustments have found their way into a loose set of rules that we know to follow, but you might not. Designing your product with these rules in mind will give you a head start, and it’ll also make your product pitch more attractive to us. The less work we have to put into scrubbing your design, the faster we can start building and shipping it!

  • Design your PCB in EAGLE– The collaborative process is easiest if we’re both speaking the same EDA language. There are dozens of design tools out there, but we’ve gotten really accustomed to EAGLE. If you’re not familiar with the software, consider checking out some of our tutorials for help getting started.
  • Use our EAGLE libraries– By using our set of EAGLE footprints and parts, you’re better assured that the parts in your design will also be on our inventory shelves. You’ll also be using the footprints that our quality-assurance team has painstakingly crafted to help optimize AOI and other testing.
    • Unless your part is a kit, aim to use as many surface-mount (SMD) parts as possible. Our production team is most efficient, when they’re letting the pick-and-place/reflow oven combo do most of the busy work.
    • For common passives (resistors, capacitors, etc.), try to us 0603 parts or bigger (0805, 1206, …).
    • If a part has multiple footprints, and you’re unsure of which one to use, consider checking the Eagle files of one of our live boards and comparing against that.

PCB Design Specifications

In as many designs as possible, we try to keep our board layouts within this set of specifications:

PCB minimum specs

  • Minimum trace width: 0.006" (6 mil)
  • Minimum trace clearance: 0.008" (8 mil)
  • Trace-to-board edge clearance: 0.008" (8 mil)
  • Minimum via drill diameter: 0.01" (10 mil)
  • Default board width: 1.6mm

EAGLE Design Rules

Further to those minimum specifications, here are some more EAGLE-specific design rules:

  • Board Frame
    • Create the board frame on a 0.1" grid. Make the lower left corner start at (0, 0).
    • Change the line width of the board frame to 0.008"
    • Board frame will be square unless called for by special requirements of the design.
  • Grid
    • All parts are placed on a 0.005" grid. If possible, use a .05" grid.
    • Make sure all 0.1" headers are lined up on a 0.1" grid. Keep it breadboard compatible!
  • Packages
    • Use 0603 packages for resistors and capacitors.
  • Traces
    • Use 10 mil (0.010") traces in general.
    • 8 mil traces can be used when necessary, 6 mil is absolute minimum.
    • Use thicker traces (as thick as possible) on power and charging traces.
    • Keep at least 8 mil of space between traces.
    • Route with straight lines and 45 degree corners only. No right angles in trace routing, but T-intersections are okay.
    • Route from pads. Avoid routing into the pads- this causes traces to be not centered on a pad. Traces should enter and exit center of pad at 90 degree angle.
  • Pours
    • Use ground pours on the top and bottom layers.
      • Change the “Isolate” setting on ground pours to 12 mil (0.012").
  • Vias
    • If something is soldered into a hole (header, connector, prototype vias, etc), use a via with a larger annular ring so that it is easier to solder. For normal prototyping vias, use 0.04" hole with a 0.074" diameter.
    • Set the default via size to 0.020."
    • 0.010" is the smallest allowed via size. Only change from the default if absolutely necessary.
    • Via size is defined by the “Drill” parameter in the DRC.
  • Misc
    • Add a version code on the bottom copper layer, and revise the version code on every revision!
    • Use the standardized I2C layout: GND, VCC, SDA, SCL.
    • The autorouter can only be used on prototypes. Hand routing and touch-up of the autorouter is expected for production boards.

Make sure to load the Sparkfun.dru for the DRC check. Pull the most up-to-date version of the Sparkfun.dru from GitHub. Don’t use the default settings!

PCB Aesthetics (Labeling)

When the bare PCB is your product, it doesn’t hurt to dress it up and make the board look nice and polished. Here are some EAGLE-specific design rules that we follow to make our boards look as good as possible.

  • Labels
    • Label the name of the board appropriately.
    • Label any LED with its purpose (power, status, D4, Lock, etc).
    • Label all connectors (Vin, Port1, Batt, 5-9V, etc).
    • Label pins where applicable (Tx, Rx, Power, +, Charger, etc).
    • Label switches and switch states (On/Off, USB, etc).
    • Label any extra information (ie. axes on gyros, accelerometers, etc).
    • Makes sure labels are on a straight line- add a line in the tDocu layer to make sure the labels line up.
    • Text should be 0.032" minimum and 15% ratio, vector font.
  • Logos
    • Every board should have the full SparkFun logo or at least the smaller SFE Flame. Add the LOGO-SFE part to the schematic. Make sure to put this part in the lower right hand corner of the schematic.
    • Every board should have the Open Source Hardware Logo unless otherwise specified. Look for OSHW-LOGO in the library and add it to the schematic. This should go in the lower right hand corner as well.
  • Misc
    • Components that are grouped together in the PCB layout will be grouped together in the schematic. Draw boxes to show functional groups.

Pitching Your Product

Pitching a product can be a daunting task. In order to make it easier for you, we have a guide for the information we need below. Please, when pitching your product be as informative as possible. The information we get from this email will be a strong indicator of whether it is something we would be interested in. Below is an explanation of the different questions to address in your email:

  • Contact Information: Pretty self explanatory. At the very least, include a name and email address.

  • Tell us about your product/project: A description of what you are pitching. A very descriptive rundown of what your product does and how it does it. Explain everything from a very basic viewpoint. Things to include (if applicable) are the major components used, scope, time, etc.

  • What stage of development is this project in: How far along are you on this? What work have you put in thus far? Again, we only consider pitches that have at least reached the point of a working prototype or proven design.

  • How does SparkFun factor into your project: What role will SparkFun play in this? How will we benefit the project?

  • What is your target MSRP: When considering the target retail for your product, consider things such as BOM cost, distribution margin, and profit margin. If you have a pricing structure already setup, please include that with all quantity price breaks present.

  • Describe the advantages of your product compared to its closest competitors: Tell us why your product is better than similar products on the market. If you feel it is unique to the market, what products come close? Please cite examples if possible.

  • Do you have a time frame in place for this product? If so, please outline it: We recognize the benefits of a strategic launch schedule. Please be realistic in your time frame and understand at no point will your project be the sole focus of SparkFun. This part especially highlights the idea that it must make sense for both parties involved.

  • What is your projected annual sales for this product: We understand, especially with our market, that this is tough to gauge. Please provide an estimate of how many units we can expect to sell. If you have any market research to back up your number, please cite that as well.

  • Describe the manufacturing process you envision for this (how are you going to get this product built?): We like to know who you are using for manufacturing and where they are located. This helps us estimate shipping costs and possible bottlenecks. What lead times can we expect?

  • If your product requires programming, what programming language does it use? What toolchain would you suggest programming it in: A bit of an overlap of the second question, but in this question go into depth about the software aspect of the project. Are any parts not open source? Does it use specific libraries?

  • Does this product require any agency approval (UL, CE, FCC, RoHS)? If so, how do you plan on addressing that: This is a tough one. Provide an informed answer if possible. Most information is regularly available online.

  • Any additional comments: This is a good place to include the URL to any web links you think are pertinent.

Submission Email

Below is the email to send in your product pitch. Again, please include as much information as possible. Once submitted you will receive an automated email letting you know that we have received your submission. We wish we could provide a response and meaningful feedback for every submission, but it simply isn’t possible considering the volume we receive. If you don’t receive a response beyond the automated message within a month, please assume that we had to pass on your idea.

Please submit your product pitch to widget@sparkfun.com


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

Load Cell Amplifier HX711 Breakout Hookup Guide

$
0
0

Load Cell Amplifier HX711 Breakout Hookup Guide a learn.sparkfun.com tutorial

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

Getting Started

The HX711 load cell amplifier is used to get measurable data out from a load cell and strain gauge. This Hookup Guide will show you how to get started with this amplifier using some of the various load cells we carry at SparkFun.

Sparkfun's HX711 load cell amplifier breakout board

What You Will Need:

For this simple hook up guide we will just be hooking up a load cell with the HX711 amplifier, and showing how you would hook up four load cells with a combinator board and the HX711 amplifier. To follow along, you’ll need:

If you are planning on using load sensors1 you will need to obtain or purchase four units. We recommend our Combinator Board to make it easy to turn the four strain gauges into a wheatstone bridge type load cell. (Single strain gauge load cells only have three wires instead of four.)

Suggested Reading

If you aren’t familiar with the following concepts, we recommend reviewing them before beginning to work with the HX711 Load Cell Amplifier Board.

1. [Strain gauges are two wired organized metal foil or wires that are set up in such a way that the resistance changes when it is compressed or stretched. When a strain gauge is placed on something (usually metallic in nature) its resistance changes based on the stress experienced by that something. When a single strain gauge is hooked up to a metallic cell, we are calling that a load sensors, which have three output wires. Load cells usually has four strain gauges hooked up in a wheatstone bridge formation, which have four output wires. For more information on load cells, strain gauges, and wheatstone bridges see our tutorial.]

Load Cell Set Up

Four types of strain gauge load cells, two bar load cell and two disc load cells

A selection of differetn load cells

Depending on the type of load cell you are using, the configuration of how it should be hooked up to plates or surfaces will change. Below are a few different types of setups.

Bar strain gauge load cell set up in a "Z" formation between two plates

Bar load cell between a two plate configuration

S type load cell hooked up to two loops

S load cell configuration

SparkFun's strain gauge load cell combinator board hooked up to a home scale, possible configuration for four disc load cells

Possible four disc load cell configuration in something like a bathroom scale

Two bar strain gauge load cells

Bar strain gauge based load cells

Usually with larger, non-push button bar load cells you will want to hook up the load cell between two plates in a “Z” shape, with fitting screws and spacers so that the strain can be correctly measured as shown below:

Bar strain gauge load cell set up in a "Z" formation between two plates

Note that only one side of the load cell is screwed into each board. This provides a moment of force, or torque, on the strain gauge rather than just compression force, which is easier to measure and much more accurate.

Two disc strain gauge load cells

For smaller, push-button or disc load cells, you will want to make sure to screw in the disc to a bottom plate (or surface you are measuring force against), and center the beam, plate, or whatever else you are wishing to measure the force of onto the “button” on the top. Usually another plate with a hole is used to make sure whatever you are measuring is hitting the same spot on the load cell each time, but it is not necessary.

Make sure to read the datasheet for the load cell you are using and get the correct screws to fit into it.

  • Note: If you are hooking together four of the SparkFun Load Sensors using the Combinator board, you should position the four load sensors equidistant from each other, just like the bathroom scales shown in this tutorial.

Load cell measurements can be off by +/- 5% due to a range of things including temperature, creep, vibration, drift, and other electrical and mechanical interferences. Before you install your scale, take a moment and design your system to allow for easy calibration or be able to adjust the code parameters to account for these variations.

Hardware Hookup

Sparkfun's HX711 load cell amplifier breakout board

The HX711 Load Cell Amplifier accepts five wires from the load cell. These pins are labeled with colors; RED, BLK, WHT, GRN, and YLW. These colors correspond to the conventional color coding of load cells, where red, black, green and white wires come from the strain gauge on the load cell and yellow is an optional ground wire that is not hooked up to the strain gauge but is there to ground any small outside EMI (electromagnetic interference). Sometimes instead of a yellow wire there is a larger black wire, foil, or loose wires to shield the signal wires to lessen EMI.

Load cell wiring, wheatstone bridge formation

Four strain gauges (SG1 through 4) hooked up in a wheatstone bridge formation

Different strain gauge load cell output wires

Here we have a large black wire, some loose wires, and foil and loose wires respectively as EMI buffers

In General, each load cell has four strain gauges that are hooked up in a wheatstone bridge formation as shown above.

The four wires coming out from the wheatstone bridge on the load cell are usually:

  • Excitation+ (E+) or VCC is red
  • Excitation- (E-) or ground is black.
  • Output+ (O+), Signal+ (S+)+ or Amplifier+ (A+) is white
  • O-, S-, or A- is green or blue

Some load cells might have slight variations in color coding such as blue instead of green or yellow instead of black or white if there are only four wires (meaning no wire used as an EMI buffer). You might have to infer a little from the colors that you have, but in general you will usually see these colors.

If the readings from the HX711 are opposite of what you are expect (for example the values decrease as you increase weight) simply reverse the O+/O- wires.

Once the load cell is is hooked up to the amplifier, you can hook up VCC, DAT, CLK, and GND to a micro controller such as a RedBoard or Arduino board.

Strain gauge load cell hooked up to SparkFun's HX711 amplifier breakout board

Strain gauge load cell hooked up to SparkFun's HX711 amplifier breakout board

Load cell wires hooked up to the HX711 Amplifier board

The example code has DAT and CLK hooked up to pin 2 and 3 respectively, but this is easily changed in the code. Any GPIO pin will work for either. Then VCC and GND just need to be hooked up to 2.7V-5V and ground respectively on your microcontroller.

alt text

Fritzing diagram of HX711 amplifier connected to a RedBoard

SparkFun's HX711 load cell amplifier breakout board hooked up to a Redboard microcontroller

HX711 Amplifier board hooked up to a RedBoard

Now, if you would like to set up four single strain gauge load cells with our combinator board and the amplifier, it works in a similar way, hooking up the red, black, and white wires from four different single strain gauge load cells and then hooking up the five RED, BLK, WHT, GRN, and YLW pins from the combinator board to the HX711.

SparkFun's strain gauge load cell combinator board

The combinator board also has room for an 8 pin RJ45 socket, which can be used to connect your project via Ethernet cables for long distance applications.

Another nice thing about our combinator board is that most home scales use four single strain gauge load cells, so this is a handy board for hacking your own scales at home!

SparkFun's strain gauge load cell combinator board hooked up to a home scale

Hacked home scale’s four load sensors hooked up to our combinator board

alt text

Example of a single strain gauge load cell, or load sensor. Here RED is the center tap

An off the shelf scale might be a little different. In the scale pictured above, the black wire was actually blue, the red more of an orange color, and the orange wire ended up being the ‘center tap’ of the strain gauge as opposed to white. I hooked the blue wires to the “B”, the orange wires to the “W” and the white wires to the “R”.

To determine how to hook up your single strain gauge load cells to the combinator, measure the resistance between the three wires. You should find a larger resistance (close to double) between a pair. In our example the resistance between White and Blue was 1.8k Ω, and the resistance between White and Red was 900 Ω. Therefore, the center tap to the strain gauge is the Red wire. The center tap or center pin of your strain gauge connects to the “W” pin on the combinator. The larger resistance wires (White and Blue in this example) connect to the “R” and “B” pins on the combinator.

The combinator board hooks up the four load sensors in such a way that two resistors in the wheatstone bridge configuration are constant values and the other two are variable in this way:

alt text

To hook up the combinator board to the HX711 match the RED, BLK, WHT, and GRN pins

Once you have the combinator board successfully soldered to the twelve wires, you can now connect it to the HX711 amplifier board via the 4 standard load cell wires. You can use short jumper wires or if your electronics are a long distance away from your scale consider using an RJ45 connector and an ethernet cable to connect the combinator to the HX711 amplifier.

Arduino Code

Now that you have your load cell, amplifier, and microcontroller hooked up, you can add your code and start calibrating your setup.

You can download the most up-to-date code and libraries from the link below.

GitHub Repository

If you have never worked with downloading Arduino libraries or need a quick reminder you might want to take a look at our tutorial on Installing Arduino Libraries.

Or you can easily get started and running with everything in Codebender!

The first thing you will want to work with is the calibration code: “SparkFun_HX711_Calibration”:

Once you have calculated your calibration factor of your load cell set up, you can move on to other code, such as the simple scale output example code, “SparkFun_HX711_Example”:

Check out the other example code in the Github repo, or Codebender for powering down the HX711 (github, codebender) and known zero startup (github, codebender).

Resources and Going Further

Want to know more? Check out this tutorial if you haven’t already:

New!

Getting Started with Load Cells

June 11, 2015

A tutorial defining what a load cell is and how to use one.

Need even more? Check out this awesome article wheatstone bridges and load cell types.


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

Getting Started with Load Cells

$
0
0

Getting Started with Load Cells a learn.sparkfun.com tutorial

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

Introduction

Have you ever wanted to know the weight of something? How about knowing the change in weight over time? Do you want your project to sense the presence of something by measuring strain or a load on some surface. If so, you’re in the right place. This tutorial is here to help you get started in the world of load cells and their variants.

SparkFun bar load cell

One of many kinds of load cells.

Suggested readings:

Before jumping into load cells and all of their awesomeness, we suggest you familiarize yourself with some basic concepts if you haven’t already:

Load Cell Basics

Types of Load Cells

A load cell is a physical element (or transducer if you want to be technical) that can translate pressure (force) into an electrical signal.

So what does that mean? There are three main ways a load cell can translate an applied force into a measurable reading.

Hydraulic Load Cells

Hydraulic load cells use a conventional piston and cylinder arrangement to convey a change in pressure by the movement of the piston and a diaphragm arrangement which produces a change in the pressure on a Bourdon tube connected with the load cells.

Diagram of a Hydraulic Load Cell

Diagram of a Hydraulic Load Cell from Nikka’s Rocketry

Pneumatic Load Cells

Pneumatic load cells use air pressure applied to one end of a diaphragm, and it escapes through the nozzle placed at the bottom of the load cell, which has a pressure gauge inside of the cell.

Diagram of a pneumatic load cell

Diagram of a pneumatic load cell from Instrumentation Today

Strain Gauge Load Cells

And lastly (though there are many other less common load cell set ups), there is a strain gauge load cell, which is a mechanical element of which the force is being sensed by the deformation of a (or several) strain gauge(s) on the element.

Strain gauge load cell diagram

Strain gauge load cell diagram from Scalenet.com

In bar strain gauge load cells, the cell is set up in a “Z” formations so that torque is applied to the bar and the four strain gauges on the cell will measure the bending distortion, two measuring compression and two tension. When these four strain gauges are set up in a wheatctone bridge formation, it is easy to accurately measure the small changes in resistance from the strain gauges.

Diagram of strain gauges on bar load cells

More in depth diagram of strain gauges on bar load cells when force is applied

In this tutorial we will be focusing on strain gauge load cells like the ones SparkFun carries:

Load Cell - 50kg, Disc (TAS606)

SEN-13331
$56.95
Load Cell - 10kg, Wide Bar (TAL201)

SEN-13330
$11.95
Load Cell - 200kg, Disc (TAS606)

SEN-13332
$56.95
Load Cell - 10kg, Straight Bar (TAL220)

SEN-13329
$6.95

Most strain gauge load cells work in very similar ways, but may vary in size, material, and mechanical setup, which can lead to each cell having different max loads and sensitivities that they can handle.

Strain Gauge Basics

A strain gauge is a device that measures electrical resistance changes in response to, and proportional of, strain (or pressure or force or whatever you so desire to call it) applied to the device. The most common strain gauge is made up of very fine wire, or foil, set up in a grid pattern in such a way that there is a linear change in electrical resistance when strain is applied in one specific direction, most commonly found with a base resistance of 120Ω, 350Ω, and 1,000Ω.

Each strain gauge has a different sensitivity to strain, which is expressed quantitatively as the gauge factor (GF). The gauge factor is defined as the ratio of fractional change in electrical resistance to the fractional change in length (strain).

(The gauge factor for metallic strain gauges is typically around 2.)

We set up a stain gauge load cell and measure that change in resistance and all is good, right? Not so fast. Strain measurements rarely involve quantities larger than a few millistrain (fancy units for strain, but still very small). So lets take an example: suppose you put a strain of 500me. A strain gauge with a gage factor of 2 will have a change in electrical resistance of only

For a 120Ω gauge, this is a change of only 0.12Ω.

0.12Ω is a very small change, and, for most devices, couldn’t actually be detected, let alone detected accurately. So we are going to need another device that can either accurately measure super small changes in resistance (spoiler: they are very expensive) or a device that can take that very small change in resistance and turn it into something that we can measure accurately.

This is where an amplifier, such as the HX711 comes in handy.

alt text

SparkFun’s HX711 Amplifier breakout board

A good way of taking small changes in resistance and turning it into something more measurable is using a wheatstone bridge. A wheatstone bridge is a configuration of four resistors with a known voltage applied like this:

alt text

where Vin is a known constant voltage, and the resulting Vout is measured. If then Vout is 0, but if there is a change to the value of one of the resistors, Vout will have a resulting change that can be measured and is governed by the following equation using ohms law:

By replacing one of the resistors in a wheatstone bridge with a strain gauge, we can easily measure the change in Vout and use that to assess the force applied.

alt text

Bar load cell wheatstone bridge example From All About Circuits

Combinator Basics

Now that you have a load cell with a strain gauges hooked up to an amplifier, you can now measure force applied to your cell. For more information about how to hook up strain gauges, load cells, and amplifiers go to our hookup guide.

alt text

Bathroom scale using the Load Sensor Combinator to combine twelve wires into one wheatstone bridge

But what happens when you don’t have a load cell with four strain gauges? Or you want to measure something really heavy on something scale like?

You can combine four single strain gauge load cells (sometimes referred to as Load sensors)! Using the same wheatstone bridge principle, you can use a combinator to combine the single strain gauge load cells into a wheatstone bridge configuration where the force applied to all four single strain gauge load cells is added to give you a higher maximum load, and better accuracy than just one, and then the combinator can be hooked up to the same amplifier for easier measuring.

For more information on hooking up load sensors go to our hookup guide.

This is the same layout that you would find in say your home scale. There would be four strain gauge load cells hooked up to a combinator and an amplifier to give you your weight reading.

Resources and Going Further

For more information about setting up load cells and how to integrate them into your next project, check out our HX711 hook up guide:

New!

Load Cell Amplifier HX711 Breakout Hookup Guide

June 11, 2015

A hookup guide for the HX711 load cell amplifier breakout board

Can’t get enough about how load cells work? Check out this article for more in depth information.


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


Teensy Arduino Shield Adapter Hookup Guide

$
0
0

Teensy Arduino Shield Adapter Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Teensy Arduino Shield Adapter is a useful tool for upgrading existing projects to a more powerful controller. If you have an Arduino shield you’d love to use, but prefer working with the Teensy, then this product is just what you need!

Teensy Adapter

Materials Required

To follow along with this tutorial, we recommend you have access to the following materials.

Suggested Reading

If you aren’t familiar with the following concepts, please review them before beginning to work with the Teensy Arduino Shield Adapter.

Hardware Overview

There are several features on the Teensy Adapter Shield to be aware of. While this shield provides basic Arduino compatibility with a standard shield, there’s a few other fun features to check out.

Teensy Compatibility

The adapter design interfaces with all features of the Teensy 3.1, but the adapter fits the Teensy LC footprint as well. Not all of the features available on the adapter are compatible with the LC due to the microcontroller’s limitations. Please check the datasheets to ensure functionality for your project to determine the best Teensy for your use case.

Real Time Clock Battery

RTC Battery Clip

The battery holder included for the shield allows the users to install this into a project and run the RTC (Real Time Clock) on the Teensy as a time keeping option. The included coin cell battery outputs 3V and will power the RTC in case of system power loss to maintain accurate time.

This feature does not work with the Teensy LC.

JST Power Connector

JST Connector

This connector breaks out the 3.3V power line from the Teensy. You can power external devices off of this using a JST jumper wire, or you can solder wires directly to this connection instead.

This header can also be used as a power input to both the Teensy and the Arduino footprint and is not regulated down. The voltage supplied on the connector must be 3.3V.

You must cut the VIN/VUSB jumper on the bottom of the Teensy if you intend to power the Teensy via this connection and use USB for communication/programming.

Barrel Jack

Barrel Jack

The barrel jack allows the user to power the Teensy and Shield combo using a wall adapter or any power supply with a male barrel jack. This voltage can be anywhere from 4-12V, and is regulated to 5V for powering the Teensy. This power supply connects directly to VRAW on the Arduino shield footprint and is not regulated down. Please read the datasheet for any shields you intend to connect to via the adapter shield.

You must cut the VIN/VUSB jumper on the bottom of the Teensy if you intend to power the Teensy via this connection and use USB for communication/programming.

I2C Jumpers

I2C Jumpers

The two solder jumpers included on the adapter allow the user to configure the I2C lines on the board. The adapter ships with the jumpers closed by default, connecting the SDA and SCL pins of the Teensy to pins A4 and A5 on the Arduino footprint respectively. If you have an Arduino Leonardo-compatible shield, you can swap this jumper to isolate the SDA and SCL lines on the same-named pins, and access A6 and A7 of the Teensy on A4 and A5 of the Arduino footprint. A4 and A5 of the Teensy will still connect to the Arduino footprint SDA and SCL.

ICSP Header

ICSP Header

The ICSP header breaks out the SPI pins for Leonardo-compatible shields. You can also use this header to reprogram the Teensy if you have an AVR programmer.

Additional Analog Pins

Analog Headers

Just because you’re using the Teensy with an Arduino shield doesn’t mean you want to lose the extra features of the Teensy! We’ve broken out additional analog pins 8-11 from the Teensy to a 6-pin header, along with AREF and GND. These pins do not interact with the Arduino shields at all, and are simply a bonus for external sensors or inputs if desired.

DAC Pin Header

DAC Header

One of the other great features of the Teensy is the onboard Digital-to-Analog converter. We’ve broken this pin out to the board’s edge, along with the PROG pin, and two corresponding GND pins.

Hardware Assembly

So you’ve got a bag of parts and are ready to get your Teensy interfaced with your Arduino shields. It’s time to bust out that soldering iron!

We’re going to solder the adapter together in order of smallest profile to largest. This will help make it easier to reach all the soldering points with the iron, as well as make it easier to line all the items up properly.

Battery Holder

Battery Holder

First, insert the battery holder and ensure it is sitting flush on the board. Flip the adapter over, and solder the connectors. Keep in mind that the battery clip is all metal and will conduct heat, so don’t burn yourself!

Because the battery clip will endure a lot of strain on battery insertion or removal, you want to make sure you fully connect the pins to the board. Make sure your solder points look nice and filled in, like this:

Battery Connectors

Capacitor

The next component to solder is the capacitor. The cap is polarized, so make sure you insert it correctly into the board. The negative side of the cap should be inserted closest to the barrel jack footprint.

Once you insert the cap, bend the legs out a bit to hold the capacitor flush against the board while you solder it.

Capacitor Sitting Flush

Once you’ve soldered the capacitor legs, clip any excess leg.

Clipped capacitor legs

JST Connector

Next, insert the JST connector. This part tends to need a bit of a push to insert fully into the board, so make sure you get it sitting flush before soldering. Make sure the opening on the connector sits along the board edge and isn’t inserted backwards.

JST Connector Inserted

Voltage Regulator

The voltage regulator does tend to be a bear to insert properly, so take your time with this step. First insert the regulator legs into the board. Make sure the regulator is inserted in the correct orientation, with the metal tab towards the ICSP header on the board and the plastic body casing closest to the JST connector.

Voltage Regulator Orientation

Proper orientation of voltage regulator from the side view.

Once you’ve verified the regulator is oriented correctly, but before soldering, bend the regulator down towards the PCB. The mounting hole on the regulator should match up with the mounting hole on the PCB.

Solder the regulator legs and clip any excess. This part does regulate the project voltage, so make sure to get a good solder connection on all the pins and ensure there are no jumpers or clippings that could short the board.

Regulator Leg clipped

Female Headers for Teensy

At this point, you will need to determine how you want your adapter shield to interface with your Teensy and your Arduino shields. The steps shown are our recommended method of interfacing everything, but you can customize this. Please check our tutorial on Getting Started with the Teensy to see other possible configurations.

Take the female headers from your kit, and cut them down into individual strips to fit in the Teensy footprint. Plug in the headers, and verify that they line up well. You may also need to use one of the 6-pin female headers on the short edge of the Teensy footprint.

Gap in Headers

If you have gaps between the headers like shown above, you may need to file down the edges of the connectors to get everything to fit compactly. Start soldering the header rows one at a time. To help keep them straight as you solder, we recommend tacking the first and last solder points first.

Tacked Headers

Notice the first and last headers are tacked down.

This allows you to easily fix any poorly inserted or angled headers that may occur.

Misaligned headers

These headers will never do!

If you have decided to solder all of the Teensy pins, you will also need to solder in the inner row of headers on the shield.

Second row headers to solder

Shield Headers

Next, solder on the 10-pin, 8-pin, and 6-pin headers onto the Adapter board. To make sure you line these headers up properly, we recommend using a pre-soldered shield as a soldering jig to hold the adapter headers in place.

Stacked headers for soldering

Pre-soldered shield used as a soldering jig to keep the headers lined up.

Keep in mind that you may need to add on the stackable headers from your kit onto your board in order to provide enough clearance between the Teensy and the shield you use.

Barrel Jack

The final part to solder is the barrel jack. Notice that when you insert it, the through holes are much larger than the standard headers.

Barrel jack pins bare

Because of the large plated through holes, you will need more solder and heat to properly connect these and fill them in (just like on that battery clip!). Be patient, and take it slow, to ensure you don’t burn the PCB or any traces.

That’s it! Your adapter should now be soldered and ready to go.

Teensy Adapter Completed Top

All pieces inserted and soldered!

Teensy Adapter Soldered Bottom

Teensy Adapter successfully soldered!

Teensy Headers

Now that your adapter is completed, you can use this as a soldering jig to connect the male headers to your Teensy. Break the strip into smaller parts, and insert them into the pre-soldered headers on the adapter. Plug the Teensy on top, and solder away!

Teensy Headers stacked

Crystal

Note: This step is optional and only necessary if you intend to use the RTC feature on the Teensy 3.1.

If you intend to use the RTC on the Teensy 3.1, you will need to solder the crystal onto the Teensy. You can solder it via the bottom or the top, but keep in mind you should insert it where it is least likely to get knocked or short the body of the crystal onto other components.

Crystal on Teensy Bottom

Double check that the crystal won’t short on any pins before soldering!

Plug it all in

Once everything is soldered properly, it’s time to put your boards together. If you did not solder the Teensy directly to the adapter, plug the Teensy into the adapter, and insert whichever shield you’ve chosen to connect.

Plug in your Teensy via USB, upload your code, and you’re good to go!

Teensy System

Final Adapter assembly with the Electric Imp Shield stacked on top.

Remember! If you intend to use an external power supply, you must cut the jumper on the bottom of the Teensy to prevent shorting VUSB and VIN.

Don’t forget to plug in your coin-cell battery, if you intend to use the RTC. This does not work with the Teensy LC.

Programming

Because this board is simply an adapter, there is no special programming required to start working with the adapter. You will, however, need to program the Teensy for any Arduino shield with which you’d like to work.

When programming your Teensy, remember to select the proper board from the Arduino IDE drop down, and select the proper serial port and baud rate.

Please review our tutorial on Getting Started with the Teensy, for more information on programming the Teensy in either the Arduino IDE or in a C compiler.

Don’t forget to verify and update your pin definitions in your shield code if you intend on using A6 or A7 in place of SDA or SCL.

Resources and Going Further

Going Further

Now that you’ve successfully got your Teensy Arduino Shield Adapter up and running, it’s time to incorporate it into your own project!

If you have any feedback, please visit the comments or contact our technical support team at TechSupport@sparkfun.com.

Additional Resources

Check out these additional resources for more information and other project ideas.


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

Getting Started with the Teensy

$
0
0

Getting Started with the Teensy a learn.sparkfun.com tutorial

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

Introduction

The Teensy line is a collection of microcontrollers from PJRC, based around several different powerful ICs. This basic getting started guide will help you start using the Teensy that’s best for your project.

Teensy Family

The Teensy 3.1, the Teensy++ 2.0, and the Teensy LC.

Required Materials

We recommend the beginner Tool Kit for soldering any of the Teensy boards.

Alternatively, if you are planning on doing a lot of intense soldering, you can also use the following wishlist as a guide.

You will also need the appropriate USB cable for the Teensy board with which you are working. The following boards work with the micro-USB cable:

Teensy 3.1

DEV-12646
$19.95
28
USB microB Cable - 6 Foot

CAB-10215
$4.95
4
Teensy LC

DEV-13305
$12.95
3

The Teensy++ 2.0 works with the mini-USB cable:

SparkFun USB Mini-B Cable - 6 Foot

CAB-11301
$3.95
2
Teensy++ 2.0

DEV-11781
$24.95
1

You will also need the appropriate headers for your project. There are several different options available.

Suggested Reading

If you aren’t familiar with the following concepts, we recommend reading these articles first before continuing with this getting started guide.

Hardware Overview

Each Teensy board has its own key features which are covered here. For individual pinout diagrams and detailed schematic information, please check PJRC’s page here.

Teensy ++ 2.0

This Teensy board is the only AVR-based Teensy that SparkFun carries. It runs off of the AT90USB1286, an 8 bit AVR running at 16MHz. It also has the largest footprint of all of the Teensy boards, at 1.375 in2.

Teensy 2.0 ++ Features
FeatureNumber Available
PWM9
Analog In8
I/O46
Serial Port1
I2C Port1
SPI Port1
Flash128K
RAM8K

The push button on the end of the Teensy 2.0 ++ is a RESET button. This is also used during programming the Teensy with Teensyduino, discussed later.

Teensy LC

The Teensy LC is 0.98 in2. It runs off of the 32 bit ARM Cortex-M0+ at 48MHz and runs at 3.3V.

Note: Teensy LC does not have 5V tolerant I/O pins. This is not the board for you if your project runs 5V signals, unless you want to use a logic shifter.

The Digital to Analog converter is on pin A12 of the microcontroller. Pin 17 outputs voltages up to the supplied Vin voltage, at 8mA.

Pins D5, D16, D17 and D21 can source signals up to 20mA. All other pins are limited to 5mA.

Teensy LC Features
FeatureNumber Available
PWM10
Analog In13
I/O27
Serial Port3
I2C Port2
SPI Port2
Touch Sense Pins11
Flash62K
RAM8K

The pushbutton on the LC is not a reset button but instead triggers HalfKay mode. This allows the board to reboot to the newest code or accept new uploaded code.

Teensy 3.1

The Teensy 3.1 is the same size and footprint as the Teensy LC but more powerful. This runs off of the MK20DX256 IC, which is a 32 bit ARM Cortex-M4. It is also 5V tolerant on its digital I/O pins and can provide up to 3.3V at 100mA to other devices. The analog pins are 3.3V tolerant only.

Teensy 3.1 Features
FeatureNumber Available
PWM12
Analog In21
I/O34
Serial Port3
I2C Port2
SPI Port1
Real Time Clock1
Touch Sense pins12
Flash256K
RAM64K

The pushbutton on the 3.1 is a reboot trigger and does not reset the entire system, similar to the pushbutton on the LC. In order to reset the board, you must access the RESET test point on the bottom of the board.

Reset

Teensy 3.1 Reset pad.

Soldering Options

When it comes to soldering your Teensy, there are many different options available to you.

Solder Directly Into your Circuit

We generally recommend against soldering directly between any two boards you want to connect – if something burns out or is connected incorrectly, you’ve set yourself up for a lot of annoying rework (and the danger of ripping a pad off of the board).

Teensy Flush on board

Soldering your Teensy directly to the board leads to a small profile, but you run the risk of needing to desolder a lot of pins!

One benefit of soldering directly to your circuit however is that it gives a very small profile for the project. If you plan on doing this, we recommend testing your circuit design with Alligator clips or Pig-tail cables before hand to verify functionality.

Solder Headers

Most users prefer using male headers on the Teensy and matching female headers on other boards into which the Teensy fits.

If you plan on using this method, you must ensure you solder the headers on straight, otherwise you’re going to have a hard time inserting or removing the Teensy from other boards.

We recommend inserting headers into a breadboard and soldering the Teensy on from there.

Breadboard Teensy

Teensy 3.1 inserted in a breadboard for soldering. Half the pins are soldered and half aren’t.

Using male headers with the Teensy allows you to solder the headers on nice and straight, preventing crooked header insertion. As you can see from the image above however, if you intend to use the Teensy LC or Teensy 3.1 on a breadboard, you cannot solder all of the headers.

Breadboard Incompatible

These pins aren’t breadboard compatible!

If you’ve already soldered together a board that works with the Teensy LC/3.1, you can simply line your headers up in that board to hold them straight while soldering to the Teensy.

Hold Headers Straight

The male headers for the Teensy are being held straight by this Teensy Arduino Shield Adapter.

Once the headers are lined up straight, it’s easy to simply ‘plug’ the Teensy into the headers and solder everything together.

Teensy Lined Up

You can see the Teensy lined up on the headers, waiting to be soldered.

You can also solder female headers or stackable headers onto the top of the board, allowing other boards to be plugged into the top of the Teensy.

TeensyOnBottom

Teensy with stackable female headers on top, allowing the Audio shield to be plugged in and the Teensy to fit into a breadboard.

If you do solder your headers on like this, keep in mind it may limit your access to the push button on board, requiring you to break out the reboot/reset signal from the header pin.

What about Those Additional Headers on the LC/3.1?

Inner Headers

Inner Pins

Inner headers - what to do with those?!

There are a few options to work with these pins. You can:

a) Leave them unconnected (boring!)

b) Solder wires to the pins as you find uses for them

c/d) Solder headers on the top/bottom

If you go for options c or d, there’s an easy way to solder connectors on there without driving yourself crazy attempting to solder a lonely pin by itself.

If you are using male headers, you can use pliers to push/pull one of the pins out. This will allow you to use the spacer to hold the pins straight, but will remove the non-compatible pin.

Using Pliers to modify Headers

Removing the unnecessary pin using pliers.

If you are using female headers, this method won’t work, but you can still use the pliers to pull out the unnecessary pins.

Female Header modification

Simply pull the header pin out, and out of the way!

Once the header strip has been modified, simply line it up with those holes, and solder them.

SMD Headers

Both the 3.1 and LC Teensy boards have SMD pins on the board bottom that you can solder to. If you know you will need access to these pins, we recommend that you solder the headers onto the top side of your Teensy.

If you already have another Teensy soldered, you can use this as a soldering jig to keep the headers straight, as shown below.

Headers Soldered On Top

Headers are soldered on the top of the board, enabling access to the SMD pads on the bottom.

With the headers soldered onto the Teensy this way, the user has access to all of the SMD pads on the bottom of the board. Keep in mind however, this does minimize access to the pushbutton, so balance that with your project needs.

If you need help with soldering to the SMD pads on the bottom of the board, please check out our tutorial here.

Programming

To start working with the Teensy, all you need to do is plug in your USB cable to your computer and your Teensy board. There are two options for programming the Teensy boards - your favorite C compiler or the Arduino IDE.

Arduino

Installation: You will need to download the Teensyduino add-on for Arduino. If you have not already installed the Arduino IDE, please do that now. Check out our tutorial on that if you need help.

You can find the Teensyduino download from PJRC here. Please follow their installation instructions for the most up-to-date version of the Teensyduino. You will also need to select which Teensy-compatible libraries you’d like to install at that time. If you aren’t sure which libraries you will want, you can always download them and install them later from the curated list.

Programming the Teensy:

When you first plug the Teensy in, the appropriate drivers will be installed (if using a Windows machine). Your Teensy should default to the standard Blink sketch. You should see the LED blinking, as a quick check to make sure your board is functioning.

Open up the Arduino IDE, and select the appropriate Teensy board from the Board menu. This will provide you with additional options in the Tools menu.

Arduino Teensy Options

Drop-down options in Arduino for Teensy boards.

If you would like to use the Teensy as an HID, MIDI, or user interface device (such as a keyboard or mouse), you can select that option from the USB Type menu.

The CPU speed can be changed for low-power applications.

Note: If you are using the Teensy 3.1, you must set the CPU speed to 24MHz or faster for proper functionality.

The Keyboard Layout option can be updated to your preferred style.

Press the button on the Teensy to open the Teensy loader program. You should see this window:

Teensy Loader

Teensy Loader Window

Verify your example code, and upload to the board as usual in the Arduino IDE. You will need to hit the on-board button once the IDE has compiled the code to finish uploading it to your Teensy. You should only need to do this the first time you upload code for the duration that your Teensy is powered.

C Compiler

This is typically a more advanced option. For step-by-step instructions on using a C-compiler for the Teensy, please check out PJRC’s directions here. You will still need to download and install the Teensyduino and modify the Arduino files to use the Makefile for the Teensy boards.

Additional support for other languages is slowly being added. Please check here for more information.

Resources and Going Further

Going Further

Now that you have a basic understanding of working with the Teensy, it’s time to start building projects with one! Make sure to check out the schematic for your particular Teensy when building any new projects.

Teensy Schematics

Teensy schematics are available here.

If you have any feedback, please visit the comments or contact our technical support team at TechSupport@sparkfun.com.

Additional Resources

Check out these additional resources for more information and other project ideas.


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

Teensy XBee Adapter Hookup Guide

$
0
0

Teensy XBee Adapter Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Teensy is a great way to get more computing power than an Arduino, and in less space. When a decently ranged, no-frills wireless serial link is required, the XBee series is a great solution. The Teensy 3.1 XBee Adapter joins the two with ease and brings wireless to your Teensy projects. This tutorial will demonstrate the basics of using the adapter board.

Teensy_XBee_Adapter

This tutorial demonstrates:

  • How to initialize Teensy 3.1 HW serial
  • How to initialize Teensy 3.1 SW serial using softwareSerialAlt library
  • The basics of packetizing data.
  • How to make a simple controller that effects something far away

Required Materials

At a minimum, you’ll need an XBee explorer, two XBees, a Teensy and the adapter board. Here’s a list of things you’ll need if you want two Teensy XBee radio stations that are both off-the-grid, plus some useful extras.

Required Basic Shop Tools

  • Soldering iron and flux core solder
  • Spare wire
  • X-acto or knife for cutting traces (possibly)

Software Requirements

Suggested Reading

Before getting started, there are a few concepts that you should be familiar with. If you haven’t used a Teensy or XBee before, read these tutorials before continuing:

  • Getting Started with the Teensy - How to install Teensyduino, comparison of the Teensy 3.1 and LC, and soldering options.
  • Exploring XBees and XCTU - Guide to configuring the XBees using the XBee tool XCTU
  • XBee Buying Guide - Shows various XBee models including current consumption use an Arduino to control the APDS-9960
  • Serial Terminal Basics - Lots of information about serial. If you’ve only ever used the Arduino Serial monitor (or no terminal at all), this is a good resource. It shows how to get serial terminals working on Mac, Linux, and Windows.

Hardware Overview

Apart from mechanically connecting the The Teensy and XBee, the adapter has a some features to help you get the most from the hardware. Here’s what each section does.

alt text

Key parts of the adapter

  1. Teensy 3.1 (and LC) footprint - Connect the Teensy here
  2. UART1/S-UART switch - Select which serial pins are connected to the XBee (pins 0/1 for the hardware UART, pins 20/21 for the software UART)
  3. XBee socket - Plug the XBee in here matching silkscreen shape
  4. VIN/EXT jumper - short to source Teensy power from the EXT_IN pins
  5. XBee status LEDs - shows data movement, signal strength, and digital IO pin 5 (XBee signals)
  6. Spare ground connections - my gift to you!
  7. TNSY/EXT jumper - selects the source of power for the XBee (Teensy onboard regulator or EXT_IN)
  8. Power LED - shows if XBee is getting power
  9. EXT_PWR in - Supply regulated 3.3v here only when necessary
  10. XBee reset switch - resets the XBee

alt text

Bottom view

alt text

With XBee and Teensy installed

Don’t forget to check out the Getting Started with the Teensy tutorial for information on attaching the Teensy to an adapter.

Assembly

There are a few theoretical steps to get a project working with the Teensy and XBee that will be discussed.

Here are the basic steps:

  • Determine how to power the system
  • Connect the hardware
  • Configure the XBees
  • Establish serial over XBee (this tests all systems - highly recommended)
  • Build and test the actual project

Determine how the system is going to be powered

The XBee requires around 3.3V to operate, depending on the model. The Teensy has an on-board regulator that outputs 3.3V, which is perfect, but only for lower power radios that consume less than 100mA.

alt text

Powering from the Teensy’s internal regulator

This is the default configuration. The internal regulator can supply about 100mA of current for 3.3V use, including what is consumed by the Teensy and things on the 3.3V rail. XBees up to 2mW (non-“pro” models) consume up to 40mA, so, if you have a basic XBee, this is probably the route for you. Supply 3.7V to 5.5V (or USB power).

alt text

Powering the XBee from an external 3.3v regulator

If you have a higher powered XBee, or more than 100mA of load on your 3.3V rail, you’ll need to disconnect the XBee from the internal regulator and supply 3.3v from somewhere else. A Breadboard Power Supply Stick is a possible power source for this application.

In this case, switch the TNSY-EXT jumper to ‘EXT’, short the VIN-EXT_PWR jumper, and cut the trace between the Teensy’s USB PWR jumper. Now both the Teensy and XBee are powered from the ext power pins, so you’ll need to provide power and plug in the USB if you want to reprogramming the device.

Connect the Teensy to the XBee.

The XBee fits straight into the adapter. Make sure the XBee outline matches the silkscreen on the adapter.

The Teensy and adapter come as PCB without headers. Check out the Sparkfun Getting Started with the Teensy for example of how pins and sockets can be attached.

Connect Periphery Equipment

Use the outer holes to connect all manor of switches and sensors that you wish to read from the Teensy. This tutorial makes a controller, so buttons and LEDs are connected as shown in this diagram.

alt text

Configure the XBees

The XBees are shipped with a default configuration (see XBee documentation). Even if they work out of the box, you’ll be using the default IDs and will be suseptable to unseen XBees interfering with your system (because some other designer had the similar thought, “I’m the only one here, why not use the default IDs.”) Also, you can change other more advanced features once you’re familiar with the concepts.

The parameters used for these demos

  • ID/PAN ID = A5F1 - This can be any 16 bit hex value used to identify your network. Make sure it is the same for both radios and unique in your area. A5F1 was randomly chosen for this guide. You can choose any ID for your network.
  • Data rate = 9600
  • Parity = N
  • All others at factory default

Configuring XBees with USB based explorers

  • Socket an XBee into the explorer matching the silkscreen orientation
  • Plug the explorer into the USB port
  • Open X-CTU
  • Select your explorer’s serial port
  • Querry the XBee to make sure the drivers are working
  • Read the configuration from the XBee
  • Modify the parameters
  • Write the new configuration to the XBee

Repeat this process so that both XBees have the new configuration.

Power the System!

Apply to the system. Powering through the Teensy, use 3.7 to 5.5v. Alternately, supply regulated 3.3v to the EXT_PWER pins. Does the power LED on the adapter illumniated? It shows if power is getting to the XBee. Try running the blink sketch to determine if the Teensy is really powered and ready to recieve firmware.

Software

Working with your serial ports

Working with wireless devices is more difficult than just a single arduino because more than one serial port is in use. Where Arduino allows you to simply load the serial monitor to talk to your code, be extra careful remembering which ports what device and which terminal are using.

The first serial link in use is between the XBee and computer through the serial explorer. Get this port open and communicating to the XBee, then leave it alone. It ushers bytes you type into it into the air, and prints whatever comes into it’s antenna to your screen. When the system is fully functional, this terminal will tell you what buttons are being pressed.

The second serial link is the Arduino serial monitor, which connects to the Teensy over the USB cable. Eventually the Teensy will be disconnected from the computer but it can be usefull to get debugging information from your program while working with it. Be careful not to confuse it with the other serial ports. When you upload a sketch, the serial monitor automatically closes. If you’re using a 3rd party terminal here make sure it is closed before upload in order to free up the USB port for programming.

The trickest serial link in this project is the one that goes from the Teensy to the XBee because we have little information about it. Without expensive scopes, use the Din and Dout LEDs to monitor if there is activity from the Teensy to the XBee. One illumniates when the Teensy sends data to the XBee, and the other for showing when data is comming from the XBee to the Teensy.

Test your serial and XBee configuration

Two sketches are provided to ease bringing the XBees on line. They pass data between the XBee and the serial monitor using the HW UART or the SW UART ‘AltSoftSerial’ library. You can get them from the Github repository for the Teensy_3_1_XBee_Adapter or by copy-pasting from below

teensy_3_1_xbee_UART1_example

Note: Teensy board not currently supported by codebender

Set the adapter’s serial switch to UART1. Then, load and run the example. Open the serial monitor. Text entered in the serial monitor will be passed to the XBee, and come out the X-CTU (or other, I use Tera Term) serial monitor. Typing in that terminal will send the text back to the Arduino serial monitor. This tests the HW UART and XBee configurations

teensy_3_1_xbee_SUART_example

Note: Teensy board not currently supported by codebender

This sketch works much like the UART1 example but with the AltSoftSerial library, leaving the HW UART free to connect to other resources. Set the adapter’s switch to UART1 and run the sketch. Text should be passed between the two serial terminals.

Running the demo sketch

One sketch is provided to demonstrate passing data between a computer with SparkFun XBee Explorer USB and the Teensy with XBee. You can get it from the Github repository for the Teensy_3_1_XBee_Adapter or by copy-pasting from below

teensy_3_1_xbee_buttons_and_leds_example

Note: Teensy board not currently supported by codebender

This sketch demonstrates bi-directional communication and shows off operation that is more than just data echo.

Connections:

  • Attach buttons to pins 14-17 of the Teensy, and to ground. The pins are pulled up inside the teensy and will float high until a button is depressed.
  • Attach LEDs from pins 4-12 of the Teensy, through a current limiting resistor, to ground. It’s not so important to have all 8, 2 or 3 is enough to demonstrate the effect.

Each time the loop() runs, the sketch:

  • Converts button presses to an ascii repersentation
  • Prints the button states to the Arduino serial monitor
  • Transmits the button states as a series of ascii characters
  • Checks for received data from the XBee. If a number 1-8 is received, the associated LED on pins 14-21 is illuminated. If any other character is received, all 8 LEDs are are switched off.

Conclusion

The Teensy is really a great small-footprint powerhouse. Paired with the XBee you can get a great long distance serial connection, and with the 72MHz of processing speed (48MHz for the Teensy-LC) you can do a lot with the information. The Teensy is also capable of being a “class driver” device, you can get that data into a computer with ease, turning it into a keyboard, mouse, serial, or midi device.

Resources and Going Further

Here’s some links for getting extra information:


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

SparkFun Blocks for Intel® Edison - PWM

$
0
0

SparkFun Blocks for Intel® Edison - PWM a learn.sparkfun.com tutorial

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

Introduction

SparkFun’s PWM Block for the Intel Edison allows you to add eight channels of I2C controlled PWM output to your Edison stack. The headers are spaced to allow you to directly connect servo motors to the block, and an auxiliary isolated power input on the headers allows for input voltages and currents above what the rest of the Edison can use or provide.

PWM Block image

PWM Block

Suggested Reading

If you are unfamiliar with Blocks, take a look at the General Guide to Sparkfun Blocks for Intel Edison.

Other tutorials that may help you on your Edison adventure include:

Board Overview

The “top” side of the board is the most interesting, so we’ll look at that first.

Labeled image of the board top

  1. PWM outputs - Each PWM channel has a three-pin, 0.1" spaced header footprint. The output order is appropriate for most servo motors. All you need to do is add male header pins, and you can connect servos directly to the block. The VIN pin is, by default, floating. Before you can drive a servo, you’ll need to provide power to that rail.
  2. Auxiliary Power Input - These pads are provided to allow you to connect an external power supply to the PWM channels. This allows you to use a higher voltage, higher current supply (for instance, a 7.2V 2S LiPo cell) to power the devices connected to the PWM outputs without risking damage to the Edison.
  3. VSYS->VIN jumper - If you don’t need the extra oomph of an external power supply (because you’re driving small LEDs or a small servo, perhaps), you can bridge this jumper with a solder blob to draw power from the Edison VSYS rail. When running from USB, you can expect that rail to be approximately 4.0V.
  4. Address jumpers - These jumpers allow you to set the address the PCA9685 PWM chip on this board will use. Each jumper corresponds to a single address bit; closing a jumper makes that bit a ‘1’. The default address is 0x40. Thus, closing A0 would make the address 0x41, A1 makes it 0x42, A0 and A1 make it 0x43, and so on.

Reverse side of the board

The “back” of the board is far more boring, with no jumpers or components to mention. This is the side that the Edison module will mate with, so you will be able to change jumpers without detaching the Edison.

Using the PWM Block

To use the PWM Block, simply attach an Intel Edison to the back of the board, or add it to your current stack. Blocks can be stacked without hardware, but it leaves the expansion connectors unprotected from mechanical stress.

alt text

PWM Block Installed

We have a nice Hardware Pack available that gives enough hardware to secure three blocks and an Edison.

alt text

Intel Edison Hardware Pack

NOTE: The PWM Block does not have console access or a voltage regulator. It is recommended to use a console communication block in conjunction with this block like ones found in the General Guide to SparkFun Blocks for Intel Edison.

C++ Code Examples

We’re assuming that you’re using the Eclipse IDE as detailed in our Beyond Arduino tutorial. If you aren’t, you’ll need to read that tutorial to get up to speed.

Getting Started

Follow the instructions in the programming tutorial to create a new project named “SparkFun_PWM_Edison_Block_Example”. Once you’ve created the project, open the project files on the disk (hint: you can find the path to the project by choosing “Properites” from the project menu), and copy the source files found in the SparkFun PWM Block for Edison C++ Library directly into the “src” directory.

Download a zip file of the repository

Hardware Connection

For this example, we’ve got a sub-micro servo motor and a common anode RGB LED connected to the PWM block outputs. We’ve closed the VSYS->VIN jumper with a solder blob, so we’re drawing power from the Edison’s supply. For a larger servo motor or more LEDs, you should open that jumper, and connect an external supply to the VIN and GND pads at the end of the header.

PWM Block Example Circuit

Of course, you can connect any other device to the outputs here – the PWM input to a motor driver, a buzzer, what have you. We just want to demonstrate the core capabilities of this block, which is to provide servo driving and visually normalized LED outputs.

Code

Everything you need to know is in the comments.

/****************************************************************************
 * SparkFun_PWM_Edison_Block_Example.cpp
 * Example code showing how to use the SparkFun PWM Edison Block
 * Mike Hord @ SparkFun Electronics
 * 9 June 2015
 * https://github.com/sparkfun/SparkFun_PWM_Block_for_Edison_CPP_Library
 *
 * This file is a demonstration program showing the various functions that we've
 * provided for working with the PCA9685 IC on the SparkFun PWM Edison Block.
 * It uses an RGB LED and a small servo motor to show what the library can do.
 *
 * Resources:
 * Requires Intel's MRAA framework. This can be downloaded from either the
 * GitHub site (https://github.com/intel-iot-devkit/mraa) or in pre-built form
 * from http://iotdk.intel.com/sdk/mraa-update/.
 *
 * Development environment specifics:
 * Developed in the Intel iot-ide-dk Eclipse on Win 7 (v1.0.0.201502201135)
 * Using lib-mraa v0.6.2
 * On Edison poky-linux image build ww18-15
 *
 * This code is beerware; if you see me (or any other SparkFun employee) at the
 * local, and you've found our code helpful, please buy us a round!
 * ****************************************************************************/

#include "mraa.hpp"
#include "SparkFun_pca9685_Edison.h"
#include <iostream>
#include <unistd.h>

using namespace std;

// These channel definitions mirror the ones used in the PWM Block hookup guide.
#define SERVO 0
#define RED 2
#define GREEN 3
#define BLUE 4

// Uncomment one or both of these defines to enable the appropriate demo. Do
//  note servo motors and LEDs are best used at different frequencies and
//  polarities, so hooking both at once will give you bad results.
#define SERVO_DEMO
//#define LED_DEMO

// main() runs once and completes; there's no infinite loop here. Do note,
//  though, that whatever settings you write to the PWM module will persist
//  after the code has completed.
int main()
{
  // Variables to be used elsewhere in the program.
  uint16_t startTime, stopTime;

  mraa::I2c* pwm_i2c;   // We need to create an I2c object that we can pass to
                        //  the pca9685 constructor. If you have more than one
                        //  PCA9685 device on your bus (either by stacking more
                        //  than one PWM block or by adding external boards via
                        //  the I2C Expansion Block), you'll need to create a
                        //  different I2c object for each one!
  pwm_i2c = new mraa::I2c(1); // Tell the I2c object which bus it's on.

  pca9685 pwm(pwm_i2c, 0x40); // 0x40 is the default address for the PCA9685.

  // In general usage, you don't need to worry about getting or setting the
  //  mode registers or the prescaler register. I'm including these lines here
  //  just for example completeness purposes.
  cout<<"Current mode register values: 0x"<<hex<<pwm.readModeRegisters()<<endl;
  cout<<"Current prescaler: "<<dec<<static_cast<int16_t>(pwm.getPrescaler())<<endl;
  pwm.setPrescaler(121);

  // There are four generic functions allowing the user to change the start and
  //  stop times of the various channels. Generally, however, you shouldn't ever
  //  have to or want to use these, since there are more useful functions
  //  available which will be covered below.
  pwm.setChlTime(RED, 0, 0);
  pwm.setChlDuty(BLUE, 0);
  pwm.setChlStart(GREEN, 0);
  pwm.setChlStop(GREEN, 0);

  pwm.setChlDuty(SERVO, 0);

#ifdef LED_DEMO
  // When you call enableLEDMode(), you set the output to be approximately 400Hz
  //  and inverted. Thus, a 0 output will be a 100% high output. This allows us
  //  to use the output to drive common anode LEDs. See the tutorial for an
  //  example circuit.
  pwm.enableLEDMode();
  // Back to this, just so you can compare the settings in LED mode with the
  //  default (which is actually LED mode).
  cout<<"Current mode register values: "<<hex<<pwm.readModeRegisters()<<endl;
  cout<<"Current prescaler: "<<dec<<static_cast<int16_t>(pwm.getPrescaler())<<endl;
  for (uint8_t i = 0; i <= 100; i++)
  {
    // Check and print the start and stop times for the RED channel, then set
    //  all three to one percentage point higher. You'll note that the start
    //  time is always 0, and that the stop times increase logarithmically. This
    //  lets us get a visually linear brightness out of the LEDs.
    pwm.getChlTime(RED, &startTime, &stopTime);
    cout<<"Start time: "<<dec<<startTime<<endl;
    cout<<"Stop time: "<<dec<<stopTime<<endl;
    pwm.setChlLEDPercent(BLUE, i);
    pwm.setChlLEDPercent(GREEN, i);
    pwm.setChlLEDPercent(RED, i);
    usleep(100000);
  }
  sleep(4);
  pwm.setChlTime(RED, 0, 0);
  pwm.setChlTime(GREEN, 0, 0);
  pwm.setChlTime(BLUE, 0, 0);
  cout<<"LED demo complete!"<<endl;
#endif

#ifdef SERVO_DEMO
  // We can set or get the minimum and maximum angles the angle set function
  //  expects to see.
  int16_t servoMinAngle, servoMaxAngle;
  pwm.getServoAngleLimits(&servoMinAngle, &servoMaxAngle);
  cout<<"Current servo min angle: "<<dec<<servoMinAngle<<endl;
  cout<<"Current servo max angle: "<<dec<<servoMaxAngle<<endl;

  // Likewise, we can set the min and max of pulse widths. Each count here is
  //  about 4.5us, depending on the clock's accuracy.
  uint16_t minServoPL, maxServoPL;
  pwm.getServoAnglePulseLimits(&minServoPL, &maxServoPL);
  cout<<"Current servo min pulse length: "<<dec<<minServoPL<<endl;
  cout<<"Current servo max pulse length: "<<dec<<maxServoPL<<endl;

  // These numbers are based on experimentation with SparkFun's generic
  //  sub-micro servo motor. You may find that they are too high or too low for
  //  your particular motor. The generic settings are fairly conservative and
  //  there is no need to use these functions unless you feel like you can get
  //  a wider range of motion by doing so.
  servoMinAngle = 0;
  servoMaxAngle = 160;
  minServoPL = 108;
  maxServoPL = 450;
  pwm.setServoAnglePulseLimits(minServoPL, maxServoPL);
  pwm.setServoAngleLimits(servoMinAngle, servoMaxAngle);

  // enabling servo mode makes the output active high and sets the frequency to
  //  approximately 50Hz.
  pwm.enableServoMode();

  // For comparison against default values or LED mode values.
  cout<<"Current mode register values: 0x"<<hex<<pwm.readModeRegisters()<<endl;
  cout<<"Current prescaler: "<<dec<<static_cast<int16_t>(pwm.getPrescaler())<<endl;

  // This steps through the full range of your servo's rotation. It also shows
  //  the start and stop time of the pulses, so you can see how those correspond
  //  to different positions.
  for (int16_t i = servoMinAngle; i <= servoMaxAngle; i++)
  {
    pwm.getChlTime(SERVO, &startTime, &stopTime);
    pwm.setChlAngle(SERVO, i);
    cout<<"Start time: "<<dec<<startTime<<endl;
    cout<<"Stop time: "<<dec<<stopTime<<endl;
    usleep(100000);
  }
  cout<<"Servo demo complete!"<<endl;
#endif

  return MRAA_SUCCESS;
}

Resources and Going Further

Now that you have had a brief overview of the PWM Block, take a look at some of these other tutorials. These tutorials cover programming, Block stacking, and interfacing with the Intel Edison ecosystems.

Edison General Topics:

Block Specific Topics:


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

SparkFun Blocks for Intel® Edison - ADC

$
0
0

SparkFun Blocks for Intel® Edison - ADC a learn.sparkfun.com tutorial

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

Introduction

SparkFun’s ADC Block for the Intel Edison allows you to add four channels of I2C controlled ADC input to your Edison stack. These four channels can be used as single-ended inputs, or in pairs as differential inputs. A ground reference is provided for each channel.

The maximum resolution of the converters is 12 bits, or 11 bits bipolar in differential mode. Step sizes range from 125uV per count to 3mV per count.

Image of the block

ADC Block

Suggested Reading

If you are unfamiliar with Blocks, take a look at the General Guide to Sparkfun Blocks for Intel Edison.

Other tutorials that may help you on your Edison adventure include:

Board Overview

Labeled picture of the board

ADC Block Functional Diagram

  • Single Inputs - Four single inputs are available. The reference voltage for each is produced internal to the ADC.

  • Differential Pairs - Use two inputs to create a differential pair. Useful for eliminating noise in some sensors.

  • I2C Address Select - Apply solder to (only) one of the four jumpers to select the address.

  • Expansion Header - The 70-pin Expansion header breaks out the functionality of the Intel Edison. This header also passes signals and power throughout the stack. These function much like an Arduino Shield.

Using the ADC Block

To use the ADC Block simply attach an Intel Edison to the back of the board or add it to your current stack. Blocks can be stacked without hardware but it leaves the expansion connectors unprotected from mechanical stress.

Installed block image

ADC Block Installed

We have a nice Hardware Pack available that gives enough hardware to secure three blocks and an Edison.

Edison hardware kit

Intel Edison Hardware Pack

NOTE: The ADC Block does not have console access or a voltage regulator. It is recommended to use a console communication block in conjunction with this block like ones found in the General Guide to Sparkfun Blocks for Intel Edison.

C++ Code Examples

We’re assuming that you’re using the Eclipse IDE as detailed in our Beyond Arduino tutorial. If you aren’t, you’ll need to go to that tutorial to get up to speed.

Getting Started

Follow the instructions in the programming tutorial to create a new project named “SparkFun_ADC_Edison_Block_Example”. Once you’ve created the project, open the project files on disk (hint: you can find the path to the project by choosing “Properites” from the project menu) and copy the three source files found in the Edison ADC Block CPP library GitHub repository into the “src” directory.

Download a zip file of the repository

Hardware Connection

For this example, we’ve just got two 5k potentiometers connected between 3.0V and GND, with the wipers connected to channels 0 and 1.

Since the v10 ADC block only has ground references, we’re using two AA batteries to provide an external bias voltage for the potentiometers. Other sources with self-contained power supplies will not need this.

Example circuit diagram

Of course, you can connect any other analog voltage signal in place of the potentiometers; we’re using them because they’re convenient to demonstrate the concepts.

Code

Everything you need to know is in the comments.

/****************************************************************
Example file for SparkFun ADC Edison Block Support

1 Jun 2015- Mike Hord, SparkFun Electronics
Code developed in Intel's Eclipse IOT-DK

This code requires the Intel mraa library to function; for more
information see https://github.com/intel-iot-devkit/mraa

This code is beerware; if you use it, please buy me (or any other
SparkFun employee) a cold beverage next time you run into one of
us at the local.
****************************************************************/

#include "mraa.hpp"

#include <iostream>
#include <unistd.h>
#include "SparkFunADS1015.h"

using namespace std;

// Declare a variable for our i2c object. You can create an
//  arbitrary number of these, and pass them to however many
//  slave devices you wish.
mraa::I2c* adc_i2c;

int main()
{
    // The ADC is (by default) connected to I2C channel 1. Here, we create
    //  a device to pass to the ads1015 object constructor.
    adc_i2c = new mraa::I2c(1);

    // Now, pass that I2C object and the address of the ADC block in your
    //  system to the ads1015 object constructor. Note that there are up to
    //  four different addresses available here, settable by jumper on the
    //  board. You'll need to create an ads1015 object for each one.
    ads1015 adc(adc_i2c, 0x48);

    // There are 6 settable ranges:
    //  _0_256V - Range is -0.256V to 0.255875V, and step size is 125uV.
    //  _0_512V - Range is -0.512V to 0.51175V, and step size is 250uV.
    //  _1_024V - Range is -1.024V to 1.0235V, and step size is 500uV.
    //  _2_048V - Range is -2.048V to 2.047V, and step size is 1mV.
    //  _4_096V - Range is -4.096V to 4.094V, and step size is 2mV.
    //  _6_144V - Range is -6.144V to 6.141V, and step size is 3mV.
    // The default setting is _2_048V.
    // NB!!! Just because FS reading is > 3.3V doesn't mean you can take an
    //  input above 3.3V! Keep your input voltages below 3.3V to avoid damage!
    adc.setRange(_0_512V);
    // getResult() returns a normalized floating point value representing the
    //  current voltage of the passed channel. User is responsible for
    //  logic to determine whether the value is at min or max.
    cout<<"Ch 0: "<<adc.getResult(0)<<endl;
    cout<<"Ch 1: "<<adc.getResult(1)<<endl;
    // getDiffResult() returns a normalized fp value representing the
    //  difference between two channels. Options are
    //  0 - Ch0 - Ch1
    //  1 - Ch0 - Ch3
    //  2 - Ch1 - Ch3
    //  3 - Ch2 - Ch3
    cout<<"Ch 0 - ch 1: "<<adc.getDiffResult(0)<<endl;

    // If you want to do the math yourself, you can determine the current gain
    //  setting by using the getScaler() command.
    cout<<"Current scaler: "<<adc.getScaler()<<"V per bit"<<endl;
    // The current voltage is the scaler/1000 multiplied by the raw value. You
    //  can get the raw ADC readings using the getRawResult() and
    //  getRawDiffResult() functions.
    cout<<"Ch 0 raw: "<<adc.getRawResult(0)<<endl;
    cout<<"Ch 1 raw: "<<adc.getRawResult(1)<<endl;
    cout<<"Ch 0 - ch 1 raw: "<<adc.getRawDiffResult(0)<<endl;

    // If you want to get *really* crazy, you can always go look up the
    //  datasheet and read and write the configuration register directly.
    cout<<"Config register: "<<hex<<adc.getConfigRegister()<<endl;
    // There's a "setConfigRegister()" function, too, which expects an
    //  unsigned 16-bit integer. Just FYI.

    return MRAA_SUCCESS;
}

Resources and Going Further

Now that you have had a brief overview of the ADC Block, take a look at some of these other tutorials. These tutorials cover programming, Block stacking, and interfacing with the Intel Edison ecosystems.

Edison General Topics:

Block Specific Topics:


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

Electric Imp Breakout Hookup Guide

$
0
0

Electric Imp Breakout Hookup Guide a learn.sparkfun.com tutorial

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

impRoduction

The electric imp is a deviously awesome development platform. Disguised as an every day SD card, the imp is actually a unique combination of microprocessor and WiFi module. The imp makes connecting any device to the Internet a breeze. Looking to catch on with this “Internet of Things” fad? The imp is an excellent place to start.

alt text

The electric imp card and imp002 Breakout Board. (Note: We didn’t misplace the copywriter, electric imp is correct.)

In this tutorial, we’ll be explaining how to use the imp card with one of our Breakout Boards as well as the imp002 breakout board. You will have the choice of which platform to use (the imp card or the imp002).

First, we’ll cover how to hook up the hardware end of the imp and imp002. Following that we’ll head over into the firmware domain, programming the imp to blink LEDs and read analog and digital inputs. The last code example shows off the coolest part of the imp: controlling hardware over the Internet!

Required Materials

You have a choice to make! You can either use the imp card and Breakout Board, or you can use the imp002 Breakout Board.

If you want to use the imp card, you will need an electric imp and the electric imp Breakout Board.

Electric Imp

WRL-11395
$29.95
1
SparkFun Electric Imp Breakout

BOB-12886
$12.95

If, on the other hand, you want to use the imp002, you will need the electric imp imp002 Breakout Board.

SparkFun Electric Imp imp002 Breakout

BOB-12958
$44.95

Aside from one of those platforms, we’ll use a few common electronics parts you may already have. Here’s a wishlist of everything else we’ll be using.

NOTE: The 2-pin jumper is only required for the electric imp Breakout Board.


In addition to those items, you’ll also need the following non-SparkFun materials:

  • Wireless network with Internet access
  • electric imp planner account (sign up is free/easy)
  • electric imp planner website pulled up in your web browser
  • SmartPhone w/ the electric imp app (Android or iOS)

Tools

There will be some soldering involved. The Breakout Board does not come with header pins soldered on, which you’ll need in order to interface with the imp’s I/O pins. You’ll need a simple soldering iron and a bit of solder (If you’ve never soldered before, this is a great place to start! The solder points are easy, through-hole jobs).

Before We Begin

This tutorial builds upon some basic electronics concepts. If you aren’t familiar with any of the topics below, consider reading through that tutorial first:

Aside from the imp’s programming language, Squirrel, there will be a variety of coding languages used in later parts of this tutorial – primarily HTML and Javascript. Don’t worry if you’re not too familiar with those, as the examples aim to be short, sweet, and easy-to-modify.


Let’s start by overviewing the imp hardware itself. It’s hard, at first, to wrap your head around the fact that this little, module is actually a powerful WiFi-enabled microcontroller platform.

About the imp Card

It may look like an everyday SD card, but the electric imp is much, much more. It's a WiFi-enabled microprocessor. It’s programmable over the air. It’s got GPIOs, UARTS, I2C and SPI interfaces, pulse-width-modulation, digital-to-analog and analog-to-digital converters. Basically, it’s what you’d get if you smushed an ARM microprocessor and a WiFi module down into a tiny SD-card-sized package.

imp card boxed up

The imp provides an easy, integrated way to connect almost any hardware device to Internet services. It is well suited to be the backbone of your Internet-enabled project, whether you’re remotely controlling your electric blanket or triggering an irrigation system via a web browser. Connecting your imp to a wireless network and programming it is a simple, streamlined process.

The Hardware: 6 Wondrous I/Os

The imp is basically made of pure awesome. But, if we lift the hood of awesomeness for a moment, we can talk a bit about the imp's hardware. The platform of the electric imp is a Cortex-M3 microprocessor. Just like any microprocessor, the imp has a collection of input and output pins, each with unique functions. There are six addressable I/O pins – not as many as an Arduino, but it makes up for it in terms of functionality. The imp has three UARTs, two I2C and SPI interfaces, and two DAC outputs; plus each pin can act as an ADC input and PWM output.

imp pin table from Imp's Pin Mux's Page
Pin #UART1289UART57UART12I2C89I2C12SPI257SPI189DACADCPWM
1CTSTXSCLSCLKYesYesYes
2RTSRXSDAMISOYesYes
5TXSCLKYesYesYes
7RXMOSIYesYes
8TXSCLMOSIYesYes
9RXSDAMISOYesYes

Of course, each of those pins can also be used as a simple inputs (with or without pull-up resistors) or outputs, sinking/sourcing up to 4mA each.

Also in that tiny SD package is a WiFi module, an antenna, and a light sensor. We’ll find out why the light sensor is critical in the coming pages.

The imp is a 1.8-3.3V device, supplying it any more voltage than that can be harmful. It can require up to 400mA (worst-case), but it’ll usually pull about 80mA (even 5mA in a power-save mode).

The IDE

All code written for the imp is done online, in a browser-based integrated development environment (IDE). Everyone can (freely) create their own account on the IDE, where both your programs and your imps are kept safe and secure. There are certainly pros and cons to this “always online” approach (though you can write and save every program locally, and upload it when you’re ready). Still, it seems like a good solution for this type of platform.

A screenshot of the imp IDE

Code in the IDE is divided into two halves: the imp device, and the agent. Code in the device half is code that actually runs on your imp. The agent is a process living on electric imp’s cloud server. It can communicate with both your imp, and the outside Internet world. We’ll dig further into the differences between these two components later.

The Language: Squirrel

Firmware for the imp is written in a language called Squirrel. Squirrel is an object oriented language similar to Javascript, but unlike most embedded system programming languages we’ve encountered (namely Arduino). Entering imp development from the world of Arduino may be somewhat jarring. There are no loop() or setup() functions, instead most actions are event or timer-driven.

Example of squirrel language

There are tons of great examples on electric imp’s wiki page, and if you're truly interested in learning Squirrel, check out the Squirrel homepage. There’s also the Electric Imp API to familiarize yourself with. These are functions and libraries used to perform actions with the imp’s GPIO pins and other hardware functionality.

About the Breakout

In order to use an electric imp, two pieces of hardware are required: the imp card and the impee. An impee is the piece of hardware that houses the imp. Aside from having a standard SD socket for the imp to slide into, the impee also needs to provide power to the imp, and do something with the imp’s I/O pins. Our impee for this tutorial is as simple as it gets…a breakout board.

Top/bottom view of imp breakout

Top and bottom views of the imp breakout.

The imp breakout provides the bare minimum you should need to add an electric imp to your project. There’s an SD socket, a step-down voltage regulator, and every I/O pin of the imp is broken out to a 0.1"-spaced header.

Powering the Breakout

A big chunk of the circuitry on the Breakout board is a 3.3V TPS62172 step-down regulator (and the inductor/capacitors supporting it). This regulator allows for input voltages anywhere between 3.3V and 17V (voltages in the upper end of that range may produce some heat). It can support up to 500mA of continuous current.

There are three power inputs on the board, all of which, are fed into the on-board 3.3V regulator:

  • “VIN” header - This standard 0.1" header feeds directly into the 3.3V regulator.
  • Battery input - These are the pins and pads labeled “+” and “-”. The footprint of the two through-hole pins matches up to a PTH 2-pin JST connector, which mates with our LiPo batteries (or AA batteries). This input needs to be selected using the jumper (see below).
  • USB mini-B connector - This power input should feed a clean, 5V source into the breakout board’s regulator. The USB voltage supply can come from either a mini-B cable connected to your computer or a USB wall adapter. This input needs to be selected using the jumper (see below).

Where the power inputs are

Setting the Jumper

To use either the battery or USB power inputs, a jumper must be set on the board. To use the jumper, first solder a 3-pin male header to the jumper pins. Then use a 2-pin jumper to span from the middle pin, to whichever of the two inputs you’d like to use.

Jumper set to USB

In this image, the jumper is set to apply USB power to the imp breakout. A JST connector was soldered to the battery input pins, in case we want to use a LiPo to power the board.

The Breakout’s Schematic

There are three main components to the breakout board: a TPS62172 step-down regulator (U2), the electric imp socket (U1), and the ATSHA204 authentication chip (U3).

Electric Imp Breakout Schematic

electric imp Breakout Schematic. Click the image to get a larger picture, or click here to view the schematic as a PDF.

Pinout

All of the imp’s GPIO pins are broken out to the 0.1"-spaced header, along with a few related power pins:

  • GND - Common pin for input voltage
  • VIN - Input voltage supply fed into regulator
  • PIN1 - imp pin 1 (UART1289 CTS, UART12 TX, I2C12 SCL, SPI189 SCLK, DAC, ADC, PWM)
  • PIN2 - imp pin 2 (UART1289 RTS, UART12 RX, I2C12 SDA, SPI257 MISO, ADC, PWM)
  • PIN5 - imp pin 5 (UART57 TX, SPI257 SCLK, DAC, ADC, PWM)
  • PIN7 - imp pin 7 (UART57 RX, SPI257 MOSI, ADC, PWM)
  • PIN8 - imp pin 8 (UART1289 TX, I2C89 SCL, SPI189 MOSI, ADC, PWM)
  • PIN9 - imp pin 9 (UART1289 RX, I2C89 SDA, SPI189 MISO, ADC, PWM)
  • CD - Card detect. This signal will connect to GND whenever a card is inserted into the socket.
  • 3V3 - 3.3V output from regulator
  • GND - Common ground

ID Chip

There’s actually one more piece of hardware required of the impee: an ID chip, which provides each impee with a unique identification code. This means that every impee you encounter should include an Atmel ATSHA204 authentication chip. The imp automatically interfaces with this chip every time it boots up, so it can identify which impee it’s plugged into. This actually turns out to be pretty awesome, because the program that an imp runs depends on what impee it’s plugged into. If you had two impees in your house – say controlling an irrigation system and another controlling a coffee machine – one, single imp would run two different programs depending on which machine it was plugged into.

You shouldn’t ever have to fuss with the ID chip. In fact, you can forget we ever said anything about the ATSHA204!

About the imp002 Breakout

The imp002 is a solder-down module version of the original imp card. We have done the hard work of creating a breakout board for you. Now, you just need one board instead of 2 to get started with the electric imp!

imp002 Breakout Board top and bottom

We recommend you read the About the imp section to learn what is in the imp, what the Planner is, and a brief overview of the Squirrel language. Like the imp card, the imp002 module contains an embedded ARM Cortex-M3 microprocessor, an onboard WiFi module, and antenna.

The Hardware: 12 Glorious I/Os

We have broken out 12 I/O pins from the imp002 module to standard 0.1" headers. Much like the imp card, these pins can be used for a variety of functions.

imp002 pin table from Imp's Pin Mux's Page
Pin #UART1289UART57UART12UART6EUARTBI2C89I2C12SPI257SPI189DACADCPWM
AYes
BRXYes
CYes
D
ERX
1CTSTXSCLSCLKYesYesYes
2RTSRXSDAMISOYesYes
5TXSCLKYesYesYes
6TX
7RXMOSIYesYes
8TXSCLMOSIYesYes
9RXSDAMISOYesYes

Powering the imp002 Breakout

The imp002 Breakout Board contains a 3.3V TPS62172 step-down regulator (and the inductor/capacitors supporting it). This regulator allows for input voltages anywhere between 3.3V and 17V (voltages in the upper end of that range may produce some heat). It can support up to 500mA of continuous current.

There are three power inputs on the board, all of which, are fed into the on-board 3.3V regulator:

  • “VIN” header - This standard 0.1" header feeds directly into the 3.3V regulator.
  • Battery input - These are the pins labeled “+” and “-” as well as the JST connector, which mates with our LiPo batteries (or AA batteries).
  • USB mini-B connector - This power input should feed a clean, 5V source into the breakout board’s regulator. The USB voltage supply can come from either a mini-B cable connected to your computer or a USB wall adapter.

imp002 Breakout Board power inputs

NOTE: There is a voltage selector circuit on the imp002 Breakout Board that will automatically use whichever voltage is higher: battery or USB. Be aware that the circuit does NOT charge the battery, it just prevents current flowing back into the source with the lower voltage (i.e. a short).

The imp002 Breakout’s Schematic

There are a number of circuits used to support the imp002, all of which can be found on the imp002 Breakout Board.

alt text

electric imp imp002 Breakout Schematic. Click the image to get a larger picture, or click here to view the schematic as a PDF.

  • Input Voltage Source Selection - automatically switches between USB and battery input (whichever voltage is higher)
  • Pin Breakout - Power and I/O pins from the imp002 module
  • DC/DC converter - the TPS62172 buck regulator and supporting components
  • Input Voltage Measurement - the jumper can be soldered to allow VIN measurements on PIN A
  • imp002 module - the imp module and decoupling capacitors
  • Status LED - the red/green LED required by the imp to display its status (connecting, error, etc.)
  • BlinkUp - Light sensor for sending WiFi credentials to the imp002 module

Pinout

All of the imp’s GPIO pins are broken out to the 0.1"-spaced header, along with a few related power pins:

  • GND - Common ground
  • VIN - Input voltage supply fed into regulator
  • PIN_A - imp002 pin A (ADC)
  • PIN_B - imp002 pin B (UARTB RX, ADC)
  • PIN_C - imp002 pin C (PWM)
  • PIN_D - imp002 pin D
  • PIN_E - imp002 pin E (UART6E RX)
  • PIN_1 - imp002 pin 1 (DAC, UART1289 CTS, UART12 TX, I2C12 SCL, SPI189 SCLK, DAC, ADC, PWM)
  • PIN_2 - imp002 pin 2 (UART1289 RTS, UART12 RX, I2C12 SDA, SPI257 MISO, ADC, PWM)
  • PIN_5 - imp002 pin 5 (UART57 TX, SPI257 SCLK, DAC, ADC, PWM)
  • PIN_6 - imp002 pin 6 (UART6E TX)
  • PIN_7 - imp002 pin 7 (UART57 RX, SPI257 MOSI, ADC, PWM)
  • PIN_8 - imp002 pin 8 (UART1289 TX, I2C89 SCL, SPI189 MOSI, ADC, PWM)
  • PIN_9 - imp002 pin 9 (UART1289 RX, I2C89 SDA, SPI189 MISO, ADC, PWM)
  • VDDA - ADC reference voltage. Connected to 3.3V by default.
  • 3.3V - 3.3V output from regulator
  • GND - Common ground

    IMPORTANT: If you disconnect the VDD/VDDA jumper, you MUST bring up the VDD (3.3V) power before bringing up the VDDA reference voltage. Additionally, if VDDA is greater than VDD (3.3V), it might cause damage to the imp002 module.

Hardware Hookup

The hardware hookup approach in this guide is just one of many ways to use the board. The breakout is made to be a versatile extension of the imp. You can connect whatever you want to the imp pins, and power the board however your project requires.

Solder Headers

In order to do much with the input/output capability of the imp, you’ll need to solder to the broken out pins. If you want to use the imp Breakout with a breadboard or perfboard, 0.1" male headers make for a good choice. Depending on your application, you could swap the headers with wire, female headers, screw terminals, or a variety of other connectors.

We’re going to solder male headers into the board, so we can use it with a breadboard later on.

Headers soldered on to breakout, inserting into breadboard

Pins soldered onto the imp Breakout Board

Headers soldered on to impt002 breakout, inserting into breadboard

Pins soldered onto the imp002 Breakout Board

Apply Power

Depending on what you want to use for your power source there are a few options here. You could use the on-board USB connector. Or you could solder down a 2-pin JST connector, and plug battery (LiPo or AA) into the board to make it mobile. If you go with either of those options on the imp card Breakout, you’ll also need to set the jumper (the imp002 Breakout will automatically select the higher voltage).

Jumper set to USB power

Note how the jumper is set. We’re using USB to power the imp in this picture.

USB power to the imp002 Breakout Board

No need to set a jumper on the imp002 Breakout Board! We’re using USB to power the imp002 here.

Alternatively, you can apply power straight to the headers labeled “VIN” and “GND”. This pin bypasses the jumper and goes straight to the regulator.

Plug in the imp!

If you have the original imp card, plug the imp card in so the suspicious little imp logo is facing up. If you’ve got power to the board, once plugged in, the imp should start blinking orange. If there’s no blinking on the card, it’s probably not getting any power. Double-check that the jumper is set correctly.

If you have the imp002, the status LED should start blinking orange as soon as you apply power.


What’s all that blinking signify? How do we get the imp connected to our wireless network? Read on!

BlinkUp

Blink Codes

The imp has an internal red/green LED, which is used to tell the world what state it’s currently in. If you’ve just plugged the imp in, and haven’t told it how to get on your WiFi network, it should be blinking orange (red/green simultaneously). Here are the rest of the codes to look out for:

imp blink codes (from the imp blinkup guide)
ColorSpeedimp State
Orange1 HzNo WiFi settings
GreenSingle PulseSuccessfully received configuration via Blinkup.
RedTriple-pulseFailed to receive configuration via Blinkup.
Red1 HzAttempting to connect to WiFi.
Red, Orange, Off1 HzGetting IP address (via DHCP).
Orange, Red, Off1 HzGot IP address, connecting to server.
Green0.5 HzConnected to cloud (turns off after 60 seconds).
Red2 HzConnection lost, attempting to reconnect.
NoneNormal operation

Let’s make that LED blink green! Time to send a BlinkUp.

BlinkUp

To get your imp connected to your WiFi network as well as the online imp servers, you need to go through the process electric imp calls commissioning. There’s a great write-up on the commissioning process over on electric imp’s Getting Started page. Here’s the gist of it, as well as a few tips.

Before you begin, you’ll need to make an Electric Imp account by visiting the IDE page.

Updating the imp with your WiFi credentials is a unique process. The imp card has a built-in light sensor, looking out of the little window on the short, flat edge of the imp. The imp002 has an external light sensor built into the breakout board. The light-sensor can be used to process small amounts of precisely modulated data in the form of a blinking light.

The edge of the imp card where the light sensor window is

The light sensor is just behind the translucent window on the edge of the imp card.

light sensor on the imp002 Breakout Board

The light sensor on the imp002 is located to the left of the module, with the lable “BU” (for BlinkUp).

To generate this blinking light, you need the electric imp app installed on your smartphone (iOS or android). Go download that app if you haven’t already!

Follow the directions in the app, and prepare to update the imp with your WiFi network. Then, when your settings all look correct, hit the Send BlinkUp button. Quickly place the screen of the phone as close to the imp’s light sensor as possible.

BlinkUp in action

Avert your eyes! Unless you enjoy staring into bright, white strobing lights.

BlinkUp for the imp002

Similar warnings about white strobing lights.

If all goes well, there should be a very short green blip of the LED, followed by a few blinks of red and orange. When the imp starts blinking green once a second, you know you’ve got your imp commissioned yay!

Troubleshooting

If you’re imp isn’t yet in the blinky green phase, use the LED blink codes to find out where it’s failing. Here are some recommended steps, depending on the failure point:

  • Connecting to the server (orange, red, off) - Make sure there’s no firewall blocking the imp’s way to the Internet (and make sure your WiFi network has an Internet connection in the first place).
  • Getting IP address via DHCP (red, orange, off) - Double check your WiFi password.
  • Attempting WiFI connection (red) - Double check your WiFi network name (SSID).

If all of the above are set correctly, try sending the BlinkUp one more time. We’ve found that it helps to close out all other app, or even try resetting your phone if it continues to fail.

More troubleshooting information can be found on electric imp’s site.

Example 0: Hello World

Now that your imp is commissioned, it’s time to upload your first bit of code!

As with any new development platform, our first goal is to make sure we can make an LED blink. If you can make an LED blink, you’re well on your way to spinning motors or communicating with sensors.

Using the IDE

To begin, go to electric imp IDE, and log in if you haven’t already.

If your electric imp was successfully commissioned, you should see your imp device appear under Unassigned Devices on the left-hand side.

New imp device added

Click the Create New Model button.

Creating a new model in electric imp

In the name field, type “Hello, blink” for the name of our model. Check the box next to our device under Unassigned Devices. Click Create Model.

Now, on the left side, you should see a new tab called Hello, blink. Select than, then click your imp name. This is the standard view of the imp IDE. It’s split into three sections:

  1. Agent– This is code that runs external to your imp, in the cloud. You can offload server tasks, like HTTP requests, here. There are built in functions to aid in communication between imp and agent.
  2. Device– This is the code that your imp runs. This is where you do all of your hardware control, like writing pins high and low, or reading inputs.
  3. Log– This is where messages and errors are printed (using the server.log() function).

Blank imp IDE

Now we’re ready to load some code and blink some LEDs!

The Circuit

The circuit for this example is very simple. We only need to connect an LED to pin 1. Don’t forget your current-limiting resistor (330 Ω)!

LED connected to pin 1

imp circuit

LED connected to pin 1

imp002 circuit

Any of the imp’s I/O pins would work for this example. After working with the code, see if you can modify it to blink on other pins (or all of them!).

Hello, blink Code

We’ll only be working with the Device portion of the IDE right now. Copy and paste the code below into the middle section of your window.

language:squirrel
/* Hello, Blink
   by: Jim Lindblom
   SparkFun Electronics
   date: October 31, 2013
   license: Beerware. Use, reuse, and modify this code however you see fit.
   If you find it useful, buy me a beer some day!

   This is an Electric Imp hello, world blink sketch. It'll blink an LED
   connected to pin 1, once every second.
*/

////////////////////////////////////////
// Global Variables                   //
////////////////////////////////////////
ledState <- 0;

////////////////////////////////////////
// Function definitions               //
////////////////////////////////////////

// Loop constantly updates the LED. If ledState is 1, we'll turn the LED on and
// set ledState to 0. Vice-versa is ledState is 0 coming in. This function
// schedules a wakeup in 1 second, and calls itself again.
function loop()
{
    if (ledState)
    {
        hardware.pin1.write(1); // Write pin 1 high
        ledState = 0; // Flip ledState
    }
    else
    {
        hardware.pin1.write(0); // Write pin 1 low
        ledState = 1; // Flip ledState
    }

    // This must be called at the end. This'll call loop() again in 1s, that way
    // it'll actually loop!
    imp.wakeup(1.00, loop);
}

////////////////////////////////////////
// Setup Stuff: Runs first at startup //
////////////////////////////////////////
hardware.pin1.configure(DIGITAL_OUT);   // Configure Pin 1 as digital output

loop(); // Call loop, and let the program go!

Then hit the >Build and Run button up top, and enjoy the blinks.

Shortcut heads up! If you’re a neurotic CTRL+S saver, the standard save shortcut doessave, but it also attempts to build and run your code. If successful, it’ll upload the code and immediately start running on your imp. If there’s an error, you’ll start hearing about it in the log window.

Into the Code

If you’re only used to working with Arduino sketches, this code may make very little sense, electric imp programs have a very different “flow” to them. Begin by looking at the 2 lines of code at the bottom (under the “Setup Stuff” header). This is actually where our imp starts when it begins to run it’s program. Everything above is simply a function or variable definition.

The majority of this code deals with the imp’s pin class, which handles all of the I/O control. If you’re used to using Arduino GPIO’s, the imp’s API isn’t too different. You have to set the pin up as either an input or output, analog or digital. Then write or read to the pin accordingly.

At the end of the setup, we make a call to a loop() function, which is defined above. loop() is simple, it checks a global variable named ledState. If ledState is 1 we turn the LED on, if it’s 0 we turn the LED off.

To write a pin high or low, we call the hardware.pin1.write([0:1]) function. You can probably extrapolate from that how to control the other five pins.

The special sauce making loop actually loop is the last line of code in the function: imp.wakeup(1.00, loop). The imp.wakeup function puts the imp to sleep, but sets a timer. When the timer goes off, the requested function (loop in this case) function is called from its beginning. In this case we set the timer to 1.00 seconds, so loop() should run once a second. This is really the only way to make the electric imp “loop” like an Arduino might.

Check out the comments in the code for a more in-depth overview of each function call. Or, for more information, check out electric imp’s API reference.

Example 1: I/O Control

The electric imp can do most anything an Arduino or similar microcontroller can. It’s got analog-to-digital converters, PWM, SPI, I2C, UARTs, and it even has digital-to-analog converters. In this snippet of example code, we’ll dig further into the imp’s I/O control delving into digital and analog input/output.

Example 1 circuit image

electric imp and Breakout Board connected the Example 1 circuit

Example 1 circuit on the imp002 Breakout Board

imp002 connected the Example 1 circuit

The Circuit

The setup for this example code requires three unique components: an LED, potentiometer, and a button (plus a current-limiting resistor for the LED). Here’s a fritzing diagram and schematic (click to see it bigger) for our circuit:

Example 1 schematic

imp schematic

imp Fritzing for example 1

imp circuit

Example 1 Fritzing diagram

imp002 circuit

Make sure the imp is getting power. USB is usually the quickest/easiest way to apply power to the breakout board, but you’ll need to set the jumper accordingly on the breakout.

The IDE

To create a new piece of code, we need to create a new “model” and associate it with our Breakout Board impee. To do this, hover over your impee and click the “settings” gear. The familiar Device settings window should pop up. Under the Associated model: box, create a new model named I/O Control. Then click Save Changes_.

Assigning the impee to a new model

This will create a new tab on the left side labeled I/O Control. If you expand that tab, you’ll see that the Breakout Board impee has be reassigned there.

The Code

Once again, we’ll only be using the Device portion of the IDE. Copy and paste everything from the below box, into your Device window and click Build and Run up top.

language:Squirrel
/* Digital Input, Analog Input, PWM Output Example
   by: Jim Lindblom
   SparkFun Electronics
   date: July 15, 2013
   license: Beerware. Use, reuse, and modify this code however you see fit.
   If you find it useful, buy me a beer some day!

   This is a simple piece of code which uses an LED, potentiometer, and button.
   The LED connects to pin 1 through a 47 ohm resistor. The cathode of the LED should connect to ground.
        This means writing pin 1 will turn the LED on, and writing it to 0 turns the LED off.
   The button connects on one side to pin 9, and the other pin of the button goes to ground.
        We'll use the internal pull-up resistors on pin 9 to bias the button high.
        When the button is pressed, pin 9 should read as low.
   The wiper of the potentiometer is connected to pin 5. The other two pins of the pot should be
        connected to +3.3V and GND. This'll make the voltage at pin 5 adjustable from 0-3.3V.
*/

////////////////////////////////////////
// Function definitions               //
////////////////////////////////////////

local ledState = 1; // Says local, but think of this as a global var. Start with LED on

// function pin9Changed() will be called whenever pin 9 goes from high->low or low->high
function pin9changed()
{
    local buttonState = hardware.pin9.read(); // Read from the button pin

    if (buttonState == 0) // Button will read low if pressed
    {
        ledState = ledState ? 0 : 1;    // Flip flop ledState
        server.log("Button pressed!");
    }
    else // Otherwise button was released, no action
    {
        server.log("Button released");
    }
}

// Loop constantly updates the LED. If ledState is 1, we'll read the pot, and set the LED brightness accordingly.
// If ledState is 0, we'll just turn the LED off. ledState is updated in the pin9Changed() function.
function loop()
{
    if (ledState == 1)
    {
        local rawValue = hardware.pin5.read();  // Read from the potentiometer. Returns a value between 0 and 65535.
        rawValue /= 65535.0;  // Make rawValue a % (and a float). The pin write function requires a value between 0 and 1.
        hardware.pin1.write(rawValue);  // Pin 1 is already configured as PWM, write potentiometer value
    }
    else
    {
        hardware.pin1.write(0);  // Write pin 1 low -- LED off
    }

    // This must be called at the end. This'll call loop() again in 10ms, that way it'll actually loop!
    imp.wakeup(0.01, loop);
}

////////////////////////////////////////
// Setup Stuff: Runs first at startup //
////////////////////////////////////////
hardware.pin1.configure(PWM_OUT, 0.0005, 0.0);   // Configure Pin 1 as PWM output, 5ms period, 0% high (off)
hardware.pin5.configure(ANALOG_IN); // Configure pin 5 as analog input
hardware.pin9.configure(DIGITAL_IN_PULLUP, pin9changed); // Configure pin 9 as digital input (with pull-up enabled). On change it'll call function pin9changed().
imp.configure("LED Trigger Wiper", [], []);

loop(); // Call loop, and let the program go!

The code creates an adjustable-brightness LED controller. The brightness of the LED is adjusted by turning the potentiometer. Pressing the button will turn the LED on and off.

Explaining the Code

The skeleton of this code acts a lot like that of Hello, blink. The function definitions are up top, the setup stuff runs at the bottom, and loop() is called at the beginning. loop() continually calls itself, using the imp.wakeup(0.01, loop) function call, every 10 ms.

The loop() function again relies on an ledState variable. If ledState is 1, we read the potentiometer voltage, and adjust the brightness of our LED accordingly.

The ledState variable is flip-flopped in the pin9changed() function. This is like an interrupt. It’s called whenever the state of pin 9 changes – if it goes from high to low, or low to high. When setting up pin 9 as a digital input, we added this function as the one to be called when the state change occurred.

Check out the comments in the code for a more in-depth overview of each function call. Or, for more information, check out electric imp’s API reference.


Enough hardware stuff! The next two examples will make use of the imp’s greatest feature…it’s web connectivity.

Example 2: Web Control (Request)

Some of the most fun you can have with the electric imp is connecting it to the Internet, and interfacing it with web pages. In this example, we’ll use a simple HTML/Javascript web page to control some LEDs connected to the imp.

This time, we’ll not only be writing code for the imp, but the agent as well. This example code will show how to pass data from the imp to the agent, and how to write a simple web page to interact with the agent half of the code.

The Circuit

The circuit for this example is very simple: a common-cathode RGB LED is connected to the imp’s pins 1, 2, and 5 (red, green, and blue anodes respectively), and another basic red LED is connected to pin 9 of the imp. Don’t forget to add some current limiting resistors (in the range of 50-100&ohm;)!

Schematic for example 2

imp schematic

imp Fritzing for example 2

imp circuit

imp002 Fritzing for example 2

imp002 circuit

The imp (Device) Code

Create a new model, as you did in the last example. We’ll call this one LED Web Control. Copy and paste the code below into the Device section of the IDE.

language:javascript
/* Electric Imp Web-controlled LEDs
    by: Jim Lindblom
    SparkFun Electronics
    date: November 1, 2013
    license: Beerware. Please use, reuse, and modify this code.
    If you find it useful, buy me a beer some day!

    This is a simple electric imp example, which shows how to interface
    the imp with an agent and webpage. This example code goes hand-in-hand with
    an HTML webpage. Check out this page for more information:
    https://learn.sparkfun.com/tutorials/electric-imp-breakout-hookup-guide/example-2-web-control
    This will show how you can use html color, text, and radio form inputs
    to control LEDs on/off, PWM them, and set a timer to turn them off.

    Circuit:
    A common cathode RGB LED is connected to the imp's pins 1, 2, and 5.
    The red anode connects to 1 through a 47 Ohm resistor, green 2, and blue 5.
    The cathode of the LED connects to ground.
    Another simple, red LED is connected to the imp to imp pin 9, through
    another 47 Ohm resistor. The cathode of the LED is grounded.
*/

imp.configure("LED Web Control", [], []); // Configure the imp

///////////////
// Pin Setup //
///////////////
// Setup reference variables for our pins:
redPin <- hardware.pin1;   // R of RGB
greenPin <- hardware.pin2; // G of RGB
bluePin <- hardware.pin5;  // B of RGB
ledPin <- hardware.pin9;   // Lonely red LED

// Configure our pins:
ledPin.configure(DIGITAL_OUT);        // Simple digital output
redPin.configure(PWM_OUT, 0.01, 0);   // PWM output 10ms clock, off
greenPin.configure(PWM_OUT, 0.01, 0); // PWM output 10ms clock, off
bluePin.configure(PWM_OUT, 0.01, 0);  // PWM output 10ms clock, off

/////////////////////////////////
// Agent Function Declarations //
/////////////////////////////////
// setLed will turn the lonely red LED on or off.
// This function will be called by the agent.
function setLed(ledState)
{
    ledPin.write(ledState);
}

// setRGB will take a table input, and set the RGB LED accordingly.
// the table input should have parameters 'r', 'g', and 'b'.
// This function will be called by the agent.
function setRGB(rgbValue)
{
    bluePin.write(rgbValue.b/255.0);
    redPin.write(rgbValue.r/255.0);
    greenPin.write(rgbValue.g/255.0);
}

// setUser will print out to the log the name of the LED changer
// This function will be called by the agent.
function setUser(suspect)
{
    server.log(suspect + " set the LEDs.");
}

// setTimer will turn the LEDs off after a specified number of seconds
// This function will be called by the agent.
function setTimer(time)
{
    if (time != 0)
        imp.wakeup(time, ledsOff); // Call ledsOff in 'time' seconds.
}

///////////////////////////////////
// Important Agent Handler Stuff //
///////////////////////////////////
// Each object that the agent can send us needs a handler, which we define with
// the agent.on function.  The first parameter in agent.on is an identifier
// string which must be matched by the sending agent. The second parameter is
// the name of a function to be called. These functions are already defined up
// above.
agent.on("led", setLed);
agent.on("rgb", setRGB);
agent.on("user", setUser);
agent.on("timer", setTimer);

//////////////////////
// Helper Functions //
//////////////////////

// ledsOff just turns all LEDs off.
function ledsOff()
{
    ledPin.write(0);
    redPin.write(0);
    greenPin.write(0);
    bluePin.write(0);
}

The key bit of new code in this example is the agent.on function call. Run during the setup portion of the code, these function calls set up a handler function to be called whenever the agent sends a specific string to the imp. For example, the agent.on("led", setLed); functions says that whenever a message tagged with an “led” string is received from the agent, call the setLed() function.

How do we send messages from the agent to the imp? Looks like it’s time to start using the other half of the IDE window…

The Agent Code

The agent is a piece of squirrel code living and running in the electric imp cloud. While the imp is managing all of its hardware pins, the agent can be off mingling with other servers and dealing with Internet traffic. There are built in functions which allow the imp to send data to the agent, and vice-versa.

In this example, we’ll set the agent up to listen for HTTP requests. Upon receiving a request, the agent will parse the query, and relay the important information back to the imp.

Copy and paste this code into the Agent half of your LED Web Control model:

language:javascript
/* Agent for imp Web-Controlled LEDs
    by: Jim Lindblom
    SparkFun Electronics
    date: November 1, 2013
    license: Beerware. Please use, reuse, and modify this code.
    If you find it useful, buy me a beer some day!

    This is the agent portion of the LED Web Controller. It defines how http
    requests to https://agent.electricimp.com/XXXXXXXXXXXX are handled. Check
    your agent URL to find out what, exactly, XXXXXXXXXXXX is.

    For example, if your agent url is https://agent.electricimp.com/UpyYpRLmBB7m
    sending https://agent.electricimp.com/UpyYpRLmBB7m?led=0 should turn the
    lonely red led off.  https://agent.electricimp.com/UpyYpRLmBB7m?led=1 would
    turn the LED on.

    * There are also request handlers for "rgb", which should be a #RRGGBB
      formatted string. E.g: https://agent.electricimp.com/UpyYpRLmBB7m?rgb=%238500b7
    * A "user" request handler can receive a string. E.g.: https://agent.electricimp.com/UpyYpRLmBB7m?user=Jim
    * And a "timer" handler looks for a number-looking string. E.g.:
      https://agent.electricimp.com/UpyYpRLmBB7m?timer=10

    The parameters can be combined in one request. E.g.:
    https://agent.electricimp.com/UpyYpRLmBB7m?led=1&rgb=%237f3fff&timer=10&user=Jim
*/

// At the start, print a message to say we're online, and print the agent URL:
server.log("LED Web Control Agent Online: " + http.agenturl());

// requestHandler handles all http requests coming into the agent. It's only
// setup to look for a select few requests: "led", "rgb", "user" and "timer".
function requestHandler(request, response)  {

    try { // Try provides us with exception handling, in case a runtime error occurs

        // check if the user sent led as a query parameter
        if ("led" in request.query) {
            // if they did, and led=1.. set our variable to 1
            if ((request.query.led == "1") || (request.query.led == "0"))
            {
                // convert the led query parameter to an integer
                local ledStatus = request.query.led.tointeger();

                // send "led" message to device, and send ledState as the data
                device.send("led", ledStatus);
            }
        }
        // check if an "rgb" query was received:
        if ("rgb" in request.query) {
            // colors are sent as a string, we've got to do some work to convert
            // them to a number, which is eventually what we'll need to do
            // pwm on our RGB led pins.
            local color = request.query.rgb; // get the query into a variable
            if (color[0] == '#') { // The request should start with '#' (%23)
                // We'll construct a table with three parameters: r, g, and b
                // Do some work to convert r, g, and b from ASCII characters
                // to 0-255 values.
                local returnTable = {
                    r = ASCIItoHex(color[1])*16 + ASCIItoHex(color[2])
                    g = ASCIItoHex(color[3])*16 + ASCIItoHex(color[4])
                    b = ASCIItoHex(color[5])*16 + ASCIItoHex(color[6])
                };
                device.send("rgb", returnTable); // send our color table to the imp
            }
        }
        // check if a "user" query was received.
        if ("user" in request.query) {
            device.send("user", request.query.user); // Simply pass the value out to the imp.
        }
        // check if a "timer" query was received:
        if ("timer" in request.query) {
            // convert to an integer, and pass it out to the imp.
            device.send("timer", request.query.timer.tointeger());
        }
        // send a response back saying everything was OK.
        response.send(200, "OK");
    }
    catch (ex) {
        response.send(500, "Internal Server Error: " + ex);
    }
}

// Set up a handler for HTTP requests. This is the function that we defined above.
// https://electricimp.com/docs/api/http/onrequest/
http.onrequest(requestHandler);

//////////////////////
// Helper Functions //
/////////////////////////////

// This function converts an ASCII character to a number
function ASCIItoHex(colorNibble) {
    if ((colorNibble >= '0') && (colorNibble <= '9')) {
        return colorNibble - 48;
    }
    else if ((colorNibble >= 'a') && (colorNibble <= 'f')) {
        return colorNibble - 87;
    }
    else if ((colorNibble >= 'A') && (colorNibble <= 'F')) {
        return colorNibble - 55;
    }
}

Check out the comments in the code for a line-by-line dissection. Most of the code on the agent is an HTTP request handler (the requestHandler(request, response) function). This function uses a series of if statements to check for a specific request parameter key (like “led” or “rgb”). In those if statements, the agent decides what to do with the parameter value (if anything) and sends a message to the imp using the device.send function.

With both of those halves of code added to your model, and the circuit built, build and run the model. Time to test it out!

Testing the Model

After initially running the model, you shouldn’t see anything happen to your imp or the LEDs it’s connected to. To change that, we need to send an HTTP request to the agent.

First, we need to locate the URL of our agent, which is printed at the top of your Agent window. It’ll be something like https://agent.electricimp.com/0123456789ABCDEF. Each imp gets its own, unique, agent URL.

electric imp agent link

How to locate the agent URL. Mine, for example, is https://agent.electricimp.com/UpyYpRLmBB7m.

We can send requests to the agent by adding URL query strings onto the agent URL. For example, type https://agent.electricimp.com/qJx35x_LTITP?led=1 (make sure you replace my unique code with your own!) into your browser’s address bar and go. Notice anything happen on your imp circuit? The lonely red LED should have turned on! Look through the agent code to see what other parameters we can send.

We can even add multiple parameters to the same request, for example try going to https://agent.electricimp.com/qJx35x_LTITP?led=1&rgb=%234080ff&timer=10 in your browser. This request turns on the LED, but it also sends an RGB string to control the RGB LED and it sets a timer to turn all LEDs off.

This is very cool, but typing these parameters into an address bar is a pain! Let’s write a simple HTML webpage to take a form input and do all of that for us!

The HTML Code

This is the last piece to the puzzle – a simple HTML page that takes a form input, and sends that information out to our electric imp agent.

Create a local file on your computer called impControl.html. Open it with a text editor, and paste the below code into it.:

language:html<html><head></head><body onLoad=updateURL()><h4>What is your agent's url?</h4><form name="url">
https://agent.electricimp.com/<input type="text" name="agentUrl" placeholder="qJx35x_LTITP" onChange=updateURL()></form><h4>Imp Inputs:</h4><form name="leds" id="ledSend" method="get">
Lonely Red LED: <input type="radio" name="led" value="0" checked>Off<input type="radio" name="led" value="1">On<br>
Set the RGB LED: <input type="color" name="rgb">  (Chrome/Opera use color input, other browsers format as "#XXXXXX", where X is 0-9, a-f, or A-F.) <br>
How long should the LEDs stay on? <input type="text" name="timer" value="10">seconds<br>
Your name? So we know who to blame! <input type="text" name="user" placeholder="Your name here"><br><br><input type="submit" value="Update!"></form></body><script language="javascript">

 function updateURL() {
    ledForm = document.leds;
    urlForm = document.url;
    ledForm.action = "https://agent.electricimp.com/" + urlForm.agentUrl.value;
}</script></html>

Then save and open the file with your browser of choice. A simple web page like this should show up:

electric imp LED control webpage

Make sure you type in the correct, unique code for your agent URL. Then play with the rest of the form inputs. The On/Off radio buttons turn the lonely red LED on or off. The RGB color selector sets the color of the RGB LED. The duration text box will turn all LEDs off after a set number of seconds. And the name textbox will print your name in your imp’s console. Try it out!

Example 2 circuit. A phone browser controlling the LED.

electric imp and Breakout Board being controlled by a phone’s browser.

Example 2 imp002 circuit

imp002 being controlled by a phone’s browser.

The code should be pretty easy to pattern-match and modify. The agent checks for specific values (like “led” or “rgb”), which are set by the name identifiers in the HTML form. To add, subtract, or modify those, simply add/remove/modify the form inputs, and add an if statement to look for it in the agent.

Example 3: Web Response

In the previous example, we used a web page to send data to the imp. But what if you wanted to send data from the imp back to a web page? This example shows how to use the imp to post a response to a web server. Maybe you want to monitor the light level in your garage with a simple photocell? Or live stream the temperature in your backyard. This is the example you’ll want to start with.

The Circuit

The circuit for this example is very open-ended. If you have any digital or analog components you’d like the imp to read, hook them up to one of it’s inputs. For example, if you want to monitor a button-press and a photocell, hook up a circuit like this:

Schematic for example 3

imp schematic

imp circuit for example 3

imp circuit

imp002 circuit for example 3

imp002 circuit

Feel free to make the circuit your own. Maybe add a tilt sensor or an analog temperature sensor to one of the unused pins. At this point you should feel somewhat comfortable modifying the imp’s pin functions to make them do what you want.

The Imp Code

Once again, we’ll need a few pieces of code to make everything work together. Move your impee into a new model and name it Web Response Example.

Starting with the imp again, copy and paste this code into the Device section of your IDE:

language:javascript
/*  electric imp Web Response Example (device)
    by: Jim Lindblom
    SparkFun Electronics
    date: November 5, 2013
    license: Beerware. Use, reuse, and modify this code however you see fit.
    If you find it useful, buy me a beer some day!
    The idea for this code was inspired by this gist by industrialinternet:
    https://gist.github.com/industrialinternet/5419730

    This example code demonstrates how an imp can publish information to a
    webpage. All of the imp's pins are configured as inputs. They can be either
    digital or analog.

    There are three parts to this code:
    1. The imp (device) code. The imp itself simply reads its pin values, and
        sends them out to the agent.
    2. The agent code. The agent waits for an http request. On such a request,
        it'll construct a JSON of the imp's pin values, and respond with that.
    3. An html page to make the http request and handle the response from the agent.
        There are a number of ways to do this. See one example at the bottom of
        The agent code.
*/

///////////
// Setup //
///////////

// Register imp. This good practice:
imp.configure("Imp Pin Web Response",[],[]);

// Configure pins:
hardware.pin1.configure(DIGITAL_IN_PULLUP);
hardware.pin2.configure(DIGITAL_IN_PULLUP);
hardware.pin5.configure(ANALOG_IN);
hardware.pin7.configure(DIGITAL_IN_PULLUP);
hardware.pin8.configure(DIGITAL_IN_PULLUP);
hardware.pin9.configure(DIGITAL_IN_PULLUP);

//////////////////////////
// Function Definitions //
//////////////////////////

// sendPins reads each of the pins, stores them in a table, and sends that
// table out to the agent.
// It calls itself every 100ms -- 10 times a second.
function sendPins()
{
    // Read each of the pins and store them in a table.
    // The key names -- "pin1", "pin2", etc. -- should be kept the same, unless
    // you also change them in the device.on() function on the agent.
    local pinValues =
    {
        pin1 = hardware.pin1.read(),
        pin2 = hardware.pin2.read(),
        pin5 = hardware.pin5.read(),
        pin7 = hardware.pin7.read(),
        pin8 = hardware.pin8.read(),
        pin9 = hardware.pin9.read(),
        voltage = hardware.voltage()    // We'll also send the operating voltage.
    }

    // Once the table is constructed, send it out to the agent with "impValues"
    // as the identifier.
    agent.send("impValues", pinValues);

    // Schedule a wakeup in 100ms, with a callback to this function.
    imp.wakeup(0.1, sendPins);
}

sendPins(); // Call sendPins once, and let it do the rest of the work.

Per usual, check out the code comments for a line-by-line overview of what’s going on. The new function this time? agent.send(string, object). agent.send is used to send data from the imp, to the agent. This time we need to create a handler on the agent side to deal with the data sent by the imp.

Speaking of agent code…

The Agent Code

On the agent side we need to accomplish two tasks:

  1. Define an imp handler function to deal with the data sent by the imp. We’ll just store the data sent by the imp into a global variable.
  2. Create another handler to be called when an HTTP request is received. Upon receiving the request the agent will construct a response based on the data received from the imp, and send that out to the requester.

There’s the overview, here’s the code. Copy and paste this into the Agent half of your model:

language:javascript
/*  electric imp Web Response Example (agent)
    by: Jim Lindblom
    SparkFun Electronics
    date: November 5, 2013
    license: Beerware. Use, reuse, and modify this code however you see fit.
    If you find it useful, buy me a beer some day!

    The agent half of this code accomplishes two tasks:
    1. In the device.on("impValues", function) definitions, the agent receives
    a table of pin values from the imp. It stores those values in a global
    variables.
    2. On an http request, respondImpValues(request, response) is called. This
    function constructs a JSON of the imp pin values, and responds with that.

    Also, check the comment at the bottom of this code for an example HTML file,
    which sends a request to the imp, then parses and prints the response.
*/

//////////////////////
// Global Variables //
//////////////////////
_pin1 <- "";    // Stores pin 1 value received from imp
_pin2 <- "";
_pin5 <- "";
_pin7 <- "";
_pin8 <- "";
_pin9 <- "";
_voltage <- "";

//////////////////////////
// Function Definitions //
//////////////////////////

// respondImpValues is called whenever an http request is received.
// This function will construct a JSON table containing our most recently
// received imp pin values, then send that out to the requester.
function respondImpValues(request,response){

    // First, construct a JSON table with our received pin values.
    local pinTable = {
        "pin1": ""+_pin1+"",    // e.g.: "pin1" : "1""pin2": ""+_pin2+"","pin5": ""+_pin5+"",    // e.g.: "pin5" : "48491""pin7": ""+_pin7+"","pin8": ""+_pin8+"","pin9": ""+_pin9+"","voltage": ""+_voltage+"" + " V",   // e.g.: "voltage" : "3.274 V"
    }

    // the http.jsonencode(object) function takes a squirrel variable and returns a
    // standardized JSON string. - https://electricimp.com/docs/api/http/jsonencode/
    local jvars = http.jsonencode(pinTable);

    // Attach a header to our response.
    // "Access-Control-Allow-Origin: *" allows cross-origin resource sharing
    // https://electricimp.com/docs/api/httpresponse/header/
    response.header("Access-Control-Allow-Origin", "*");

    // Send out our response.
    // 200 is the "OK" http status code
    // jvars is our response string. The JSON table we constructed earlier.
    // https://electricimp.com/docs/api/httpresponse/send/
    response.send(200,jvars);
}

// device.on("impValues") will be called whenever an "impValues" request is sent
// from the device side. This simple function simply fills up our global variables
// with the equivalent vars received from the imp.
device.on("impValues", function(iv) {
    _pin1 = iv.pin1;
    _pin2 = iv.pin2;
    _pin5 = iv.pin5;
    _pin7 = iv.pin7;
    _pin8 = iv.pin8;
    _pin9 = iv.pin9;
    _voltage = iv.voltage;
    });

///////////
// Setup //
///////////

// http.onrequest(function) sets up a function handler to call when an http
// request is received. Whenever we receive an http request call respondImpValues
// https://electricimp.com/docs/api/http/onrequest/
http.onrequest(respondImpValues);

There are two things to point out here. The first is the device.on function. This function sets up a handler to be called when the imp sends a defined string. In this case, we’re looking for the imp sending “impValues”. The data associated with this string is a table, full of all of the imp’s pin readings. That function is called every time the imp sends that specific string to the agent.

The real magic happens in the respondImpValues() function. The agent sets this function as the handler for any HTTP request (using the http.onrequest function). This function constructs a JSON string of data, in the form of “"key”:“value”, “key”:“value”, …,“, which the requesting HTTP client should be able to parse and understand.

Check the comments in the code for more information on the agent code.

For now, Build and Run the code. Don’t expect it to do anything of interest until we add the last bit of magic…

The Web App – AJAX, jQuery, JSON Oh My!

The final piece to this puzzle is constructing a web page that can both send an HTTP request and deal with the response from the agent.

Create a new HTML file named pinView.html. Paste the code below into it.

language:html<html><head><title>Electric Imp Breakout</title><script src="http://code.jquery.com/jquery-1.9.1.min.js"></script><script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script><script>
        $( function() {
            // Edit these values first! The externalURL variable should be the
            // unique URL of your agent. e.g. the last part of:
            // https://agent.electricimp.com/UpyYpRLmBB7m
            // pollRate defines how often the values on your page will refresh.
            var externalURL ="UpyYpRLmBB7m";
            var pollRate ="1000";

            function poll(){
                // Construct an ajax() GET request.
                // http://www.w3schools.com/jquery/ajax_ajax.asp

                $.ajax({
                    type: "get",
                    url: "https://agent.electricimp.com/"+externalURL,  // URL of our imp agent.
                    dataType: "json",   // Expect JSON-formatted response from agent.
                    success: function(agentMsg) {   // Function to run when request succeeds.

                        // jQuery find "pin1" id and overwrite its data with "pin1" key value in agentMsg
                        $("#pin1").html(agentMsg.pin1);
                        $("#pin2").html(agentMsg.pin2);
                        $("#pin5").html(agentMsg.pin5);
                        $("#pin7").html(agentMsg.pin7);
                        $("#pin8").html(agentMsg.pin8);
                        $("#pin9").html(agentMsg.pin9);
                        $("#vin").html(agentMsg.voltage);

                        updateBG(agentMsg.pin5);    // Try this if you have a photocell connected to pin 5
                    },
                    error: function(err) {
                        console.log("err"+ err.status)
                    }
                });
            }

            // setInterval is Javascript method to call a function at a specified interval.
            // http://www.w3schools.com/jsref/met_win_setinterval.asp
            setInterval(function(){ poll(); }, pollRate);

            // This function updates the
            function updateBG(lightSensor)
            {
                if (lightSensor > 30000)
                {
                    document.body.style.backgroundColor = "#FFFFFF";
                }
                else
                {
                    document.body.style.backgroundColor = "#AAAAAA";
                }
            }
        });</script></head><body><h3>Imp Pins:</h3><div id="pins"><p> <b>Pin 1:</b> <span id="pin1"><!-- This is where the pin 1 reading will go --></span></p><p> <b>Pin 2:</b> <span id="pin2"><!-- This is where the pin 2 reading will go --></span></p><p> <b>Pin 5:</b> <span id="pin5"><!-- This is where the pin 5 reading will go --></span></p><p> <b>Pin 7:</b> <span id="pin7"><!-- This is where the pin 7 reading will go --></span></p><p> <b>Pin 8:</b> <span id="pin8"><!-- This is where the pin 8 reading will go --></span></p><p> <b>Pin 9:</b> <span id="pin9"><!-- This is where the pin 9 reading will go --></span></p><p> <b>Voltage:</b> <span id="vin"><!-- This is where the voltage reading will go --></span></p></body></html>

Before saving and closing the file, edit this line of code to point to your agent’s unique URL:

var externalURL ="UpyYpRLmBB7m"; // Put your agent's unique URL here

Sweet! Save and open the file with your favorite web browser. Assuming your imp is running with the new device/agent code, you should see something like this:

pinView.html view

Those 1’s, 0’s, and other numbers might be a little different on your screen. Try pressing a button. Or cover the photocell. Or mess with the imp’s pins in some other way. Are the values changing? How cool is that!

The code for this webpage is a little ugly. It uses some web “stuff” that my fragile, electrical engineer mind can barely grasp. There may be a better way to do this, but this works for us. If you find another cool way to request and use data from the imp, let us know in the discussion section!

Towards the bottom of the HTML code is a series of <span> tags, with ids like “pin1”, “pin2” etc. But they’re blank. Remember those, they’ll come in handy.

The real magic here is happening in the poll() function in the <script> area up top. This function sets up an AJAX) request to the electric imp agent. If the request succeeds, function(agentMsg) is executed. This function parses the JSON message received from the agent, and dynamically updates the data in our blank <span> tags defined below. poll() is set to be called every pollRate (defaulted to 1000) milliseconds.

Whew! Hopefully all of this stuff is easy enough to pattern-match and modify as you please. To make some other information stream to the webpage, you have to:

  1. Edit the imp Device code to send the desired data to the agent. Use the agent.send() function to do this.
  2. Edit the Agent code in two places:
    1. Read the data in from the imp in the device.on() function.
    2. In an HTTP request handler, send the data out as a JSON string.
  3. Add something in the AJAX success function to look for the correct JSON “key” and “value” combination. Then do something with that data.
  4. Add a location in the HTML body to show the data. E.g. <span id="myData"><!--Data goes here--></span>

Give it a try! It sounds like a lot of work, but most of the constructs are already there for you to quickly add new displayable data. You could print the imp’s measured RSSI, or do some math on the analog input reading to turn it into a voltage.

Resources & Going Further

Now that you know how to hook up the electric imp and its Breakout, what project will you be making with it? Will you be adding to the “Internet of Things”? Need some inspiration? Check out some of these products and projects:

Wireless Arduino Programming with Electric Imp

Reprogram your Arduino from anywhere in the world using the Tomatoless Boots wireless bootloader with the Electric Imp.

Weather Station Wirelessly Connected to Wunderground

Build your own open source, official Wunderground weather station that updates every 10 seconds over Wifi via an Electric Imp.

Arduino Wireless Communication via the Electric Imp

How to communicate between an Electric Imp and Arduino using serial.

Pushing Data to Data.SparkFun.com

A grab bag of examples to show off the variety of routes your data can take on its way to a Data.SparkFun.com stream.

If you’re looking to interface an electric imp with an Arduino, check out the Electric Imp Shield. We’ve also written a tutorial on communicating via serial between the imp and Arduino.

Resources

The folks at electric imp have loads of great resources on their wiki. Among the many links on that page, these ones stand out for being extra helpful:

  • electric imp API Reference - Here you’ll find all of the imp-specific functions.
  • electric imp Developer Forums - There’s a wealth of knowledge in the imp community. If you’ve got a question, search for an answer here, or start a new topic.
  • imp Card Datasheet - A good datasheet for the imp (now called the imp001). You’ll find electrical characteristics here, along with other useful info.
  • imp002 Datasheet - The datasheet for the imp002 module.

If you’re still left with imp-related questions, try consulting their forums.


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

Large Digit Driver Hookup Guide

$
0
0

Large Digit Driver Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Large numerical displays are a great addition to any project where you want to be able to see information at a distance. Scorekeepers and lap timers would be a great application for large 7-segment LED displays. The Really Big 7-Segment Display (6.5") fits that bill nicely. Driving several displays at the same time would be handy, which is where the Large Digit Driver board comes in.

HX711 Large Digit Driver board

The Large Digit Driver can be soldered directly to the bottom of the 7-Segment Display.

HX711 board attached to large 7 segment display

Several Large Digit Drivers can be chained together to create a display with multiple digits.

HX711 boards chained together

Covered in This Tutorial

In this tutorial, we will give you an overview of the Large Digit Driver and provide an example of hooking up the driver to an Arduino:

  • Board Overview– To begin, we’ll go over each of the pins on the breakout board and their function.
  • Hardware Hookup– In this section, we’ll show you how to hook the Large Digit Driver up to an Arduino.
  • Example: One Large Digit– Here, we give an example of an Arduino sketch to control one of the large 7-segment displays through the Large Digit Driver.
  • Example: Two Large Digits– We show how to daisy chain two large 7-segment displays together and control them with two Large Digit Drivers.
  • Resources and Going Further– This section gives some additional resources for getting more out of the Large Digit Driver.

Materials Used

You will need a few components and tools to follow along with this tutorial. Here is what you will need:

For each additional digit you want to add, you will need:

Recommended Reading

Before getting started with the Large Digit Driver, there are a few concepts that you should be familiar with. Consider reading some of these tutorials before continuing:

Board Overview

Pin Descriptions

The Large Digit Driver has 6 input pins and 6 output pins.

Overview of HX711 board

IN PinDescription
GNDConnect to ground
LATData transfer in from SER on the rising edge of the latch pin
CLKData transfer in from SER on the rising edge of the clock pin
SERSerial data in
5VConnect to power (5V)
12VConnect to power (12V)

OUT PinDescription
GNDConnect to ground (used to provide a ground pin to the next Large Digit Driver in the chain)
LATConnect to the LAT pin on the next Large Digit Driver in the chain
CLKConnect to the CLK pin on the next Large Digit Driver in the chain
SERSerial data out to the next Large Digit Driver
5V5V out to the next Large Digit Driver
12V12V out to the next Large Digit Driver

Hardware Hookup

Attach the Board

You will need to solder the Large Digit Driver to the back of the 7-segment display. Have the Driver’s 10 pins facing toward the bottom of the large 7-segment display and lined up with the traces on the back of the 7-segment display. Follow the Soldering Castellated Vias Guide to solder all 10 of the castellations as well as the 2 castellations at the top of the board (these should be attached to the 12V line and are just for mechanical support).

Soldering pins on HX711 Large Digit Driver

Connect the Board

We will be using the Arduino’s regulated 5V and unregulated 12V (from the wall adapter) to power the 7-segment display and Large Digit Driver.

Connect the Large Digit Driver to the the following pins on the Arduino.

Fritzing of Large Digit Driver connections

Large Digit DriverArduino
GND GND
LAT5
CLK6
SER7
5V5V
12VVIN

Example: One Large Digit

Load the Single Digit Example Code

Plug your Arduino into your computer via USB cable. Open up the Arduino program and copy in the following sketch.

Run

Upload the sketch to your Arduino, and plug the 12V adapter into the Arduino.

Provide 12V to the Arduino to power the large 7 segment display

Flip the 7-segment display over. You should see it count the digits 0-9 (the decimal point will appear on 9).

Single digit powered by HX711

Example: Two Large Digits

Attach a Second Digit

Use the 6-pin jumper wire to attach a second 7-segment display to the first display unit. Make sure that you connect GND of the OUT on the first display to the GND of the IN on the second display, LAT of the OUT on the first display to the LAT of the IN on the second display, and so on.

Chaining HX711 boards together

You will want to connect the Large Digit Driver on the right to the Arduino as per the Hardware Hookup section.

Load the Two Digit Example Code

Make sure the Arduino is plugged into your computer using a USB cable. Copy the following sketch into the Arduino program.

Run

Upload the sketch to your Arduino, and plug in the 12V supply. The 7-segment display (now two digits!) should count from 00 to 99.

Powering 2 digits from the HX711 Large Digti Driver

Resources and Going Further

Now that we have tested the large 7-segment displays, they are ready to be used in your project! Feel free to change the code to display other numbers or symbols on the displays.

Resources

Here are some additional resource to help you with the Large Digit Driver:

Other Tutorials

What will you make with the Large Digit Driver? If you need some inspiration, check out these related tutorials:

Dungeons and Dragons Dice Gauntlet

A playful, geeky tutorial for a leather bracer that uses a LilyPad Arduino, LilyPad accelerometer, and seven segment display to roll virtual 4, 6, 8, 10, 12, 20, and 100 side dice for gaming.

Galileo Unread Email Counter

How to create a simple unread-email checker with the Intel/Arduino Galileo.

Interactive Hanging LED Array

Learn how we converted 72 lightbulbs into an interactive LED array for our conference room.

Alphanumeric GPS Wall Clock

This is a GPS controlled clock - a clock you truly never have to set! Using GPS and some formulas, we figure out what day of the week and if we are in or out of daylight savings time.

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


Ardumoto Shield Kit Hookup Guide

$
0
0

Ardumoto Shield Kit Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Ardumoto Shield is an easy-to-use dual motor controller for Arduino. Combined with an Arduino, the Ardumoto makes a fantastic controller platform for RC vehicles or even small autonomous robots.

Ardumoto

Ardumoto Shield assembled and situated on a RedBoard.

We sell the Ardumoto Shield either alone, or with a set of motors and wheels in our ArduMoto Shield Kit. This kit includes the Shield as well pairs of tires, motors, connectors, and wires. And, of course, it’s all stuffed in a classic SparkFun red box (which may come in handy as a robot chassis).

ArduMoto Shield Kit

Contents of the Ardumoto Shield Kit.

Covered in this Tutorial

This tutorial covers assembly and use of both the Ardumoto Shield and the Ardumoto Shield Kit. Digging deeper, we’ll get into some assembly tips, and finish with an example Arduino sketch.

The tutorial is split into sections covering:

If all you have is the shield, everything but the “Motor and Wheel Assembly” section will apply.

Required Tools & Materials

To follow along with this tutorial, you’ll need an Ardumoto Shield or the Ardumoto Shield Kit, and an Arduino or Arduino-compatible development board.

Arduino Uno - R3

DEV-11021
$24.95
28
SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
54
SparkFun Ardumoto - Motor Driver Shield

DEV-09815
$24.95
3
SparkFun Ardumoto Shield Kit

KIT-13201
$29.95

Equipping the Ardumoto Shield (Non-kit version)

If all you have is the shield, you’ll also probably want a couple of DC motors to drive. The Ardumoto can control most small DC motors, like any of those in our DC motor category.

You’ll also need a handful of connectors to get everything wired up together. We recommend Stackable Headers to connect your Ardumoto to your Arduino. And two or three 3.5mm Screw Terminals to help connect motors to your Ardumoto.

As an example, here are the contents of the Ardumoto Shield Kit, which should be enough to get you started:

Powering the Shield

Both the Shield and the Kit will require a power source. Batteries are usually your best bet – we recommend a 9V alkaline battery, which will work perfectly with the included 9V-to-Barrel Jack Adapter.

Required Tools

Finally you’ll also need a few tools, including a soldering iron, solder, wire strippers, and a screwdriver:

Wire Strippers - 30AWG (Hakko)

TOL-12630
$9.95
Soldering Iron - 30W (US, 110V)

TOL-09507
$9.95
1
Solder Lead Free - 15-gram Tube

TOL-09163
$3.5
1
Needle Nose Pliers

TOL-08793
$1.95
Pocket Screwdriver Set

TOL-12891
$3.95
3

Suggested Reading

The Ardumoto is a great platform for first-time motor users (and experienced ones too!). There are, however, a few concepts you should be familiar with before clicking over to the next few pages. Here are some tutorials we recommend reading first:

Meet the L298

At the heart of the Ardumoto – the big, black chip right in the middle – is an L298, one of our favorite dual-channel motor drivers around. On this page, we’ll give you some background information on the chip we’ll be depending on to drive our motors.

But First…Why a Motor Driver?

DC motors are the easiest motors to use. They’re dumb (they don’t provide feedback), but they’re good at spinning in one direction or the other when we tell them to. Unlike servos or steppers, DC motors don’t require any special signals – just a straight DC voltage. So why can’t we just connect them directly to the Arduino?

Well, motors tend to draw a lot of current, and trying to drive a motor straight from your Arduino output pins will make your Arduino quite cross with you. The Ardumoto lets you control a whole bunch of current (good for motors) with an itty-bitty signal (good for Arduinos). Everyone’s happy!


Here are some of the important features and specifications of the L298. These extend out to be the specifications of the Ardumoto as well:

Two Channels @ 2A Each

The L298 is a two-channel motor driver. That means it can individually drive up to two motors. So it’s perfect for a two-wheel drive vehicle, but if you have a special, four-wheel drive platform, you might need something else (or just two L298’s).

Each channel on the L298 can deliver up to 2A to the motor to which it’s connected. Keep in mind, though, that the amount of current available to your motor also depends on your system’s power source. Batteries are great power sources because they’re mobile, and can discharge a lot of current, but high current draw also means they’ll drain faster.

The Control Signals

Controlling the L298 is very easy. If you’ve ever blinked or dimmed an LED, you already have all the tools necessary to control the L298.

For each of the L298’s channels, there are two types of input we need to send to drive a motor: direction and enable. Each of these inputs are boolean – either high or low.

Using the direction inputs, we can control whether the motor spins clockwise or counterclockwise. The L298 actually has two direction inputs for each channel, but on the Ardumoto, as we’ll show on the next page, we’ve merged those two inputs into one.

The enable input can be driven either high or low to make the motor spin or stop. But, with pulse-width modulation (PWM), we can actually use this input to control the speed of our motor. Just like it can be used to dim LEDs, PWM is perfect for controlling how fast our DC motor spins.

All of the control signals are limited to a maximum of 7V. Which is great, because our Arduino is only going to supply a maximum of 5V.


That covers the basics of the L298. If you’re curious, or want to know more about the chip, checking out the datasheet is a good place to start.

Ardumoto Overview

Before you get your soldering iron out, or start attaching motors, it’d be best if we briefly covered the basics of the Ardumoto Shield. On this page, we’ll highlight the important inputs and outputs of the shield, so you can get a better idea of how you want to assemble it later.

Pins and Connectors

Here’s an annotated view of the shield, highlighting the important pins and components:

Annotated

The Ardumoto Shield lays claim to four Arduino pins: 3, 11, 12, and 13. Each motor uses two pins – one for direction, the other controls the speed.

Arduino PinArdumoto Shield Pin LabelNotes
3PWM AA PWM signal to control the speed of motor A. 0=off, 255=max speed.
11PWM BA PWM signal to control the speed of motor B. 0=off, 255=max speed.
12DIR AA digital signal to control the rotation direction of motor A (e.g. HIGH/LOW => CW/CCW).
13DIR BA digital signal to control the rotation direction of motor B (e.g. HIGH/LOW => CW/CCW).

While the Ardumoto Shield is attached to an Arduino, these pins shouldn’t be connected to anything else.

Motor Outputs

Both of the L298’s motor driver outputs are broken out to the left-edge of the shield. These 2-pin outputs are broken out to two footprints: a 3.5mm-pitch screw terminal and a 0.1"-pitch header. You can use either to wire up your motor, but screw terminals make life much easier if you need to disconnect your motor. The L298 is perfect for building simple 2 wheel drive robot platforms – connect one motor to port A and the other motor to port B.

Using screw terminals on the Ardumoto shield

Technically, there is no right or wrong way to connect your motor’s wires to the two output pins, but to help keep things straight, we suggest connecting the red / black wire for each motor to pins 1 / 2 on port A and pin 3 / 4 on port B, respectively.

Don’t worry if you swap this, the direction control of the motor will just be swapped as well.

LED Indicators

Next to each of the motor outputs are a pair of blue and yellow LEDs, which indicate the direction your motor is spinning. These are great once you get to debugging your project. They’re also useful if you want to test your sketch without wiring up any motors.

Supply Voltage

The Ardumoto Shield should be powered through one of two power supply inputs. Pick one or the other:

  1. The barrel jack input on the Arduino.
  2. The VIN input on the shield

If you don’t want to use the Arduino’s barrel jack input, you can use the VIN input on the shield instead. This voltage input will supply both the shield and the Arduino. Like the motor outputs, this connection is broken out to both a 3.5mm screw terminal and a 0.1"-pitch header.

Do not supply power to both the Arduino barrel jack input and VIN on the shield!

Spec'ing a Power Supply

Because VIN powers both your Arduino and your motors, you need to take extra care in deciding what you’ll use to power your Arduino/Ardumoto combo. Not only does VIN have to fall within the acceptable range of your Arduino (usually 6-15V), but it also has to meet the specifications of your motor.

Check the voltage and current requirements of your motor before deciding how to power your Ardumoto project. These specifications vary. The 65RPM Hobby Gearmotors, for example, have a recommended range of 3-6V, but can be safely powered at up to 9V.

We recommend 9V Alkaline Batteries as an easy, if not-very-sustainable option. Dual-cell LiPo battery packs (7.4V nominal, 1000mAh capacity) are also a good option if you’re looking for something mobile. A 9V wall wart can work if your project is stationary. For more help picking a power supply, check out our How to Power a Project tutorial.

Ardumoto Shield Assembly Tips

Before you can start using the Ardumoto Shield, you have to do a little assembly. Embrace your inner electronics technician and whip out that soldering iron! Time to turn a mish-mash of parts into a fully-functional ‘duino shield!

Arduomoto parts list

On this page we’ll go over some assembly tips. You don’t have to follow these steps exactly – assemble the shield as best fits your project’s needs – but this is good for general use of the shield.

Add Screw Terminals (Optional)

If you please, you can add screw terminals to both of the motor outputs and/or the VIN input.

If you’re adding screw terminals to the motor outputs, slide them together first:

Screw terminals sliding together

Then insert them into the shield and solder.

Soldering screw terminals

Solder the Arduino Headers

To interface the shield with your Arduino, soldering male connectors to the 28 header pins is a must. Soldering ensures a reliable physical and electrical connection. If you’ve never soldered before, check out our through-hole soldering tutorial.

There are usually two options for connectors when you’re assembling a shield: stackable or straight. We recommend stackable headers, because it allows you to stack other shields or jumper wires on top. The smaller male headers are a good option if you’re looking for lower-profile installation.

If this is your first shield assembly, we recommend reading through our shield assembly guide. There are all sorts of tricks to installing shield headers, and making them look as good and straight as possible!

Shield assembly in progress

In the process of soldering stackable headers. Still a lot of pins to go!

Once you’re done soldering the headers, plug the shield in to make sure everything fits cozily.

Headers installed

Prototyping Area

Let’s address the elephant in the room. There’s almost half-a-shield that we’ve failed to talk about thus far. The prototyping area! These rows and columns of 0.1"-spaced plated through-holes can be used to solder in all sorts of fun components.

You could add an accelerometer to enable bump detection in your robot. Or just fill it with LEDs to make your project as blinky as possible. Or, if you don’t have any plans for the area, leave it be – maybe you’ll come up with something later.

Unlike other prototyping areas you may have encountered in the past, these holes are not wired together. You don’t need to do any trace-slicing, but you will need to do some soldering and wire routing.

Motor and Wheel Assembly

This is where the shield assembly gets very project-specific. Have you picked out which motors you’ll be driving with the shield? Do you know how long the wires need to be trimmed? There’s a lot to be answered here before continuing on…

Wiring the Motors

If you have the kit, you already have a couple pairs of wires, but they still need to be stripped. Grab your Wire Strippers, and remove about 1cm of insulation from each end of each wire.

Wires stripped

Then it’s time to solder the wires to your motors. Slide a black wire through the “eyelet” connector on a motor, then use a pair of pliers to crimp it around creating a decent mechanical connection.

Careful! The connectors on these motors are very delicate. Avoid stressing them or bending them any more than you have to. We highly recommend globbing each connector with some epoxy or hot glue after you've soldered them.

Wire crimped around motor connector

Then coat it with a warm blob of solder. Repeat the same set of steps for the red wire and the motor’s opposite connector.

Motor wires soldered

Make sure the wires don’t short on the motors nearby metal body.

Repeating the same set of steps on the other motor, try to match the positions of the red and black wires.

Both motors soldered

And make sure you don’t yank the wires too hard now – those motor terminals are rather delicate.

Connecting Motors

Connecting the motors to your shield is much easier – especially if you have screw terminals. If you added screw terminals in the last step, break out your screw driver, slide the wires in, and tighten the terminals down

Motors connected to the shield

In lieu of screw terminals, you can solder the motor wires into either the 0.1" header or the screw terminal header.

Upcycling the SparkFun Box

If you have the Ardumoto Shield Kit, you probably also have a robust, resplendently red SparkFun box. These SparkFun boxes come in handy for all sorts of projects – including robot chassis!

With some measured hobby knife incisions, you can cut out some mounts for the motors and tie your Arduino/shield combo down as well:

Ardumoto RedBox Bot

You may want to add a Ball Caster to the front, to keep the box from scraping against the floor. Now time to program the Arduino and make your RedBox-bot mobile.

Example Code

Controlling the Ardumoto Shield is super-easy. If you can blink LEDs, you can make the Ardumoto Shield spin its motors. Here, we’ll provide a simple, expandable example sketch to show how to drive the pair of motors on the Ardumoto.

The Example Sketch

We’ve embedded the example sketch in a Codebender window below. Run it from there, copy and paste it into your Arduino IDE, or click here to download it:

Then upload to your Arduino and watch your motors spin! If you want to dig really deep into the sketch, check out the comments.

Explaining the Sketch

For each motor there are two mechanisms we can control – the direction of rotation and the speed. Each of those mechanisms is controlled by one pin on the Arduino.

Controlling Rotation Direction

We can only spin the motor in two directions – clockwise or counter-clockwise – so we only need two values – 0 or 1 – to control that from the Arduino. We can simply digitalWrite either of the direction pins (pin 12 for motor A, pin 13 for motor B) HIGH or LOW to go forward or backward.

For example, if you want motor A to spin clockwise, you simply need to digitalWrite pin 12 LOW:

language:c
digitalWrite(12, LOW);  // Motor A will spin clockwise

To make it spin the other way, write the pin HIGH.

language:c
digitalWrite(12, HIGH);  // Motor A will spin counter-clockwise

(Note: The rotation direction depends on how you wired the motor to your shield. If you swapped the red and black wires, the motor will spin opposite of how we’ve described here.)

Speeding

To control the speed of a motor we need to analogWrite to the PWM pins (pin 3 for motor A, pin 11 for motor B). A higher analogWrite value means a faster spin. Writing the pin LOW (or 0) will stop the motor.

PWM valueMotor Spin Speed
0Off (Stop)
127Half speed
255Full speed

If we want to turn motor A up to maximum speed, this is all we need:

language:c
analogWrite(3, 255);  // Motor A at max speed

After that line of code is executed, the motor will spin until stopped. To stop the motor, replace 255 with 0:

language:c
analogWrite(3, 0);  // Stop motor A

Don’t forget to set your direction before spinning your motor!

Resources & Going Further

Resources

Going Further

  • HUB-ee Buggy Project - Build your own buggy using an Ardumoto shield.
  • Assembly Guide for RedBot– If you’re looking for a complete, beginner-level robotics platform, check out the RedBot Kit. It’s Arduino-compatible, and the RedBot Mainboard has a motor driver built into it, so you don’t even need an Ardumoto Shield.
  • Getting Started with the MiniMoto– The MiniMoto is a more advanced, digitally-controlled, low-voltage DC motor driver. Great if you need a smaller form-factor motor controller.
  • How to Power a Project– Batteries? Wall-warts? Solar? If you’re not sure how to power your Ardumoto Shield project, take a trip over to this tutorial.

How to Power a Project

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

Building the HUB-ee Buggy

Let's build the HUB-ee Buggy: A simple robot based on the HUB-ee wheel system!

MiniMoto DRV8830 Hookup Guide

MiniMoto is an I2C-based low-voltage DC motor driver.

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.

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

Photon IMU Shield Hookup Guide

$
0
0

Photon IMU Shield Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Does your Photon project need an accelerometer? What about a gyroscope or a magnetometer? With the SparkFun Photon IMU Shield, you can get all three, thanks to the LSM9DS1 IC module.

alt text

The SparkFun Photon IMU (Inertial Measurement Unit) Shield is a versatile motion-sensing add-on board for your Photon device that houses a 3-axis accelerometer, 3-axis gyroscope, and 3-axis magnetometer. That’s right, 9 degrees of freedom (9DOF) from a single IC!

Each sensor in the LSM9DS1 supports a large variety of ranges: the accelerometer’s scale can be set to ± 2, 4, 6, 8, or 16 g, the gyroscope supports ± 245, 500, and 2000 °/s, and the magnetometer has full-scale ranges of ± 2, 4, 8, or 12 gauss. As a bonus, the SparkFun Photon IMU Shield comes with the headers already soldered on, so you can plug your Photon (or Core) in and get started!

Please Note: All SparkFun shields for the Photon are also compatible with the Core from Particle. The WKP, DAC and VBT pins on the Photon will be labeled A7, A6 and 3V3*, respectively, on the Core, but will not alter the functionality of any of the Shields.

Covered in this tutorial

This tutorial will cover the functionality of the IMU shield, how to hook it up in your project, and how to program with it using the SparkFun LSM9DS1 Library from the online Particle build environment.

Required Materials

To get started with the Photon IMU Shield you’ll want a Photon, a micro-USB cable, and of course the shield itself. You’ll also want to sign up for an account on particle.io and register your Photon. Instructions on how to do this can be found at docs.particle.io.

Photon Kit

KIT-13345
$29
SparkFun Photon IMU Shield

DEV-13629
$24.95

Suggested Reading

Here’s a few things you may want to brush up on or dive into if you plan on making the most of your IMU Shield.

  • Accelerometer Basics– It’s always a good idea to know what you’re measuring, what’s possible, and what is not.
  • Gyroscopes!– Learn what makes a gyro tick…er, rotate.
  • Magnetometers– Magnetometers…how do they work!?
  • I2C– I2C is the preferred method used to control the IMU. It uses less wires, but is quite a bit slower than, for instance, SPI.
  • Serial Peripheral Interface (SPI)– SPI is another method of communication with the IMU. Refer to the section on jumpers if you’d like to use this board in SPI mode.

IMU Shield Overview

Pin Descriptions

Since the shield does all of the work for you, there’s no need to actually wire these connections - but in case you’re looking at datasheets, or code examples, this table will give you a clue as to what the shield is doing. As always, you can check the schematic for more info.

alt text

IMU Shield PinPhoton PinFunction
GNDGNDGround
VDD3.3VRegulated 3.3V in
SCLD1SCL Serial clock
SDAD0Serial Data in

We also broke out a few pins at the top of the board that some of you may wish to make use of. From left to right in the picture above, they are:

IMU Shield PinFunction
DEN AGData Enable Accel/Gyro
INT2 AGProgrammable Interrupt Accel/Gyro
INT1 AGProgrammable Interrupt Accel/Gyro
INT MProgrammable Interrupt Magnetometer
DRDY MMagnetic sensor data ready

Setting the Jumpers

With the board flipped over, you’ll notice there are six jumpers. The majority of these jumpers are used to switch between SPI and I2C mode. As the board ships, these jumpers are set to configure the IMU in I2C mode.

alt text

The SDO M-MISO and SDO A/G-MISO jumpers can be used to set the I2C addresses (In I2C mode) or, if open, can be used either to set I2C address or for SPI control. The default out of the box has both jumpers pulled high for I2C mode.

I2C Address Table
SDOM /AGAG Addr.M Addr.
00x6A0x1C
10x6B0x1E

The CS A/G-SS2 and CS M-SS are the chip select jumpers for the accelerometer/gyro and the magnetometer, respectively. The board ships with them both pulled high to enable I2C mode. Close the jumpers and cut the former traces to enable SPI mode.

The same story holds true for the SDA-MOSI and SCL-SCK jumpers. They are pulled high to enable I2C communication. Close the jumpers in the other direction and cut the former traces to enable SPI mode.

Using the LSM9DS1 Library

Now that we understand the IMU hardware, let’s put some code on this thing and see what it can do. Using the Particle library we’ve written, you’ll be able to capture acceleration, angular rotation, and magnetic field strength with ease!

Getting the Particle LSM9DS1 Library

For this page we’ll be using the online Particle environment. If you’re using the Particle Dev environment instead, you can get the library and code examples from the GitHub repository.

Download the Particle IMU Library

Load the Demo Example

If you haven’t created a Particle user account and claimed your board, you’ll need to do that now. Starting here is a great idea if you’re having trouble.

Once you’re logged into build.particle.io and have a device selected (all this is covered at the link above), you’ll want to click on the create new app button in the sidebar – it’s big and blue, you can’t miss it. Call your app something like ‘IMU_test’.

Next – this is the important part – we include the LSM9DS1 library. To do this:

  • Click on the icon that looks like a bookmark (it’s all the way to the left on the black skinny sidebar, 4th up from the bottom)
  • In the text box under ‘community libraries’, search for ‘SparkFunLSM’ and you’ll see ‘SparkFunLSM9DS1’ come up (though it might be cut off a little bit, don’t worry).

It should look something like this:

alt text

  • Click on the library name, and a bunch of stuff will pop up, including all the library files as well as a few options of what to do with the library.
  • In this case, we just want to use the library in our app, so click on the ‘include in app’ button.
  • This will lead you to list of all your apps - click on the name of the app you just created, and you should see a statement like #include "SparkFunLSM9DS1/SparkFunLSM9DS1.h" at the top of your app.

Now that we’ve included the library in our app, let’s give it some code - just copy the demo code below and paste it into your app, below the include statements. NOTE: this example uses I2C - check out the “LSM9DS1_BASIC_SPI.CPP” file in the Particle library for and SPI example.

language:cpp
/*****************************************************************
LSM9DS1_Basic_I2C.ino
SFE_LSM9DS1 Library Simple Example Code - I2C Interface
Jim Lindblom @ SparkFun Electronics
Original Creation Date: April 30, 2015
https://github.com/sparkfun/SparkFun_LSM9DS1_Particle_Library

The LSM9DS1 is a versatile 9DOF sensor. It has a built-in
accelerometer, gyroscope, and magnetometer. Very cool! Plus it
functions over either SPI or I2C.

This Photon sketch is a demo of the simple side of the
SFE_LSM9DS1 library. It'll demo the following:
* How to create a LSM9DS1 object, using a constructor (global
  variables section).
* How to use the begin() function of the LSM9DS1 class.
* How to read the gyroscope, accelerometer, and magnetometer
  using the readGryo(), readAccel(), readMag() functions and
  the gx, gy, gz, ax, ay, az, mx, my, and mz variables.
* How to calculate actual acceleration, rotation speed,
  magnetic field strength using the calcAccel(), calcGyro()
  and calcMag() functions.
* How to use the data from the LSM9DS1 to calculate
  orientation and heading.

Hardware setup: This library supports communicating with the
LSM9DS1 over either I2C or SPI. This example demonstrates how
to use I2C.

If you have the Photon IMU shield, no extra wiring is required.
If you're using a breakout, the pin-out is as follows:
    LSM9DS1 --------- Photon
     SCL -------------- D1 (SCL)
     SDA -------------- D0 (SDA)
     VDD ------------- 3.3V
     GND ------------- GND
(CSG, CSXM, SDOG, and SDOXM should all be pulled high.
Jumpers on the breakout board will do this for you.)

Development environment specifics:
    IDE: Particle Build
    Hardware Platform: Particle Photon
                       SparkFun Photon IMU Shield

This code is released under the MIT license.

Distributed as-is; no warranty is given.
*****************************************************************/
#include "SparkFunLSM9DS1/SparkFunLSM9DS1.h"
#include "math.h"

//////////////////////////
// LSM9DS1 Library Init //
//////////////////////////
// Use the LSM9DS1 class to create an object. [imu] can be
// named anything, we'll refer to that throught the sketch.
LSM9DS1 imu;

///////////////////////
// Example I2C Setup //
///////////////////////
// SDO_XM and SDO_G are both pulled high, so our addresses are:
#define LSM9DS1_M   0x1E // Would be 0x1C if SDO_M is LOW
#define LSM9DS1_AG  0x6B // Would be 0x6A if SDO_AG is LOW

////////////////////////////
// Sketch Output Settings //
////////////////////////////
#define PRINT_CALCULATED
//#define PRINT_RAW
#define PRINT_SPEED 250 // 250 ms between prints

// Earth's magnetic field varies by location. Add or subtract
// a declination to get a more accurate heading. Calculate
// your's here:
// http://www.ngdc.noaa.gov/geomag-web/#declination
#define DECLINATION -8.58 // Declination (degrees) in Boulder, CO.

void setup()
{

  Serial.begin(115200);

  // Before initializing the IMU, there are a few settings
  // we may need to adjust. Use the settings struct to set
  // the device's communication mode and addresses:
  imu.settings.device.commInterface = IMU_MODE_I2C;
  imu.settings.device.mAddress = LSM9DS1_M;
  imu.settings.device.agAddress = LSM9DS1_AG;
  // The above lines will only take effect AFTER calling
  // imu.begin(), which verifies communication with the IMU
  // and turns it on.
  if (!imu.begin())
  {
    Serial.println("Failed to communicate with LSM9DS1.");
    Serial.println("Double-check wiring.");
    Serial.println("Default settings in this sketch will " \"work for an out of the box LSM9DS1 " \"Breakout, but may need to be modified " \"if the board jumpers are.");
    while (1)
      ;
  }
}

void loop()
{
  printGyro();  // Print "G: gx, gy, gz"
  printAccel(); // Print "A: ax, ay, az"
  printMag();   // Print "M: mx, my, mz"

  // Print the heading and orientation for fun!
  // Call print attitude. The LSM9DS1's magnetometer x and y
  // axes are opposite to the accelerometer, so my and mx are
  // substituted for each other.
  printAttitude(imu.ax, imu.ay, imu.az, -imu.my, -imu.mx, imu.mz);
  Serial.println();

  delay(PRINT_SPEED);
}

void printGyro()
{
  // To read from the gyroscope, you must first call the
  // readGyro() function. When this exits, it'll update the
  // gx, gy, and gz variables with the most current data.
  imu.readGyro();

  // Now we can use the gx, gy, and gz variables as we please.
  // Either print them as raw ADC values, or calculated in DPS.
  Serial.print("G: ");
#ifdef PRINT_CALCULATED
  // If you want to print calculated values, you can use the
  // calcGyro helper function to convert a raw ADC value to
  // DPS. Give the function the value that you want to convert.
  Serial.print(imu.calcGyro(imu.gx), 2);
  Serial.print(", ");
  Serial.print(imu.calcGyro(imu.gy), 2);
  Serial.print(", ");
  Serial.print(imu.calcGyro(imu.gz), 2);
  Serial.println(" deg/s");
#elif defined PRINT_RAW
  Serial.print(imu.gx);
  Serial.print(", ");
  Serial.print(imu.gy);
  Serial.print(", ");
  Serial.println(imu.gz);
#endif
}

void printAccel()
{
  // To read from the accelerometer, you must first call the
  // readAccel() function. When this exits, it'll update the
  // ax, ay, and az variables with the most current data.
  imu.readAccel();

  // Now we can use the ax, ay, and az variables as we please.
  // Either print them as raw ADC values, or calculated in g's.
  Serial.print("A: ");
#ifdef PRINT_CALCULATED
  // If you want to print calculated values, you can use the
  // calcAccel helper function to convert a raw ADC value to
  // g's. Give the function the value that you want to convert.
  Serial.print(imu.calcAccel(imu.ax), 2);
  Serial.print(", ");
  Serial.print(imu.calcAccel(imu.ay), 2);
  Serial.print(", ");
  Serial.print(imu.calcAccel(imu.az), 2);
  Serial.println(" g");
#elif defined PRINT_RAW
  Serial.print(imu.ax);
  Serial.print(", ");
  Serial.print(imu.ay);
  Serial.print(", ");
  Serial.println(imu.az);
#endif

}

void printMag()
{
  // To read from the magnetometer, you must first call the
  // readMag() function. When this exits, it'll update the
  // mx, my, and mz variables with the most current data.
  imu.readMag();

  // Now we can use the mx, my, and mz variables as we please.
  // Either print them as raw ADC values, or calculated in Gauss.
  Serial.print("M: ");
#ifdef PRINT_CALCULATED
  // If you want to print calculated values, you can use the
  // calcMag helper function to convert a raw ADC value to
  // Gauss. Give the function the value that you want to convert.
  Serial.print(imu.calcMag(imu.mx), 2);
  Serial.print(", ");
  Serial.print(imu.calcMag(imu.my), 2);
  Serial.print(", ");
  Serial.print(imu.calcMag(imu.mz), 2);
  Serial.println(" gauss");
#elif defined PRINT_RAW
  Serial.print(imu.mx);
  Serial.print(", ");
  Serial.print(imu.my);
  Serial.print(", ");
  Serial.println(imu.mz);
#endif
}

// Calculate pitch, roll, and heading.
// Pitch/roll calculations take from this app note:
// http://cache.freescale.com/files/sensors/doc/app_note/AN3461.pdf?fpsp=1
// Heading calculations taken from this app note:
// http://www51.honeywell.com/aero/common/documents/myaerospacecatalog-documents/Defense_Brochures-documents/Magnetic__Literature_Application_notes-documents/AN203_Compass_Heading_Using_Magnetometers.pdf
void printAttitude(
float ax, float ay, float az, float mx, float my, float mz)
{
  float roll = atan2(ay, az);
  float pitch = atan2(-ax, sqrt(ay * ay + az * az));

  float heading;
  if (my == 0)
    heading = (mx < 0) ? 180.0 : 0;
  else
    heading = atan2(mx, my);

  heading -= DECLINATION * M_PI / 180;

  if (heading > M_PI) heading -= (2 * M_PI);
  else if (heading < -M_PI) heading += (2 * M_PI);
  else if (heading < 0) heading += 2 * M_PI;

  // Convert everything from radians to degrees:
  heading *= 180.0 / M_PI;
  pitch *= 180.0 / M_PI;
  roll  *= 180.0 / M_PI;

  Serial.print("Pitch, Roll: ");
  Serial.print(pitch, 2);
  Serial.print(", ");
  Serial.println(roll, 2);
  Serial.print("Heading: "); Serial.println(heading, 2);
}

Now hit the ‘flash’ button (the one that looks like a lightning bolt) and wait for the magic to begin!

Resources & Going Further

Here are a few links that should help with any further questions you may have about the Photon IMU Shield:

Going Further

Now that you’re comfortable with the Photon IMU Shield and its Particle library, what are you going to make with it? Need some inspiration? Check out these related tutorials:

Hackers in Residence - Sound and Motion Reactivity for Wearables

How to consciously wear light-up and and sound reactive clothing.

Gyroscope

Gyroscopes measure the speed of rotation around an axis and are an essential part in determines ones orientation in space.

LSM9DS0 Hookup Guide

How to assemble, connect to, and use the LSM9DS0 -- an accelerometer, gyroscope, and magnetometer all-in-one.

ESP8266 Thing Hookup Guide

An overview of SparkFun's ESP8266 Thing - a development board for the Internet of...Things. This tutorial explains the circuitry driving the board, and how to get it up and running in an Arduino environment.

And don’t forget about the other Photon shields in our lineup!

SparkFun Photon Weather Shield

DEV-13630
$32.95
SparkFun Photon ProtoShield

DEV-13598
$2.5
SparkFun Photon Wearable Shield

DEV-13328
$4.95
SparkFun Photon Battery Shield

DEV-13626
$12.95
SparkFun Photon Micro OLED Shield

DEV-13628
$19.95

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

Photon OLED Shield Hookup Guide

$
0
0

Photon OLED Shield Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Want your Photon projects to display sensor readings, play pong, or draw little doodles? The Photon OLED Shield might be the perfect fit, and we’re going to show you how to use it.

alt text

If the OLED screen in the picture above looks familiar, it’s probably because we use the same component in our Microview and Micro OLED Breakout products, as well as the OLED Block for the Edison. We love it for it’s combination of small footprint yet surprisingly clear graphics – the screen itself is 0.66" across, with a display area measuring 64 pixels wide by 48 pixels tall.

Please Note: All SparkFun shields for the Photon are also compatible with the Core from Particle. The WKP, DAC and VBT pins on the Photon will be labeled A7, A6 and 3V3*, respectively, on the Core, but will not alter the functionality of any of the Shields.

Covered in this Tutorial

This tutorial will cover the functionality of the OLED shield, how to hook it up in your project, and how to program with it using the SparkFun Micro OLED Library.

Required Materials

All you need to get started with the Photon OLED Shield is a Photon, a micro-USB cable, and the OLED shield. You’ll also want to sign up for an account on particle.io and register your photon. Instructions on how to do this can be found at docs.particle.io.

Photon Kit

KIT-13345
$29
SparkFun Photon Micro OLED Shield

DEV-13628
$19.95

Suggested Reading

  • Serial Peripheral Interface (SPI)– SPI is the preferred method of communication with the display.
  • I2C– Alternatively, I2C can be used to control the display. It uses less wires, but is quite a bit slower.

OLED Shield Overview

Pin Descriptions

Since the shield does all of the work for you, there’s no need to actually wire these connections - but in case you’re looking at datasheets, or code for the Microview or OLED breakout, this table will give you a clue as to what the shield is doing. As always, you can check the schematic for more info.

alt text

OLED Shield PinPhoton PinSPI FunctionI2C FunctionNotes
GNDGNDGroundGround0V
3V3 (VDD)3V3 PowerPowerShould be a regulated 3.3V supply.
D1 (SDI/MOSI)A5MOSISDASerial data in
D0 (SCK)A3SCKSCLSPI and I2C clock
D2 (SDO)MISOCan be unused in SPI mode. No function for I2C.
D/CD6Data / CommandI2C address selectionDigital pin to signal if incoming byte is a command or screen data.
RSTD7ResetResetActive-low screen reset.
CSA2SPI chip select (active-low)

Setting the Jumpers

With the board flipped over, you’ll notice there are six jumpers. The majority of these jumpers are used to switch between SPI and I2C mode. As the board ships, these jumpers are set to configure the display in SPI mode.

alt text

Here’s an overview of each jumper, moving from left-to-right, top-to-bottom in the picture above:

  • VD/VB -- This jumper shorts the digital power supply (VDD) to the battery power supply (VBAT). Because both of these supplies can be powered at 3.3V, an easy one-supply solution is to short them together and provide them a single supply. If you need to power the digital supply at something lower, like 1.8V, you may need to cut this jumper and provide two supplies.
  • D1/D2 -- This jumper can be used to short D1 to D2. If you want to use SPI, leave this jumper open. If you're using I2C, short the jumper. By default this jumper is open.
  • D/C -- This jumper can be used to short D/C to either 3.3V (1) or 0V (0). In I2C mode, the D/C pin sets the 7-bit address of the display. In SPI mode this jumper should be left open, as the D/C pin needs to be toggled to determine if an incoming byte is data or command.
  • BS2 and BS1 -- These pins on the OLED determine which interface you're using to control the OLED. With the two signals, there are four possible combinations:
    BS2BS1Interface
    00SPI
    01I2C
    108-bit Parallel (6800)
    118-bit Parallel (8080)
    By default, both of these jumpers are set to 0, which puts the display in SPI mode. If you want to change it to I2C mode, clear the BS1 jumper and set it to 1.

That brief overview should cover the 99% use case. Consult the schematic and the notes therein if you have any questions about jumpers or pins.

Using the OLED Shield

When attaching your Photon to the top of the OLED shield, make sure the beveled end of your Photon (next to A0 and D0) matches up with the beveled lines on the top of the OLED shield (the end with the Open Source Hardware Logo). The pin labels on the Photon should match those on the OLED shield as well. You can stack many of our Photon shields together, which is why the OLED screen juts out to the side. So, you can end up with something like this:

alt text

Using the Particle OLED Library

Great, now that we understand the hardware setup, let’s put some code on this thing and see what it can do. Using the Particle library we’ve written, you’ll be able to write text, draw lines and shapes, and generally display anything that’ll fit on the screen.

Getting the Particle OLED Library

For this page we’ll be using the online Particle environment. If you’re using the Particle Dev environment instead, you can get the library and code examples from the GitHub repository.

Download the Particle OLED Library

Load the Demo Example

If you haven’t created a Particle user account and claimed your board, you’ll need to do that now. Starting here is a great idea if you’re having trouble.

Once you’re logged into build.particle.io and have a device selected (all this is covered at the link above), you’ll want to click on the create new app button in the sidebar – it’s big and blue, you can’t miss it. Call your app something like ‘OLED_test’.

Next – this is the important part – we include the SparkFunMicroOLED library. To do this:

  • Click on the icon that looks like a bookmark (it’s all the way to the left on the black skinny sidebar, 4th up from the bottom)
  • In the text box under ‘community libraries’, search for ‘OLED’ and you’ll see ‘SparkFunMicroOLED’ come up (though it might be cut off a little bit, don’t worry).

It should look something like this:

alt text

  • Click on the library name, and a bunch of stuff will pop up, including all the library files as well as a few options of what to do with the library.
  • In this case, we just want to use the library in our app, so click on the ‘include in app’ button.
  • This will lead you to list of all your apps - click on the name of the app you just created, and you should see a statement like #include "SparkFunMicroOLED/SparkFunMicroOLED.h" at the top of your app.
  • Last thing is to add the math library to our sketch - on the line below the first #include statement, type in: #include "math.h"

Now that we’ve included the library in our app, let’s give it some code - just copy the demo code below and paste it into your app, below the include statements.

language:cpp
/*
Micro-OLED-Shield-Example.ino
SparkFun Micro OLED Library Hello World Example
Jim Lindblom @ SparkFun Electronics
Original Creation Date: June 22, 2015

This sketch prints a friendly, recognizable logo on the OLED Shield, then
  goes on to demo the Micro OLED library's functionality drawing pixels,
  lines, shapes, and text.

  Hardware Connections:
  This sketch was written specifically for the Photon Micro OLED Shield, which does all the wiring for you. If you have a Micro OLED breakout, use the following hardware setup:

    MicroOLED ------------- Photon
      GND ------------------- GND
      VDD ------------------- 3.3V (VCC)
    D1/MOSI ----------------- A5 (don't change)
    D0/SCK ------------------ A3 (don't change)
      D2
      D/C ------------------- D6 (can be any digital pin)
      RST ------------------- D7 (can be any digital pin)
      CS  ------------------- A2 (can be any digital pin)

  Development environment specifics:
    IDE: Particle Build
    Hardware Platform: Particle Photon
                       SparkFun Photon Micro OLED Shield

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

  Distributed as-is; no warranty is given.
*/

//////////////////////////////////
// MicroOLED Object Declaration //
//////////////////////////////////
// Declare a MicroOLED object. If no parameters are supplied, default pins are
// used, which will work for the Photon Micro OLED Shield (RST=D7, DC=D6, CS=A2)

MicroOLED oled;

void setup()
{
  oled.begin();    // Initialize the OLED
  oled.clear(ALL); // Clear the display's internal memory
  oled.display();  // Display what's in the buffer (splashscreen)
  delay(1000);     // Delay 1000 ms
  oled.clear(PAGE); // Clear the buffer.

  randomSeed(analogRead(A0) + analogRead(A1));
}

void loop()
{
  pixelExample();  // Run the pixel example function
  lineExample();   // Then the line example function
  shapeExample();  // Then the shape example
  textExamples();  // Finally the text example
}

void pixelExample()
{
  printTitle("Pixels", 1);

  for (int i=0; i<512; i++)
  {
    oled.pixel(random(oled.getLCDWidth()), random(oled.getLCDHeight()));
    oled.display();
  }
}

void lineExample()
{
  int middleX = oled.getLCDWidth() / 2;
  int middleY = oled.getLCDHeight() / 2;
  int xEnd, yEnd;
  int lineWidth = min(middleX, middleY);

  printTitle("Lines!", 1);

  for (int i=0; i<3; i++)
  {
    for (int deg=0; deg<360; deg+=15)
    {
      xEnd = lineWidth * cos(deg * M_PI / 180.0);
      yEnd = lineWidth * sin(deg * M_PI / 180.0);

      oled.line(middleX, middleY, middleX + xEnd, middleY + yEnd);
      oled.display();
      delay(10);
    }
    for (int deg=0; deg<360; deg+=15)
    {
      xEnd = lineWidth * cos(deg * M_PI / 180.0);
      yEnd = lineWidth * sin(deg * M_PI / 180.0);

      oled.line(middleX, middleY, middleX + xEnd, middleY + yEnd, BLACK, NORM);
      oled.display();
      delay(10);
    }
  }
}

void shapeExample()
{
  printTitle("Shapes!", 0);

  // Silly pong demo. It takes a lot of work to fake pong...
  int paddleW = 3;  // Paddle width
  int paddleH = 15;  // Paddle height
  // Paddle 0 (left) position coordinates
  int paddle0_Y = (oled.getLCDHeight() / 2) - (paddleH / 2);
  int paddle0_X = 2;
  // Paddle 1 (right) position coordinates
  int paddle1_Y = (oled.getLCDHeight() / 2) - (paddleH / 2);
  int paddle1_X = oled.getLCDWidth() - 3 - paddleW;
  int ball_rad = 2;  // Ball radius
  // Ball position coordinates
  int ball_X = paddle0_X + paddleW + ball_rad;
  int ball_Y = random(1 + ball_rad, oled.getLCDHeight() - ball_rad);//paddle0_Y + ball_rad;
  int ballVelocityX = 1;  // Ball left/right velocity
  int ballVelocityY = 1;  // Ball up/down velocity
  int paddle0Velocity = -1;  // Paddle 0 velocity
  int paddle1Velocity = 1;  // Paddle 1 velocity

  //while(ball_X >= paddle0_X + paddleW - 1)
  while ((ball_X - ball_rad > 1) &&
         (ball_X + ball_rad < oled.getLCDWidth() - 2))
  {
    // Increment ball's position
    ball_X+=ballVelocityX;
    ball_Y+=ballVelocityY;
    // Check if the ball is colliding with the left paddle
    if (ball_X - ball_rad < paddle0_X + paddleW)
    {
      // Check if ball is within paddle's height
      if ((ball_Y > paddle0_Y) && (ball_Y < paddle0_Y + paddleH))
      {
        ball_X++;  // Move ball over one to the right
        ballVelocityX = -ballVelocityX; // Change velocity
      }
    }
    // Check if the ball hit the right paddle
    if (ball_X + ball_rad > paddle1_X)
    {
      // Check if ball is within paddle's height
      if ((ball_Y > paddle1_Y) && (ball_Y < paddle1_Y + paddleH))
      {
        ball_X--;  // Move ball over one to the left
        ballVelocityX = -ballVelocityX; // change velocity
      }
    }
    // Check if the ball hit the top or bottom
    if ((ball_Y <= ball_rad) || (ball_Y >= (oled.getLCDHeight() - ball_rad - 1)))
    {
      // Change up/down velocity direction
      ballVelocityY = -ballVelocityY;
    }
    // Move the paddles up and down
    paddle0_Y += paddle0Velocity;
    paddle1_Y += paddle1Velocity;
    // Change paddle 0's direction if it hit top/bottom
    if ((paddle0_Y <= 1) || (paddle0_Y > oled.getLCDHeight() - 2 - paddleH))
    {
      paddle0Velocity = -paddle0Velocity;
    }
    // Change paddle 1's direction if it hit top/bottom
    if ((paddle1_Y <= 1) || (paddle1_Y > oled.getLCDHeight() - 2 - paddleH))
    {
      paddle1Velocity = -paddle1Velocity;
    }

    // Draw the Pong Field
    oled.clear(PAGE);  // Clear the page
    // Draw an outline of the screen:
    oled.rect(0, 0, oled.getLCDWidth() - 1, oled.getLCDHeight());
    // Draw the center line
    oled.rectFill(oled.getLCDWidth()/2 - 1, 0, 2, oled.getLCDHeight());
    // Draw the Paddles:
    oled.rectFill(paddle0_X, paddle0_Y, paddleW, paddleH);
    oled.rectFill(paddle1_X, paddle1_Y, paddleW, paddleH);
    // Draw the ball:
    oled.circle(ball_X, ball_Y, ball_rad);
    // Actually draw everything on the screen:
    oled.display();
    delay(25);  // Delay for visibility
  }
  delay(1000);
}

void textExamples()
{
  printTitle("Text!", 1);

  // Demonstrate font 0. 5x8 font
  oled.clear(PAGE);     // Clear the screen
  oled.setFontType(0);  // Set font to type 0
  oled.setCursor(0, 0); // Set cursor to top-left
  // There are 255 possible characters in the font 0 type.
  // Lets run through all of them and print them out!
  for (int i=0; i<=255; i++)
  {
    // You can write byte values and they'll be mapped to
    // their ASCII equivalent character.
    oled.write(i);  // Write a byte out as a character
    oled.display(); // Draw on the screen
    delay(10);      // Wait 10ms
    // We can only display 60 font 0 characters at a time.
    // Every 60 characters, pause for a moment. Then clear
    // the page and start over.
    if ((i%60 == 0) && (i != 0))
    {
      delay(500);           // Delay 500 ms
      oled.clear(PAGE);     // Clear the page
      oled.setCursor(0, 0); // Set cursor to top-left
    }
  }
  delay(500);  // Wait 500ms before next example

  // Demonstrate font 1. 8x16. Let's use the print function
  // to display every character defined in this font.
  oled.setFontType(1);  // Set font to type 1
  oled.clear(PAGE);     // Clear the page
  oled.setCursor(0, 0); // Set cursor to top-left
  // Print can be used to print a string to the screen:
  oled.print(" !\"#$%&'()*+,-./01234");
  oled.display();       // Refresh the display
  delay(1000);          // Delay a second and repeat
  oled.clear(PAGE);
  oled.setCursor(0, 0);
  oled.print("56789:;<=>?@ABCDEFGHI");
  oled.display();
  delay(1000);
  oled.clear(PAGE);
  oled.setCursor(0, 0);
  oled.print("JKLMNOPQRSTUVWXYZ[\\]^");
  oled.display();
  delay(1000);
  oled.clear(PAGE);
  oled.setCursor(0, 0);
  oled.print("_`abcdefghijklmnopqrs");
  oled.display();
  delay(1000);
  oled.clear(PAGE);
  oled.setCursor(0, 0);
  oled.print("tuvwxyz{|}~");
  oled.display();
  delay(1000);

  // Demonstrate font 2. 10x16. Only numbers and '.' are defined.
  // This font looks like 7-segment displays.
  // Lets use this big-ish font to display readings from the
  // analog pins.
  for (int i=0; i<25; i++)
  {
    oled.clear(PAGE);            // Clear the display
    oled.setCursor(0, 0);        // Set cursor to top-left
    oled.setFontType(0);         // Smallest font
    oled.print("A0:");          // Print "A0"
    oled.setFontType(2);         // 7-segment font
    oled.print(analogRead(A0));  // Print a0 reading
    oled.setCursor(0, 16);       // Set cursor to top-middle-left
    oled.setFontType(0);         // Repeat
    oled.print("A1:");
    oled.setFontType(2);
    oled.print(analogRead(A1));
    oled.setCursor(0, 32);
    oled.setFontType(0);
    oled.print("A7:");
    oled.setFontType(2);
    oled.print(analogRead(A7));
    oled.display();
    delay(100);
  }

  // Demonstrate font 3. 12x48. Stopwatch demo.
  oled.setFontType(3);  // Use the biggest font
  int ms = 0;
  int s = 0;
  while (s <= 50)
  {
    oled.clear(PAGE);     // Clear the display
    oled.setCursor(0, 0); // Set cursor to top-left
    if (s < 10)
      oled.print("00");   // Print "00" if s is 1 digit
    else if (s < 100)
      oled.print("0");    // Print "0" if s is 2 digits
    oled.print(s);        // Print s's value
    oled.print(":");      // Print ":"
    oled.print(ms);       // Print ms value
    oled.display();       // Draw on the screen
    ms++;         // Increment ms
    if (ms >= 10) // If ms is >= 10
    {
      ms = 0;     // Set ms back to 0
      s++;        // and increment s
    }
    delay(1);
  }
}

// Center and print a small title
// This function is quick and dirty. Only works for titles one
// line long.
void printTitle(String title, int font)
{
  int middleX = oled.getLCDWidth() / 2;
  int middleY = oled.getLCDHeight() / 2;

  oled.clear(PAGE);
  oled.setFontType(font);
  // Try to set the cursor in the middle of the screen
  oled.setCursor(middleX - (oled.getFontWidth() * (title.length()/2)),
                 middleY - (oled.getFontWidth() / 2));
  // Print the title:
  oled.print(title);
  oled.display();
  delay(1500);
  oled.clear(PAGE);
}

Now, click the ‘flash’ button (the one that looks like a lightning bolt) and wait for the magic to begin!

Resources & Going Further

Here are a few links that should help with any further questions you may have about the Photon OLED Shield:

Going Further

Now that you’re comfortable with the Photon OLED Shield and its Particle library, what are you going to make with it? Need some inspiration, check out these related tutorials:

OLED Display Hookup Guide

A simple hookup guide to get you started with the OLED LCD.

Serial Graphic LCD Hookup

Learn how to use the Serial Graphic LCD.

RGB Panel Hookup Guide

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

Reaction Timer

Demonstrate mental chronometry with this simple reaction timer!

And don’t forget about the other Photon shields in our lineup!

SparkFun Photon Weather Shield

DEV-13630
$32.95
SparkFun Photon ProtoShield

DEV-13598
$2.5
SparkFun Photon Wearable Shield

DEV-13328
$4.95
SparkFun Photon Battery Shield

DEV-13626
$12.95
SparkFun Photon IMU Shield

DEV-13629
$24.95

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

Photon Battery Shield Hookup Guide

$
0
0

Photon Battery Shield Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Free your Photon from its USB cable by powering it through the Photon Battery Shield. The Battery Shield has everything your Photon needs to run off, charge, and monitor a LiPo battery.

Photon Battery Shield

The Shield features two unique IC’s: an MCP73831 charge controller and a MAX17043 LiPo fuel gauge. With them, you’ll be able to charge your battery through USB and monitor its voltage and state-of-charge.

Please Note: All SparkFun shields for the Photon are also compatible with the Core from Particle. The WKP, DAC and VBT pins on the Photon will be labeled A7, A6 and 3V3*, respectively, on the Core, but will not alter the functionality of any of the Shields.

Covered In This Tutorial

The purpose of this hookup guide is to familiarize you with the hardware and software of the Photon Battery Shield. It’s split into the following sections:

Required Materials

The Photon Battery Shield equips your Photon with just about everything it should need to use a LiPo battery – it even includes headers! Of course you’ll need the Battery Shield and a Photon.

SparkFun Photon Battery Shield

DEV-13626
$12.95
Photon Kit

KIT-13345
$29

The one thing the Battery Shield doesn’t include is a battery. Our compatible LiPo batteries come in a variety of shapes and capacities – the larger the battery, the longer it will last. Any of the following will work:

Polymer Lithium Ion Battery - 400mAh

PRT-10718
$6.95
6
Polymer Lithium Ion Battery - 2000mAh

PRT-08483
$12.95
1
Polymer Lithium Ion Battery - 110mAh

PRT-00731
$6.95
1
Polymer Lithium Ion Battery - 1000mAh

PRT-00339
$9.95
5
Polymer Lithium Ion Battery - 850mAh

PRT-00341
$9.95
5
Polymer Lithium Ion Battery - 6Ah

PRT-08484
$32.95
Polymer Lithium Ion Battery - 40mAh

PRT-11316
$4.5

If you want to use a battery of your own, just make sure it’s a single-cell (3.7V nominal, ~4.2V max) lithium-polymer (LiPo) or lithium-ion (Li+). Optimally, choose one that is terminated with a 2-pin PH-series JST connector, otherwise you may need to do some wire splicing.

If you don’t already have one (or just want to stock up), you may also need a Micro-B USB Cable, which will come in handy when you need to recharge the battery. If you don’t want to plug that cable into a computer, a USB Wall Charger is useful to have on hand.

Suggested Reading

Using the Photon Battery Shield doesn’t require a whole lot of pre-existing knowledge. If you want to learn more about the foundational concepts in this tutorial, here are some guides we recommend:

Battery Technologies

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

How to Power a Project

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

I2C

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

How Lithium Polymer Batteries are Made

We got the opportunity to tour the Great Power Battery factory. Checkout how LiPos are made!

Battery Shield Overview

Let’s do a quick rundown of the Photon Battery Shield’s hardware features. Here are some highlights of the board’s main components:

Top of shield annotated

  • LiPo Connector (PH-Series JST)– The battery goes here. This connector is polarized, so it’ll only plug in the right way.
  • Photon Socket– Each Photon comes pre-soldered with male headers, so all of our shields come pre-populated with female connectors on their top-side.
  • Photon Pin Breakouts– Need more access to the Photon’s I/O? These pin break-outs have that covered. These break outs are in the same place on each of our Photon Shields– should you need to interface them together that way.
  • Photon Polarity Indicator– Nothing’s going to work if your Photon isn’t plugged in correctly. These angled edges should match up to those on the Photon’s PCB.
  • Charge LED Indicator– This red LED will light up whenever the LiPo battery is being charged.

Flipping the Shield over reveals a few, less commonly-used features of the board:

Bottom of shield annotated

  • “Stackable” Male Pins– Whether you want to plug the battery shield into more Photon shields, or use it in a breadboard, these male pins should do the job. If you don’t need this feature, the pins can all be quickly beheaded by some flush cutters.
  • SMD Barrel Jack footprint– This footprint allows you to add an SMD Barrel Jack to the Battery Shield’s underside. This’ll allow you to charge the battery with a 5V Wall Adapter, or even a Small Solar Panel. Just make sure your power source isn’t higher than 5.5V.
  • I2C Pull-up Resistor Enable/Disable– The Photon Battery Shield includes a pair of 10kΩ pull-up resistors on the SDA and SCL lines (D0 and D1). If you’ve got more I2C devices to connect, you may need to disable those. These jumpers are closed by default, but can be opened with a couple slices of a hobby knife.
  • Alert Interrupt Jumper– The MAX17043 features a programmable interrupt output, which can fire whenever your battery gets below a set percentage of charge. This pin can be connected to the Photon’s D6 pin by adding a blob of solder between these two pads. Note that this jumper is open by default, as other shields make use of D6.

Using and Charging a LiPo Battery

Before plugging your battery in, grab your Photon, and plug it into the battery shield. Make sure you line up the Photon’s angled edges with the matching white silkscreen on the shield. The Photon’s USB connector should be pointing out the same direction as the black JST connector.

Next, grab your LiPo battery and mate its white JST connector with the black one on the shield. These connectors are polarized, so you can only plug it in the right way.

Photon running off a battery

Running your Photon off a LiPo is as simple as plugging in a battery and the Photon.

If the battery had any charge, your Photon should turn on, and its RGB LED should begin being colorful. If it was already commissioned, your Photon should connect to your WiFi network. You can even load up the Particle Build IDE and truly start loading code over-the-air.

Charging the Battery through USB

Eventually your LiPo’s power capacity will be drained, and it’ll be time to charge it back up. To avoid any extra USB connectors, the Photon Battery Shield was designed to use the Photon’s USB connector as a charge-source.

With the LiPo and Photon still connected to the Battery Shield, simply plug a Micro-B USB cable into your Photon (the other end of the USB cable can be plugged into a computer or USB wall adapter).

Charging a battery through USB

To charge the LiPo, just plug a USB cable into the Photon’s USB port.

Once USB is attached, the red charge LED indicator should illuminate – it’ll remain lit up until the battery is fully charged.

(Optional) Charging the Battery through Barrel Jack

The Battery Shield provides additional options for charging your LiPo in an unpopulated barrel jack footprint. If you need to charge the LiPo sans-Photon, this may be the best option for you.

To add this feature, you’ll need our Surface-Mount Barrel Jack, and some soldering tools. If you’re a novice solderer, don’t be scared off by the “SMD” soldering – these joints are about as easy as it gets. Check out or soldering tutorial for some guidance.

The barrel jack’s input should face out towards the edge of the board. Make sure you solder all four pads:

SMD barrel jack soldered on bottom

To charge a LiPo through this jack, you’ll need a 5V power source– our 5V Wall Adapter should do the trick. Or, if you really want to avoid wires, you can use our small, 0.45W solar panel, which will source up to 5V when it’s nice and sunny.

Charging with barrel jack solar panel


If you don’t want to solder the barrel jack on, but still have a 5V power source available, you can supply that voltage to the “VIN” and “GND” pins on the shield’s header. This is a more advanced charge technique, and only recommended for more experienced users.

Using the MAX17043 LiPo Fuel Gauge

One of the most unique features of the Photon Battery Shield is the integrated MAX17043 LiPo fuel gauge. The MAX17043 sits between the battery and your Photon – it uses a calibrated ADC to measure the battery voltage. Comparing that measured voltage against their “ModelGauge” algorithm, the IC can produce a state-of-charge (SOC) estimate, to give you an idea of what percentage remains of the battery charge.

Loading the SparkFunMAX17043 Library

The MAX17043 communicates over I2C, so coding an interface between the Photon and the fuel gauge can be a little tricky. Luckily, we’ve done the hard work for you! We’ve written a Particle library for the MAX17043. You can load it up in the Particle IDE by going to the “Libraries” tab, and searching for SparkFunMAX17043.

MAX17403_Simple example in Particle Build

Search the “Libraries” tab for “SparkFunMAX17043” to find the Fuel Gauge library.

If you’re using the desktop version of the IDE, Particle Dev, and still want to use the library, you can grab the latest version from our GitHub repository.

Running the MAX17043_Simple Example

After finding the library, navigate to “MAX17043_Simple.cpp” and click Use This Example– the Build IDE will create a clone of this sketch in your “Code” tab.

You shouldn’t have to change anything, just make sure your Photon is selected in the “Devices” tab, and click “Flash”.

Once your Photon is running the code, there are two ways to view its data. One is to open a serial terminal (see our Serial Terminal Basics tutorial if you need help with this). Find your Photon’s serial port number (“COM#” on Windows “/dev/tty.usbmodemXXXX” on Mac) and set the baud rate to 9600. The battery’s voltage, state-of-charge, and alert status will stream by.

Serial terminal output

Using TeraTerm to view the Photon’s Serial.print debug output.

Since USB is plugged in, the voltage and percentage should steadily increase as the battery charges.

Alternatively, if you want to monitor the battery discharge, you can use the Photon’s Internet-connectivity to view the battery voltage and charge status. First, though, you’ll need to identify your Photon’s device ID as well as your account’s access token. The device ID can be found in Particle Build by clicking the ‘>’ next to your device name.

Particle Device ID

Find your Device ID under the “Devices” tab, by clicking the carrot next to your Photon.

Your access token can be found under the “Settings” tab.

Access Token

Find your access token under the “Settings” tab.

Armed with those long strings of hex characters, open a new browser tab and navigate to:

https://api.particle.io/v1/devices/DEVICE_ID/voltage?access_token=ACCESS_TOKEN

Make sure to sub in the proper values for DEVICE_ID and ACCESS_TOKEN. If everything was entered correctly, you should see something like this:

Spark Variable JSON string

The Spark variable responds with a JSON string including a “result” key and value.

Among the data in that JSON response is a “result” key, which shows the current voltage reading. You can also view the state-of-charge, and alert status by navigating to:

https://api.particle.io/v1/devices/DEVICE_ID/soc?access_token=ACCESS_TOKEN

and

https://api.particle.io/v1/devices/DEVICE_ID/alert?access_token=ACCESS_TOKEN

Yay Spark Variables!

Using the SparkFunMAX17043 Library

The SparkFunMAX17043 library is simple. There’s some initialization required. Make sure to include the library, and in your setup() call lipo.begin().

language:c
#include "SparkFunMAX17043/SparkFunMAX17043.h" // Include the SparkFun MAX17043 library

void setup()
{
    // Set up the MAX17043 LiPo fuel gauge:
    lipo.begin(); // Initialize the MAX17043 LiPo fuel gauge

    // Quick start restarts the MAX17043 in hopes of getting a more accurate
    // guess for the SOC.
    lipo.quickStart();
}

Calling lipo.quickStart() will re-calibrate the MAX17043’s ADC, and usually results in more accurate readings.

If you’re using the library in Particle Build, make sure you go to the SPARKFUNMAX17043 library in the “Libraries” tab, select INCLUDE IN APP, and add it to your desired code file.

Include library in app

Any sketch using the SparkFunMAX17043 library needs to have it “included” first.

Reading Voltage and SoC

Two functions are used to read the MAX17043’s voltage and state-of-charge values:

language:c
// lipo.getVoltage() returns a voltage value (e.g. 3.93)
voltage = lipo.getVoltage();
// lipo.getSOC() returns the estimated state of charge (e.g. 79%)
soc = lipo.getSOC();

Both functions return a float variable. lipo.getVoltage() should usually be between 0.0 and about 4.2. lipo.getSOC() should be somewhere between 0.0 and 100.0.

Using the Alert Interrupt

One of the MAX17043’s nifty features is a programmable alert interrupt. You can tell it to trigger a flag whenever the state-of-charge falls below a certain threshold.

To set up the alert, use lipo.setThreshold([percentage]). For example:

language:c
lipo.setThreshold(15); // Set Alert threshold to 15%

…will set the alert threshold to 15%.

The alert status can be read in both software and hardware. To get the alert status in software, call lipo.getAlert(). This function will return 0 if the alert is not triggered, and 1 if it is.

As mentioned in the Battery Shield Overview section, a jumper on the bottom of the board can optionally be closed to connect the MAX17043’s alert pin to Photon pin D6. This alert is active-low– meaning it’ll be HIGH when it’s not triggered and LOW when the SoC has fallen below threshold.

Once an alert has been triggered, you’ll need to clear it before it can fire again. That’s what lipo.clearAlert() will do for you. Even if the SoC rises above the threshold, you’ll still need to manually clear the alert.

Resources & Going Further

If you need any resources detailing the Photon Battery Shield, here are some schematics, datasheets, and other links you may find handy:

If you are interested in putting your Photon into sleep mode to conserve more battery power, check out the Particle Docs links below:

  • Photon System Modes - Playing with different modes allows you to have control over when the Photon is and isn’t connected to the web.
  • Photon System Sleep Function - The sleep function puts the Photon to sleep while it isn’t performing any actions to conserve power.

Now that you’ve become familiarized with the Photon Battery Shield, what project are you going to make with it? Need some inspiration? Check out the below SparkFun tutorials for some ideas:

HID Control of a Web Page

Learn how to move a slider on a webpage and make a motor spin. We connect HTML and HID to read sensors and interface with the physical world.

Are You Okay? Widget

Use an Electric Imp and accelerometer to create an "Are You OK" widget. A cozy piece of technology your friend or loved one can nudge to let you know they're OK from half-a-world away.

Pushing Data to Data.SparkFun.com

A grab bag of examples to show off the variety of routes your data can take on its way to a Data.SparkFun.com stream.

ESP8266 Thing Hookup Guide

An overview of SparkFun's ESP8266 Thing - a development board for the Internet of...Things. This tutorial explains the circuitry driving the board, and how to get it up and running in an Arduino environment.

And don’t forget about the other Photon shields in our lineup!

SparkFun Photon Weather Shield

DEV-13630
$32.95
SparkFun Photon ProtoShield

DEV-13598
$2.5
SparkFun Photon Wearable Shield

DEV-13328
$4.95
SparkFun Photon Micro OLED Shield

DEV-13628
$19.95
SparkFun Photon IMU Shield

DEV-13629
$24.95

Photon Wearable Shield Hookup Guide

$
0
0

Photon Wearable Shield Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Photon Wearable Shield breaks out each pin on the Photon, so it is easier to use the Photon in WiFi wearables projects. Due to the large pins, you can also use other conductive materials like copper tape and conductive paint for non-wearable projects.

Photon Wearable Photon Shield

Please Note: All SparkFun shields for the Photon are also compatible with the Core from Particle. The WKP, DAC and VBT pins on the Photon will be labeled A7, A6 and 3V3*, respectively, on the Core, but will not alter the functionality of any of the Shields.

Suggested Reading

If you have never worked with the Photon or the Core before, we highly recommend visiting the getting started documentation available on the Particle site.

If you are unfamiliar with any of the concepts below, we suggest checking out those tutorials as well.

Hardware Overview

This might be a simple shield for the Photon, but you can use it in many different types of projects! Here is a list of hardware features for this shield.

Female Headers for the Photon

Photon Wearable Shield SMD headers

Double check that you put the Photon in the female headers the correct way!

No soldering required! The shield comes with two SMD headers already soldered on, which makes easy to place the Photon on top and start a new project. There is a white Photon silkscreen outline to help show what direction the Photon needs to be placed.

Large Sewable Pins

Photon Wearable Shield Large Sewable pads

There is a large pad for each one of the Photon’s pins.

The larger pins makes it possible to use different types of conductive materials to connect sensors, LEDs, and other components to the Photon. Conductive paint, conductive thread, and copper tape are just few different conductive materials you can use with the large pins. When prototyping, the large pads makes it easy to use alligator clips.

Alligator clips for Photon Wearable Shield

Alligator clips are great to make sure connections and code examples are correct before sewing components into a garment.

Normal Sized Pins

Photon Wearable Shield Normal Pins holes

There are normal sized pins for soldering hook-up wire to the shield. Which, is great for projects needing tons of LEDs or a solid connection.

Hardware Hookup (Conductive Thread, Paint, and Tape)

There are different types conductive materials that can be used with the shield. Depending on the project, some materials are better then others. Here are the most common conductive materials to hook-up external components to the shield and the Photon.

Conductive Thread

Want to make an IoT wearable fitness project and be able to sew an accelerometer into your clothes? Sewing with conductive thread is a great way to add sensors into a wearables or other e-textiles projects. It provides more flexibility then standard hook-up wire.

Conductive thread Photon Wearable Shield

Tip: Loop around a large pin hole and component three or more times, with conductive thread, to get a solid connection.

The Photon can also work with 3.3V LilyPad products like the LilyPad Temperature Sensor, LilyPad Accelerometer, and LilyPad Vibe Board.

Conductive Paint

Thinking of doing an interactive art painting or wall? Conductive paint opens doors for traditional artists and tinkers to combine art and electronics together. The conductive paint can go under or over the large pads on the shield.

Conductive Wearable Paint

Great for art installations!

Copper Tape

Copper tape is great for paper crafts or other e-crafts. Copper tape has an adhesive backing, which isn’t as conductive as the nonadhesive side. We recommend to place the copper tape under the large pads on the shield.

Copper Tape Photon Wearable Shield

Use the copper tape with the large pins on the shield.

Resources and Going Further

Now that you know a little bit more about the Photon Wearables Shield, it is time to start your project! These links may be useful in your journey:

Check out these related wearables tutorials:

Sewing with Conductive Thread

How to use conductive thread with e-textile components.

LDK Experiment 1: Lighting Up a Basic Circuit

The first experiment in the LilyPad Design Kit series. In this exercise, you will learn how a basic e-textiles circuit works, and light up a sewable LED using a coin cell battery holder and conductive thread.

Insulation Techniques for e-Textiles

Learn a few different ways to protect your conductive thread and LilyPad components in your next wearables project.

Need inspiration? Here are some great project tutorials!

Bare Conductive Musical Painting

Learn how to make a musical painting using the Bare Conductive Touch Board and Conductive Paint.

Origami Paper Circuits

A quick tutorial to get you started in the world of light up origami flowers.

And don’t forget about the other Photon shields in our lineup!

SparkFun Photon Weather Shield

DEV-13630
$32.95
SparkFun Photon ProtoShield

DEV-13598
$2.5
SparkFun Photon Battery Shield

DEV-13626
$12.95
SparkFun Photon Micro OLED Shield

DEV-13628
$19.95
SparkFun Photon IMU Shield

DEV-13629
$24.95

Finished your project? Make sure to share it with us in the comment section! We love to see what amazing projects you are making.


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>