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

Cherry MX Switch Breakout Hookup Guide

$
0
0

Cherry MX Switch Breakout Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Cherry MX Keyswitches are top-of-the-line mechanical keyboard switches. They’re satisfyingly “clicky”, reliable up to tens-of-millions of key presses, and an essential component in gaming and programming keyboards. To help make the switches more easily adaptable to breadboard or perfboard-based projects, we created the SparkFun Cherry MX Switch Breakout.

Cherry MX Switch in action

In addition to breaking out the switch contacts to breadboard-compatible headers, the breakout also provides access to an optional switch-mounted LED. Plus, the pin break-outs are designed with keyboard matrix-ing in mind, so you can interconnect as many boards as you’d like into a row-column configuration, keeping the I/O-pin requirements as low as possible.

The Cherry MX Switch Breakout is a perfect prototyping tool for input devices ranging from a single key to fully-custom 101-key keyboards.

Covered In This Tutorial

This tutorial documents the SparkFun Cherry MX Switch Breakout, providing an overview of the breakout, plus some assembly and usage tips. It’s broken down into a few sections, which you can navigate around using the buttons on the right.

Or use these links below to skip ahead:

  1. Hardware Overview– A breakdown of the Cherry MX Switch Breakout Board features.
  2. Assembly Tips– Tips for adding headers, wires, resistors, and diodes to the breakout board.
  3. Testing the Circuit– A simple circuit to test the switch, LED, and any other components you may add on.
  4. Matrixing Breakouts– A guide to combining two or more breakout boards into a row/column matrix, and scanning them with an Arduino.

Bill of Materials

In addition to the Cherry MX Switch there are a few additional items you may want to add on to the Breakout Board.

3mm LEDs can be placed inside the switch. Pick any color you please: red, green, yellow, or cycling.

LED - Basic Green 3mm

COM-09650
$0.35
1
LED - Basic Yellow 3mm

COM-00532
$0.35
LED - Basic Red 3mm

COM-00533
$0.35
LED - 3mm Cycling RGB (slow)

COM-11448
$0.5

The breakout board also provides a footprint for an optional LED-current-limiting resistor. 1/6W PTH resistors, like these 330Ω’s, are recommended.

If you’re matrixing multiple breakout boards together, you may want to add a small-signal diode to the board to help isolate the switches and prevent any possible “ghosting”. Standard 1N4148 diodes should do the trick for this.

If you need to tie the board down, it has mounting holes designed to fit 2-56 screws and nuts.

Resistor 330 Ohm 1/6 Watt PTH - 20 pack

COM-11507
$0.95
2
Diode Small Signal - 1N4148

COM-08588
$0.15
Nut - Metal (2-56)

PRT-08995
$0.15
Screw - Flat Head (3/8", 2-56)

PRT-08992
$0.15

You’ll need soldering tools, including a soldering iron and solder. Other tools, like wire strippers, flush cutters, and a third hand, can also be helpful.

Wire Strippers - 30AWG (Hakko)

TOL-12630
$9.95
1
Flush Cutters - Hakko

TOL-11952
$6.95
14
Soldering Iron - 30W (US, 110V)

TOL-09507
$9.95
3
Solder Lead Free - 15-gram Tube

TOL-09163
$3.5
1

Finally, headers or wire will help connect the breakout board to your breadboard or development platform.

Suggested Reading

This hookup guide relies on some beginner-level electronics knowledge. If any of the subjects below sound foreign to you, consider checking out that tutorial first:

Resistors

A tutorial on all things resistors. What is a resistor, how do they behave in parallel/series, decoding the resistor color codes, and resistor applications.

Diodes

A diode primer! Diode properties, types of diodes, and diode applications.

Switch Basics

A tutorial on electronics most over-looked and under-appreciated component. The switch! Explaining the difference between momentary and maintained switches. And what all those acronyms (NO, NC, SPDT, SPST, ...) stand for.

Light-emitting Diodes (LEDs)

Learn the basics about LEDs as well as some more advanced topics to help you calculate requirements for projects containing many LEDs.

Hardware Overview

While it may seem like a simple breakout, the Cherry MX Switch Breakout board is a little over-engineered. Here’s a quick breakdown of the pin breakouts and additional features of the board.

Top of board annotated

Breakout Pin Labels

Up to four pins are used to interact with the Cherry MX Switch – two for the switch contacts and two for the optional LED. These pins are broken out on all sides of the board, labeled either “1”, “2”, “+”, or “-”. Those labels are short for:

Pin LabelPin Description
1Switch contact 1
2Switch contact 2
+LED anode
-LED cathode

If you only want to use the switch, the pins labeled “1” and “2” should be all you need. If you’re integrating a 3mm LED, the LED’s anode and cathode will be accessible on the “+” and “-” pins respectively.

Header Pairs

Every side of the breakout board is equipped with a four-pin header (don’t confuse them with the diode or resistor pins), but not all of these headers are created equally! Two headers break out all four pins, while the other two headers only break out the LED anode and one of the switch contacts.

Switch headers labeled

The pair of headers on the left and right sides of the board break out all four pins. These are intended for primary use. You can solder male pins into both of these headers, and plug the switch into a breadboard.

Example solder job on main headers on ly

The pair of headers breaking only the LED anode and switch contact 1 are designed for keypad matrices, where multiple boards are connected in row/column pairs. More on this later in the tutorial.

Assembly Tips

To use the breakout board, at a bare minimum you’ll need to solder the Cherry MX Switch and either headers or wires to the “1” and “2” pins. Male headers work well for most breadboarding applications, while solid-core or stranded wire work well if you’re wiring the breakout up to something afar.

Break Away Headers - Straight

PRT-00116
$1.5
19
Hook-Up Wire - Assortment (Solid Core, 22 AWG)

PRT-11367
$16.95
13
Hook-Up Wire - Assortment (Stranded, 22 AWG)

PRT-11375
$16.95
9
Break Away Male Headers - Right Angle

PRT-00553
$1.95
3

There are plenty of other addon options, including a 3mm LED, current-limiting resistor, and switch isolating diodes, which are all documented below.

3mm LED

Most Cherry MX Switches – including the blue, MX1A-E1NW switch we carry – have a recess in their body designed to fit a small 3mm LED.

An “A” on the top side of the switch and a diode symbol on the backside both show the recommended polarity of the LED.

LED footprint in switch

The LED’s recessed home in the switch. Note the “A” indicator for the LED’s “anode.”

To add an LED to the switch, insert the anode and cathode legs of the LED into their respective pins – the LED’s longer, anode leg should be inserted into the “A” pin – then flip the board over, and solder the LED to the breakout board.

LED connected to breakout

Adding a Current-Limiting Resistor

If you’re adding an LED to the switch, more likely than not, you’ll need a current-limiting resistor. The breakout provides a resistor footprint, in-line with the LED. You’ll find the resistor pads on the bottom-right corner of the board.

Small PTH resistors are recommended for this application – 1/6W or 1/8W through-hole packages work best. 1/4W resistors can be too large – potentially interfering with any keycap that may be on the switch.

To connect an LED to the board, bend one of the resistor legs so it’s parallel with the other. Then insert both legs into the board like so:

Resistor connected to board

You’ll also need to cut the “R” jumper on the back side of the board, which might be easier to do before you solder anything. A hobby knife and a steady hand should do the trick.

Resistor jumper location

By default, the board has a short across the current-limiting resistor. Cutting this jumper removes the short, and functionally adds the resistor to the circuit.

Ghost-Prevention Diode

If you plan on interconnecting four-or-more breakouts – creating a row/column matrix of switches – you may also want to consider adding a small-signal diode to help prevent “ghosting”. The 1N4148 small-signal diode is perfectly fit for this task.

Switch Matrix Ghosting

"Ghosting" is a problem that can adversely affect the detection of multiple, simultaneous button presses. Without diode protection, certain combinations of simultaneous button-presses can cause one-or-more un-actuated buttons to appear pressed ("ghosted"). The result is a false-positive key-press, which can cause undesired behavior in a project.

To avoid button ghosting, small-signal diodes can be placed in-circuit, after every key. The diode prevents a key's signal from "backfeeding" back through the line.

Ghost problem illustrated

While the diode does prevent ghosting, it does place certain restrictions on your button-press detection. It forces the switch contact on the diode's anode (positive) side to be at a higher voltage than the other contact, as the switch can only conduct meaningful current in one direction.

For more on keypad ghosting, check out Byron's explanation in the Button Pad Hookup Guide.

A small, “vertical” diode footprint is broken out in the upper-right corner of the board. Near one of the pads in this footprint, a small, white line designates which pin should be connected to the diode’s cathode (negative) pin.

To solder a diode into the board, bend the anode leg down, so it’s parallel with the cathode leg. Then insert the diode into the board – making sure to place the cathode leg (usually indicated by a black bar) into the marked hole.

Diode added to breakout

You’ll also need to cut the “D” jumper on the back side of the board – otherwise the diode will be shorted over. (This may be easier if you do it before soldering anything.)

Diode jumper location

Like the resistor, the breakout shorts across the diode. Cutting this jumper removes the short and functionally adds the diode to the circuit.

Mounting Hole Size

A pair of mounting holes are provided on opposite corners of the breakout board. These holes are designed to fit 2-56 (3/8") screws. Flat heads are recommended, though rounded heads can work as well.

Screw - Phillips Head (3/8", 2-56)

PRT-08993
$0.15
Nut - Metal (2-56)

PRT-08995
$0.15
Screw - Flat Head (3/8", 2-56)

PRT-08992
$0.15

If you’re going to be doing a lot of jamming on your keyboard, you’ll want it tied down!

Testing the Circuit

With just a power supply and a few wires, you can create a quick circuit to test out your switch, LED, resistor and diode. Wire up the “+” pin to 5V (or 3.3V). Then connect “-” and “1” together. And wire up “2” to ground. (If you didn’t add a current-limiting resistor, make sure you add one externally! It can take the place of the wire from “+” to power, or 2 to ground.)

Breadboard test circuit

Now actuate the switch, and watch for the LED to illuminate.

Note that, if you’ve added the ghosting diode, this is the only polarity in which the switch will work – pin 1 must be at a higher voltage than pin 2.

Matrixing Breakouts

The Cherry MX Switch Breakout Board’s are designed with switch matrix-ing in mind. By creating a row/column matrix of switches, you can save on potentially dozens of microcontroller I/O pins. A 64-key keyboard, for example, can be scanned with just 16 I/O pins.

Key Spacing

While there is no specific standard for keyboard key spacing, most full-size keyboard keys are spaced by ¾" (0.75in) from center-to-center. Rows may be offset by either 3/8" (0.375in) or 3/16" (0.1875in), or not at all.

Typical keyboard offsets

Typical keyboard row offsets. (Image courtesy of The PC Guide.)

The breakout is designed to make typical key spacing as easy as possible. By cleverly jumping one board to the next, you can add any of the standard offsets to nearby rows.

standard keyboard spacing

So, plan out your keyboard, and grab a soldering iron!

Creating a Key Matrix

To create a matrix of switches, arrange your boards as desired. Along the rows, line up the “2”, “1”, “-”, and “+” labels. You will, however, only connect the “2” and “-” pins across rows. Solder your rows together first:

Row of three built up

There’s not an easy method to soldering boards together. You’ll probably need wire strippers to split and cut solid-core wire into tiny (~3/8") pieces. A third hand can be a big-time help keeping boards stationary while you solder the little wires in place.

Once you’ve created your rows, line up the columns by matching the “1” and “+” pins. There are three offset options available, as documented in the image above.

Two rows put together

Here is an example of a fully built-up 3x3 matrix. The middle row is offset from the top by 3/16", and the bottom row is offset from the middle by 3/8". This will make the middle row equivalent to a keyboard’s A, S, and D keys, the top row Q, W, and E, and the bottom row Z, X, and C – we’re making a 9-key keypad centered around WASD!

3x3 keyboard layout

Finish off the soldering job by connecting wires to the row and column pins you’ll need access to. If you’re not using any LEDs, you’ll only need to solder to the “1” pins along the rows, and “2” pins along the columns.

3x3 keypad fully soldered

Don’t forget to add your switches, and LEDs, resistors, or diodes, should your project require them!

Keypad Scanning Arduino Code

Here’s a simple Arduino sketch, designed to work with a 9-key, 3x3 matrix, but easily expandable for larger keypads.

The sketch assumes a circuit like this:

Example 9-key keypad hookup

It may look like a mess of wires, but – with 9 switches and LEDs – we’ve at least turned 18 wires into 12.

Row/Column NameBreakout LabelArduino Pin
LED Row 1-2
LED Row 2-3
LED Row 3-4
LED Column 1+5
LED Column 2+6
LED Column 3+7
Switch Row 128
Switch Row 229
Switch Row 3210
Switch Column 1111
Switch Column 2112
Switch Column 3113

Then copy this code and upload:

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

Whenever you press a switch, the LED on that switch should also light up. Releasing the switch turns the LED off.

Adapting the Code

The code is adaptable for larger or smaller matrices, with a few modifications towards the top of the sketch.

Modify the number of rows or columns in the Config Variables section:

language:c
//////////////////////
// Config Variables //
//////////////////////
#define NUM_LED_COLS (3) // Number of LED columns (+, anode)
#define NUM_LED_ROWS (3) // Number of LED rows (-, cathode)
#define NUM_BTN_COLS (3) // Number of switch columns (diode anode)
#define NUM_BTN_ROWS (3) // Number of switch rows (diode cathode)

And/or convert the pin connections in the Hardware Setup section:

language:c
////////////////////
// Hardware Setup //
////////////////////
static const uint8_t btnRowPins[NUM_BTN_ROWS] = {8, 9, 10}; // Pins connected to switch rows (2)
static const uint8_t btnColPins[NUM_BTN_COLS] = {11, 12, 13}; // Pins connected to switch columns (1)
static const uint8_t ledRowPins[NUM_LED_ROWS] = {2, 3, 4}; // Pins connected to LED rows (-)
static const uint8_t ledColPins[NUM_LED_COLS] = {5, 6, 7}; // Pins connected to LED cols (+)

If you've added ghost-prevention diodes, keep in mind that the switch's "1" pins (organized as the columns) must be at a higher potential than the row, "2" pins.

To scan the keypad matrix, we recommend pulling the row pins high using a pull-up resistor (often internal to I/O pins). Then progressively pulling the column pins to ground and checking which of the rows, if any, are pulled low as well.

Resources & Going Further

The Cherry MX Switch Breakout Board is open-source! If you want to check out the schematic or PCB design files, feel free to peruse our GitHub repository.

Once you’ve completed your keypad, consider topping off your keys with a keycap.

Switch with keycap

There is a ridiculous variety to Cherry MX keycaps – they vary by color, translucence, height, labels, and size. There are plenty of keycap sources out there, including WASD Keyboards and MechanicalKeyboards.com.

If you’d like to keep exploring SparkFun tutorials for project ideas, here are some guide’s we’d recommend:

Reaction Timer

Demonstrate mental chronometry with this simple reaction timer!

WAV Trigger Hookup Guide V11

An introduction to being able to trigger music and sound effects based on buttons, sensors, or switches using the WAV Trigger board.

SX1509 I/O Expander Breakout Hookup Guide

Learn how you can use the SX1509 to control 16 LEDs or up to 64 buttons with just two pins.

Button Pad Hookup Guide

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

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


Flex Sensor Hookup Guide

$
0
0

Flex Sensor Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

This flex sensor is a variable resistor like no other. The resistance of the flex sensor increases as the body of the component bends. Sensors like these were used in the Nintendo Power Glove. They can also be used as door sensors, robot whisker sensors, or a primary component in creating sentient stuffed animals.

Flex Sensor 2.2"

SEN-10264
$7.95
5

Flex sensors are available in two sizes: one 2.2" (5.588cm) long and another coming in at 4.5" (11.43cm) long.

Left flat, these sensors will look like a 30kΩ resistor. As it bends, the resistance between the two terminals will increase to as much as 70kΩ at a 90° angle.

By combining the flex sensor with a static resistor to create a voltage divider, you can produce a variable voltage that can be read by a microcontroller’s analog-to-digital converter.

Suggested Materials

This tutorial serves as a quick primer on flex sensor’s, and demonstrates how to hook them up and use them. Aside from the sensor, the following materials are recommended:

Arduino Uno– We’ll be using the Arduino’s analog-to-digital converter to read in the variable resistance of the sensor. Any Arduino-compatible development platform – be it a RedBoard, Pro or Pro Mini– can substitute.

Resistor Kit– To turn the flex sensor’s variable resistance into a readable voltage, we’ll combine it with a static resistor to create a voltage divider. This resistor kit is handy for some trial-and-error testing to hone in on the most sensitive circuit possible.

Breadboard and Jumper Wires– The flex sensor’s terminals are breadboard-compatible. We’ll stick that and the resistor, then use the jumper wires to connect from breadboard to Arduino.

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
94
Resistor Kit - 1/4W (500 total)

COM-10969
$7.95
89
Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
24
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$1.95
20

Suggested Reading

Analog components, like these flex sensor’s, are a great sensor-reading entry-point for beginners, but there are a few electronics concepts you should be familiar with. If any of these tutorial titles sound foreign to you, consider skimming through that content first.

Analog to Digital Conversion

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

Voltage Dividers

Turn a large voltage into a smaller one with voltage dividers.

What is an Arduino?

What is this 'Arduino' thing anyway?

Analog vs. Digital

This tutorial covers the concept of analog and digital signals, as they relate to electronics. It will discuss what each signal looks like, where each type of signal are prevalent, and some examples of analog and digital electronic components.

Flex Sensor Overview

Before we get to circuit-building and Arduino-programming, here’s a quick rundown of the flex sensor’s important electrical characteristics.

How it Works

One side of the sensor is printed with a polymer ink that has conductive particles embedded in it. When the sensor is straight, the particles give the ink a resistance of about 30k Ohms. When the sensor is bent away from the ink, the conductive particles move further apart, increasing this resistance (to about 50k-70K Ohms when the sensor is bent to 90°, as in the diagram below).

Sensor bent

When the sensor straightens out again, the resistance returns to the original value. By measuring the resistance, you can determine how much the sensor is being bent.

Sensor straight

The flex sensor is designed to be flexed in just one direction – away from the ink – as demonstrated in the image below.


Flex sensor bend direction (from SpectraSymbol Datasheet).

Bending the sensor in the other direction will not produce any reliable data, and may damage the sensor. Also take care not to bend the sensor close to the base, as they have a tendency to kink and fail.

Example Circuit

The simplest way to incorporate this sensor into your project is by using it in a voltage divider. This circuit requires one resistor. Many values from 10KΩ to 100KΩ will work. If you have a resistor kit, you may want to introduce some trial-and-error to hone in on that perfect static resistance.

A value between the minimum and maximum resistance values is usually a good choice. We’ll use a 47kΩ resistor in this example. Here’s the hookup:

Example circuit fritzing diagram

And a schematic:

Example circuit schematic

The 47kΩ resistor on the ground side, and the flex sensor on the 5V side, means as the flex sensor’s resistance increases (meaning the sensor is bending) the voltage on A0 will decrease.

Example Program

Here is a simple Arduino example based on the circuit above. Copy and paste this into your Arduino IDE (or use Codebender), then upload!

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

After uploading, open your serial monitor, and set the baud rate to 9600 bps. Or you can use the embedded serial monitor below.

If you bend the flex sensor, you should see resistance and estimated angle calculations change:

flex sensor readings to serial monitor

If the value’s don’t seem correct, make sure the constants VCC and, more importantly, R_DIV are accurate. If you used something other than a 47kΩ resistor, enter that value in for R_DIV.

Through trial-and-error, try to hone in on more accurate values for STRAIGHT_RESISTANCE and BEND_RESISTANCE– your flex sensor’s resistance when it’s straight and bent at 90°.

Resources and Going Further

Looking for more flex sensor related documentation? Here are a few sources you may want to consult:

Need some project inspiration? Want to check out some similar analog sensors? Check out some of these related tutorials:

Getting Started with Load Cells

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

SIK Keyboard Instrument

We can use the parts and concepts in the SparkFun Invetor's Kit to make a primitive keyboard instrument.
New!

Sensor Kit Resource Hub

An overview of each component in the SparkFun Sensor Kit, plus links to tutorials and other resources you'll need to hook them up.
New!

Force Sensitive Resistor Hookup Guide

How to hook a force-sensitive resistor up to an Arduino to measure pressure variances.

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

Sensor Kit Resource Hub

$
0
0

Sensor Kit Resource Hub a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Sensor Kit is a conglomeration of all of our favorite sensors. The contents of this kit give you the ability to sense touch, vibration, flex, motion, weather patterns, magnetism…nearly every physical quantity known to man. Combine them all together to create a tricorder, or divide them up into tons of unique projects!

SparkFun Sensor Kit

DEV-13754
$129.95

This guide is a hub for all-things-Sensor Kit. It introduces the basic skills and tools you’ll need to use the sensors and points you in all the right directions to hook them up. It’ll have you on your way to SENSING ALL THE THINGS in no time!

Encouraged Extras

The Sensor Kit includes a huge variety of sensors and some supporting components for those devices, but it doesn’t include everything you’ll need to hook them up. Here are a few extra tools and components you may need to get started.

Prototyping Bits

About half of the sensors in this kit are immediately breadboard-compatible, ready to plug in and connect to a development board. Here is what you’ll need to get started with those components.

Arduino Uno– Every sensor in the kit is supported by a hookup tutorial, which includes an example Arduino circuit, and code written specifically for the popular development platform. The reliable Arduino Uno can interface with any-and-every sensor in this kit. Alternatively, any Arduino-compatible development platform – be it a RedBoard, Pro or Pro Mini– should be able to substitute.

Arduino Pro Mini 328 - 5V/16MHz

DEV-11113
$9.95
90
Arduino Uno - R3

DEV-11021
$24.95
66
SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
94
Arduino Pro 328 - 3.3V/8MHz

DEV-10914
$14.95

Breadboard– These are a recurring player in every example circuit for every sensor in the kit. The breadboard holds your sensors, resistors, and other components, and even does some of the wiring for you.

Jumper Wires– Like the breadboard, jumper wires are a part of every example circuit. These jumper wires act as an intermediary between breadboard and Arduino.

Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
24
Breadboard - Giant

PRT-12614
$19.95
9
Breadboard - Classic

PRT-00112
$9.95
8
Breadboard - Mini Modular (Green)

PRT-12046
$3.95
1

Soldering Tools

Once you move beyond some of the simple components in this kit, like photocells and flex sensors, you’ll advance to the breakout boards. Breakout boards, like the LSM9DS1 and MPL115A1, are shipped without interface connectors, which means you’ll need to whip out your soldering tools before connecting them to a development board.

Soldering Iron– An iron obviously tops the soldering tool list. Even the most basic soldering iron will be enough to get you by, or invest in your future tinkering with a Hakko.

Hakko FX888D Soldering Station

TOL-11704
$99.95
24
Soldering Iron - 30W (US, 110V)

TOL-09507
$9.95
3
Hakko FX-901 Cordless Soldering Iron

TOL-13151
34.9500$30.95
18
Soldering Iron - 30W (EU, 230VAC)

TOL-11650
$9.95
1

Solder– Large, small, leaded, lead-free…there are a few options to consider when you’re picking out solder. Leaded solder is easier to use, and produces shinier joints, but has a certain stigma to it.

Solder Lead Free - 100-gram Spool

TOL-09325
$7.95
3
Solder Leaded - 100-gram Spool

TOL-09161
$5.95
2
Solder - 1/4lb Spool (0.020") Special Blend

TOL-10242
$29.95
4
Solder Lead Free - 15-gram Tube

TOL-09163
$3.5
1

Headers or Wire– You’ll need to solder something to the breakout board. Whether that something is male headers, female headers, stranded wire, solid-core wire, or something else is completely up to you.

Break Away Headers - Straight

PRT-00116
$1.5
20
Female Headers

PRT-00115
$1.5
6
Hook-Up Wire - Assortment (Solid Core, 22 AWG)

PRT-11367
$16.95
13
Hook-Up Wire - Assortment (Stranded, 22 AWG)

PRT-11375
$16.95
9

Suggested Skills

The Sensor Kit’s sensors are a great entry-point for electronics beginners, but they do build on some assumed knowledge. Here are a few electrical engineering-specific tutorials you may want to check out before venturing further into the sensor depths.

What is a Circuit?

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

What is Electricity?

We can see electricity in action on our computers, lighting our houses, as lighting strikes in thunderstorms, but what is it? This is not an easy question, but in this tutorial we will shed some light on what is electricity!

Series and Parallel Circuits

An introduction into series and parallel circuits.

We’ll be relying heavily on Arduino throughout these tutorials. New to the Arduino scene? We’ve got a lot of reading material for you!

Installing an Arduino Library

How do I install a custom Arduino library? It's easy!

How to Use a Breadboard

Welcome to the wonderful world of breadboards. Here we will learn what a breadboard is and how to use one to build your very first circuit.

What is an Arduino?

What is this 'Arduino' thing anyway?

Installing Arduino IDE

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

One last biggie: If you’ve never soldered before, don’t fret – this is a great opportunity to get started! Check out our How to Solder - Through-Hole Soldering guide for tips, tricks, and a tutorial.

How to Solder - Through-hole Soldering

September 19, 2013

New to electronics and soldering? Have you soldered before but need a refresher? This tutorial with cover everything you need to know about through-hole soldering.

Resource Rundown

This section briefly overviews each sensor included in the Sensor Kit – describing what the sensor senses, how it relays that data, and what kind of power it requires. Links to separate tutorials are also provided. When you’re ready to hook a sensor up and do some sensing, check out the tutorial for that device.

All of these sensors can be organized into one of two categories analog or digital. Analog sensors are generally easier to set up and use, but digital sensors can be more powerful and accurate. If you’re just getting started with electronics, consider exploring some of the analog sensors first.

Analog Sensors

Most of these analog sensors are either variable resistors or potentiometers. The data they sense is usually translated to a variable voltage, which is read by a microcontroller’s analog-to-digital converter (ADC) and compared against other measurements.

Force-Sensitive Resistor

Force Sensitive Resistor 0.5"

SEN-09375
$6.95
6

A force-sensitive resistor (FSR) is a variable resistor that increases or decreases depending on how hard something is pressing down on it. When no pressure is being applied to the FSR its resistance will be larger than 1MΩ.

The harder you press on the sensor’s circular head, the lower the resistance between the two terminals drops. This FSR can sense applied force anywhere in the range of 0.1kg-10kg.

By creating a voltage divider with the FSR and another resistor, you can create a variable voltage output, which can be read by a microcontroller’s ADC input.

These sensors are simple to set up and great for sensing pressure, but they aren’t incredibly accurate. They’re useful for sensing the presence of something, but not all that great at measuring something’s weight.

(Note: force-sensitive resistors cannot detect the presence of Midichlorians.)

The Force Sensitive Resistor Hookup Guide examines the basic characteristics of FSR’s, and demonstrates how to hook them up to an Arduino so you can start gauging pressure.

Use the Force (on an FSR)!


Flex Sensor

Flex Sensor 2.2"

SEN-10264
$7.95
5

This flex sensor is a variable resistor like no other. The resistance of the flex sensor increases as the body of the component bends. Sensors like these were used in the Nintendo Power Glove.

Left flat, the sensor will look like a 30kΩ resistor. As it bends, the resistance will increase to as much as 70kΩ at a 90° angle.

Combined with another resistor to create a voltage divider, the flex sensor can produce a variable analog voltage to be read by a microcontroller’s ADC pin.

Consult the Flex Sensor Hookup Guide for help connecting the bend-sensor up to an Arduino.

Get Your Flex On!


Mini Photocell

Mini Photocell

SEN-09088
$1.5
6

Photocell’s are light-sensitive, variable resistors. As more light shines of the sensor’s head, the resistance between the photocell’s terminals decreases.

In pitch-black conditions, the photocell’s resistance will be in the megaohm’s (1.0MΩ+). Shining an LED on the sensor can drop the resistance to near-zero. Usually the resistance of the photocell will range between 8k-20kΩ in normal lighting conditions.

As with other resistive sensors, to use the photocell with an ADC they’re usually paired with a static resistor to form a voltage divider.

Photoresistor’s won’t give you incredibly accurate lux readings (that’s what sensors like the TSL2561 is for), but they’re great for at least identifying the general state of ambient light.

The Photocell Hookup Guide provides a quick overview of the photocell’s resistive characteristics, plus an example circuit and code.

See the Light With a Photocell


Soft Potentiometer

SoftPot Membrane Potentiometer - 50mm

SEN-08680
$4.95
1

Soft potentiometers, or “softpots”, are very thin potentiometers “wiped” by pressing down on various parts of the strip.

Like any potentiometer, the softpot is a three terminal device. The middle pin is the wiper, and the other two terminals are the high and low ends of the resistive element.

The resistance between the wiper and either of the other two terminals varies between 0Ω and 10kΩ. Or, if nothing is pressing down on the softpot, the connection between the two terminals looks like an (almost) open circuit. By applying a voltage across the two outside terminals, the middle terminal can produce a voltage somewhere in the applied range.

These sensors can be used for position detection or in projects that require linear user input, like a volume slider.

Take a stroll through the SoftPot Hookup Guide to learn how simple and fun these sensors are to use!

Slide Along the Soft Pot!


Piezo Vibration Sensor

Piezo Vibration Sensor - Large with Mass

SEN-09197
$2.95

Piezo sensors are flexible devices that generate electric charge when they’re stressed. This characteristic makes piezo’s an ideal solution for low-power flex, touch, and vibration sensing. This piezo sensor in particular has a heavy mass at the end to help accentuate its vibrations.

In more advanced applications, piezo’s can be the foundation for energy harvesting. They produce large AC voltage spikes – ranging as high as ±90V – when vibrating, but the current and total power they produce is still minuscule.

Because they produce such high voltage spikes, large resistors are often used to “load down” the piezo sensor in vibration-sensing applications. The 1MΩ resistors included with the sensor kit are designed to help dampen the piezo’s voltage output.

The Piezo Vibration Sensor Hookup Guide examines the AC-voltage-supplying capabilities of Piezo sensors, then shows how you can dampen that voltage and hook it up to an Arduino.

Sense Good Vibrations with a Piezo Sensor


Soil Moisture Sensor

The Soil Moisture Sensor is a simple breakout for measuring the moisture in soil and similar materials. By monitoring soil conditions you can create a tweeting plant, that will alert you when it’s thirsty.

The sensor consists of two conductive “stakes”, that plug into the ground. Three wires – power, ground, and a signal – are all it takes to get the sensor up-and-running.

Soil Moisture Sensor

These probes measure the soil’s conductivity. Soaked soil is much less resistive to current flow than flaky, dry dirt, so the lower the moisture sensor’s reading, the happier your plant will be.

Check out the Soil Moisture Sensor Hookup Guide for assembly and implementation tips.

Monitor Your Plant's Moisture Levels and Keep it Thriving!


Sound Detector

SparkFun Sound Detector

SEN-12642
$10.95
7

The Sound Detector is a small and very easy to use audio-sensing board. It has three different outputs: binary sound detection, audio envelope, and a true audio output. The 3 outputs are simultaneous and independent, so you can use as many or as few as you want at once.

The digital binary output produces you a high or low signal indicating if sensed audio is over a set threshold – it’s an incredibly handy feature, which offboards complicated firmware programming onto pre-built hardware! The analog envelope filter is equally useful, especially if all you really want to monitor is the general amplitude of local sounds.

The sound detector has a built-in electret microphone, and all sorts of amplifying goodies on-board as well. You can add external resistors to customize the detector’s gain and binary threshold.

The comprehensive Sound Detector Hookup Guide will walk you through assembly, hookup, and custom-modification of the breakout.

Monitor for Aural Disturbances with Sound Detector


Optical Detector/Phototransistor - QRD1114

Optical Detector / Phototransistor - QRD1114

SEN-00246
$0.95
2

Photodetectors like the QRD1114 are actually built out of two components: an LED to emit infrared light and a phototransistor to detect it. The sensor can measure proximity or even color by measuring the amount of IR light that gets reflected back into it.

One of the most common applications for these sensors is black-or-white color detection – they’re a popular sensor choice for line following robots. A black, sharpie-marked line will absorb more light, meaning less light is reflected back into the sensor’s phototransistor. When the sensor transitions over a white surface, more light is reflected and the sensor’s output increases.

These sensors can be used with a microcontroller’s ADC input to measure the amount of IR light reflected back. The LED does not have a current-limiting resistor built-in, so an external 330Ω resistor is usually added for that purpose.

Head over to the QRD1114 Optical Detector Hookup Guide to learn how the QRD1114 senses proximity by measuring reflectance of an IR LED. Then hook it up to an Arduino to do some proximity sensing of your own.

Reflect on Proximity With the QRD1114


Digital Sensors

"Digital" here is a broad term. These sensors range from emitting simple HIGH/LOW signals, to communicating over more complex serial interfaces like SPI or I2C. In most cases, the latter devices will require an Arduino library to help with communication between device and microcontroller.

Reed Switch

Reed Switch

COM-08642
$1.95
1

A reed switch is a magnetically actuated switch. When the switch is exposed to a magnetic field, two ferrous materials inside pull together and the switch closes. When there is not a strong enough magnetic field nearby, the switch acts as an open circuit.

Magnets, like the small, square magnet included with this kit, can be used to actuate the reed switch. Just hold it about 1cm away, and let your current flow!

Reed switches are perfect for applications that require non-contact control. For example, a reed switch is present in magnetic door switches– both parts of the switch are separate, allowing the door to open and close (maintaining its duties as a door).

The Reed Switch Hookup Guide describes the general characteristics of reed switches, and shows how to use one to turn on an LED with the magic power of magnets.

Flip a Reed Switch Without Ever Touching It


PIR Motion Sensor

PIR Motion Sensor (JST)

SEN-13285
$9.95
8

PIR (passive infrared) sensors are motion-detecting devices used in security systems across the world – even though you may not see them, they probably see you!

PIR sensors consist of an infrared “camera”, which periodically measures the amount of infrared light it sees, and compares that against past measurements. When the IR measurement changes beyond a set threshold, the PIR sends a digital signal communicating that something in its field-of-view has moved.

PIR’s are easy to hook up – all they require is power (5-12V) and a pin to read the digital output. When motion is detected, the alarm output line goes low.

For help hooking up the PIR sensor to an Arduino, check out our PIR Motion Sensor Hookup Guide.

Monitor Your Hallways with the PIR Sensor


IR Receiver & IR LED

IR Receiver Diode - TSOP38238

SEN-10266
$1.95

The TSOP38238 Infrared Receiver Diode– or a part like it – is embedded into every TV, cable receiver, and Blu-Ray player in your house. These IR receivers look for encoded infrared light, carrying messages like “channel up” or “volume down”, and produce a signal that can be read by any microcontroller.

Before emitting a signal, infrared remotes modulate their signals at a set frequency. This diode has brains built into it that can automatically demodulate a standard 38kHz infrared signal. What comes out of the chip are a series of specifically timed 1’s and 0’s, that can in turn be converted to common IR remote commands.

The IR receiver diode can be paired with any household remote. Or you can use the included 950nm Infrared LED to create a remote of your own!

The IR Control Kit Hookup Guide demonstrates how to hook up the IR receiver diode, and set it to listen to any remote you may have in your household. It also shows how to create your own IR remote, by combining an Arduino with an IR LED.

Control Your Arduino, Control the World – with IR!


Capacitive Touch Breakout - AT42QT1010

SparkFun Capacitive Touch Breakout - AT42QT1010

SEN-12041
$5.95
3

The AT42QT1010 is a dedicated, single-button capacitive sensing chip. Our breakout board for this chip wires it up to a fingertip-sized, circular electrode – perfect for creating non-contact user-input.

The problem with physical buttons is they wear out over time. Even the hardiest of mechanical switches may only be rated for millions of key presses. Capacitive buttons are less prone to degrading over time. Plus, tapping them feels like tapping the future!

The breakout produces a digital output, just as if you were reading the state of a switch. The output signal will be low if the button is inactive and high if the button is pressed.

The breakout also includes an LED indicator, which will illuminate whenever the board senses a “press.”

Check out the AT42QT1010 Capacitive Touch Breakout Hookup Guide for all of your capacitive switch needs. This tutorial documents assembly, wiring, and code.

Add Non-Contact User Input to your Project!


9 Degrees of Freedom IMU Breakout - LSM9DS1

SparkFun 9 Degrees of Freedom IMU Breakout - LSM9DS1

SEN-13284
$24.95
3

The LSM9DS1 is actually three sensors in one– it houses an accelerometer, gyroscope, and magnetometer. Plus, each of these sensors are three-dimensional, meaning this sensor produces nine degrees of motion information.

The accelerometer measures acceleration – how fast an object is speeding up or slowing down. They’re often used to monitor the direction of the force of gravity, which helps determine the orientation of a device. They can also be used to watch for an object in free-fall, or to count steps like a pedometer.

The gyroscope measures angular rotation – how fast an object is spinning around an axis. Gyroscopes can be used by autonomous robots (drones, balancing bots, etc) to sense any sudden “rolling” movements and compensate for them.

The magnetometer measures the strength of nearby magnetic fields. These sensors can measure any magnetic field, but they’re primarily used to sense that of Earth. By sensing Earth’s magnetic field, magnetometers can be used as a compass, to help determine the orientation of movement.

I2C– a two-wire, serial interface – is the primary communication interface, although it also supports SPI. Don’t worry, the SparkFun LSM9DS1 Arduino Library simplifies all of that for you.

For all-things-LSM9DS1, check out the LSM9DS1 IMU Hookup Guide. That tutorial will demonstrate how to assemble the sensor, connect it to an Arduino, and interface with it over an I2C interface.

Start Using the LSM9DS1 9DOF IMU!


RGB and Gesture Sensor - APDS-9960

SparkFun RGB and Gesture Sensor - APDS-9960

SEN-12787
$14.95

The APDS-9960 is a multi-talented, powerful sensor that can measure light, color, proximity, and even hand gestures.

At it’s most basic, the APDS-9960 is an ambient light sensor (much like the photocell). It can be used to monitor whether lights are on or off, or what time the sun rises. But it can also tell you how much red, green, and blue it’s detecting in that light, so you can use it to sense nearby colors.

The sensor also features proximity detection. It can determine the sensor’s distance from a nearby object anywhere from 4 to 8 inches away.

Finally, the APDS-9960 can sense nearby hand wave gestures (anywhere from 2-10 inches (5-25 cm) away). It can tell you if a hand is waving up, down, left, or right. Sensor’s like these are the magic behind touchless toilet’s!

The APDS-9960 is another I2C-based device. If you’re using an Arduino, the Wire library helps take care of I2C.

The APDS-9960 RGB and Gesture Sensor Hookup Guide demonstrates how to assemble the breakout board, connect it to an Arduino, and interface with it over an I2C interface.

Start Using the APDS-9960 Color, Light, and Gesture Sensor!


Humidity and Temperature Sensor Breakout - Si7021

SparkFun Humidity and Temperature Sensor Breakout - Si7021

SEN-13763
$11.95

The Si7021 is an easy-to-use, highly accurate, humidity and temperature sensor.

This sensor is perfect for a weather stations or humidor control systems. You can log the data to memory, to be read later, or you can use an Internet-enabled microcontroller, and log the data, in real-time, to data.sparkfun.com.

All you need is two lines for I2C communication and you’ll have relative humidity readings and very accurate temperature readings as a bonus!

The Si7021 Breakout Hookup Guide demonstrates how to assemble the breakout board, connect it to an Arduino, and interface with it over an I2C interface.

Sense Temperature and Humidity with the Si7021 Breakout!


Altitude and Pressure Sensor Breakout - MPL3115A2

SparkFun Altitude/Pressure Sensor Breakout - MPL3115A2

SEN-11084
$14.95
9

The MPL3115A2 is a air pressure sensor. Air pressure is inversely proportional to altitude, which means the higher you go, the lower the pressure. The relationship between altitude and pressure makes these sensors a common component in altitude-dependent projects, like weather balloons and quadcopters.

Of course, the MPL3115A2 can also be used to monitor pressure as it relates to changing weather patterns. Higher-than-normal pressure may indicate a sunny day, while low pressure systems might indicate precipitation. Not coincidentally, the chip includes a built-in temperature sensor, putting you one step closer to creating a comprehensive weather station.

Like most of the other breakout boards, the MPL3115A2 features an I2C interface. That’s actually a huge bonus. I2C interfaces are powerful because they support communication with multiple devices on a single, two-wire bus. For example, you could control both this sensor and the Si7021 humidity sensor – creating the basis for a weather monitor – with just a pair of I/O pins.

The MPL3115A2 is documented in our MPL3115A2 Pressure Sensor Hookup Guide. The hookup guide demonstrates how to assemble the breakout and use it with an Arduino.

Measure Altutide or Monitor Weather Patterns with the MPL3115A2


Resources and Going Further

With one hookup guide per sensor, you’ve already got plenty of reading material. We don’t want to overwhelm you, but we do want to instill some project ideas in the back of your mind. There are plenty of directions you can take a project with all of the sensors in this kit.

You can take the pressure, humidity, and temperature sensors to build a weather station– one that can wirelessly post to Weather Underground.

Weather Station Wirelessly Connected to Wunderground

April 11, 2014

Build your own open source, official Wunderground weather station that updates every 10 seconds over Wifi via an Electric Imp.

You can use the piezo vibration sensor or the accelerometer third of the 9DOF to create a laundry monitor.

Blynk Board Washer/Dryer Alarm

March 31, 2016

How to configure the Blynk Board and app to notify you when your washer or dryer is done shaking.

Maybe use the reed switch to control a TARDIS-themed music box.

MP3 Player Shield Music Box

January 21, 2013

Music Box Project based on the TARDIS

Or just combine all of the sensors to create your very own tricorder! It’s up to you from here. Go sense!


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

SoftPot Hookup Guide

$
0
0

SoftPot Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Soft potentiometers are very thin and very unique potentiometers. Instead of a knob or physical slider, the softpot’s wiper is any object – a finger, pen cap, stylus, etc – that can slide across its sensor membrane. Softpots can be used as position sensors in CNC machines, volume control sliders in custom stereos, throttles for drones, or in any project that requires linear movement sensing.

SoftPot Membrane Potentiometer - 50mm

SEN-08680
$4.95
1

Like any potentiometer, the softpot is a three terminal device. The middle pin is the wiper, and the other two terminals are the high and low ends of the resistive element. By supplying the outer terminals with a power and ground connection, the middle terminal can be used to produce a variable voltage.

Suggested Materials

This tutorial serves as a quick primer on soft potentiometers, and demonstrates how to hook them up and use them. In addition to the softpot, the following materials are recommended:

Arduino Uno– We’ll be using the Arduino’s analog-to-digital converter to read in the variable voltage of the softpot. Any Arduino-compatible development platform – be it a RedBoard, Pro or Pro Mini– can substitute.

Breadboard and Jumper Wires– The soft pot three terminals are breadboard compatible. The breadboard is used as an intermediary device between sensor and jumper wires to the Arduino.

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
94
Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
24
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$1.95
20

Suggested Reading

SoftPot’s are a great entry-level component for beginners, but there are still a few basic electronics concepts you should be familiar with. If any of these tutorial titles sound foreign to you, consider skimming through that content first.

Analog to Digital Conversion

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

What is an Arduino?

What is this 'Arduino' thing anyway?

Resistors

A tutorial on all things resistors. What is a resistor, how do they behave in parallel/series, decoding the resistor color codes, and resistor applications.

Analog vs. Digital

This tutorial covers the concept of analog and digital signals, as they relate to electronics. It will discuss what each signal looks like, where each type of signal are prevalent, and some examples of analog and digital electronic components.

SoftPot Overview

Softpots come in a variety of sizes. The SparkFun catalog sports 50mm, 200mm, and 500mm long softpot strips. You can also find circular, arc-shaped, or other uniquely-shaped softpots in the market.

SoftPot Membrane Potentiometer - 500mm

SEN-08681
$16.95
SoftPot Membrane Potentiometer - 200mm

SEN-08679
$9.95
SoftPot Membrane Potentiometer - 50mm

SEN-08680
$4.95
1

The 50mm and 200mm softpot’s feature a 10kΩ overall resistance between the outer-two terminals, while the larger 500mm softpot measures in at 20kΩ.

Placing your wiper at the base of the soft pot will effect a nearly 0Ω resistance between the middle pin and pin 1 (indicated by the arrow). When the wiper reaches the far end of the soft pot, the resistance will approach 10kΩ. And, if the wiper is in the middle, the resistance should be around 5kΩ.

Resistance along soft pot

The softpot is generally linear across the entire sensor area, so any math you’ll do to determine a wiper’s position should be relatively simple!

Example Circuit

By supplying a voltage to the outer pins of the SoftPot, we can generate a variable voltage on the middle wiper pin. Here’s an example hookup:

Fritzing example circuit

You could build this same circuit using a breadboard.

By connecting pin 1 to ground and pin 3 to 5V, we cause the voltage on the middle pin to rise from 0V to 5V as the wiper moves from the bottom of the softpot (towards the terminals) to the top. Reversing the power supply can swap that relationship around.

Example Code

Here is a simple Arduino example based on the circuit above. Copy and paste this into your Arduino IDE (or use Codebender), then upload!

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

After uploading, open your serial monitor, and set the baud rate to 9600 bps. Or, you can use the embedded serial monitor below.

Then actuate the softpot by sliding a finger, pencil eraser, tool grip, or anything slide-able across the sensing area of the potentiometer.

Softpot slider in action

A series of line graphs should begin flowing by in the serial monitor.

Serial monitor example

The raw ADC reading is also printed out after each reading. Take that, and start building sliding control systems of your own!

Resources and Going Further

If you need any further SoftPot-related documentation, here are a few resources that may help:

Now that you’ve set your Arduino up with slide-control, what are you going to build? Need some inspiration? Check out some of these SparkFun tutorials:

Touch Potentiometer Hookup Guide

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

Rotary Switch Potentiometer Hookup Guide

How to use the Rotary Switch Potentiometer breakout board, with some sample applications.

Bare Conductive Musical Painting

Learn how to make a musical painting using the Bare Conductive Touch Board and Conductive Paint.

MP3 Trigger Hookup Guide V24

Incorporate sound into your next project easily with the MP3 Trigger.

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

QRD1114 Optical Detector Hookup Guide

$
0
0

QRD1114 Optical Detector Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The QRD1114 is a half-LED, half-phototransistor, all infrared reflective optical detector. It can be used to sense objects in close proximity or even detect the difference between black and white surfaces. Photodetector’s like these are critical components for projects ranging from line-following robots to close-proximity detection in smartphones.

Optical Detector / Phototransistor - QRD1114

SEN-00246
$0.95
2

The QRD1114 is easy to hook up: All you need is a current-limiting resistor for the IR LED and a pull-up resistor on the phototransistor’s collector pin. The component can be used to produce an analog signal – read by a microcontroller’s analog-to-digital converter pin – proportional to a nearby object’s proximity.

Suggested Materials

This tutorial serves as a quick primer on reflective photodetector’s and demonstrates how to hook them up and use them. Beyond the sensor itself, the following materials are recommended:

Arduino Uno– We’ll be using the Arduino’s analog-to-digital converter to read in the analog output voltage of the photodetector. Any Arduino-compatible development platform – be it a RedBoard, Pro or Pro Mini– can substitute.

Resistor Kit– The LED portion of the photodetector requires a current-limiting resistor – somewhere in the range of 330Ω. On the other half of the sensor we’ll need a 10kΩ pull-up resistor to take advantage of the phototransistor’s light-dependent current throughput. This resistor kit is handy for some trial-and-error testing to hone in on the most sensitive circuit possible.

Breadboard and Jumper Wires– The photodetector’s legs can be bent and shaped to fit a standard 0.1"-spaced breadboard. We’ll then use the jumper wires to connect from breadboard to Arduino.

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
94
Resistor Kit - 1/4W (500 total)

COM-10969
$7.95
89
Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
24
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$1.95
20

Suggested Reading

Reflective photodetector’s are a great entry-level component for beginners, but there are still a few basic electronics concepts you should be familiar with. If any of these tutorial titles sound foreign to you, consider skimming through that content first.

Light

Light is a useful tool for the electrical engineer. Understanding how light relates to electronics is a fundamental skill for many projects.

Analog to Digital Conversion

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

Light-emitting Diodes (LEDs)

Learn the basics about LEDs as well as some more advanced topics to help you calculate requirements for projects containing many LEDs.

Transistors

A crash course in bi-polar junction transistors. Learn how transistors work and in which circuits we use them.

QRD1114 Overview

The QRD1114 is a 4-pin device. Two legs break out the infrared LED, and the other two legs break out the collector and emitter pins of the phototransistor (the “base” of the phototransistor is controlled by the IR light returned). The image below, from the datasheet, shows which pin is which.

internal circuit diagram

Pin 1, the collector of the transistor, can be found by locating the dot on the top of the component. You should also be able to see two noticeably different-colored rectangles – one black and one clear. The black rectangle is the phototransistor (the black part is actually a filter cover), and the clear half is the LED.

pin 1 location

Top-down diagram of the QRD1114. Note the pin 1 indicator.

Looking from the top down, the pins increment in counter-clockwise order. Pin 2 – the transistor’s emitter – is adjacent to pin 1 along the long side of the body. Pin 3, the LED anode is across the short side of the photodetector from pin 2. And the cathode pin 4 is next to pin 3 and across the body from pin 1.

The length of the legs can also help determine which pin is which. Pins 1 and 3 are longer than the other pins; (probably) not coincidentally, these are the “positive” pins of their respective components (collector and anode).

Photodetector leg lengths

Sensor Characteristics

The QRD1114’s infrared LED is just like any other LED you may have used in the past. The forward voltage is typically between 1.2V and 1.7V, which means you’ll need at least that much potential on your supply to power the LED. 3.3V or 5V supplies can work just fine, as long as you have a current-limiting resistor.

The LED’s maximum forward current is 50mA; more than that has a chance of permanently damaging the part. It’s best to aim at delivering around 20mA to the diode.

One of the most interesting graphs in the QRD1114 datasheet is this distance versus transistor collector current curve:

alt text

The graph above makes assumptions (LED intensity, power to the across the transistor, reflecting material), but it’s still a good gauge for estimating a distance based on the output signal. It at least demonstrates a few things about the sensor:

  • The output tops out at about 30 mils (0.03", 0.76mm).
  • From the peak, it slopes down exponentially.
    • At about 125 mil (0.125", 3.18mm), the output signal is already 30% of the peak.
    • At about 300 mil (0.3", 7.62mm), changes in the signal become nearly indistinguishable.
  • If an object gets too close to the sensor, it will enter a dead zone. Anything closer than about 30 mils (0.03", 0.76mm) is difficult for the detector to see.

TLDR: these sensor’s don’t have a very large range. They’re designed for close proximity sensing. They can reliably detect distances ranging from 0.03 to about 0.4 inches (0.75-10.15mm).

Example Circuit

Incorporating a 330Ω current-limiting resistor and a 10kΩ pull-up resistor, here’s an example circuit connecting the QRD1114 to an Arduino:

Schematic example

The LED is supplied by 5V with a 330Ω current-limiting resistor. The value of this resistor can be decreased to around 175Ω to increase the LED current closer to 20mA.

The transistor’s emitter is grounded, and the collector is connected to the Arduino’s A0 pin. The 10kΩ pull-up resistor helps turn the transistor’s light-variable current into a light-variable voltage.

Here is an example breadboard wiring diagram for the circuit:

Breadboard example

There are many ways to assemble this circuit on a breadboard. The example above straddles both the LED and phototransistor across the breadboard’s median.

Example Code

Here is a simple Arduino example based on the circuit above. Copy and paste this into your Arduino IDE (or use Codebender), then upload!

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

After uploading, open your serial monitor, and set the baud rate to 9600 bps. Or, you can use the embedded serial monitor below.

While you monitor the voltage outputs in the serial monitor, move your hand towards the sensor’s head. You should see the voltage dip from ~4.8V to less than 0.2V. Keep moving in and out to get a feel for the sensor’s viewing distance.

Serial monitor example

After testing it out with your finger, try testing other objects. In addition to distance, the output voltage also depends on the object’s color and reflectance. As an example, here’s a very unscientific comparison we did between black and white sheets of paper:

Voltages, distances, and colors

The sensor is much more sensitive to the white paper than the black. The black surface absorbs more light from the LED, meaning less is reflected back to the phototransistor. Try doing some science of your own to test out your sensor’s behavior!

Resources and Going Further

For more information on the QRD1114, be sure to check out the datasheet.

Now that you’ve got your Arduino sensing proximity, and even color, what project are you going to create? Need some inspiration? Check out some of these related tutorials:

Vernier Photogate

Vernier Photogate Timer -- using the Serial Enabled LCD Kit.

APDS-9960 RGB and Gesture Sensor Hookup Guide

Getting started guide for the Avago APDS-9960 color, proximity, and gesture sensor.

ZX Distance and Gesture Sensor Hookup Guide

How to connect and use the SparkFun ZX Distance and Gesture Sensor with an Arduino.
New!

PIR Motion Sensor Hookup Guide

An overview of passive infrared (PIR) motion detecting sensors, and how to hook them up to an Arduino.

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

Reed Switch Hookup Guide

$
0
0

Reed Switch Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Reed switches are magnetically-actuated electrical switches (not magically-actuated, though it seems that way sometimes). When the body of the switch is exposed to a magnetic field – like a magnet or even a strong electrical current – two ferrous materials inside pull together, the connection closes, and current can flow. In absence of a magnetic field, the switch opens as does the circuit it’s a part of.

Reed Switch

COM-08642
$1.95
1

There are all sorts of creative applications for reed switches. They’re perfect for any projects that require non-contact control. A magnetic door switch, for example, is just a dressed up reed switch and a mating magnet – by keeping both parts of the switch separate, the door can open and close freely (and maintain its regular duties as a door). The anemometer in our weather meter combines a number of reed switches, which all open and close in order as the wind blows; count the time between switch closures to determine the wind speed.

Suggested Materials

This tutorial serves as a quick primer on reed switches and demonstrates how to hook them up and use them. Beyond the switch itself, the following materials are recommended:

Magnet– You’ll need something to actuate the reed switch, and this small magnet should fit the bill.

Arduino Uno– We’ll be using a digital pin on the Arduino to read the state of the switch. Any Arduino-compatible development platform – be it a RedBoard, Pro or Pro Mini– can substitute.

Breadboard and Jumper Wires– With it’s legs properly bent, the reed switch is breadboard-compatible. We’ll use the breadboard as an intermediary between reed switch and jumper wires, which will connect the switch to an Arduino.

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
94
Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
24
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$1.95
20
Magnet Square - 0.25"

COM-08643
$1.5
2

Suggested Reading

Read switches are a fun and easy-to-use component for beginners, but there are still a few basic electronics concepts you should be familiar with. If any of these tutorial titles sound foreign to you, consider skimming through that content first.

Pull-up Resistors

A quick introduction to pull-up resistors - whey they're important, and how/when to use them.

How to Use a Breadboard

Welcome to the wonderful world of breadboards. Here we will learn what a breadboard is and how to use one to build your very first circuit.

What is an Arduino?

What is this 'Arduino' thing anyway?

Switch Basics

A tutorial on electronics most over-looked and under-appreciated component. The switch! Explaining the difference between momentary and maintained switches. And what all those acronyms (NO, NC, SPDT, SPST, ...) stand for.

Reed Switch Overview

Reed switches come in a variety of shapes and sizes. Through-hole, surface-mount, insulated, pre-formed – there are a lot of factors to consider.

Magnetic Door Switch Set

COM-13247
$2.95
Reed Switch - Insulated

COM-10601
$1.95
Reed Switch

COM-08642
$1.95
1
LilyPad Reed Switch

DEV-13343
$2.95

The basic glass reed switches are relatively fragile. If you’re project will feature large magnets repeatedly slamming against the body of the switch, consider upgrading to an overmolded variant.

You may also need to consider the current and voltage capabilities of your reed switch – they’re usually not designed to carry a high amount of power. The glass switch we’re using in this tutorial is rated for a maximum of 1.2A and 10W. Higher-power-capable switches are hard to find and can be expensive.

Normally Open, Normally Closed?

One thing all of these switches have in common is the two-terminal interface. But whether those terminals are normally open or closed is another question. The reed switch we’ll be using in this example is normally-open. That means “normally”, when the switch is unaffected by a magnetic field, the switch is open and does not conduct electricity. When a magnet comes close enough for the switch to activate, the contacts close and current can flow.

Looking for a normally-closed switch? You can make one by adding a second magnet. Check it out!

Magnetic Sensor Activation

Just as your magnet may have two poles, the reed switch’s pair of ferrous contacts are also polarized. The position, distance, and orientation of your magnet all play a role in determining how the switch activates.

These example graphs, from the Hamlin App Note AN104 do a great job of demonstrating how the position of the magnet affects the activation of the switch.

Reed switch activation graphs

The graph on the left shows an expected activation area when the magnet is held parallel to the reed switch. This area, as expected, is a mostly parabolic field. The graph on the right demonstrates what you can expect when the magnet is perpendicular to the switch. In this orientation, there is usually a dead zone in the center of the switch. If it’s in the middle of the body, it might not activate, even when the magnet is touching the reed switch.

The polarity and position of the magnet plays an important role in how your reed switch activates. If your switch doesn’t seem as sensitive as you’d like, try placing the magnet to one side or the other. Make sure you test the pair of components out before mounting either in place.

Example Circuit

The circuit set up for this example is about as easy as can be. First bend both legs of the switch to point perpendicularly away from the body of the switch, so they form a “U” shape.

Fragile! The body of the glass-tubed reed switch is very delicate. While you're bending the legs, try not to place any stress on the body of the switch.

Insert the reed switch into the breadboard. Then use jumper wires to connect one end of the switch to ground and the other end to the Arduino’s D2 pin. Here’s an example circuit:

Reed switch circuit

That’s all it takes! We’ll use the Arduino’s internal pull-up resistor on pin 2 to bias the switch high. When the switch closes, it will connect pin 2 directly to ground, and it should read low.

Example Code

Here is a simple Arduino example based on the circuit above. Copy and paste this into your Arduino IDE (or use Codebender), then upload!

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

The sketch depends on an LED being attached to the Arduino’s pin 13. That should be the case on 99% of the Arduino boards out there, but, if yours is different, you may need to check the serial monitor for verification of the switch’s operation.

With the sketch uploaded, grab your magnet, and draw it close to the switch. It should trigger when the magnet approaches, as close as 1cm away from the body of the reed switch. Try mapping out the entire activation region of the reed switch. See how far away you can get the magnet!

Resources and Going Further

Reed switches are a perfect trick for non-contact activation applications. We used a reed switch to detect when the doors of this TARDIS-themed music box opened. Or you can hook a large, door-specific reed switch up to a Blynk Board and have it send push notifications to your phone when the door state changes.

Now that you’ve got a reed switch wired up to your Arduino, what are you going to create? Need some inspiration, check out some of these related SparkFun tutorials:

MP3 Player Shield Music Box

Music Box Project based on the TARDIS

MYST Linking Book

Create your own Linking Book from the classic computer game, MYST

LilyPad Reed Switch Hookup guide

A guide to using the LilyPad Reed Switch breakout in your projects.

Blynk Board Project Guide

A series of Blynk projects you can set up on the Blynk Board without ever re-programming it.

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

Force Sensitive Resistor Hookup Guide

$
0
0

Force Sensitive Resistor Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Force-sensitive resistor’s (FSR) are easy-to-use sensors designed for measuring the presence and relative magnitude of localized physical pressure.

Force Sensitive Resistor 0.5"

SEN-09375
$6.95
6
Force Sensitive Resistor - Square

SEN-09376
$7.95
3
Force Sensitive Resistor - Small

SEN-09673
$5.95
2
Force Sensitive Resistor - Long

SEN-09674
$17.95
1

The resistance of an FSR varies as the force on the sensor increases or decreases. When no pressure is being applied to the FSR, its resistance will be larger than 1MΩ. The harder you press on the sensor’s head, the lower the resistance between the two terminals drops. By combining the FSR with a static resistor to create a voltage divider, you can produce a variable voltage that can be read by a microcontroller’s analog-to-digital converter.

Suggested Materials

This tutorial serves as a quick primer on FSR’s and demonstrates how to hook them up and use them. Beyond an FSR of your choice, the following materials are recommended:

Arduino Uno– We’ll be using the Arduino’s analog-to-digital converter to read in the variable resistance of the FSR. Any Arduino-compatible development platform – be it a RedBoard, Pro or Pro Mini– can substitute.

Resistor Kit– To turn the FSR’s variable resistance into a readable voltage, we’ll combine it with a static resistor to create a voltage divider. This resistor kit is handy for some trial-and-error testing to hone in on the most sensitive circuit possible.

Breadboard and Jumper Wires– The FSR’s terminals are breadboard-compatible. We’ll stick in that and the resistor, then use the jumper wires to connect from breadboard to Arduino.

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
94
Resistor Kit - 1/4W (500 total)

COM-10969
$7.95
89
Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
24
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$1.95
20

Suggested Reading

Analog components, like these FSRs, are a great sensor-reading entry-point for beginners, but there are a few electronics concepts you should be familiar with. If any of these tutorial titles sound foreign to you, consider skimming through that content first.

Analog to Digital Conversion

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

Voltage Dividers

Turn a large voltage into a smaller one with voltage dividers.

What is an Arduino?

What is this 'Arduino' thing anyway?

Analog vs. Digital

This tutorial covers the concept of analog and digital signals, as they relate to electronics. It will discuss what each signal looks like, where each type of signal are prevalent, and some examples of analog and digital electronic components.

FSR Overview

There are a variety of FSR options out there, and a few key characteristics to differentiate them: size, shape, and sensing range. Here’s a quick overview:

NameShapeSensing AreaMin PressureMax Pressure

Force Sensitive Resistor - Small
(SEN-09673)
Circular7.62 mm dia
(0.3 in)
0.1 kg
(0.22 lb)
1 kg
(2.2 lb)

Force Sensitive Resistor 0.5"
(SEN-09375)
Circular12.7 mm dia
(0.5 in)
100 g
(0.22 lb)
10 kg
(22.04 lb)

Force Sensitive Resistor - Square
(SEN-09376)
Square44.45 x 44.45 mm
(1.75 x 1.75 in)
100 g
(0.22 lb)
10 kg
(22.04 lb)

Force Sensitive Resistor - Long
(SEN-09674)
Rectangular6.35 x 609.6 mm dia
(0.25 x 24.0 in)
100 g
(0.22 lb)
10 kg
(22.04 lb)

Shape and Size

Most FSR’s feature either a circular or rectangular sensing area. The square FSR is good for broad-area sensing, while the smaller circular sensors can provide more precision to the location being sensed.

The rectangular FSR’s include a small-ish square 1.75 x 1.75" sensor and a long 0.25 x 24" strip. The rest of the sensors feature a circular sensing area.

Sensing Range

Another key characteristic of the FSR is it’s rated sensing range, which defines the minimum and maximum amounts of pressure that the sensor can differentiate between.

The lower the force rating, the more sensitive your FSR hookup has the potential to be. But! Any pressure beyond the sensor’s maximum limit will be unmeasurable (and may damage the component). The small 1kg-rated FSR will provide more sensitive readings from 0 to 1kg, but won’t be able to tell the difference between a 2kg and 10kg weight.

Force vs. Resistance

The graph below, figure 2 from the FSR Integration Guide, demonstrates the typical force-resistance relationship:

FSR force vs resistance

The relationship is generally linear from 50g and up, but note what the relationship does below 50g, and even more-so below 20g. These sensor’s have a turn-on threshold– a force that must be present before the resistance drops to a value below 10kΩ, where the relationship becomes more linear.

These sensors are simple to set up and great for sensing pressure, but they aren’t incredibly accurate. They’re useful for sensing the presence of something, and the relative magnitude of that force, but they’re not all that great at measuring weight (that’s what load cell’s are for!).

Example Hardware Hookup

By creating a voltage divider with the FSR and another resistor, you can create a variable voltage output, which can be read by a microcontroller’s ADC input.

Selecting a Static Resistor

The tricky part of voltage-dividing an FSR is selecting a static resistor value to pair with it. You don’t want to overpower the maximum resistance of the FSR, but you also don’t want the FSR’s minimum resistance to be completely overshadowed either.

It helps to know what range of force you’ll be reading. If your project’s force-sensing covers the broad range of the FSR (e.g. 0.1-10kg), try to pick a static resistance in the middle-range of the FSR’s resistive output – something in the middle of 200-6kΩ. 3kΩ, or a common resistor like 3.3kΩ, is a good place to start.

Short on resistors? If all you have is 10kΩ resistors (looking at you Sensor Kit visitors), you can still make something close to 3k! Try putting three 10kΩ's in parallel to create a 3.33kΩ monster resistor. Or put three 330Ω resistors in series to create a 990Ω concoction, which will work pretty well too.

Example Circuit

Here’s a fritzing diagram combining the FSR, 3.3kΩ resistor, three jumper wires and the Arduino:

Fritzing circuit

And the schematic:

Fritzing schematic

This voltage divider will cause the voltage at A0 to increase as the resistance of the FSR decreases. When the FSR is left untouched, measuring as nearly an open circuit, the voltage at A0 should be zero. If you press as hard as possible on the FSR, the voltage should increase close 5V.

Example Arduino Sketch

Here is a simple Arduino example based on the circuit above. Copy and paste this into your Arduino IDE (or use Codebender), then upload!

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

After uploading, open your serial monitor, and set the baud rate to 9600 bps. Or you can use the embedded serial monitor below.

If you apply pressure to the FSR, you should see resistance and estimated pressure calculations begin to appear:

FSR readings to serial monitor

Play with the circuit and see how high or low you can get the readings to be. If you have more resistors, try swapping larger or smaller values in for the 3.3kΩ to see if you can make the circuit more sensitive. Don’t forget to change the value of R_DIV towards the top of the sketch if you do!

Resources and Going Further

Now that you’ve got a force-sensing Arduino circuit, what project are you going to create? If you need more FSR-related resources, be sure to check out the FSR Integration Guide, which goes in-depth on the sensor’s characteristics. The guide also presents a few more complex circuits you can try hooking up to get even more sensitivity out of your FSR.

Check out the FSR Integration Guide

Need some project inspiration? Want to check out some similar analog sensors? Check out some of these related tutorials:

Getting Started with Load Cells

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

SIK Keyboard Instrument

We can use the parts and concepts in the SparkFun Invetor's Kit to make a primitive keyboard instrument.
New!

Sensor Kit Resource Hub

An overview of each component in the SparkFun Sensor Kit, plus links to tutorials and other resources you'll need to hook them up.
New!

Flex Sensor Hookup Guide

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

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

Photocell Hookup Guide

$
0
0

Photocell Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Photocell’s are light-sensitive, variable resistors. As more light shines of the sensor’s head, the resistance between its two terminals decreases. They’re easy-to-use, and an essential component in projects that require ambient-light sensing.

Mini Photocell

SEN-09088
$1.5
6

In pitch-black conditions, the photocell’s resistance will be in the megaohm’s (1.0MΩ+) range. Shining an LED on the sensor can drop the resistance to near-zero, but usually the resistance of the photocell falls between 8-20kΩ in normal lighting conditions.

By combining the photocell with a static resistor to create a voltage divider, you can produce a variable voltage that can be read by a microcontroller’s analog-to-digital converter.

Suggested Materials

This tutorial serves as a quick primer on resistive photocells’s, and demonstrates how to hook them up and use them. Beyond the light sensor, the following materials are recommended:

Arduino Uno– We’ll be using the Arduino’s analog-to-digital converter to read in the variable resistance of the photocell. Any Arduino-compatible development platform – be it a RedBoard, Pro or Pro Mini– can substitute.

Resistor Kit– To turn the photocell’s variable resistance into a readable voltage, we’ll combine it with a static resistor to create a voltage divider. This resistor kit is handy for some trial-and-error testing to hone in on the most sensitive circuit possible.

Breadboard and Jumper Wires– The photocell’s legs, like any through-hole resistor, can be bent and shaped to fit. We’ll stick them and the resistor into a breadboard, then use the jumper wires to connect from breadboard to Arduino.

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
94
Resistor Kit - 1/4W (500 total)

COM-10969
$7.95
89
Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
24
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$1.95
20

Suggested Reading

Photocells are a great entry-level component for beginners, but there are still a few basic electronics concepts you should be familiar with. If any of these tutorial titles sound foreign to you, consider skimming through that content first.

Light

Light is a useful tool for the electrical engineer. Understanding how light relates to electronics is a fundamental skill for many projects.

Analog to Digital Conversion

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

Voltage Dividers

Turn a large voltage into a smaller one with voltage dividers.

Analog vs. Digital

This tutorial covers the concept of analog and digital signals, as they relate to electronics. It will discuss what each signal looks like, where each type of signal are prevalent, and some examples of analog and digital electronic components.

Photocell Overview

The photocell, sometimes referred to as a photoresistor or light-dependent resistor (LDR), is a two-terminal, resistive component that increases or decreases its resistance depending on the light it senses. They’re available in a variety of shapes, sizes, and form factors; the mini photocell in our catalog features a 5x4.3mm head, and through-hole legs that can be soldered into a PCB or inserted into a breadboard.

Mini photocell dimensions

In pitch black conditions, the resistance of most photocells will measure in the megaohms range. The typical light resistance of photocells varies by component. The mini photocell, for example, usually produces a resistance between 8-20kΩ in normal lighting conditions.

The graph below demonstrates the mini photocell’s illumination and resistance relationship:

Mini photocell illuminance vs resistance

Light vs. Resistance graph from the mini photocell datasheet.

As you can tell from the graph above, these sensor’s aren’t designed for absolute lux-measurement accuracy – they leave a lot of room for interpretation. But, by measuring the photocell’s resistance, they can provide a relative idea of a room’s lighting conditions, or tell us if the sun has risen or set.

Example Circuit

To measure the photocell’s resistance with a microcontroller’s ADC, we actually have to use it to generate a variable voltage. By combining the photocell with a static resistor, we can create a voltage divider that produces a voltage dependent on the photocell’s resistance.

A static resistor value between 1kΩ and 10kΩ should pair well with the photocell. If you have a resistor kit, you may want to introduce some trial-and-error to hone in on that perfect static resistance.

In this example, we’ll use a 4.7kΩ resistor to divide voltage with the photocell. Here’s the example circuit:

Example circuit fritzing diagram

And a schematic:

Example circuit schematic

The 4.7kΩ resistor on the ground side, and the photocell on the 5V side, means as the cell’s resistance increases (meaning the sensor’s surroundings are getting darker) the voltage on A0 will decrease.

Example Program

Here is a simple Arduino example based on the circuit above. Copy and paste this into your Arduino IDE (or use Codebender), then upload!

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

After uploading, open your serial monitor, and set the baud rate to 9600 bps. Or, you can use the embedded serial monitor below.

Then trigger some changes in light; cover the photocell with your hand, turn your lights off, or shine a flashlight on the cell. You should see the voltage and resistance calculations vary with the light. If it gets darker, the resistance should go up. If it gets lighter, the resistance should go down.

FSR readings to serial monitor

If the values don't look correct to you, make sure the R_DIV variable at the top of the sketch is set to your static resistor's value.

When the sensed light gets too dark, the Arduino should turn on the pin 13 LED to try to brighten things up. By adjusting the DARK_THRESHOLD variable, you can change what lighting conditions trigger this LED illumination.

Going Further

Now that you’ve got your Arduino reacting to ambient lighting conditions, what light-dependent project are you going to create? Need some inspiration? Check out some of these SparkFun tutorials:

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.

SparkFun Inventor's Kit for MicroView

The SparkFun Inventor's Kit for MicroView follows our tried and true inventor's kit model, bringing you 11 simple yet fun experiments to introduce you to the SparkFun MicroView.

LilyPad Light Sensor Hookup Guide

How to hook up the LilyPad Light Sensor as well as some project ideas and example code.

Blynk Board Project Guide

A series of Blynk projects you can set up on the Blynk Board without ever re-programming it.

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


Si7021 Humidity and Temperature Sensor Hookup Guide

$
0
0

Si7021 Humidity and Temperature Sensor Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The Si7021 is a low-cost, easy to use, highly accurate, digital temperature and humidity sensor. All you need is two lines for I2C communication, and you’ll have relative humidity readings and accurate temperature readings as well! This sensor is ideal for environmental sensing and data logging, perfect for a weather station or humidor control system.

Si7021 Breakout Board

The Si7021 also comes equipped with a hydrophobic PTFE filter covering the inlet on the sensor. This filter blocks contaminants but allows water vapor to pass through, keeping your sensor safe from water damage while still proving accurate sensor readings.

Required Materials

To follow along with this hookup guide, you will need the following:

Suggested Reading

Before embarking upon this tutorial, you may find the following links useful:

Board Overview

Let’s go over the Si7021 Breakout in detail.

alt text

Si7021 Details:

  • Uses the I2C interface
  • Typical humidity accuracy of ±2%
  • Typical temperature accuracy of ±0.3C
  • Operates from 0 to 100% humidity but this sensor isn’t recommended for harsh environments where it could come in contact with water (such as rain)
  • 3.3V sensor - use inline logic level converters or 10kΩ resistors to limit 5V signals
  • Only one Si7021 sensor can reside on the I2C bus at a time

Pull-up Resistors

This breakout board has built-in 4.7KΩ pull up resistors for I2C communications. If you’re hooking up multiple I2C devices on the same bus, you may want to disable/enable the pull-up resistors for one or more boards. On the Si7021, the pull-ups are enabled by default. To disable them, simply use some solder wick to remove the solder on the jumper labeled PU. This will disconnect the resistors from VCC and from the I2C bus.

PTFE Filter

The tiny white cover on the IC is known as a Polytetrafluorethylene (PTFE) Membrane Filter. It keeps moisture out but allows humidity in. This filter is very low-profile, hydrophobic and oleophobic, and excludes particulates down to 0.35 microns in size.

Heads up! Do not remove this white filter, mistaking it for some IC tape that was left on by mistake. Removing the filter may result in a shorted life span of the device or failure in highly humid areas.

From the Si7021 datasheet:

“Because the sensor operates on the principal of measuring a change in capacitance, any changes to the dielectric constant of the polymer film will be detected as a change in relative humidity. Therefore, it is important to minimize the probability of contaminants coming into contact with the sensor. Dust and other particles as well as liquids can affect the RH reading.”

alt text

Image courtesy of Silicon Labs datasheet

Hooking It Up

Wiring up the Si7021 is very easy! We recommend soldering four male headers to the breakout board. You can also solder wires if your application needs.

Power

This board runs at 3.3V. Be sure to power the board from the 3.3V pin! Because I2C is an open drain signal, there’s no need to worry about level shifting the signal; the 3.3V signal will be adequate to communicate with the Arduino and the signal will never reach a dangerous level for the pins on the Si7021.

Connections: Breakout to Arduino

Method 1

There are two ways to connect an Si7021 to an Arduino. The first is using pins A4 and A5 on classic Arduino boards. This breakout was designed using our standard I2C pinout, allowing the sensor to be connected directly to an Arduino without using a breadboard or wires.

  • GND → A2
  • VCC → A3
  • SDA → A4
  • SCL → A5

This would look like the following:

Fritzing

If using this wiring scheme, be sure to assign pins A2 and A3 as GND and VCC, respectively, in your code.

Method 2

This method is for those with newer model Arduino boards that have the SDA and SCL lines broken out. We’ll be hooking up VCC and GND to the normal power pins and two data lines for I2C communication. Connect the SDA and SCL lines directly to the SDA and SCL lines broken out on the Arduino headers.

  • VCC → 3.3V
  • GND → GND
  • SDA → SDA
  • SCL → SCL

This would look something like the following:

alt text

Si7021 Library and Example Code

To get started immediately, use the example code and library files below.

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

Once you’ve uploaded the code, connect using this serial terminal to see the output.

If you prefer to work in the Arduino IDE, you can download the library from the link below. Check out our Installing an Arduino Library tutorial for more help.

Si7021 Arduino Library

Once the library is installed, open Arduino, and expand the examples menu. You should see the Si7021 example.

menu

The examples menu expanded to show Si7021 example

Si7021 Functions:

Weather::getRH() - Returns current Relative Humidity measurement.

Weather::readTemp() - Returns temperature in Celsius from previous RH measurement.

Weather::getTemp() - Returns current temp in Celsius.

Weather::readTempF() - Returns temperature in Fahrenheit from previous RH measurement.

Weather::getTempF() - Returns current temp in Fahrenheit.

Weather::changeResolution() - Allows the user to change the humidity and temperature resolution. The vast majority of users do not need to change the resolution. By default the sensor will be in its highest resolution settings. This function is useful if you need to decrease the amount of time between readings or to save power. See the datasheet for more information. As an example, to change the resolution to 11 bit RH and 11 bit temperature, you would call myHumidity.SetResolution(0b10000001); to set bit 7 and bit 0.

alt text

Resolution table can be found on page 25 of the datasheet.

Resources and Going Further

With that, you should now have a functional humidity and temperature sensing system. Check the links below for more information.

Need some inspiration? Check out these other tutorials:

HTU21D Humidity Sensor Hookup Guide

The HTU21D humidity sensor is an easy to use, digital, low-cost humidity sensor.

MPL3115A2 Pressure Sensor Hookup Guide

Getting started with this amazing barometric pressure sensor.

Weather Shield Hookup Guide

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

T5403 Barometric Pressure Sensor Hookup Guide

T5403 Barometric Pressure Sensor Hookup Guide

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

PIR Motion Sensor Hookup Guide

$
0
0

PIR Motion Sensor Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Passive infrared (PIR) sensors are motion-detecting devices used in security systems across the world – even though you may not see them, they probably see you!

PIR Motion Sensor (JST)

SEN-13285
$9.95
8

Using the PIR sensor is simple: power it up, connect a pull-up resistor to the open-collector signal pin, and watch for it to go low. The PIR can sense abrupt changes in scenery as far as 10 feet (~3m) away. Once your microcontroller is sensing movement, it can trigger a buzzer, text message, tweet, or a klaxon.

Suggested Materials

This tutorial serves as a quick primer on PIR motion sensor and demonstrates how to hook them up and use them. Beyond the sensor itself, the following materials are recommended:

Arduino Uno– We’ll be using a digital pin on the Arduino to read the state of the PIR sensor’s signal output. Any Arduino-compatible development platform – be it a RedBoard, Pro or Pro Mini– can substitute.

Jumper Wires– The PIR sensor is terminated with a 3-pin JST cable one of the easier ways to connect this to an Arduino is to plug a few jumper cables into the connector and run them straight to an Arduino.

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
94
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$1.95
20
Piezo Speaker - PC Mount 12mm 2.048kHz

COM-07950
$1.95
5
LED Mixed Bag - 10mm

COM-13326
$7.95
3

Beyond those two items, you may want to add a buzzer or large LED to make range testing of the PIR sensor more convenient.

Suggested Reading

PIR sensors are a great entry-level component for beginners, but there are still a few basic electronics concepts you should be familiar with. If any of these tutorial titles sound foreign to you, consider skimming through that content first.

Pull-up Resistors

A quick introduction to pull-up resistors - whey they're important, and how/when to use them.

Light

Light is a useful tool for the electrical engineer. Understanding how light relates to electronics is a fundamental skill for many projects.

What is an Arduino?

What is this 'Arduino' thing anyway?

Resistors

A tutorial on all things resistors. What is a resistor, how do they behave in parallel/series, decoding the resistor color codes, and resistor applications.

PIR Motion Sensor Overview

At their most fundamental level, PIR sensor’s are infrared-sensitive light detectors. By monitoring light in the infrared spectrum, PIR sensors can sense subtle changes in temperature across the area they’re viewing. When a human or some other object comes into the PIR’s field-of-view, the radiation pattern changes, and the PIR interprets that change as movement.

That white cap dominating most of the top side of the PIR assembly is a lense, which helps focus the PIR sensor’s field-of-view. The actual PIR sensor is hiding under that lense:

Under PIR cover

The back side of the assembly sports amplifiers, voltage regulators and other supporting circuitry to help drive the PIR. All that’s left for us to connect is three pins: power, ground, and the output signal.

Power and Signal Pins

The top side of the PIR assembly includes two labels: “+” and “AL”. The “AL” pin is the alarm pin – don’t let the black wire fool you, this isn’t ground! “+” is the PIR sensor’s power supply input, leaving the unlabeled middle pin, with the white wire, as ground.

Wire ColorPinNotes
RedPower5-12V
WhiteGround
BlackAlarmOpen-collector output – active low

The PIR sensor should be powered with at least 5V, but it can work with voltages as high as 12V. Fortunately, even if a PIR is powered higher than 5V, the alarm pin can still connect directly to an input pin because it is designed as an open-collector.

When the PIR senses activity in it’s viewing area, it pulls the alarm pin low. But when the sensor is inactive, the pin is basically floating. To avoid any false-positives, the alarm output should be pulled high to 5V. Most microcontroller’s have internal pull-up resistors on their I/O pins, which can easily accomplish that task.

Example Circuit

The circuit for this example is about as simple as it gets. Grab three jumper wires and insert them into the JST connector. It gets a little tight, but they should all be able to fit in there.

Connect the power (red) and ground (white) wires up to 5V and GND respectively. Then connect the black alarm wire to Arduino pin 2.

PIR sensor hookup

We’ll use the internal pull-up resistor on D2 to complete the circuit. Whenever the sensor is inactive, the pin should read high. When motion is detected, the sensor will pull D2 low.

Example Code

Here is a simple Arduino example based on the circuit above. Copy and paste this into your Arduino IDE (or use Codebender), then upload!

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

After uploading, have a look at your Arduino’s pin 13 LED. You can also open your serial monitor, and set the baud rate to 9600 bps. Or, you can use the embedded serial monitor below.

The PIR sensor requires a couple seconds of motion-free activity, while it gets a “snapshot” of it’s viewing area. Try not to move until the pin 13 LED turns off, then wave your hands, jump in the air, go crazy!

Resources and Going Further

For more information on the PIR sensor, the PIR motion sensor datasheet may provide some insight.

Now that you’ve got your Arduino hooked up to a PIR sensor what motion-detecting project are you going to create? Need some inspiration? Check out some of these related tutorials:

Vernier Photogate

Vernier Photogate Timer -- using the Serial Enabled LCD Kit.

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.

ZX Distance and Gesture Sensor Hookup Guide

How to connect and use the SparkFun ZX Distance and Gesture Sensor with an Arduino.

Boss Alarm

Build a Boss Alarm that alerts you of anyone walking into your office and automatically changes your computer screen.

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

Piezo Vibration Sensor Hookup Guide

$
0
0

Piezo Vibration Sensor Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Piezo sensors are flexible devices that generate electric charge when they’re stressed. This characteristic makes piezos an ideal solution for low-power flex, touch, and vibration sensing. In more advanced applications, piezos can be the foundation for energy harvesting. Piezo’s are the perfect sensor for catching when your fridge is running or as the power source for energy harvesting shake-lights.

Piezo Vibration Sensor - Large with Mass

SEN-09197
$2.95

Piezo’s have the potential to produce very large AC voltage spikes – ranging upwards of ±50V. Because they produce such high voltages, large resistors are often used to “load down” the piezo sensor in vibration-sensing applications. Zener diodes can also be used to clamp voltages down to safe levels.

Suggested Materials

This tutorial serves as a quick primer on piezo vibration sensors, and demonstrates how to hook them up and use them. Beyond the sensor, the following materials are recommended:

Arduino Uno– We’ll be using the Arduino’s analog-to-digital converter to read in the voltage produced by the piezo sensor. Any Arduino-compatible development platform – be it a RedBoard, Pro or Pro Mini– can substitute.

Resistor Kit– To dampen the piezo sensor’s AC voltage spikes, a large load resistor – somewhere around 1MΩ – is used. This resistor kit includes multiple 1MΩ’s, in case you want to combine a few in series.

Breadboard and Jumper Wires– The piezo sensor’s legs are spaced by 0.2" and are breadboard compatible. We’ll stick them and the resistor into a breadboard, then use the jumper wires to connect from breadboard to Arduino.

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
94
Resistor Kit - 1/4W (500 total)

COM-10969
$7.95
89
Breadboard - Self-Adhesive (White)

PRT-12002
$4.95
24
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$1.95
20

Suggested Reading

Piezos are an great entry-level component for beginners, but there are still a few basic electronics concepts you should be familiar with. If any of these tutorial titles sound foreign to you, consider skimming through that content first.

Analog to Digital Conversion

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

What is an Arduino?

What is this 'Arduino' thing anyway?

Analog vs. Digital

This tutorial covers the concept of analog and digital signals, as they relate to electronics. It will discuss what each signal looks like, where each type of signal are prevalent, and some examples of analog and digital electronic components.

Vibration Sensor Overview

Piezo vibration sensors come in a variety of shapes and sizes. Here is a selection from the SparkFun catalog:

Piezo Vibration Sensor - Large

SEN-09196
$2.95
Piezo Vibration Sensor - Large with Mass

SEN-09197
$2.95
Piezo Vibration Sensor - Small Vertical

SEN-09199
$2.95
Piezo Vibration Sensor - Small Horizontal

SEN-09198
$2.95
1

Some piezo sensor’s include weights at the end to help encourage vibration.

AC Voltage Source

Piezo sensors are unique because they produce an alternating current (AC) voltage when stressed, converting mechanical energy to electrical. If you hooked an oscilloscope up to a piezo sensor, you might see waveforms like this when the sensor shakes:

Piezo flicked, unloaded

The signals above were generated by simply inserting a large, weighted piezo into a breadboard and flicking it a few times. Note the voltage spikes are reaching almost +20V and -12V. Signals at that level have the potential to permanently damage a microcontroller’s analog-to-digital converter (ADC) pins.

To dampen those voltage spikes, we have a few simple tricks up our sleeve. The easiest fix is to load the piezo with a large resistor. By placing a 1MΩ resistor in parallel with the sensor, for example, we can drop the voltage spikes down to safer levels.

Piezo sensor loaded with 1M, connected to ADC

In the graph above, the sensor is loaded with a 1MΩ resistor and connected to an Arduino ADC. The voltages spike between -0.5 and +5V are safely within the tolerable range of the ATmega328’s I/O pins.

More complex piezo damping circuits might include zener diodes to clamp the voltage or op amps to buffer a signal, but this simple resistor-loading circuit is a good place to start.

Example Circuit

Using the 1MΩ load resistor dampening method described above, here’s a simple example circuit demonstrating how to hook up the vibration sensor:

Piezo hookup example

The Piezo is grounded on one end, and a generated voltage is routed to the Arduino’s A0 ADC pin. Reading the voltage at that pin should give us an idea of how much the piezo is moving.

Example Code

Here is a really simple Arduino example based on the circuit above. Copy and paste this into your Arduino IDE (or use Codebender), then upload!

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

Once the circuit is set up and code is uploaded, open your serial monitor, and set the baud rate to 9600 bps. Or, you can use the embedded serial monitor below.

You should be seeing 0.00’s stream by endlessly. Try shaking the sensor to see the voltages go up.

Serial terminal

Your eye’s probably aren’t fast enough to catch all of those numbers change. You can either introduce a delay to the end of the loop (e.g. delay(250);), or you can view the output in the serial plotter, found in newer versions of the Arduino IDE. Open the plotter by going to Tools>Serial Plotter.

Serial plotter

Now, you can create oscilloscope measurements of your own! The graph helps demonstrate the piezo sensor’s voltage spikes and ringing. Try flicking, shaking, or stomping the ground to see how those movements affect the measurements of the piezo sensor.

Once you’ve gotten a handle on that, you can find a “vibration threshold” that will fit your project needs and have your Arduino look for any measurements above that value to detect vibrations.

Resources and Going Further

For more information on piezoelectricity and piezo sensors, check out some of these resources:

Now that you’ve got your Arduino sensing those good vibrations, what kind of shake-sensing project are you going to start? Need some inspiration? Check out some of these related tutorials:

Wake-on-Shake Hookup Guide

A basic hookup guide for getting started with the SparkFun Wake-on-Shake.

MMA8452Q Accelerometer Breakout Hookup Guide

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

LSM9DS1 Breakout Hookup Guide

A hookup guide for the LSM9DS1, which features a 3-axis accelerometer, 3-axis gyroscope, and 3-axis magnetometer. It's an IMU-in-a-chip!

Blynk Board Washer/Dryer Alarm

How to configure the Blynk Board and app to notify you when your washer or dryer is done shaking.

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

IOIO-OTG Hookup Guide

$
0
0

IOIO-OTG Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The IOIO-OTG (pronounced “yo-yo-O-T-G"; the OTG stands for On-The-Go) is a development board specially designed to allow developers to add advanced hardware I/O capabilities to their Android or PC application. It features a PIC microcontroller, which acts like a bridge that connects an app on your PC or Android device to low-level peripherals like GPIO, PWM, ADC, I2C, SPI and UART. An app-level library helps you write control code for these low level peripherals in the same way you’d write any other Java app!

IOIO-OTG

What separates the IOIO-OTG from previous IOIO boards is its ability to leverage the USB On-The-Go specification to connect as a host or an accessory. There are several ways to connect the IOIO to your Java app. If the app is running on your Android device, the IOIO-OTG will act as a USB host and supply charging current to your device (meaning the IOIO-OTG will need its own power source). If your app is running on a Windows, Linux or OSX machine, the IOIO-OTG will assume device mode and present itself as a virtual serial port. When in device mode, the IOIO-OTG can be powered by the host. Connecting a USB Bluetooth® dongle will cause the IOIO-OTG to show up as a Bluetooth serial connection, so you can go wireless!

Required Materials

A USB Female A to Micro A OTG Cable should have been included with the purchase of your IOIO-OTG.

In addition to the IOIO and this cable you will need these items to follow along with this tutorial.

Suggested Reading

While not covered in this tutorial directly, the IOIO-OTG is capable of the functions mentioned below. Should you find any of them unfamiliar, take a detour over to that tutorial, then head on back here when finished.

You should have a good understanding of using the Command Line before getting started with the IOIO-OTG.

IOIO Board Overview

This section will cover the various parts and features found on the IOIO-OTG board.

USB Micro-AB Connector

MicroAB

The micro USB connector is used to connect the IOIO to a number of devices. You can connect the IOIO to a PC using a micro-B USB Cable. The supplied USB Female A to micro-A OTG Cable should be used whenever connecting to an Android device, with the IOIO acting as host (for charging the Android), OR to a Bluetooth dongle.

Please Note: This connector is a USB micro-AB connector, which means it can accept both USB micro-A and USB micro-B connections.

closeup

Power

power

Power LED

In the bottom-left corner of the image, we have the red power LED. This illuminates when the IOIO is powered through either the USB port, the JST connector or the VIN pins.

2-pin JST Female Power Jack

Used for power supply to the board. Voltage between 5V–15V should be supplied. The simplest way to power the IOIO-OTG is to use a wall power supply (5–15V) coupled with our Barrel Jack to JST adapter. Consider a supply that is 1.5V+ higher than 5V. This will result in a more stable 5V supply coming from the voltage regulator.

VIN pins (3 pins)

Used for outputting the supply voltage to your circuit, or as an alternative input to the power jack.

5V Pins (3 pins)

5V output from the onboard regulator, which can be used in your circuit.

3.3V Pins (3 pins)

3.3V output from the onboard regulator, which can be used in your circuit.

You can read more about ways to power the IOIO-OTG here.

GPIO Pins

GPIO

General Purpose Input/Output (GPIO) pins are the meat of the IOIO-OTG and are the pins used to interface your applications to the physical world. There’s a lot going on here and many variations amongst these pins. Luckily, there is a handy key located on the back of the IOIO to clarify which pins are capable of which functionality.

back

To clarify, the key is as follows:

  • Pins with Black Circles around them can be used as 5V Tolerant I/O. Pins without circles should only be used with 3.3V devices.
  • Pins with Black Squares can be used as Analog Inputs.
  • Pins marked with a ‘P’ can be used as Peripheral Inputs/Outputs.
  • Pins marked with a ‘Pi’ can be used as Peripheral Inputs only.
  • Pins marked with CL or DA can be used as the Clock and Data lines for the various I2C ports on the IOIO. There are three I2C ports available on the IOIO-OTG.

By default, pins might be damaged if exposed to voltage outside the 0V-3.3V range. 5V-tolerant pins extend this range to 0V-5V, thus allowing us to communicate with 5V logic.

You can read more about the IOIO-OTG’s I/O pins here.

Status LED

statLED

Normally, this yellow LED is under application control (“pin 0”). In very few special cases (e.g., bootloader mode), it has a special meaning (to indicate entry into bootloader mode or an unconfigured oscillator).

Charge Current Trimpot (CHG)

trimpot

The CHG adjusts the amount of current supplied on the VBUS line of the USB when acting as a USB host (or when it is connected to your Android). It is typically used in battery-powered applications to prevent battery drain. Turning in the clockwise (+) direction increases charge current. Generally, this can be left at the default factory setting, which is fully clockwise.

Host/Device Switch

switch

Not normally used. Keep switch in A mode. In “A” mode, the IOIO-OTG will detect whether it should act as host or as device automatically, according to whichever USB connector is plugged in (micro-A or micro-B). The only reason to put it in H mode is when working with a non-standard USB-OTG cable or adapter that doesn’t identify itself correctly on the host side or the cable. This should never be the case with the provided USB-OTG cable.

MCLR and Boot Pins

mclr and boot pins

MCLR

This pin will only be used on occasion by the user for firmware upgrades. This pin is for programming a new bootloader onto the IOIO-OTG board.

BOOT

This pin will only be used on occasion by the user for firmware upgrades. This pin is used to switch the IOIO-OTG into bootloader mode on power-up. Note that this pin is shared with the Stat LED.


More information about the IOIO-OTG hardware can be found here.

Software Downloads and Installation

This section will cover the installation of all the software necessary to get started with the IOIO-OTG. All of these pieces of software will be used throughout the tutorial, though not all of them will be used in each example. If you only wish to use your PC to develop on the IOIO or, alternatively, only want to develop on an Android device/emulator, you may only need to install the software for those specific applications.

Set Aside Some Time: Installing all of these pieces of software at once will be time-consuming. Set aside 30-60 minutes, depending on your computer's speed and internet connection.

Client Software and IOIO Application Firmware

Head over to the Downloads section of the IOIO wiki on GitHub. Scroll down until you see the section titled Client Software and IOIO Application Firmware Images. Under the Client-side Software column, download the latest version, which will be delivered as a .zip file (App-IOIOxxxx, where xxxx is the software/library version number). Unzip it, and place that folder in a location of your choosing (we recommend your home directory). Remember the location, as it will be used frequently throughout this tutorial. You can also download it directly from the link below.

IOIO Library and Examples

This folder contains all the Client-side software for the IOIO, including the IOIO Library and the examples we will be using both on a PC and on an Android device/emulator. These files will be necessary to get started with the IOIO no matter which method you choose for development.

No further action is needed after downloading and unzipping this folder.

Note: If you are using an older IOIO board, make sure the version number of your IOIO Library is less than or equal to the version number of your firmware.

IOIO Bridge

Another piece of software we’ll need from the IOIO GitHub wiki is IOIO Bridge, which can be found under the Tools section. Or, you can download it directly using the link below.

IOIO Bridge

This tool allows you to have your Android device and your IOIO plugged into your computer at the same time, allowing for faster development.

No further action is needed after downloading and unzipping this folder.

IOIO Device Driver

To use the IOIO-OTG with your personal computer, download and install the device driver for the IOIO. You may need to plug the IOIO-OTG into your computer to complete the driver installation.

Windows

Provide this file (right-click, and choose Save Link As…) to the “Add Hardware” wizard on your Windows machine.

Linux

Copy this udev rules file to the udev rules directory. More information can be found here.

OSX

No driver installation is necessary if using the Mac OS.

You can find more information about interfacing your IOIO with your PC over on the IOIO wiki.

Java Development Kit (JDK)

Whether you’re developing with the PC, an Android device or both, it’s necessary to have Java installed. If it’s not installed already, you can find it on Oracle’s website. Choose the correct file for your OS.

While it’s only necessary to have the Java Runtime Environment (JRE) installed, you may find it easier to just install the entire Java Development Kit (JDK). The version of Java pointed to by your command line may be an outdated version. Installing the latest version of the JDK will update all references to Java your system may need.

Note that your OS may come with Java already installed. You can check by typing java -version into your command line window on any OS. This command will also let you know if the installation from above was successful.

Android Studio and Android SDK

To create your own Android apps or to use existing Android app examples, you will need to have Android Studio installed. If you wish to work exclusively on your PC, you do not need to install Android Studio. If needed, download it from the link below.

Android Studio and Android SDK

Once downloaded, follow the appropriate instructions for your OS, and install it as you would with other applications. Remember its location for later use.

Follow the setup wizard. You will eventually reach a page verifying all the installation settings to be installed. Take note of where the SDK Folder is, as it will be needed following installation.

alt text

We will need to use the Command line in conjunction with Android Studio. You will most likely need to add the Android SDK platform-tools folder to your $PATH, which can be found in the SDK Folder mentioned previously.

Windows users can find GUI $PATH instructions here. Command line instructions can be found here. The command should look something like this:

PATH %PATH%;~/Android/sdk/platform-tools/

Mac and Linux users can find $PATH instructions here. The command should look something like this:

export PATH=$PATH:~/Library/Android/sdk/platform-tools/

In the Command line, type adb, which stands for Android Debug Bridge. If you see a list of adb commands print out, the installation and $PATH update was a success!

Gradle

Gradle is an open source build automation system used to compile Java code. We will be using this to build our own PC application for the IOIO. Android Studio comes with a copy of Gradle, so, if you wish to skip the PC app sections and move straight to the Android app sections, you do not need to install this separately.

Download Gradle here. You can grab the Binary only distribution.

You will most likely need to add the Gradle bin folder to your $PATH.

Windows users can find GUI $PATH instructions here. Command line instructions can be found here. The command should look something like this:

PATH %PATH%;~/gradle-2.12/bin/

Mac users can find $PATH instructions here. The command should look something like this:

export PATH=$PATH:~/gradle-2.12/bin/

You can check to see if it worked by typing gradle -v. You should see some version info print out.

gradle version

Running Your First PC App

We will begin by running a PC application from the App-IOIOxxxx folder downloaded from the IOIO GitHub repo. Download it now, if you have not done so already. Using this known-good application will help to ensure everything is working correctly, both on the hardware and software side.

Plug the IOIO into Your PC

Using a micro USB cable, plug the IOIO-OTG into your computer’s USB port. You should see the red power LED illuminate. No other connections are necessary at this time.

Find the IOIO’s Serial Port

Next, find the IOIO’s serial port so we can communicate with it through the command line. Install the drivers mentioned in the Software Installation section, if you have not done so already.

On Mac OSX or Linux, open the Command Line Interface (CLI) of your choice and type:

ls /dev/tty.*

You should see the IOIO appear as tty.usbmodemXXXX, where the X’s are some specific characters and numbers.

On Windows, open the Device Manager, and check to see which COM Port the IOIO has enumerated as under the ports section. The IOIO will appear as COMXX, where the X’s are a specific number.

Take note of this, as we will need it shortly.

Navigate to the Pre-Built App

In your command line, navigate to the App-IOIOxxxx folder. Then cd into the bin folder. In here, there is a binary file titled HelloIOIOConsole-5.07-standalone.jar. We’re going to run this application from the command line. It will establish a connection with the IOIO and allow you to control the onboard Stat LED from the command line.

To run the app, type the following:

java -Dioio.SerialPorts=YOUR_IOIO_SERIAL_PORT -jar HelloIOIOConsole-5.07-standalone.jar

where YOUR_IOIO_SERIAL_PORT is replaced by the serial port from the previous step.

On Mac and Linux, this will look something like:

java -Dioio.SerialPorts=/dev/tty.usbmodemfd141 -jar HelloIOIOConsole-5.07-standalone.jar

On Windows, this will look something like:

java -Dioio.SerialPorts=COM65 -jar HelloIOIOConsole-5.07-standalone.jar

You should see some information printed to the command line. The most important line is IOIO connection established. If you see that, you’re connected to your IOIO through the command line!

Now, press enter. You should see some instructions print to the screen.

Unknown input. t=toggle, n=on, f=off, q=quit.

Press t + ENTER. You should see the stat LED turn on. Press t + ENTER again, and it should turn off. You are now controlling your IOIO from your PC! Try using the other commands.

You have just run your first IOIO PC application!

If you are having trouble getting the app to work, please visit the Troubleshooting section.

Building Your First PC App

In the previous section, we ran a pre-built PC application. In this section we will use that same application’s code to learn how to build/compile our own PC application (.jar file) for the IOIO.

Download Gradle

To begin, we need to first download Gradle to compile the code. Gradle is an open source build automation system used to compile code – Java in this case.

Download Gradle here, if you have not done so already. You can grab the Binary only distribution.

Extract the .zip file, and place it somewhere you’ll remember. It’s recommended you place it in your home directory.

You will most likely need to add the Gradle bin folder to your $PATH.

Windows users can find GUI $PATH instructions here. Command line instructions can be found here. The command should look something like this:

PATH %PATH%;~/Android/sdk/platform-tools/

Mac users can find $PATH instructions here. The command should look something like this:

export PATH=$PATH:~/gradle-2.12/bin/

You can check to see if it worked by typing gradle -v. You should see some version info print out.

gradle version

Looking at the Code

In the command line, navigate to the App-IOIOxxxx folder you downloaded from GitHub previously. Then cd to the /src/applications/pc directory. Here you will find all the PC applications and all their source code. The application we used previously was the HelloIOIOConsole app. From here, continue to navigate to this directory: /HelloIOIOConsole/src/main/java/ioio/examples/hello_console/. In here you’ll find a HelloIOIOConsole.java file. This is the code we want to have a look at. Open this file in vim or your favorite editor. You can copy the line below.

vim /src/applications/pc/HelloIOIOConsole/src/main/java/ioio/examples/hello_console/HelloIOIOConsole.java

You can also navigate to that folder from your file explorer and open the file in your favorite code viewer.

The code you see should look like the code below:

language:java
1 package ioio.examples.hello_console;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6
7 import ioio.lib.api.DigitalOutput;
8 import ioio.lib.api.IOIO;
9 import ioio.lib.api.exception.ConnectionLostException;
10 import ioio.lib.util.BaseIOIOLooper;
11 import ioio.lib.util.IOIOConnectionManager.Thread;
12 import ioio.lib.util.IOIOLooper;
13 import ioio.lib.util.pc.IOIOConsoleApp;
14
15 public class HelloIOIOConsole extends IOIOConsoleApp {
16         private boolean ledOn_ = false;
17
18         // Boilerplate main(). Copy-paste this code into any IOIOapplication.
19         public static void main(String[] args) throws Exception {
20                 new HelloIOIOConsole().go(args);
21         }
22
23         @Override
24         protected void run(String[] args) throws IOException {
25                 BufferedReader reader = new BufferedReader(new InputStreamReader(
26                                 System.in));
27                 boolean abort = false;
28                 String line;
29                 while (!abort && (line = reader.readLine()) != null) {
30                         if (line.equals("t")) {
31                                 ledOn_ = !ledOn_;
32                         } else if (line.equals("n")) {
33                                 ledOn_ = true;
34                         } else if (line.equals("f")) {
35                                 ledOn_ = false;
36                         } else if (line.equals("q")) {
37                                 abort = true;
38                         } else {
39                                 System.out
40                                          .println("Unknown input. t=toggle, n=on, f=off, q=quit.");
41                         }
42                 }
43         }
44
45         @Override
46         public IOIOLooper createIOIOLooper(String connectionType, Object extra) {
47                 return new BaseIOIOLooper() {
48                         private DigitalOutput led_;
49
50                         @Override
51                         protected void setup() throws ConnectionLostException,
52                                         InterruptedException {
53                                 led_ = ioio_.openDigitalOutput(IOIO.LED_PIN, true);
54                         }
55
56                         @Override
57                         public void loop() throws ConnectionLostException,
58                                         InterruptedException {
59                                 led_.write(!ledOn_);
60                                 Thread.sleep(10);
61                         }
62                 };
63         }
64 }

If you have programmed Arduinos or other microcontrollers before, you will see some familiar lines of code. Starting on line 16, we have a variable called ledOn_. This boolean holds the state of the LED, true or false for high or low.

Following that, we have the run() function on line 24. Then you can see the if and if/else statements that control the state of the LED based on the input received in the Command line.

Next, on line 51, there’s the void setup() function and the void loop() function on line 57, with which you may be familiar. Inside the setup() function on line 53, there is the led_ variable that is set to IOIO.LED_PIN. This is telling the code to use the IOIO’s onboard Stat LED, “pin 0.”

Last, in the loop() function on line 59, there is the led_.write() function that alters the state of the Stat LED, !ledOn_, when the appropriate characters are received from user input. The Thread.sleep(10); is just a delay, having the loop check every 10ms.

Compile the Code

Now that we have a better understanding of what’s happening in the code, it’s time to build our own executable .jar file that will allow us to run this PC app on the IOIO.

To compile the code, change directories back to:

/src/applications/pc/HelloIOIOConsole

In this directory, you will see the src folder we were just exploring and a build.gradle file. If you would like, you may open the build.gradle file in your favorite editor to see how the compiler works. Going into those details is beyond the scope of this tutorial.

Type gradle build. You should see some info print out followed by BUILD SUCCESSFUL.

gradle build

Run the Application

Type ls once the compilation is complete. You should now see a folder titled build. Inside that build folder is the .jar app we intend to run on the IOIO. Navigate to:

cd build/libs

Here, you should see two .jar files. The one titled HelloIOIOConsole-standalone.jar is the one we’re after.

jar file

Connect the IOIO to the PC if it isn’t connected already.

Back in your Command line, type the following to run the app. Don’t forget to change YOUR_IOIO_SERIAL_PORT to the port to which your IOIO is connected, as mentioned in the previous section.

java -Dioio.SerialPorts=YOUR_IOIO_SERIAL_PORT -jar HelloIOIOConsole-standalone.jar

As in the previous section, you should see some info print out followed by IOIO connection established. You can now control the IOIO Stat LED just as before, typing t + ENTER to toggle its state.

Congratulations, you just built your first Java app for the IOIO!

From here, you can use this code as a base to start exploring the IOIO’s capabilities. Change or add a few lines of code, compile with Gradle, and see what happens!

For a complete list of all the commands you can issue to the IOIO, go back to the IOIO folder you downloaded from GitHub. Inside that folder is another folder titled doc. Navigate to doc, and open the index.html file in your browser. There you will find a reference of all the IOIO classes. See if you can get an LED to blink on one of the IOIO’s digital I/O pins.

Check the Resources and Going Further section for more information and links to IOIO resources.

If you are having trouble getting the app to work, please visit the Troubleshooting section.

Running Your First Android App

We will transition from using the PC to using an Android device or emulator to run apps created for the IOIO.

Download Android Studio

If you have not done so already, you will need to download and install Android Studio.

Once downloaded, follow the appropriate instructions for your OS, and install it as you would with other applications. Remember its location for later use.

Follow the setup wizard. You will eventually reach a page verifying all the installation settings to be installed. Take note of where the SDK Folder is, as it will be needed following installation.

alt text

We will need to use the Command line in conjunction with Android Studio. You will most likely need to add the Android SDK platform-tools folder to your $PATH, which can be found in the SDK Folder mentioned previously.

Windows users can find GUI $PATH instructions here. Command line instructions can be found here. The command should look something like this:

PATH %PATH%;~/Android/sdk/platform-tools/

Mac user can find $PATH instructions here. The command should look something like this:

export PATH=$PATH:~/Library/Android/sdk/platform-tools/

In the command line, type adb, which stands for Android Debug Bridge. If you see a list of adb commands print out, the installation was a success!

Plug in Your Android Device to Your PC

Before plugging your Android device into your PC, you’ll need to first turn on USB Debugging. To do so, navigate to your device’s Settings and under the System heading click on Developer options. Then, under Debugging, make sure the USB Debugging check box is checked.

Heads up! When switching from having your Android device plugged into your PC and having the IOIO plugged into your device, you will need to constantly turn on and off USB Debugging. Don't fret, though; we'll show you a way around this in the IOIO Bridge section.

With USB Debugging enabled, you can now plug your Android device into your PC. Once plugged in, you can check to see if your device is showing up in the command line with the following command:

adb devices

You should see your device’s info print out after the List of devices attached line.

Note: If you have not plugged your device into your PC before, you'll need to wait for the PC to finish installing the device drivers before it will show up using the adb devices command.

Check for any prompts on your Android device before continuing. Your device may ask to allow USB Debugging for this computer. Click OK, and check the ‘Always allow from this computer’ check box, if you desire.

Debugging

Upload App to Android Device

With your device connected to your PC, navigate to the bin folder in the App-IOIOxxxx folder via the Command line. In this folder is a pre-compiled app (.apk file) titled HelloIOIO-debug-unaligned.apk. Upload this app to your device using the following command:

adb install HelloIOIO-debug-unaligned.apk

You should see the following success message print out:

success

On your Android device, navigate to your applications. You should now see a HelloIOIO app on your device.

app

Plug in the IOIO to your Android Device

Heads up! Be sure to disable USB Debugging before you plug your IOIO into your Android device.

Unplug your device from the PC, keeping the micro USB cable attached to your Android device. Attach the red USB Female A to micro-A OTG Cable to the end of the micro USB cable. Then attach the micro-A end of the OTG cable to the micro-AB connector on the IOIO-OTG.

Provide power to your IOIO using the Barrel Jack-to-JST Adapter. The red power LED should illuminate.

alt text

Open the HelloIOIO app. Your device may ask you if you want to automatically open that app when the IOIO is plugged in. You will be presented with this screen:

app

Press the button on the touchscreen to turn the Stat LED on and off. You’ve just uploaded and successfully used your first IOIO Android application!

alt text

If you are having trouble getting the app to work, please visit the Troubleshooting section.

Building Your First Android App

Now that we know how to upload a known-good application, let’s see what it takes to build our own using Android Studio.

Open Android Studio

Note: Going into detail about how to use Android Studio is beyond the scope of this tutorial. This section will minimally cover how to upload an app using this software. For more information on getting started with Android Studio, we suggest you complete their Building Your First App tutorial.

Open Android Studio. If this is the first time you’re opening it, it may take a few minutes. There may be several setup/first-time-tips windows to navigate through.

You should eventually be presented with the following screen asking what action you’d like to perform:

alt text

Choose ‘Open an existing Android Studio project.’

Open HelloIOIO Application

Inside the Android Studio file explorer window, navigate to ~/App-IOIO0507/src/applications, and open the folder titled HelloIOIO.

alt text

Heads up! Upon opening the project, Android Studio may yell at you about there being mismatched versions of various pieces needed to compile the code, such as the Android SDK or the Gradle Wrapper. It will offer downloads of the version(s) needed to correct the mismatch.

Keep clicking OK and installing any missing platforms until Android Studio is happy.

The project tree has many files. The file that contains the Java code for the IOIO is in HelloIOIOscrioio.examples.helloMainActivity.java. Double click on the MainActivity.java file, and you should see this:

alt text

The MainActivity.java file contains the code that talks to the IOIO board. If you want to change the UI (user interface or graphics) of your app, the res → layout → main.xml file is where you make the changes. Here you can start writing code and changing the HelloIOIO sketch, if you desire.

Delete App from Android Device

Though we’ll be installing the same app as in the previous section (unless you decided to alter the code), you will need to uninstall the app on your Android device to ensure that Android Studio is working properly.

Make sure that you are uninstalling the app and not just removing it from your home page. On most devices, this requires long tapping the app and dragging it to the Uninstall (trash bin) area at the top of the screen.

Plug in Your Android Device to Your PC

Plug your Android device into your PC.

Heads up! Be sure to enable USB Debugging before you plug in your Android device.

Upload App to Android Device

With your device connected to your PC, click the ‘Run’ button:

run

Android Studio will ask to which device you’d like to upload the application. Assuming you only have one device plugged in, there should only be one option. You can also use the Android emulator if you do not have an Android device.

select device

You should see the build status at the bottom of the window. It will say Gradle Build Running, followed by Gradle build finsihed.

build

On your Android device, navigate to your applications. You should now see a HelloIOIO app on your device.

app

Plug in the IOIO to Your Android Device

Heads up! Be sure to disable USB Debugging before you plug your IOIO into your Android device.

Unplug your device from the PC, keeping the micro USB cable attached to your Android device. Attach the red USB Female A to Micro A OTG Cable to the end of the micro USB cable. Then attach the micro A end of the OTG cable to the Micro A-B connector on the IOIO-OTG.

Provide power to your IOIO using the Barrel Jack-to-JST Adapter. The red power LED should illuminate.

alt text

Open the HelloIOIO app, and you should be presented with this now familiar screen:

app

Press the button on the touchscreen to turn the Stat LED on and off. You’ve just successfully built, uploaded and used your first IOIO Android application!

alt text

For a complete list of all the commands you can issue to the IOIO, go back to the IOIO folder you downloaded from GitHub. Inside that folder is another folder titled doc. Navigate to doc, and open the index.html file in your browser. There you will find a reference of all the IOIO classes. See if you can get an LED to blink on one of the IOIO’s digital I/O pins.

Check the Resources and Going Further section for more information and links to IOIO resources.

If you are having trouble getting the app to work, please visit the Troubleshooting section.

IOIO Bridge for Development

By now you’ve come to realize how inefficient it can be to have to plug in your device, turn on USB debugging, upload your app, unplug, turn off debugging, plug in the IOIO, test and repeat for every change you want to make. Luckily there’s a tool to help aid in your IOIO/Android development.

Download IOIO Bridge

If you have not done so already, go and download the latest version of IOIO Bridge from the IOIO wiki on GitHub. It can be found under the Tools section. Or, you can download it directly using the link below.

IOIO Bridge

Plug in Android Device and IOIO-OTG to Your PC

Heads up! Be sure to enable USB Debugging before you plug in your Android device.

Using two (2) micro USB cables, plug both your Android device and your IOIO-OTG into your PC.

connected to PC

Find the IOIO’s Serial Port

If you have not done so already, find the IOIO’s serial port so you can communicate with it through the Command line. You may need to install the drivers mentioned in the Software Installation section.

On Mac OSX or Linux, open the Command Line Interface (CLI) of your choice and type:

ls /dev/tty.*

You should see the IOIO appear as tty.usbmodemXXXX, where the X’s are some specific characters and numbers.

On Windows, open the Device Manager, and check to see which COM Port the IOIO has enumerated as under the ports section. The IOIO will appear as COMXX, where the X’s are a specific number.

Take note of this, as we will need it shortly.

Run IOIO Bridge

Navigate to the IOIO Bridge folder, in your Command line, and run the IOIO Bridge executable followed by the IOIO’s serial port.

On Mac and Linux, this will look something like:

./ioiobridge /dev/tty.usbmodemfd141

On Windows, this will look something like:

ioiobridge COM65

You should see a printout stating connections to both devices were successful and the bridge is running.

bridge running

Note: If IOIO Bridge has stalled while waiting to connect to the Android application, you will need to open the HelloIOIO app (or other IOIO app) to establish that connection.

You can now interact with the application, and it should be controlling the IOIO-OTG through IOIO Bridge and your PC! Try pressing the button to control the Stat LED.

You can now upload applications to your device (PC or Android) while leaving it plugged in. Then you can test the IOIO’s behavior right away so long as IOIO Bridge is running. Be sure to turn off IOIO Bridge (Ctrl-C) before uploading a new application and starting it once the app has been uploaded.

Going Wireless with Bluetooth

The last thing we’ll cover is how to make your project wireless using Bluetooth. Going wireless is another method to make development a little easier as you don’t have to connect and disconnect the IOIO every time you want to test changes made to your app.

Bluetooth Dongle

In order to utilize the IOIO’s Bluetooth capabilities, you’ll need to acquire a Bluetooth dongle. Most models of dongles should work with the IOIO-OTG. The dongle below has been tested with the IOIO and works great.

Bluetooth USB Module Mini

WRL-09434
$10.95

To connect the dongle, attach it to the larger end of the USB Female A to Micro A OTG Cable, with the other end attached to the IOIO. Then, power the IOIO-OTG with the Barrel Jack-to-JST Adapter.

alt text

Some dongles may have a flashing LED to indicate they are receiving power and awaiting a connection.

Bluetooth Connection

On your Android device, turn Bluetooth on, if it isn’t already. Search for new devices. You should eventually see the IOIO appear. Pair your device with the IOIO.

alt text

When your device asks for the passcode code to pair with the IOIO, enter:

4545

Your device should now be wirelessly connected to the IOIO-OTG.

Open the HelloIOIO app used in the previous examples. Press the button to control the LED over the Bluetooth connection!

You can leave your device plugged in while you develop, all while maintaining the wireless connection with the IOIO.

Troubleshooting

Driver Installation

If your IOIO is not showing up as a serial port, make sure you have installed the drivers from the Software Installation section. Going through the installation process again may solve any issues you may have with your PC communicating with the IOIO-OTG.

Updating Java

Some users may have computers running an outdated version of Java. If you encounter issues, please consider updating to the latest version.

To check which version of Java you are running, run this command in the Command line:

java -version

Download latest version here. Accept the License Agreement, and download the version that matches your OS.

JDK vs JRE

Using on an older MacBook to develop with the IOIO, I found that my Java version was outdated. When just the JRE was installed, it still did not update the version of Java pointed to by my Terminal. I found this Stack Overflow post about the same issue. Downloading the entire JDK solved my issue. However, if you do not wish to download the entire JDK, you can visit that post to see how to tell your Command line which version of Java to use.

USB Debugging

If you are having issues with your Android device not communicating with your IOIO, check the USB Debugging.

Ensure that USB Debugging is ENABLED (checked) when you have your Android device plugged into a computer.

Ensure that USB Debugging is DISABLED (not checked) when you have your IOIO plugged into your Android Device.

Check USB Connections

If the IOIO or your Android device is not communicating with the computer, check the micro USB connections. It’s easy to plug one end of the cable most of the way in, but not quite enough.

Visit the Wiki

There is a plethora of information on IOIO’s GitHub wiki. Visit there for more troubleshooting suggestions.

Contact SparkFun’s Technical Support

If you have any tutorial feedback, please visit the Comments or contact our technical support team at TechSupport@sparkfun.com.

Resources and Going Further

You should now be well on your way to becoming a software and hardware integration master. This tutorial has only scratched the surface of what the IOIO-OTG is capable of. It is now up to you to choose your own adventure and explore what possibilities the IOIO-OTG has in store for you.

Hardware Resources

IOIO-OTG Resources

Android Resources


Looking for inspiration for your next project? Check out these other great SparkFun tutorials:

LogicBlocks & Digital Logic Introduction

Introducing fundamental digital logic concepts and LogicBlocks

General Guide to SparkFun Blocks for Intel® Edison

A general guide for using SparkFun Blocks for Intel® Edison in your next project!

MG2639 Cellular Shield Hookup Guide

Learn how to equip your Arduino with an MG2639 Cell Shield and use it to send SMS or TCP via GPRS.

Getting Started with the SparkFun Blynk Board

How to provision a Blynk Board - get it connected to Wi-Fi and Blynk, so you can start Blynking!

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

Sparcade: Edison as a Web Server for Browser Games

$
0
0

Sparcade: Edison as a Web Server for Browser Games a learn.sparkfun.com tutorial

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

Introduction

The Intel® Edison is essentially a tiny computer with onboard WiFi. As such, we can configure the Edison to act as an access point (AP) and a web server at the same time to serve simple browser-based games.

Edison as a game server

At big events like Maker Faires, internet is often nonexistent or hard to come by. One way to serve a web page to attendees is to create a WiFi access point to which they connect. This type of off-grid “dark node” is how projects like LibraryBox work.

Required Materials

Parts for this project can be found in the Edison SIK. Specifically, you will need:

Suggested Reading

Before continuing with this project, we suggest you be familiar with a few concepts:

Hardware Hookup

Connect the Edison to a Base Block and GPIO Block. See this guide on how to connect the Blocks (note that the ADC Block is not needed for this project).

Edison with LCD

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Configure the Edison

We need to configure the Edison to act as an access point before we can program it with the server and game.

Install XDK

Follow these instructions to install the Intel® XDK.

Flash the Latest Firmware

Follow the Edison firmware flashing guide to update to the latest firmware.

Connect to the Edison

Plug a USB cable into the OTG port of the Edison. Follow these instructions to set up USB networking on your host computer.

Use an SSH program (e.g., PuTTY) or the built-in SSH terminal of the XDK to connect to the Edison. Note that the default IP address of the Edison on the USB network is 192.168.2.15.

Configure WiFi

Once logged into the Edison over SSH (username: root, no password), run the command:

configure_edison --setup

Follow the onscreen instructions to set a password (highly recommended!), change the Edison’s name (e.g., “sparcade”), and connect to the internet via WiFi.

NOTE: Remember the device name you set! It should be the same name used for the SSID and hostname in future steps. This is because mDNS uses the hostname for the local network name, and we want it to match with the Dnsmasq name. I use "sparcade" for everything.

Configure Hostapd

Hostapd is a Linux utility capable of turning WiFi network cards into access points. Luckily, the Edison has Hostapd installed by default. All we have to do is configure it. Back up the original hostapd.conf file, and modify a new one:

mv /etc/hostapd/hostapd.conf.bak
vi /etc/hostapd/hostapd.conf

In the vi text editor, press ‘i’ to edit text and insert the following (you can copy the text and press ‘shift’ + ‘insert’ together to paste into vi):

interface=wlan0
ssid=sparcade
hw_mode=g
channel=6
auth_algs=1
wmm_enabled=0

Save and exit by pressing ‘esc’, type :wq, and press ‘enter’.

Configure Hosts

The hosts file lets us map names to IP addresses without having to rely on a DNS server. We want to associate the name “sparcade” and “sparcade.local” with our own IP address, which is 192.168.42.1 by default.

Backup the original hosts file and edit a new one:

mv /etc/hosts /etc/hosts.bak
vi /etc/hosts

Add the following:

127.0.0.1       localhost.localdomain           localhost       sparcade.local  sparcade
192.168.42.1    sparcade.local                  sparcade

Save and exit.

Configure DHCP

The Edison uses udhcp as a lightweight DHCP server for access point (AP) mode. This service hands out IP addresses to clients that connect to its AP. We’ll want to configure the udhcp daemon so that sparcade.local is associated with the AP’s IP address (192.168.42.1). It’s a bit of a cheat, since we aren’t running a full DNS server to associate website names with IP addresses.

Edit the configuration file:

vi /etc/hostapd/udhcpd-for-hostapd.conf

Scroll down to the bottom of the file, and add the following:

opt subnet 255.255.255.0
opt hostname sparcade
opt domain local
opt dns 192.168.42.1

Save and exit.

Install Dnsmasq

We will also use another tool, dnsmasq, to help associate the server name (“sparcade.local”) with the Edison’s WiFi IP Address (192.168.42.1). Install it with the following commands:

wget http://www.thekelleys.org.uk/dnsmasq/dnsmasq-2.45.tar.gz
tar xvf dnsmasq-2.45.tar.gz
cd dnsmasq-2.45
make install

Configure dnsmasq with:

vi /etc/dnsmasq.conf

Enter the following:

no-resolv
interface=wlan0

Save and exit.

Set Dnsmasq to Run on Boot

Because we manually compiled and installed dnsmasq, there is nothing that tells it to run whenever the Edison boots. To do that, we need to create a systemd service.

vi /lib/systemd/system/dnsmasq.service

Copy in the following:

[Unit]
Description=DHCP and DNS caching server.
After=network.target

[Service]
ExecStart=/usr/local/sbin/dnsmasq -k --conf-file=/etc/dnsmasq.conf
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Save and exit. To register the service (so it runs on boot), enter the commands:

systemctl daemon-reload
systemctl enable dnsmasq.service

Disable Default Server

Finally, we want to disable the web server that the Edison runs whenever it enters into AP mode. To do that, run:

systemctl disable edison_config.service

And now we can restart the Edison:

reboot

Set Edison as Access Point

Once the Edison has finished booting back up, turn on AP mode. Do that by holding the PWR button (on the side of the Base Block) for two to seven seconds (I recommend counting to 4).

Hold this button for 4 seconds

The Code

Download the Sparcade game server code:

Sparcade code

Unzip it and open the project in XDK. Connect to the Edison, upload the code, and run it. If you need a refresher on how to use the XDK, see this guide.

XDK  running Sparcade code

The XDK showing the Sparcade server running. Click on the image to see a larger version.

What’s Going On?

The code for Sparcade might be confusing at first glance. In main.js, we use the express and http node modules to create a simple web server. These serve the files found in the www directory (our game).

If you open up www/index.html, you will see the basic web page that gets sent to any client that requests a page from “sparcade.local”. This page tells the client’s browser to download a few JavaScript (.js) files, which then run a Phaser-based game on the Canvas element in the page.

Whenever the player dies (loses all lives), the client creates a socket.io connection back to the server and sends the player’s score. The server compares the player’s score against its list of Top 10 high scores, and, if the player ranked, it sends an initials request back to the client.

The player, if ranked in the top scores, enters their initials into the game, and their client sends their initials back to the server. The server then adds the user’s initials and score to the list of Top 10 scores, which is continuously displayed on the LCD.

Play!

From your phone, tablet or computer, connect to the Sparcade WiFi access point. Note that you will not have internet connection!

Connecting to the dark node

Open up a browser and navigate to http://sparcade.local/.

NOTE: Some browsers require you to type the "http://" part or the "/" at the end of the address. If your browser is still having trouble getting the web page, try typing in the IP address of the Edison in the browser's address bar: 192.168.42.1.

You should see the game appear in your browser. Vortex is a Tempest clone. You pilot a ship around a circle and shoot incoming enemies. Prevent any ships from leaving the blue circle, and don’t get shot!

Vortex is a simple arcade game – you have three extra lives, and one shot kills. The purpose is to get the high score.

Playing Vortex

As you and other people play the game, scores will be sent back to the server. If you are lucky and skilled enough to be in the Top 10, the game will ask you for your initials. The LCD on the Edison will scroll through the Top 10 high scores of everyone who has played!

Vortex with high scores from the Sparcade server

Smaller jumper wires are used here to keep the breadboard looking nice.

Resources and Going Further

To connect the Edison to the internet, connect via SSH and run the command:

configure_edison --WiFi

Follow the instructions to connect to a WiFi AP. Additionally, you can start running the Edison’s default web server again with:

systemctl enable edison_config.service
reboot

Note that you may want to load a different program via XDK so that the custom server does not continue to run on boot.

What other games can you make? To learn about how Vortex was made, check out the Phaser.io framework. Controlling hardware (specifically, the LCD) from the Edison is accomplished using the Johnny-Five platform.

All the resources used in this tutorial can be found below.

For more Intel® Edison fun, check out the following tutorials:

Loading Debian (Ubilinux) on the Edison

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

Using an LCD on the Edison

How to connect an LCD controlled by an ILI9341 driver to the Intel® Edison.

Interactive Smart Mirror

Build a smart mirror that displays weather data using the Intel® Edison.

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

Getting started with the SparkFun Inventor's Kit for Google's Science Journal App

$
0
0

Getting started with the SparkFun Inventor's Kit for Google's Science Journal App a learn.sparkfun.com tutorial

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

Introduction

Google announced their Making & Science Initiative at the 2016 Bay Area Maker Faire. Making & Science is an initiative at Google to inspire future scientists through making and tinkering, and we’re proud to be working with them to provide an electronics kit that is designed to support the Making & Science activities developed by Google with a team at the Exploratorium.

alt text

More information about the Making & Science initiative and these activities can be found at: makingscience.withgoogle.com

alt text

This kit includes all the electronics parts needed to start exploring and measuring your environment. The kit includes:

  • Arduino 101 pre-programmed to work with the Science Journal App
  • Breadboard & Breadboard holder
  • 9V Battery & 9V Battery holder
  • 9V Wall adapter
  • Mini Photocell
  • 10k Ohm resistors
  • Temperature Sensor
  • Cardboard cutouts for building your own Wind-Spinner Project
  • And more!

The parts in this kit complement the features in the Science Journal App, a digital science notebook for your Android device. We’ve pre-programmed the Arduino 101; so, all you have to do is get the app, power up your Arduino 101, and start exploring the awesome activities with the Science Journal.

This guide is only a supplement to the materials found on the Science Journal site. In this guide, we’ll show you how to hook up two external sensors to the Arduino 101 with the Science Journal. With the materials in the kit and the ideas from the Science Journal website, you’ll be able to make your very own windspinner project like the one pictured below and more! Let’s get started.

alt text

The Science Journal App

The Science Journal App is a digital science notebook. It interfaces directly with the built-in sensors on your device such as a light sensor, sound sensor, and accelerometer. With the app, you can record data, make notes, and save it all to your Google Drive account.

alt text

If you haven’t already done so, click here to download the Science Journal App for your android device or find it on the Google Play Store.

This app will enable you to explore your surroundings using the built-in sensors on the phone, take notes on your scientific observations, and interface with additional sensors that you build and connect up to the pre-programmed bluetooth-enabled Arduino 101.

The first few experiments in the Making & Science activities are focused around the sensors directly on the phone. These are designed to acquaint you with the app and the interface. Be sure to explore those first. Explore your environment using the built-in light sensor, sound level, and accelerometer on your phone. The app can show either the present value of a sensor or a real-time graph of the data:

alt text  alt text

And, you can also tap the record button to log your trial and save your data to analyze later. Now that you’ve explored the app, let’s add some external sensors using the Arduino 101.

The Arduino 101

The Arduino 101 is a development board based on the Intel Curie module that leverages the simplicity of the Arduino programming environment. If you got the SIK for Google’s Science Journal App, we pre-programmed this board for you to work directly with the Google Science Journal. If you have your own Arduino 101 and need to program it for the Science Journal, you can get the full source-code on github here.

alt text

This board has a built-in Bluetooth chip and is pre-programmed to communicate directly with the Science Journal App. This board will allow you to connect a variety of sensors to the Science Journal App through the Analog Pins (A0 - A5) with a little bit of circuit building.

When you’ve completed your science experiments with the Science Journal and you want to go further, we have a whole series of activities and experiments that you can explore to learn more about programming and electronics using your Arduino 101, but we’re getting ahead of ourselves. Let’s start with pairing the Arduino 101 to your Science Journal App.

Pairing the Arduino 101 to your Science Journal

The Arduino 101 will allow you to add external sensors to your Science Journal. First power up the Arduino 101 using either the USB cable, the 9V battery and battery adapter, or the wall adapter. Next, open up the Science Journal App and click on the add device icon in the upper right corner of the screen:

alt text

Click on the icon in the upper right corner to add external sensors

Next, identify the name of the Arduino 101 that you have. It will start with the letters “Sci” for Science and then have 4 extra unique characters that follow it. In our case, it’s named Scidc3e.

alt text

The device should automatically appear, if it doesn’t simply tap the refresh icon in the upper right corner.

Configuring the Arduino 101 readings

Tap on this device name to pair it. Now, you have a few options that you can configure for how you want to read sensor data from your Arduino 101. As a default, the Arduino 101 is looking at the voltage on pin A0. The app is configured to show this information as either Rotations or Raw values.

alt text

The two main modes of operation for a sensor on pin A0 are Rotation and Raw (%).

The Rotations setting takes an average of the number of light and dark transitions and estimates the rotations per minute (RPM) that an encoder disk is spinning. We use this in the Wind Spinner project later on. And, the Raw setting will display the voltage as a percentage from 0 to 100. A voltage of 3.3V will show 100%.

Going further with the Custom setting

If you want to explore other sensors or see the raw analog-to-digital (ADC) value, you can go into the Custom option. Under this option, you can select any of the available Analog pins on the Arduino 101 (A0 - A5).

alt text

Notice that you can select any of the pins (including ones that don’t exist on the Arduino 101!)

Once you’ve configured the sensor on the app, tap the back arrow to get back to your experiment, and slide your finger sideways until you see the new icon appear on the right side. For the custom sensor, this will appear as a bluetooth icon, and this will show a value of 0 - 1023 based on the actual sensor reading of the Arduino device. These are really unit-less values, but I’m pretty sure we can still make some good predictions and conclusions based on patterns that we see in the data.

alt text

The value from the Arduino 101 is shown here on this app as a value from 0 - 1023

If you’ve explored all of the features of the app, you know that we can also display this data graphically. Here’s a graph of a “pendulum” chandalier that I made swing back and forth over the top of the light sensor.

alt text

Notice that the period of the oscillation stays the same, but the amplitude appears to get smaller? Isn’t that peculiar?

Last thing. If you haven’t mounted your Arduino 101 board onto the plastic breadboard holder, you should do that now. Orient the Arduino 101 board and the breadboard (the white thing with a lot of holes in it) so that it looks like the diagram below. There are some little screws that you can use to afix the Arduino 101 board down, and the breadboard has a self-adhesive backing that you can use.

alt text

Now you’re ready to go and start exploring with the Science Journal and your new Arduino 101 sensor kit. We’ve included two sensors in the kit that we’ll show you how to setup next.

Exploring Light (and rotations) with the photocell

In our kit, we provide a simple photocell that can be used for measuring the light level in an area. The device changes resistance based on the amount of light reaching the face of the sensor.

alt text

To use the photocell, we need to build a simple voltage divider circuit. We will use the solderless breadboard to to build our circuit. The solderless breadboard is the white, rectangular board that has a series of holes all over it. It is used to connect wires together without twisting them together or using solder. When you plug two wires into the same row (of 5 adjacent holes), the two wires are held together by a small metal clip. These are the parts that you’ll need to gather.

alt text

Parts needed

  • photocell
  • 10k Ohm resistor (brown-black-orange)
  • 3 male-to-male jumper wires
  • 2 alligator clip to male pin jumpers
  • Arduino 101 and breadboard
  • cardboard photocell holder and encoder disk - pdf / svg template
  • an axle (a 3/32 welding rod or a bamboo skewer)
  • heavy base (2x4 piece of lumber or a hockey puck with a 3/32 hole drilled into it)

Find the photocell and a 10k ohm resistor. The 10k ohm resistor will have the color bands (brown-black-orange). Connect up the parts to the circuit on the breadboard so that it matches the diagram below. Pay close attention to where the wires go. Remember that wires are connected together when they share the same row of holes.

alt text

Now, go back to the Science Journal and setup the external sensor to display the external sensor data as % Raw.

alt text

In the Experiment view, select the graph setting, and move your hand up and down in front of the light sensor. What do you see? You should get a graph that’s similar to the one below. What value does it show when there’s a lot of light? How about when it’s dark?

alt text

Now, you have a light sensor that you can place anywhere! What kinds of things would you monitor?

What’s Going on?

The circuit that you built is what is called a voltage divider. Drawn in circuit form it looks a little bit like this:

alt text

When you have two resistors connected up in series like this. The voltage is divided across the two resistors proportionally based on their resistances. So, if the resistance of the photocell changes, then the voltage split between the two resistors also changes. This is why they call it a voltage divider.

Measuring RPM and Building a Wind Spinner!

One of the great activities that the team at Google and the Exploratorium developed is the Windspinner. To use the photocell to measure windspeed, we need to build a photocell encoder wheel. The photocell encoder wheel is a rotating disk with a window cutout. As the wheel spins, it exposes the photocell to light once per rotation. The Arduino 101 is constantly monitoring the sensor and it sends the raw sensor data to the Science Journal App. When the external sensor is setup to display Rotations the app converts these light / dark pulses into a measurement of rotations per minute (RPM).

alt text

The encoder disk covers and uncovers the photocell once per rotation.

To make this project, you might need a few extra parts that aren’t included in the kit. Most of these are materials that you can find around the average household.

  • You’ll need something to make an axle - a bamboo skewer or a 3/32" welding rod work great.
  • You’ll also need something to form the base of your Wind Spinner. We’re using a hockey puck that we drilled a small hole into, but a 2x4 or scrap piece of wood works as well!
  • And, finally, you’ll need some craft materials. We suggest some paper straws, construction paper, and chenille stems (pipe cleaners) to start!

To start, remove the photocell from the breadboard. Bend the head of the photocell 90 degrees so that it is flat. This will make it easier to fit into the photocell holder.

alt text

Now, insert the photocell into the small offset hole on the photocell holder, and tape it in place using a small piece of masking tape.

alt text

Using a 3/32" welding rod or a bamboo skewer as an axle, insert the axle through the center of the photocell holder. We also made a base using a hockey puck, but a piece of 2x4 or other material will work too. Remove the red wire from the 3.3V pin on the Arduino 101 to the breadboard, and connect the photocell back using the alligator clips as shown in the figures below.

alt text

alt text

Now you have the base of your photocell encoder built. Time to build the rest of the Wind Spinner.

Build your Wind Spinner!

When testing the wind speed, make sure to change the sensor settings in the app back to Rotations. The encoder disk (the one with an offset window cutout) will form the base of the wind spinner. Use a straw to make a sleeve for your wind spinner to spin around the axle, and use the other cardboard cut-out wheels or other craft materials to invent your own wind spinner. Be sure to record your ideas and observations inside the Science Journal App!

What factors affect the speed of your design?

Need more ideas? Check out the resources at g.co/sciencejournal

alt text

Exploring Temperature

While the Making & Science activities don’t include a temperature measuring activity, we thought we’d include a temperature sensor anyway. Let’s take a look at how this sensor works!

alt text

This is the TMP36. It’s a simple to use linear temperature sensor that’s calibrated in degrees C.

This little sensor has three legs and looks a bit like a transistor. It has a flat edge on one side and a rounded edge on the other.

alt text

The three legs of this sensor are power, signal, and ground. When you hold the temperature sensor with the flat edge facing to the left, the top pin is power, the bottom pin is ground, and the one left is the signal. Connect up the circuit as shown in the figure.

Setup the Science Journal to view this reading as a % Raw. Recall that this percentage is based off of a 3.3V scale on the Arduino 101. Cup your hands and blow deeply over the temperature sensor. Watch what happens to the Raw sensor reading!

alt text

This is showing the voltage read in on pin A0 as a percentage of 3.3V

Translating this to a real temperature

The way that this little temperature sensor works is this. The voltage on the signal pin (middle pin of the sensor) varies directly with temperature in degrees Celsius. The datasheet on the sensor shows a way to convert the voltage read on the pin into a temperature:

alt text

So, if I’m seeing a raw value of about 21%, what is that as a temperature? First, start with converting this to a voltage. 21% of 3.3V is (21/100)*3.3 = 0.693V.

Now, we simply plug this into the equation above:

alt text

But, what is this in Fahrenheit? Let me look up another quick conversion! Okay, the conversion for Celsius to Fahrenheit is:

alt text

And, we get the temperature in degrees Fahrenheit:

alt text

That’s how the sensor works, and how you can connect it to your Arduino 101 and the Science Journal App. Because the Science Journal App only measures raw values for voltage, you will need to process your raw data using a calculator or in a spreadsheet to get values into degrees Fahrenheit. Use the equations we show above as an example to explore your world.

Going Further

With the Science Journal app and the Arduino 101, there are a lot of different science experiments you can perform. You can use the Custom option in the Science Journal and view the actual raw data value read in by the Arduino 101. These values will vary from 0 - 1023 and are directly proportional to a voltage scale from 0 to 3.3V. With this information, can you make your very own voltmeter?

Next steps?

Google and the Exploratorium are developing more activities and experiments for you to investigate, and they’ve asked us for feedback from the Sparkfun Community. Let us know if you have other ideas of science experiments you’d like to try or that you’d to see developed!

Click on the comments tab on the right to share your ideas with us!

We look forward to seeing what you make!


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

Getting Started with the SparkFun Inventor's Kit for Google's Science Journal App

$
0
0

Getting Started with the SparkFun Inventor's Kit for Google's Science Journal App a learn.sparkfun.com tutorial

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

Introduction

Google announced their Making & Science Initiative at the 2016 Bay Area Maker Faire. Making & Science is an initiative at Google to inspire future scientists through making and tinkering, and we’re proud to be working with them to provide an electronics kit that is designed to support the Making & Science activities developed by Google with a team at the Exploratorium.

alt text

More information about the Making & Science initiative and these activities can be found at: makingscience.withgoogle.com

alt text

This kit includes all the electronics parts needed to start exploring and measuring your environment. The kit includes:

  • Arduino 101 pre-programmed to work with the Science Journal App
  • Breadboard & Breadboard holder
  • 9V Battery & 9V Battery holder
  • 9V Wall adapter
  • Mini Photocell
  • 10k Ohm resistors
  • Temperature Sensor
  • Cardboard cutouts for building your own Wind-Spinner Project
  • And more!

The parts in this kit complement the features in the Science Journal App, a digital science notebook for your Android device. We’ve pre-programmed the Arduino 101; so, all you have to do is get the app, power up your Arduino 101, and start exploring the awesome activities with the Science Journal.

This guide is only a supplement to the materials found on the Science Journal site. In this guide, we’ll show you how to hook up two external sensors to the Arduino 101 with the Science Journal. With the materials in the kit and the ideas from the Science Journal website, you’ll be able to make your very own windspinner project like the one pictured below and more! Let’s get started.

alt text

The Science Journal App

The Science Journal App is a digital science notebook. It interfaces directly with the built-in sensors on your device such as a light sensor, sound sensor, and accelerometer. With the app, you can record data, make notes, and save it all to your Google Drive account.

alt text

If you haven’t already done so, click here to download the Science Journal App for your android device or find it on the Google Play Store.

This app will enable you to explore your surroundings using the built-in sensors on the phone, take notes on your scientific observations, and interface with additional sensors that you build and connect up to the pre-programmed bluetooth-enabled Arduino 101.

The first few experiments in the Making & Science activities are focused around the sensors directly on the phone. These are designed to acquaint you with the app and the interface. Be sure to explore those first. Explore your environment using the built-in light sensor, sound level, and accelerometer on your phone. The app can show either the present value of a sensor or a real-time graph of the data:

alt text  alt text

And, you can also tap the record button to log your trial and save your data to analyze later. Now that you’ve explored the app, let’s add some external sensors using the Arduino 101.

The Arduino 101

The Arduino 101 is a development board based on the Intel Curie module that leverages the simplicity of the Arduino programming environment. If you got the SIK for Google’s Science Journal App, we pre-programmed this board for you to work directly with the Google Science Journal. If you have your own Arduino 101 and need to program it for the Science Journal, you can get the full source-code on github here.

alt text

This board has a built-in Bluetooth chip and is pre-programmed to communicate directly with the Science Journal App. This board will allow you to connect a variety of sensors to the Science Journal App through the Analog Pins (A0 - A5) with a little bit of circuit building.

When you’ve completed your science experiments with the Science Journal and you want to go further, we have a whole series of activities and experiments that you can explore to learn more about programming and electronics using your Arduino 101, but we’re getting ahead of ourselves. Let’s start with pairing the Arduino 101 to your Science Journal App.

Pairing the Arduino 101 to your Science Journal

The Arduino 101 will allow you to add external sensors to your Science Journal. First power up the Arduino 101 using either the USB cable, the 9V battery and battery adapter, or the wall adapter. Next, open up the Science Journal App and click on the add device icon in the upper right corner of the screen:

alt text

Click on the icon in the upper right corner to add external sensors

Next, identify the name of the Arduino 101 that you have. It will start with the letters “Sci” for Science and then have 4 extra unique characters that follow it. In our case, it’s named Scidc3e.

alt text

The device should automatically appear, if it doesn’t simply tap the refresh icon in the upper right corner.

Configuring the Arduino 101 readings

Tap on this device name to pair it. Now, you have a few options that you can configure for how you want to read sensor data from your Arduino 101. As a default, the Arduino 101 is looking at the voltage on pin A0. The app is configured to show this information as either Rotations or Raw values.

alt text

The two main modes of operation for a sensor on pin A0 are Rotation and Raw (%).

The Rotations setting takes an average of the number of light and dark transitions and estimates the rotations per minute (RPM) that an encoder disk is spinning. We use this in the Wind Spinner project later on. And, the Raw setting will display the voltage as a percentage from 0 to 100. A voltage of 3.3V will show 100%.

Going further with the Custom setting

If you want to explore other sensors or see the raw analog-to-digital (ADC) value, you can go into the Custom option. Under this option, you can select any of the available Analog pins on the Arduino 101 (A0 - A5).

alt text

Notice that you can select any of the pins (including ones that don’t exist on the Arduino 101!)

Once you’ve configured the sensor on the app, tap the back arrow to get back to your experiment, and slide your finger sideways until you see the new icon appear on the right side. For the custom sensor, this will appear as a bluetooth icon, and this will show a value of 0 - 1023 based on the actual sensor reading of the Arduino device. These are really unit-less values, but I’m pretty sure we can still make some good predictions and conclusions based on patterns that we see in the data.

alt text

The value from the Arduino 101 is shown here on this app as a value from 0 - 1023

If you’ve explored all of the features of the app, you know that we can also display this data graphically. Here’s a graph of a “pendulum” chandalier that I made swing back and forth over the top of the light sensor.

alt text

Notice that the period of the oscillation stays the same, but the amplitude appears to get smaller? Isn’t that peculiar?

Last thing. If you haven’t mounted your Arduino 101 board onto the plastic breadboard holder, you should do that now. Orient the Arduino 101 board and the breadboard (the white thing with a lot of holes in it) so that it looks like the diagram below. There are some little screws that you can use to afix the Arduino 101 board down, and the breadboard has a self-adhesive backing that you can use.

alt text

Now you’re ready to go and start exploring with the Science Journal and your new Arduino 101 sensor kit. We’ve included two sensors in the kit that we’ll show you how to setup next.

Exploring Light (and rotations) with the photocell

In our kit, we provide a simple photocell that can be used for measuring the light level in an area. The device changes resistance based on the amount of light reaching the face of the sensor.

alt text

To use the photocell, we need to build a simple voltage divider circuit. We will use the solderless breadboard to to build our circuit. The solderless breadboard is the white, rectangular board that has a series of holes all over it. It is used to connect wires together without twisting them together or using solder. When you plug two wires into the same row (of 5 adjacent holes), the two wires are held together by a small metal clip. These are the parts that you’ll need to gather.

alt text

Parts needed

  • photocell
  • 10k Ohm resistor (brown-black-orange)
  • 3 male-to-male jumper wires
  • 2 alligator clip to male pin jumpers
  • Arduino 101 and breadboard
  • cardboard photocell holder and encoder disk - pdf / svg template
  • an axle (a 3/32 welding rod or a bamboo skewer)
  • heavy base (2x4 piece of lumber or a hockey puck with a 3/32 hole drilled into it)

Find the photocell and a 10k ohm resistor. The 10k ohm resistor will have the color bands (brown-black-orange). Connect up the parts to the circuit on the breadboard so that it matches the diagram below. Pay close attention to where the wires go. Remember that wires are connected together when they share the same row of holes.

alt text

Now, go back to the Science Journal and setup the external sensor to display the external sensor data as % Raw.

alt text

In the Experiment view, select the graph setting, and move your hand up and down in front of the light sensor. What do you see? You should get a graph that’s similar to the one below. What value does it show when there’s a lot of light? How about when it’s dark?

alt text

Now, you have a light sensor that you can place anywhere! What kinds of things would you monitor?

What’s Going on?

The circuit that you built is what is called a voltage divider. Drawn in circuit form it looks a little bit like this:

alt text

When you have two resistors connected up in series like this. The voltage is divided across the two resistors proportionally based on their resistances. So, if the resistance of the photocell changes, then the voltage split between the two resistors also changes. This is why they call it a voltage divider.

Measuring RPM and Building a Wind Spinner!

One of the great activities that the team at Google and the Exploratorium developed is the Windspinner. To use the photocell to measure windspeed, we need to build a photocell encoder wheel. The photocell encoder wheel is a rotating disk with a window cutout. As the wheel spins, it exposes the photocell to light once per rotation. The Arduino 101 is constantly monitoring the sensor and it sends the raw sensor data to the Science Journal App. When the external sensor is setup to display Rotations the app converts these light / dark pulses into a measurement of rotations per minute (RPM).

alt text

The encoder disk covers and uncovers the photocell once per rotation.

To make this project, you might need a few extra parts that aren’t included in the kit. Most of these are materials that you can find around the average household.

  • You’ll need something to make an axle - a bamboo skewer or a 3/32" welding rod work great.
  • You’ll also need something to form the base of your Wind Spinner. We’re using a hockey puck that we drilled a small hole into, but a 2x4 or scrap piece of wood works as well!
  • And, finally, you’ll need some craft materials. We suggest some paper straws, construction paper, and chenille stems (pipe cleaners) to start!

To start, remove the photocell from the breadboard. Bend the head of the photocell 90 degrees so that it is flat. This will make it easier to fit into the photocell holder.

alt text

Now, insert the photocell into the small offset hole on the photocell holder, and tape it in place using a small piece of masking tape.

alt text

Using a 3/32" welding rod or a bamboo skewer as an axle, insert the axle through the center of the photocell holder. We also made a base using a hockey puck, but a piece of 2x4 or other material will work too. Remove the red wire from the 3.3V pin on the Arduino 101 to the breadboard, and connect the photocell back using the alligator clips as shown in the figures below.

alt text

alt text

Now you have the base of your photocell encoder built. Time to build the rest of the Wind Spinner.

Build your Wind Spinner!

When testing the wind speed, make sure to change the sensor settings in the app back to Rotations. The encoder disk (the one with an offset window cutout) will form the base of the wind spinner. Use a straw to make a sleeve for your wind spinner to spin around the axle, and use the other cardboard cut-out wheels or other craft materials to invent your own wind spinner. Be sure to record your ideas and observations inside the Science Journal App!

What factors affect the speed of your design?

Need more ideas? Check out the resources at g.co/sciencejournal

alt text

Exploring Temperature

While the Making & Science activities don’t include a temperature measuring activity, we thought we’d include a temperature sensor anyway. Let’s take a look at how this sensor works!

alt text

This is the TMP36. It’s a simple to use linear temperature sensor that’s calibrated in degrees C.

This little sensor has three legs and looks a bit like a transistor. It has a flat edge on one side and a rounded edge on the other.

alt text

The three legs of this sensor are power, signal, and ground. When you hold the temperature sensor with the flat edge facing to the left, the top pin is power, the bottom pin is ground, and the one left is the signal. Connect up the circuit as shown in the figure.

Setup the Science Journal to view this reading as a % Raw. Recall that this percentage is based off of a 3.3V scale on the Arduino 101. Cup your hands and blow deeply over the temperature sensor. Watch what happens to the Raw sensor reading!

alt text

This is showing the voltage read in on pin A0 as a percentage of 3.3V

Translating this to a real temperature

The way that this little temperature sensor works is this. The voltage on the signal pin (middle pin of the sensor) varies directly with temperature in degrees Celsius. The datasheet on the sensor shows a way to convert the voltage read on the pin into a temperature:

alt text

So, if I’m seeing a raw value of about 21%, what is that as a temperature? First, start with converting this to a voltage. 21% of 3.3V is (21/100)*3.3 = 0.693V.

Now, we simply plug this into the equation above:

alt text

But, what is this in Fahrenheit? Let me look up another quick conversion! Okay, the conversion for Celsius to Fahrenheit is:

alt text

And, we get the temperature in degrees Fahrenheit:

alt text

That’s how the sensor works, and how you can connect it to your Arduino 101 and the Science Journal App. Because the Science Journal App only measures raw values for voltage, you will need to process your raw data using a calculator or in a spreadsheet to get values into degrees Fahrenheit. Use the equations we show above as an example to explore your world.

Going Further

With the Science Journal app and the Arduino 101, there are a lot of different science experiments you can perform. You can use the Custom option in the Science Journal and view the actual raw data value read in by the Arduino 101. These values will vary from 0 - 1023 and are directly proportional to a voltage scale from 0 to 3.3V. With this information, can you make your very own voltmeter?

Next steps?

Google and the Exploratorium are developing more activities and experiments for you to investigate, and they’ve asked us for feedback from the Sparkfun Community. Let us know if you have other ideas of science experiments you’d like to try or that you’d to see developed!

Click on the comments tab on the right to share your ideas with us!

We look forward to seeing what you make!


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


Continuous Rotation Servo Trigger Hookup Guide

$
0
0

Continuous Rotation Servo Trigger Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

When we introduced the regular Servo Trigger, we mentioned that it could be reprogrammed to be more useful with continuous rotation servo motors. However, reprogramming the firmware is somewhat tedious, and users asked for a Servo Trigger preprogrammed with the continuous rotation logic.

alt text

You asked, and we listened! Introducing the Continuous Rotation Servo Trigger! The name is a mouthful, but if you’re looking for an easy way to deploy continuous rotation servos, it should be exactly what you’re looking for.

alt text

The Continuous Rotation Servo Trigger

Like its sibling, the Continuous Rotation Servo Trigger allows you to control a hobby servo motor without any programming. The servo speed and direction are adjusted using trimpots, and the direction can be changed by attaching a switch.

In this guide, we’ll show you how to quickly get your CR Servo Trigger working, then discuss some of the finer details of using and configuring it. Finally, we’ll show how it was used to build a simple automated camera dolly.

Suggested Reading

  • We’re not going to get too deep into the basics of hobby servos in this hookup guide. If you want more detailed information, check out our Hobby Servo Tutorial.
  • Some more background on motors.
  • If you came here looking for information about the regular Servo Trigger, you can find its hookup guide over here.

Continuous Rotation Servo Motors

A continuous rotation servo (sometimes called a full rotation or 360° servo) looks like a regular hobby servo. While a regular servo motor only turns over a narrow range, with precise control over position, a continuous rotation servo has a shaft that spins continuously, with control over its speed and direction.

alt text

The control is performed using a pulse train signal, typically with pulses that vary from 1 to 2 milliseconds, sent every 20 milliseconds (50 Hz). A one millisecond pulse corresponds to full speed in one direction, while a two millisecond pulse is full speed in the other direction. These pulses are easy to generate using the pulse-width-modulation hardware on a modest microcontroller.

alt text

Two millisecond pulses, sent every 20 milliseconds.

Halfway between those extremes, a 1.5 millisecond pulse should cause the motor to stop. Most CR servos have an adjustment screw or trimpot that allows you to fine tune the point at which it stops, a calibration procedure often called nulling.

alt text

Nulling trimpot

With the CR Servo Trigger, the stop point can be adjusted on the board, but if it behaves unexpectedly, double check that the trim on the servo itself isn’t the root of the problem.

Getting Started Quickly

Let’s jump in and build a circuit to show how the Servo Trigger works!

Materials and Tools

You’ll need to following materials to build this example circuit found in this tutorial.

Servo - Generic High Torque Continuous Rotation (Standard Size)

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

TOL-12889
$5.95
11
Momentary Pushbutton Switch - 12mm Square

COM-09190
$0.5
4
Break Away Male Headers - Right Angle

PRT-00553
$1.95
4
DC Barrel Jack Adapter - Female

PRT-10288
$2.95
SparkFun Servo Trigger - Continuous Rotation

WIG-13872
$19.95

You’ll also need some hookup wire and a small screwdriver.

Doublecheck The Trigger

Before we start building, doublecheck that you’ve got a Continuous Rotation Servo Trigger. There are tick boxes on the back of the PCB, and the “continuous rotation” box should be marked.

alt text

Preparations

To start, solder some wires to the tactile switch. If you solder to legs on on opposite corners (top-right and lower-left, for instance), you can be confident that you’ll get a contact closure when you press the button.

alt text

Switch Assembly

Next, prepare the power plug pigtail. Take a pair of wires, and strip the ends. Then screw them to the power jack adapter – if you look closely at the adaptor, you’ll notice that there are a small + and - embossed in the plastic. We used a red wire for VCC on the + terminal and a black wire for ground on the - terminal.

alt text

Power Jack Closeup

Take your right-angle male headers, and snap of a section of three headers. Solder the 3-pin header to the three pads on the end the board, and plug the servo into the the header. Be careful to get the plug oriented correctly – you can check the color code table in the servo tutorial, or consult the servo manufacturer’s datasheet.

Solder the switch wires to the IN and GND pads on the Servo Trigger and the power pigtail to the VCC and GND pads on the edge of the board. These are mirrored on opposite edges of the board – they’re wired in parallel, so you can use either set of pads. The red wire should connect to the VCC pad and the black to GND.

Before we power up, take a moment to double-check your work against the photo below (click on the picture for a larger version). In particular, make sure that the power and servo connections are oriented correctly.

alt text

Adjusting the trimpots.

Adjust the trimpots on the back of the board. Set A fully counterclockwise, B fully clockwise, and set T to the middle.

Finally, apply power. The servo should start to turn. If not, power down, and recheck your work.

While it’s running, tap the switch. The servo will take a couple of seconds to slow down, stop, then reverse. Tap the switch again, and it will go back to the original direction.

Now you can adjust the trimpots to configure the servo.

  • A sets the speed and direction of the motor before the switch is actuated.
  • B sets the speed and direction of the motor after the switch is actuated.
  • T sets the time it takes to get from A to B and back.

When A and B are near the middle of their rotation, the servo will stop. Turning them clockwise from there instructs the servo to turn in one direction; turning them counterclockwise results in the opposite direction. The farther from the center, the faster the servo turns. The transition time is adjustable between 50 milliseconds and 10 seconds. The transition time is constant – when set to 2 seconds, the servo will take 2 seconds to move between A and B, regardless of how close the A and B settings are.

In the next section, we’ll explore some of the finer details of the Continuous Rotation Servo Trigger.

Theory Of Operations

The Servo Trigger consists of two major engineering deliverables, the hardware design, and the firmware. The hardware is actually the same for the regular and continuous rotation boards, but they’re loaded with different firmware, tailoring the board’s behavior to each type of servo motor. Both sets of deliverables are in the Servo Trigger Github repository.

On The Board

Let’s look at the components on the board and examine what they do.

alt text

The heart of the Servo Trigger is an Atmel ATTiny84 microcontroller, running a small program that implements the servo control features we are discussing here. Just because the Servo Trigger saves you from needing to write code doesn’t mean that there was no programming involved!

The servo control signal is generated using a 16-bit hardware timer. It runs off a 1 MHz clock, counting to 20000 to generate the 20 mSec (50 Hz) period and is configured to generate pulses that range from 1000 to 2000 µSec (1 to 2 milliseconds).

The three potentiometers are connected as voltage dividers between VCC and ground. They are read using analog inputs ADC0, ADC3, and ADC7.

The switch input is read using PortA, input pin 1. It is debounced in software and can be configured to watch for a switch closure or a logic level pulse.

The board also includes the common 6-pin in-system-programming header, which we’ll discuss in the Servo Trigger Programming Guide. But we’re getting a bit ahead of ourselves – there are some configuration options you can use without programming.

Configuration

The Servo Trigger has a couple of configuration options. If you look at the back of the PCB, you’ll notice two solder jumpers that can be used to change Servo Trigger’s response.

alt text

Configuration Jumpers, SJ1 and SJ2.

When it first powers up, the servo trigger reads these jumpers and configures itself accordingly.

Modes

The Servo Trigger has two different servo control modes, selected with solder jumper 1 (SJ1). They can be used to tailor the response of the board for different applications.

The default mode implements toggling control. The trigger initializes driving the servo as instructed by trimmer A. When the switch closes, it transitions to the speed indicated by B. When the switch closes again, it returns to A. The time taken to get between A and B is selected using trimmer T, which ranges from nearly instantaneous to 10 seconds, allowwing the motor to gradually slow, stop, and reverse.

alt text

Mode Jumper Cleared - Toggling Control

This behavior can be changed by flowing solder between the pads of the mode jumper.

alt text

Closing SJ1 to select bistable mode.

With the solder jumper closed, the mode changes to bistable control – the servo will drive at speed A while the switch is open, and speed B while the switch is closed. While the switch input stays in a state, the servo drives at the corresponding speed – it is stable in two different states.

alt text

Mode Jumper Cleared - Bistable Control

Input Polarity

The Servo Trigger input sensitivity can also be changed, using solder jumper 2 (SJ2).

The default configuration, with no solder applied, configures the Servo Trigger for use with a normally-open switch, with the internal pull-up resistor on the microcontroller enabled. This configuration is also suitable for use with an active-low logic input.

With SJ2 closed, the internal pull-up is disabled, and the input is set as an active-high logic input.

If SJ2 is closed, be careful about powering up the Servo Trigger when the input is not connected to anything. When the input is floating, it can randomly jump between active and inactive and may cause the motor to behave unpredictably.

A note about nomenclature: since the input polarity can be swapped, it can be hard to talk about – the voltage might be high, but when the sense is inverted, it indicates that the input isn’t being actuated. To help navigate this, the polarity-neutral terms active or asserted are used to describe when the input is being used, and inactive or deasserted to describe the default state.

More components

The servo trigger can be used with a wider variety of external components than used in the example above. We used a standard size continuous rotation servo, though we also offer a micro size one.

You can also use different switches, such as micro switches or foot pedals.

Power Notes

Compared to a servo motor, the Servo Trigger board draws very little current – roughly 5 mA.

The motor draws significantly more – a quick bench test using a small servo, with only a lightwieght horn attached, shows the motor draws 10 mA sitting idle, and about 70 mA while moving. Grabbing the horn and twisting causes the controller to apply current to the motor, counteracting the twist. It drew 700 mA during this test – a larger servo could draw even more!

These currents can get surprisingly high as you add more motors to the system – you’ll need to select a power supply with adequate capacity. An Ampere per motor is a reasonable guideline. For more information about powering servos, please see the powering a servo section of our Servo Tutorial.

When in doubt, grab a multimeter, measure the current consumed, and check whether VCC at the board input is falling below the expected voltage when the servos are turning.

Troubleshooting

If there’s no change when you actuate the input, first check that A and B are not set to the same position, otherwise there’s no speed change!

If you’re feeding the input with a logic signal from an external device, be sure to drive the signal for more than 50 milliseconds. The PWM signal is updated every 50 mSec, and events shorter than that may be missed.

If the servo only turns on one direction, doublecheck that the trimpot on the servo is near the center of its range. If it’s near one end or the other, the servo will go from full speed to stopped, but not reverse.

For additional servo troubleshooting ideas, please consult the Servo Turorial.

Example Project

To demonstrate the usefulness of the Continuous Rotation Servo Trigger, we put a continuous rotation servo on a small camera dolly. The dolly has a whisker switch at each end, allowing it to do automated tabletop camera moves.

alt text

Lacking an old-fashioned rollerskate to dismantle for the chassis, we started with a commercial camera skate dolly.

Polymer Lithium Ion Battery - 2000mAh

PRT-08483
$12.95
18
SparkFun Power Cell - LiPo Charger/Booster

PRT-11231
$19.95
8
Servo - Generic High Torque Continuous Rotation (Standard Size)

ROB-09347
$13.95
4
Jumper Wire - 0.1", 2-pin, 4"

PRT-10362
$0.95
SparkFun RedBot Sensor - Mechanical Bumper

SEN-11999
$4.95
1
Jumper Wire - 0.1", 2-pin, 6"

PRT-10367
$1.5
SparkFun Servo Trigger - Continuous Rotation

WIG-13872
$19.95

We also had some derelict robot parts around the workshop that we used to hold everything together. We improvised using materials we had handy and suggest that you do the same!

Build the Circuit

To start, we assembled the circuit on the workbench.

alt text

We used male and female headers to stack the Power Cell atop the Servo Trigger board.

alt text

Headers used to stack Power Cell on Servo Trigger.

The whisker switches were assembled as described in this hookup guide, with one built in right-hand orientation and the other left-handed.

The whisker switches also needed a quick electronic modification to make them compatible with the Servo Trigger. We desoldered the resistor from the PCB and replaced it with a blob of solder, so the whisker acts as a simple switch closure.

alt text

We plugged the 2 pin jumper wires into the GND and 5V pins on the switches and stuck some long pin headers through the switch contacts on the trigger PCB, so the switches could both plug in in parallel, one from above, the other from beneath.

alt text

We gave it a quick test on the bench. Each time a whicker switch closed, the motor drove the other way. The A, B, and T adjustments each had the desired effect.

Mechanical Integration

With the electronics working, we put them on the chassis.

The chassis itself consists of a platform with a couple of protruding M6 machine screws. The axles are mounted to the screws with wingnuts.

alt text

The drive mechanism for the cart is a simple slip clutch. We fashioned a double-width rubber wheel onto the servo using Actobotics 2" wheels and a pair of servo hubs. The motor was mounted to a B-type servo bracket, which was connected to the end of a 4.5" channel. The bracket was free to pivot in the end of the channel.

alt text

The bracket channel was simply placed over the axle bolt on the cart chassis. A rubber band was looped around the assembly, putting tension on the servo, so that the drive wheel gently touched one of the skate wheels.

On the other end of the cart, a 1.5" channel was placed over the other pivot. This allowed both axles on the cart to be spaced evenly, ensuring that all four skate wheels touch the tabletop. It also gave us some holes to mount the front whisker switch and a place to secure the battery and other electronics.

Testing Results

The first time out was somewhat disappointing – the cart would drive until the first switch closed, then stall. It turns out the battery was nearly discharged! After a couple hours charging from a USB port, it behaved as expected.

We adjusted the trimmers so it drove slowly in both directions, with a medium transition time, so it wouldn’t skid or jerk as it turned around.

Resources and Going Further

Resources

Going Further


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

Servo Trigger Programming Guide

$
0
0

Servo Trigger Programming Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun Servo Trigger is a useful little board that control hobby servo motors. It comes in both standard and continuous rotation flavors.

alt text

The Servo Trigger was designed to make using servo motors easy, but it may not fit every application. You might need different timing, or different logic that interprets how the input is translated into the motor drive signal. You might even have some idea that doesn’t involve servo motors at all!

Since the heart of the Servo Trigger is a microcontroller, the firmware can be reprogrammed. And, because the design is released as Open Source Hardware, the source code is published in the device’s GitHub Repository. You’re welcome to download and modify it!

This guide applies to both versions of the Servo Trigger. They use identical hardware, but they get loaded with different firmware.

This guide will introduce the tools used to program the Servo Trigger and guide you through the software design. By the end, you’ll be able to transmute a regular Servo Trigger into a Continuous Rotation one (or vice versa), or even develop new behaviors from scratch.

Suggested Reading

Programming Tools

This guide will walk you through recreating the development environment used in Servo Trigger developemt. Atmel Studio makes a nice graphical front end and has a full-featured debugger, it is not required to recompile the firmware or reprogram the IC.

However, it only runs under Windows.

If you're running Linux or OSX, you can still use the the command-line AVR-GCC tools. Here is a guide to setting them up. However, you'll be in uncharted territory, as the author isn't using those environments.

The IDE

The Servo Trigger firmware was developed using Atmel Studio 6.2. Atmel Studio merges Microsoft’s Visual Studio IDE with compiler and debugging tools targeting Atmel microcontrollers. The AVR tools use AVR-GCC, the same compiler used by the Arduino IDE.

alt text

The IDE communicates with the microcontroller using a programming dongle. The Servo Trigger was developed with the JTAGICE3 and AtmelICE PCBA debugging modules. These units can configure and program the chip and also offer a full-featured interactive debugger. You can pause execution and inspect the chip internals, which makes troubleshooting the application significantly simpler – especially because the Tiny84 lacks a serial port that could print debugging information. If you’re coming from platforms that don’t offer it, interactive debugging is a very powerful technique.

alt text

If you’re using Atmel Studio, the /firmware/ directory in the repo contains the solution (*.atsln) file.

Getting Started

The Atmel debug tools are very convenient, but they require detailed configuration to get working. This page will walk you through creating a brand new project and getting the debugger talking to the Servo trigger.

Hardware Configuration

The Servo Trigger has the standard 6-pin in-system programming (ISP) connector.

alt text

In order to connect to this header, you can solder a header to the PCB or use a pogo pin adapter.

SparkFun ISP Pogo Adapter

KIT-11591
$9.95
Header - 2x3 (Male, 0.1")

PRT-12807
$0.5
If you're going to use the debugger, soldering in a header is highly recommended. Otherwise, you'll have to hold the pogo pins in place for the duration of your debug session.

Finally, the debug interface box isn’t designed to serve as a power supply for the board. You’ll need to power the Servo Trigger by applying 5 Volts to its VCC and GND pins.

Creating a New Project

In order to use the debugger, you’ll need a project file. Let’s create one from scratch.

To create a project, first open Atmel Studio, and select “New Project”.

alt text

Select the GCC C or C++ Executable Project options.

alt text

It will take a moment to initialize the project, then show a list of target microcontrollers. Select ATtiny84 from the list.

alt text

It takes another moment, then comes up with empty project. main() is the entry point for your application.

alt text

Programming Interface Modes

Before we go any deeper, lets take a quick break to explore the two modes that the debugger uses to communicate with the chip. While they appear to be similar, they aren’t totally equivalent. They’re also configured in two places in the IDE, and the settings need to match in order for them to function correctly.

  • The first mode is ISP, which uses clock and data signals akin to SPI. It’s the older of the two modes, intended to be used to program the flash memory on the processor and interact with some of the low-level nonvolatile configuration, such as the chip ID register and fuse bits. Being low level, it doesn’t allow for interactive debugging.
  • The other mode is debugWIRE. It was developed more recently, retrofitted into the chips, using communications over the reset pin. debugWIRE can program the flash and allows interactive debugging, but it can’t access the ID register or fuse bits.

alt text

Since neither mode has all of the capabilities, we’ll have to switch between them, depending on what we’re doing. If you’re having trouble using the features of one mode, the most likely problem is that the chip and IDE don’t agree on the current mode.

Getting the Interface Talking The First Time

With a new project open in the IDE, connect the debugger module to the USB port.

Click “Project-> Properties…”, then select the Tool tab along the left edge to configure the debugging tools.

alt text

Select the connected debugger, and set the interface to ISP.

After selecting the interface, click on “tools->device programming” to open the chip configuration dialog. It will open with the tool, target device, and interface selected. Click Apply, and it initializes the interface. More information will appear in the lower portion of the window.

alt text

Connect the debugger unit to the servo trigger, and power it up. Click the “Target Voltage Read” button near the top right.

alt text

The neighboring box should indicate approximately 5.0V. This verifies that the chip has power and should be able to communicate.

Then, click the “Read device signature” button.

alt text

It should report an ID of 0x1E930C in the neighboring box, indicating an ATTiny84.

At this point, we’ve got confidence that the ISP interface is working, and we can turn on debugWIRE mode.

Enabling debugWIRE

In the Device Programming dialog, click on the “Fuses” tab on the left side of the box. Then mark the box next to the “DWEN” (Debug Wire ENable) fuse. The circle next to the name will turn yellow, to indicate that the bit has not been programmed.

alt text

Make sure “Verify after programming” box is checked, then press “program.” The progress will be reported in the lower portion of the dialog. If the IDE requests a power cycle of the target, do so. At the end, it should say “Verify registers …OK”, and the circle next to DWEN should turn green.

At this point, close the Device Programming dialog. You should be back at the project properties tab. Now, switch the interface to debugWIRE.

alt text

DebugWIRE has been enabled by setting the fuse on the chip, and the IDE has been instructed to use it instead of ISP.

Using Debug Wire

After the steps above have been completed, select Debug->Start Debugging and Break.

alt text

The compiler will run, and the IDE will rearrange its windows several times. Ultimately, it will open some memory inspection windows and the source code file.

alt text

The yellow arrow in the left margin indicates that the debugger is running and has paused at the entry to main().

At this point, Atmel Studio performs like most debuggers. You can set breakpoints on specific lines of code, observe the call stack, inspect variables, and interact with the peripherals by accessing I/O registers in the memory map.

When you’re done, select the “debug->stop debugging” option.

alt text

The program we’ve got in the default empty project is pretty trivial – main contains an empty, infinite loop. If we were developing a more meaningful application, we would be adding more code to the source file, building and debugging as needed.

If you’re making round trips from the editor to the debugger and back, stopping debugging is a reasonable way to switch modes.

If, however, you need to go back to the Device Programming dialog (for example, to change clock settings or adjust other fuse bits), you’ll need to disable debugWIRE when ending the debug session.

alt text

This clears the DWEN fuse. You can then return to the first time instructions above. Don’t forget that the project configuration and device programming need to both be set to ISP. To return to debug mode, you’ll need to set the DWEN fuse again.

When You Get Stuck

It plays out like this: Yesterday you were debugging, today you start and decide to go and check the chip configuration in the Device Programming dialog.

Nothing works, and the error details contain “Got 0xc0, expected 0x00.”

alt text

The trick to unjamming it:

  • Set the project to debugWIRE.
  • Start a debug session (Debug->Start Debugging and Break).
  • Once the debugger is initialized, select “Debug->Disable debugWIRE and Close” to get out.
  • Set the project back to ISP, and now the Device Programming dialog should be functional.

One Final Warning

Be careful playing with the fuse bits. It's possible to select invalid clock configurations, or lock the programming interface, which leave the processor in hard to recover states.

Knowing the fundamentals of starting and stopping the debugger, lets look more closely at the Servo Trigger firmware design.

Firmware Modifications

Let’s take a look at some of the finer points of the Servo Trigger code.

There’s a single source file in the project, ServoTrigger.c, and some additional configuration in the Atmel Studio project.

Timing

The range of transit times accessed by the T potentiometer is defined by a table of software values – the table interprets pot position using an exponential curve, which allows for fine control of very short times on the low end, but still permits a useful longer range at the top. But perhaps these times don’t fit your application especially well – maybe you need extra resolution at the low end, or much longer times at the top end. You can change the timing table to do this.

In the GitHub repository, there is a speadsheet, translation.ods, which calculates the timing tables. Simply type the desired time in seconds into the green cells. The sheet recalculates the timing values, and updates the yellow cells. Cut and paste the yellow cells into the timelut array.

alt text

The table is only 17 entries long, which seems rather short – but keep in mind we’re using a microcontroller with only 8KB of flash memory and 512 Bytes of RAM – we wouldn’t want the timing table to fill the whole memory. To increase resolution between the table entries, the firmware performs linear interpolation to create more finely grained points in between.

Modes

The Servo Trigger comes with a couple of response modes that should be useful for most servo control needs, but, in the case they’re not a good fit, they can be modified.

The two versions of the product (standard and continuous rotation) are managed with a different build configuration for each version. You can select the build configurations in the toolchain tab of the project settings. If all you’re looking to do is transmute a regular Servo Trigger into a Continuous Rotation one (or vice versa), simply select the desired configuration.

alt text

The modes are configured by defining symbols that get passed to the compiler. All of the modal variations are present in the same source code, enabled using macros. You can select which modes get loaded by changing the compile-time symbols in the project. In Atmel Studio, select the “Servo Trigger” tab, then navigate to “Toolchain-> AVR/GNU C Compiler->Symbols” item.

alt text

If you're using the command-line tools, the symbol definitions are found in the compiler invocation in the Makefile.

The FSMA and FSMB symbols determine which modes are programmed on the Servo Trigger. FSMA defines the unjumpered (default) mode, and FSMB defines the jumpered mode. There are five modes currently defined in the source file.

  1. bistableFSM - The default mode - when the input is asserted, it moves from position A to B. While input is held, it will stay at B. When released, it moves back to A.
  2. oneshotFSM - Does a complete cycle every time the input is asserted - from A to B, then back to A.
  3. ctpFSM- A customization of the oneshotFSM for interactive artist Christopher T Palmer, which allows the B-to-A return cycle to be interrupted by a fresh input actuation.
  4. togglingFSM - Each time the input is asserted, it changes from A to B, or B to A. This mode is especially useful for driving continous rotation servos.
  5. astableFSM - When the input is asserted, it cycles back and forth between A and B. When the input is inactive, it sits where it was.

You can put any mode in either slot, or even put the same mode in both.


Implementation Details

As you may have guessed from the names, the modes are implemented using Finite State Machines. Finite state machines are a design concept the defines a set of states and a corresponding set of rules that determine how to transition between the states.

Within the Servo Trigger, each mode uses the same basic set of states, which in turn describe how it drives the servo. The states are:

  1. Sitting at position A.
  2. Moving from A to B.
  3. Sitting in position B.
  4. Moving from B to A.

The rules that define when the states can change can alter the behavior in significant ways. The different modes of the Servo Trigger are all implemented using the same states but with different transition rules.

FSMs are commonly illustrated using “bubble diagrams,” which draw the states as circles and the rules as arrows between the circles. Here’s the bubble diagram for the bistable FSM.

alt text

Building New State Machines

In the Servo Trigger, a state machine is implemented as a single function, which contains a switch statement wherein each state is a case. At the start of every PWM cycle, the state machine function is called to determine the pulse width and possibly move to new states.

If you want to implement a new state machine, it can be useful to start by drawing the bubble diagram.

If your new FSM is a slight alteration to an existing one, the next best place to look at the existing FSMs – it might be as simple as transplanting a state transition rule from one function to another. If your FSM is more ambitious, it’s still useful to read and understand how the FSM interacts with the rest of the firmware.

Your application may need a subtle variation of an existing FSM or a complete re-formulation. Since the source code is available, you’re welcome to modify it to suit your needs!

Starting From Scratch

The Servo Trigger can also be used as an ATTiny84 development board with three trimpots on it for any application you can dream up. Start with an empty project as described in the Getting Started section, and start programming at main()!

Resources & Going Further

Resources

  • The firmware was developed in Atmel Studio 6.2, and the controller was programmed with a JTAGICE3.
  • If you’re writing new features for the Servo Trigger, you’ll probably need to reference the Tiny84 datasheet.
  • The source code for the Servo Trigger can be found in this Github Repo.
  • Atmel Studio contains the AVR-GCC compiler.

Going Further

For more servo fun, check out these other SparkFun tutorials:

Mario the Magician's Magical Lapel Flower

A guest tutorial from the astonishingly talented Mario the Magician showing how to put together your own servo-controlled lapel flower.

SparkFun Blocks for Intel® Edison - PWM

A quick overview of the features of the PWM Block.

Servo Trigger Hookup Guide

How to use the SparkFun Servo Trigger to control a vast array of Servo Motors, without any programming!
New!

Continuous Rotation Servo Trigger Hookup Guide

How to use the SparkFun Continuous Rotation Servo Trigger with continuous rotation servos, without any programming!

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

Hobby Servo Tutorial

$
0
0

Hobby Servo Tutorial a learn.sparkfun.com tutorial

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

Introduction

Servo motors are an easy way to add motion to your electronics projects. Originally used in remote-controlled cars and airplanes, they now crop up in all sorts of other applications. They’re useful because you can instruct these small motors how far to turn, and they do it for you.

alt text

A typical hobby servo

You ordinary, small DC motor has two hookup wires and simply turns continuously when power is applied. If you want it to spin in the opposite direction, you reverse the power. If you want to know how far it has turned, you’ll need to devise a way to measure that.

alt text

DC motor (left) and hobby servo

In contrast, you instruct a servomotor where to turn using a command protocol. The servo has three wires – power and ground, plus a third wire, to carry those commands.

Suggested Reading

Servo Motor Background

In the most generic sense, a “servomechanism” (servo for short) is a device that uses feedback to achieve the desired result. Feedback control is used in many different disciplines, controlling parameters such as speed, position, and temperature.

In the context we are discussing here, we are talking about hobby or radio-control servo motors. These are small motors primarily used for steering radio-controlled vehicles. Because the position is easily controllable, they are also useful for robotics and animatronics. However, they shouldn’t be confused with other types of servo motors, such as the large ones used in industrial machinery.

alt text

An Assortment of Hobby Servos

RC servos are reasonably standardized - they are all a similar shape, with mounting flanges at each end, available in graduated sizes, from “ultra-nano” to “giant”. Servos often come with multiple attachments, such as wheels or levers, known as “horns”, than can be attached to the shaft, to fit the device they are operating.

alt text

Example Servo Horns

Electrical Connection

Most hobby servos use a standard type of 3-pin plug, with the same control signaling, which makes RC servos reasonably interchangeable.

The connector is a female, 3-pin, 0.1" pitch header. One thing that can be confusing is that the wiring color code isn’t always consistent – there are several color codes at play. The good news is that the pins are usually in the same order, just that the colors are different.

alt text

Servo Cables

The table below summarizes common color schemes. A useful mnemonic is that the most drab color (black or brown) is usually ground, and red is usually the power supply.

Pin NumberSignal NameColor Scheme 1
(Futaba)
Color Scheme 2
(JR)
Color Scheme 3
(Hitec)
1Ground Black BrownBlack
2Power SupplyRedRedRed or Brown
3Control SignalWhiteOrangeYellow or White

Servo connection Color Coding

Heads up! If you’re in doubt about your color scheme, check the documentation – don’t plug it in backwards!

Control signal

The third pin of the servo connector carries the control signal, used to tell the motor where to go. This control signal is a specific type of pulse train. The pulses occur at a 20 mSec (50 Hz) interval, and vary between 1 and 2 mSec in width. The Pulse Width Modulation hardware available on a microcontroller is a great way to generate servo control signals.

Common servos rotate over a range of 90° as the pulses vary between 1 and 2 mSec – they should be at the center of their mechanical range when the pulse is 1.5 mSec.

alt text

pulse to position

Powering Servos

In RC vehicles, the nominal battery voltage is 4.8V. It will be somewhat higher after a charge, and it will droop as the batteries discharge. As the voltage drops, the available torque also drops – if you’ve driven RC vehicles, you’re no doubt familiar with the loss of control that occurs as the batteries get weaker. It starts to feel sluggish just before it dies.

If you’re not using batteries, the 5VDC available from a garden variety power supply is a good option. If you’re using an Arduino or other microcontroller (such as the SparkFun Servo Trigger) to control your motor, the absolute maximum supply voltage that should be applied is 5.5 VDC.

Regardless of how you’re powering them, it’s worth noting that the current consumed by the motor increases as the mechanical loading increases. A small servo with nothing attached to the shaft might draw 10 mA, while a large one turning a heavy lever might draw an Ampere or more! If your power supply isn’t up to the task, a straining or stalled servo can cause the supply to sag, which may have other unpredictable repercussions, such as causing microcontrollers to reset.

Additionally, if you’ve got multiple servos, or in applications where the motors are moving non-trivial loads, it’s best to use heavy gauge wires and give each servo a direct connection to the power supply, rather than daisy-chaining power from one to the next. This configuration is commonly known as “star power.” If one servo causes the power rail to droop, it’s less likely to effect the others when each has a direct connection.

alt text

Star power.

When in doubt, grab a multimeter, measure the current consumed, and check whether VCC sags when the servos are turning.

Show Me The Guts

Internally, the mechanism of a servo motor uses a potentiometer attached to the rotating shaft to sense the position. It measures the width of the incoming pulse and applies current to the motor to turn the shaft, until the potentiometer indicates that the position corresponds to the incoming pulse width. This is a form of feedback control. The motor has received the desired position from the pulse width, and the actual shaft position is fed back to the circuit via the potentiometer. It compares the desired value to the actual value and drives the motor in the direction that causes actual to match desired.

Here are the insides of a servo that’s been dissected. You can see the gears, DC motor, position potentiometer, and a small PCB. The PCB has a chip on one side, possibly a small microcontroller or specialized servo IC.

alt text

Inside an RC servo

The other side of the PCB has some discrete transistors, probably in an H-bridge configuration, which allow the controller to steer current through the motor in either direction, for both clockwise and counterclockwise rotation.

alt text

Back of the PCB

A Handful of Distinctions

When you’re shopping for servos for your project, there are several parameters that you’ll want to keep in mind.

Range Constraints

The 1-to-2 millisecond pulse range is more of a convention than a hard-and-fast standard. Some servo motors respond to even shorter or longer pulses with an extended range of motion.

Be warned that there is a risk – this expanded range of motion isn’t universal. Some servos are mechanically limited to 90° rotation. Attempting to drive them beyond their limits can cause damage, such as stripped gears. The servo that we see dismantled here suffered exactly that fate.

alt text

The nub on the gear is used to constrain the range of rotation.

Position vs. Continuous Rotation

Moving even further from the 90° range, there are also full rotation, continuous rotation, or simply 360° servos. As the name states, the shaft turns continuously, making them useful as drive motors. Visually, they look just like regular servos.

alt text

Look carefully, and you’ll notice the “360°” mark on the packaging.

Rather than controlling position, the continuous rotation servo translates the 20 mSec pulse-train signal into the rotational speed and direction of the shaft. Otherwise, they’re very similar to regular RC servos – they use the same power supply, control signals, 3-pin connector, and are available in the same sizes as RC servos.

The overall speed is relatively low – around 60 RPM is a common maximum rate – if you need higher rotation speed, servos aren’t the best fit – DC gearmotors or brushless DC motors are more likely candidates, but they aren’t directly compatible with servo control signals.

alt text

Nulling Trimpot

On closer inspection, continuous rotation servos have one small difference from regular servos: they usually have a “nulling” trimpot, used to adjust their response to the control signal. It’s typically set so that a 1.5 mSec pulse stops the motor. Shorter pulses will cause it to turn counterclockwise, and longer pulses cause it to turn clockwise.

Analog vs. Digital

The pulse-controlled servos we’re discussing here are analog. There are also digitally-controlled servos that use a high-speed pulse train, and have a serial communication interface that allows more detailed configuration, typically with parameters that are tailored to RC vehicles.

Plastic vs. Metal Gears

One last thing to look at when considering a servo is the type of gears it contains.

Inexpensive servos (such as the one dismantled here) usually contain molded plastic gears, while more expensive servos have metal gears. Plastic gears are more likely to strip if the motor is jammed or overloaded. The old adage rings true: you get what you pay for.

alt text

Note the missing tooth at about 3:00 o'clock on the inner gear!

Deploying Servos

Traditional RC Application

As we stated in the introduction, the usual application of hobby servo motors is for steering radio-controlled vehicles.

alt text

RC transmitter (top left), with receiver and steering servo.

RC vehicles are controlled with a transmitter unit – the box with the joysticks and antenna. The transmitter sends control information to receiver modules (the orange box shown above), which connect to the servo motors. When the sticks on the transmitter are moved, the receiver generates corresponding pulses, instructing the motors to move.

Configuring older RC craft required a fair amount of patience, because adjusting the servos meant careful mechanical tweaking of the servo horns, mechanical linkages, and trim controls on the transmitter. Modern transmitters and receivers are microcontroller-based, tweaked through the LCD on the transmitter, or even a computer interface.

Controlling a Servo with Arduino

Because they move on command, servo motors are an easy way to add motion to any project. If you’re working with an Arduino-compatible platform, the Arduino servo library provides a ready-to-go servo pulse generation solution.

Materials

To build this example, you’ll need the following materials.

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
96
Servo - Generic (Sub-Micro Size)

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

TOL-12889
$5.95
11
Jumper Wires Premium 12" M/F Pack of 10

PRT-09385
$4.5
1

Hookup

Hooking a servo to a RedBoard is pretty straightforward. It only requires 3 connections.

alt text

Connecting a Servo to a RedBoard

In particular, notice that power to the servo motor is supplied from the VIN pin, which bypasses the onboard regulator. The onboard regulator in insufficient to drive anything but the smallest of servos. You’ll also notice that the project is powered with a 5V wall adapter. On the author’s workbench, performance was marginal when the board was powered by the USB port.

Firmware

With the circuit hooked up, load the following sketch.

NOTE: For this example, we're hosting the code on codebender, which not only features code-sharing, but also allows anyone to upload and debug Arduino sketches from within a web browser. Plus, it works on lower-tech machines, like Chromebooks!

There are codebender plugins for Chrome, Chromium, and Firefox. Visit the codebender plugin page for help installing the codebender plugin.

This sketch drives the servo back and forth.

Pay particular attention to the attach() call on line 26. It is using the optional min and max parameters, to constrain the pulses to the 1000 to 2000 microsecond (1 to 2 millisecond) range. As noted in the Range Constraints section above, driving a servo outside that range may damage the servo.

The Servo object can be a little bit confusing about the ranges and positions, particularly if the minimum and maximum pulses are defined in the `attach()` call. With the minimum and maximum defined, the parameters to the `.write()` method (ideally expressed in degrees) get retranslated to the constrained range. In the example, `write(0)` will result in a 1 millisecond pulse, and `write(180)` yields a 2 millisecond pulse. On an average servo, this translates to approximately 90° of motion, not the 180° that the call parameters would indicate.

The servo library also has a few other limitations. Most notably, it overrides analogWrite()on pins 9 and 10. For more information about the library, check the Arduino reference pages.

If things don’t seem to be quite right, please look through the troubleshooting section.

With the Servo Trigger

Having programmed a servo example from scratch in the last section, there’s another way to deploy servos that doesn’t require any programming.

alt text

The Servo Trigger

The SparkFun Servo Trigger is a small board dedicated to driving hobby servos. It has trimpots that allow you to set the servo positions and jump between the positions by actuating a switch. It is available in standard and continuous rotation versions. For more detailed information about the Servo Triggers, consult their respective hookup guides.

Troubleshooting

Regardless of how you’re driving it, servos sometimes require a little extra attention to get working. Here are a few troubleshooting tips.

  • Even unloaded servos can draw quite a bit of power. For full strength, you should be sure that your power supply can provide at least one Ampere per servo.
    • When the power supply isn’t up to the task, servos behave poorly. They’ll move more slowly than a properly powered servo.
    • Underpowered servos are prone to hunting, where they don’t move cleanly to the desired position, but instead move back and forth near that position. They might also audibly hum, or repeatedly reset.
    • In some circumstances, when the servos and processor are running off the same power supply, the servos can draw so much current (or put so much noise on the line) that it may cause your processor to reset or misbehave. The simplest solution to this issue is to run your processor and servos off separate power supplies (but be sure to have a common ground between them). More complex solutions involve power supply noise filtering techniques; Google for advice.
    • Powering your project via USB is only suitable for the smallest of servo motors. A medium servo easily exceeds the 100 mA available from a USB port.
    • If your power LEDs flicker when you try to actuate the servo, you’re in risky territory!
  • Servos have a maximum speed. If your servo is acting erratically, you may be trying to get it to switch from one position to another too quickly. Pausing between your commands gives the servo time to react.
  • As mentioned in the Range Constraints section, some servos have different ranges of movement.
    • When servos are driven past their end stops, they might hum, or grind their gears. Be careful if your servo starts clicking, a sign that the gears are binding.
    • If this will affect your project, look for a servo that is specified to provide 180° of rotation. Also, note that the Servo library’s attach() command allows you to fine-tune each servo’s min and max position, to help avoid driving it beyond the limits.

Happy Servoing!

Resources & Going further

Resources

Going further

  • The Wikipedia article on Radio control Servos contains more more detailed information and history of servos.
  • The uArm is a robotic arm that is driven by servo motors.
  • You can hack a regular servo to turn it into a continuous rotation one.
  • You can also remove the control board, turning a servo into a small DC gearmotor.

For more servo fun, check out these other SparkFun tutorials:

Mario the Magician's Magical Lapel Flower

A guest tutorial from the astonishingly talented Mario the Magician showing how to put together your own servo-controlled lapel flower.

SparkFun Blocks for Intel® Edison - PWM

A quick overview of the features of the PWM Block.

Servo Trigger Hookup Guide

How to use the SparkFun Servo Trigger to control a vast array of Servo Motors, without any programming!
New!

Continuous Rotation Servo Trigger Hookup Guide

How to use the SparkFun Continuous Rotation Servo Trigger with continuous rotation servos, without any programming!

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

How to Build a Remote Kill Switch

$
0
0

How to Build a Remote Kill Switch a learn.sparkfun.com tutorial

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

When Things Get Out of Control

The remote control kill switch

Kill Switches: It’s not a question of if, but when.

I highly recommend building something that scares you every once and awhile. In this case, I’m planning to enter an autonomous vehicle into the AVC in 2016, and it’s pushing my limits of comfort. A 1,000W motor with a large battery pack behind it mean that if things go wrong, it could be dangerous. For that reason, one of the new safety requirements of the AVC is a remote kill switch that allows the user to remotely power down the vehicle. This tutorial is my solution to safely disconnecting the motor from the motor controller in case things get out of control…

Here’s a quick video showing the kill switch controlling the 1kW motor (that just happens to be attached to a blender).

System Requirements

Here are the design requirements for my system. These should fulfill the kill switch safety requirements of the A+PRS rules.

  • If user presses the green button the system should energize the cut-off relay allowing power to flow to the motor.
  • If user presses the red button the system should de-energize the cut-off relay shorting the + and - of the motor causing the motor to brake.
  • If user presses the yellow button the system should assert a signal pin. This will be connected to the master controller to let it know that the race is in “yellow flag” mode.
  • If the vehicle fails to hear from the remote after a certain length of time the vehicle should go into safety-shutdown (de-energize the cut-off relay causing engine to brake).
  • If the remote fails to hear a response from the vehicle (out of range), then go into disconnect mode (blink all three LEDs).
  • If the link is re-established, then start in safety-shutdown mode.

I broke the killswitch system into two parts: the Vehicle Control Unit that lives on the vehicle and the Remote Control Unit that the human holds in their hand.

Remote control electronics

The electronics in the hand held remote (RCU)

Vehicle Control Electronics

The electronics on the vehicle (VCU)

VCU Parts List

Vehicle Control Unit Electronics

Click on the image to see the electronics without highlighting

The Beefcake Relay can be seen next to the larger, blue, 24V/80A relay. The VCU itself (the Pro Mini connected to the RFM69 breakout board) can be seen in the lower right corner.

Parts used on the Vehicle Control Unit:

I use our SparkFun RFM69 Breakout for a variety of reasons:

  • Encryption: This allows me to rest easy that no one else (ok I’m sure someone could hack it) will power up/down my car.
  • Software Defined Radio: The AVC has nearly 100 teams, all with their own radios and telemetry systems. It’s excellent to be able to sit in the 434MHz or 915MHz spectrum rather than the very crowded 2.4GHz arena.
  • Data Rate Scaling: The data rates can be reduced and frequency changed so that range can be increased quite significantly. UKHASnet has even setup a network of RFM69 based repeaters across Europe with transmission ranges pushing 65km (40miles)! I plan to be within sight of my autonomous power wheels at all times, but it’s good to know the 100mW transmission power of the RFM69 can do the job.
  • Library Support: The community has been writing various libraries to support the RFM type modules for years now. The latest I use for this project is RadioHead by AirSpayce. It does everything I need with some decent documentation to boot.

Vehicle Control Unit

Vehicle Control Unit Electronics

RFM69, Arduino Pro Mini, and two relays make up the VCU

The Vehicle Control Unit (VCU) sits between the motor controller and the motor. The VCU only connects the motor to power if the Remote Control Unit (RCU) is powered up and transmitting the ‘User pressed the green button, go for it’ signal.

I’ve decided to run my PRS vehicle at 48V, which is the higher end of allowed system voltages. Luckily, there are some really nice DC to DC buck converters to get 48V down to 24V (to control the cut-off relay) and 5V (to power the 3.3V Pro Mini). See the parts list for links to the particular ones I used.

Relay up close

Under load and at top speed, the motor controller will be putting out 10’s of amps at 48V. The VCU needs a substantial relay big enough to handle that load. Some of the lowest cost, highest current relays I could find were 24V relays. Because my 3.3V/8MHz Pro Mini can only turn on/off 3.3V, I decided to use a two relay setup.

Bootstrapped two relay setup

The relay setup

This is an example of a ‘bootstrapped’ relay system. Bootstrapping allows a small signal to control big loads. The 3.3V signal from the Pro Mini can’t control the large 24V relay directly, so I used the 3.3V signal to control a 5V relay to activate the 24V relay.

When we want to allow power to the motor, the Pro Mini activates the Beefcake Relay with a 3.3V signal (KILL_LOW goes from 0 to 3.3V). This signal grounds the Q1 transistor allowing current to flow across the coil in R1. Next, the reed on R1 moves from the normally closed position (where it is connected to nothing) to the normally open position. Current begins to flow freely from 24V through the R2 coil to ground. This flow causes the reed on R2 to move from the normally closed position to the upper position connecting the + lead of the motor to the +M on the motor controller. In real life, this whole process produces a most satisfying thunk. Note this does not power the motor; rather, it allows the motor controller to control the motor. If the motor controller is outputting 0% power, the motor will just sit happily still.

48V / 24V / 5V Subsystems

You may be wondering why I am running a 24V subsystem? For my A+PRS entry, I am controlling the steering with a 12V linear actuator that I am over-driving with 24V. The actuator is very strong but slow, and the extra voltage drives the actuator much faster. The 24V cut-off relay (R2) fit nicely into this design as well.

Motor Braking

When R2 is in the normally closed (unactivated) position, the + and - of the motor are shorted together. This is called motor braking. To see what this feels like, find a large DC motor, and try spinning the axle. It should be relatively easy. Now, short + and - of the motor together; the axle will be considerably harder to turn. By setting R2 up this way we have another layer of safety in that, if everything goes wrong and the Kill Switch goes haywire, the system should fail safe, turn off all the relays, short the motor and brake to a stop. It is not yet clear to me how aggressive this braking power is. If the braking is too abrupt (as in it ejects the human rider) it could be more dangerous than it is helpful, in which case I will disconnect the MOTOR- from the lower pin of R2 and let the motor freewheel in the event of a safety shutdown. That way the human passenger has the ability to control braking with the brake rather than something they cannot control.

RCU Parts List

Inside the kill switch

Inside the remote control unit

Parts Used on the Remote:

Remote Control Unit

The remote control kill switch

The remote control kill switch

The RCU is the thing that the user holds in their hand and jams the red button in case the autonomous vehicle becomes sentient, or is just doing something it shouldn’t.

Schematic for kill switch

Schematic for kill switch

Let’s start with the simple bits: The LEDs are simply on/off and don’t need PWM pins. I chose to connect the LEDs to pins 3, 4, and 5 because it allowed me to solder in a 3-pin JST connector. The three buttons within the switch station are the Normally Open (NO) type. I wired them to pins 6, 7 and 9 with 8 serving as the ground pin. I did this because I ran out of GND pins on the Pro Mini. You can use a GPIO as ground, you just set it as an output and LOW. Also, by creating a bank of four pins it allowed me to solder a 4-pin JST directly to the Pro Mini.

The RFM69 is wired according to Mike’s excellent hookup guide. Note: The connection from pin 2 on the Pro Mini to DIO0 on the RFM69 is required and serves as the interrupt from RFM to Pro Mini. You cannot use a different pin on the Pro Mini because pin 2 is a hardware interrupt pin, and the library depends on interrupts.

The remote needs to have a battery! I used the 3.7V 850mA LiPo. The average current draw is about 42mA, so this should last for around 20 hours on a charge. I didn’t do any power minimization efforts because 20 hours was plenty for my purposes. To avoid having to open and close the enclosure to charge the battery, I installed a LiPo charger with miniB connector. Plugging a miniB cable in will charge the battery any time, and pressing S4 (a latching switch) will turn on/off the remote. Note that if the remote is turned off, the vehicle will go into automatic safety shutdown (a good thing).

I really enjoy the quality and feel of the three buttons in the Switch Station, but they are very big and packing all the electronics into the enclosure is a challenge. If I were to build another remote, I would look for a better trade off of more room vs quality (there are many low quality switch stations on Amazon with more room inside the enclosure).

Code

You can find the code for the RCU and VCU in this github repo. Here is the code via Codebender as well:

Above is the code for the VCU

Above is the code for the RCU

The RCU waits for the user to press a button and monitors the link to the VCU. If the link is not detected, the RCU flashes all three LEDs letting the user know the VCU is offline (either unpowered or out of range). Once the user presses the green button, the RCU turns the LED to green and begins transmitting the ‘Ok, go for it’ signal. Once received, the VCU sets the KILL_LOW pin to high, thus activating both relays and connecting the motor to the motor controller.

Certain settings can be changed in the code for your specific application:

  • MAX_DELIVERY_FAILURES: It turns out that the RF link will drop a packet every once and a awhile, so the MAX_DELIVERY_FAILURES is set to three. If we don’t get a valid send/response after 3 tries, the system goes into disconnected mode. Setting this lower than 3 means the car may shutdown prematurely because we had some RF traffic/collisions.
  • CHECKIN_PERIOD: The remote will broadcast the system state every 25ms.
  • MAX_TIME_WITHOUT_OK: The vehicle will shut down if it doesn’t hear from the remote after 250ms.

These settings worked well for me and created a responsive, dependable link that shut the vehicle down within 250ms if things went pear-shaped. You may need to adjust these settings for other, longer-range applications.

Future Improvements - Reverse!

The kill switch is working nicely over a long range and I have moved on to other challenges on the vehicle. Testing will tell if motor braking is a good thing or not. I’m also pretty sure Mr. Auto is going to drive me into the barrier quite often during testing and I’ll need the ability to stop and back up. As designed, the system doesn’t have the ability to reverse. For that I’ve looked into continuous duty solenoids. These are common on golf carts and other small DC vehicles. I’m waiting to find a cheap, used one somewhere to keep from going over the $500 PRS budget.

I hope you can learn a bit from my setup. If you have similar projects please link them in the comments. One of the great aspects of the AVC is all the great stuff I learn from other people so please let me know how you did your kill switch!


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

GPS Differential Vector Pointer

$
0
0

GPS Differential Vector Pointer a learn.sparkfun.com tutorial

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

Introduction

In this tutorial you’ll learn how to use GPS receivers to have two objects, a base and a target, point towards one another. This can be used to aim sensors, antennas, lasers, etc. from one object to another over long distances.

Project Background

GPS technology is a very useful and elegant technology. The satellites used in the GPS network do most of the work so that the GPS receiver can be made small and simple. As GPS technology becomes more and more accurate, applications in many areas have really taken off. Some of these include driver-less cars, mission planning for UAVs, assisted landing of commercial aircraft and many more. GPS receivers vary in cost depending on accuracy and what other functions they provide, so the right receiver needs to be chosen for the desired application. In this project, I am demonstrating that an expensive receiver is not necessary to create an amazing project.

This project began as a proof of concept for the ANACONDA 2014/2015 Aerospace Senior project whose mission was to:

“Design and construct an autonomous tracking and communication support system for an antenna to be used to track unmanned aircraft during flight.”

If you want to check out this and other projects, follow the link below to the CU senior projects page, and go to the 2015 projects page.

CU Aerospace Senior Projects

Project Overview

The underlying principle here is that, if two GPS locations are provided by two different receivers, a position vector can be calculated between them. This can be used to aim a directional antenna (or in the case of this project a laser) from one object (the base station) to the other object (the target) at any distance, which is only limited to your ability to provide the base station with the target’s GPS location. The target’s only purpose is to receives its GPS location, parse the data and send that back to the base station. The base station then receives the target’s GPS location and compares it to its own GPS location to calculate the positional vector. The base station also includes a 180 degree servo and a laser, so the direction can be visualized.

System Diagram

Block diagram of the system described above.

Knowing the horizontal and the vertical difference between points, you can use the inverse tangent function to give you the pointing angle needed to control the mechanism. See the image below.

Theory Diagram

The final product looked like the following:

Final Base and Target

The Target (left) and the Base Station (right).

This tutorial will go over how to replicate this system.

Suggested Materials

To follow along with this tutorial, we recommend the following supplies:

Electrical Supplies

Here is a list of all the SparkFun materials you will need for this project:

Mechanical Supplies

You will need some hardware to mount electronics in the final system:

  • Access to a 3D printer
  • Tripod with universal camera mount platform
  • Magnetic compass
  • Mounting Hardware
    • 4 X 8-32 Machine screws
    • 3x 1/2” spacers with #5 sized through hole
    • 3x 2-56 ½” Machine screws
    • 3x 2-56 ¾” Machine screws
    • 6x 2-56 Hex Nuts
    • 6x 1-72 ½” Flathead screws
    • 6x 1-72 Hex Nuts
    • 2 x 0-80 Flathead screws
    • 1 5/16th O-ring with 1/16th wall thickness or less

3D Models

A custom enclosure was created for each piece in this project. These files are provided in the link below, if you wish to download and print them. These files can also be found in the 3D Models section.

3D Model STL Files

Suggested Reading

Before embarking upon this tutorial, you may find the following links useful:

Serial Communication

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

GPS Basics

The Global Positioning System (GPS) is an engineering marvel that we all have access to for a relatively low cost and no subscription fee. With the correct hardware and minimal effort, you can determine your position and time almost anywhere on the globe.

XBee Shield Hookup Guide

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

Exploring XBees and XCTU

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

3D Models

For this project, the cases and laser mount were all created on a student edition of SolidWorks to be printed using a 3D printer. The printer used in this project is an XYZ da Vinci 1.0 AiO. There are four pieces that need to be printed for this project, and their files are included below, saved as .STL.

If you have not done so already, the 3D model files can be downloaded from the following link.

3D Model STL Files

Target

Target

Base Bottom

Base Bottom

Base Top

Base Top

Laser Mount

Base Laser Mount

Electronics Assembly

All the electronics in this project plug directly into pins on the XBee Shield (with the exception of the laser diode), which makes this part pretty straightforward. I have designed this mechanism so that the connections are not permanent and can be taken apart, but you can solder the connections instead, if desired.

The first step is to configure both XBees so that they are set up on the right channel. This is described in detail in this tutorial.

Once everything is configured, you will need to create two identical assemblies of the RedBoard with the XBee shields attached. Stackable headers will need to be soldered onto the XBee Shield, so that it can be mounted on top of the RedBoard and wires can still be attached. A detailed walk-through of this process is described here.

XBee Shield Assembly

Note: You will have to take off the XBee Shields to mount the RedBoards in the final system.

Next, prepare the wires of the two GPS receivers and the servo so they can easily be plugged into the shield. I cut off the existing connectors and soldered them to male jumper wires for easy pluggability. The wires for the target GPS receiver can be made shorter so you don’t have excess wire. Make sure you leave enough length to reach the pins from where the receiver will be mounted.

Preppedcables

The last step will be to connect the Laser diode. To do this, you will first need to solder stranded wire to the two holes located on the laser PCB. Ensure they are attached to the correct pads, as shown here. Take care when soldering these pads as too much heat can damage the laser electronics.

Laser Wire Connections

Because the laser will be moving, these wires should be soldered rather than just plugged in. This will be done on the XBee shield used on the Base. The following diagrams show how everything should be connected. Note that the LED in the diagram represents the laser.

Fritzing Diagram

Click the image for a closer look.

System Assembly

This section will cover how to install the electronics in the 3D printed enclosures.

Base Station Bottom

Attach the RedBoard to the base using 32-56 ¾” machine screws with the three spacers in between so it is elevated off the bottom of the case. This is to ensure that the mounting hole is available, which you may need depending on your tripod mounting situation.

Spacers

Connect the 9V battery. Mount the battery enclosure onto the holes located on the wall of case.

Mounted Parts

Depending on your tripod, this step may be different. The tripod used in this guide had a piece with the mounting screw that can be threaded into the available mounting hole and works quite nicely.

Tripod Mount

Base Station Top

Place the servo in the available cavity with the gear closer to the GPS cavity. Once in place, screw the four 8-32 screws into the available holes on the servo. You shouldn’t need nuts for the other side since the holes are close fit and the ABS used is soft and allows them to easily thread themselves into place. If the servo moves around too much, you can add nuts for stability.

Servo Mount

Attach the circular servo disk (a.k.a. horn) to the laser mount aligning the hole on the bottom of the laser mount with the hole on the disk. Attach this by placing two 0-80 Flathead screws through the countersunk holes within the laser cavity. You may need to open up the holes on the circular wheel since they will be used as pins, and you will not be able to screw them in. These are to ensure that the two parts are connected in the right orientation, and, if loose, you may need to use an adhesive to attach these.

Laser Mount

Next, attach this assembly to the servo. Slide the circular disk back onto the servo, then screw it to the servo, using to the available hole in the laser mount to access it with a screw driver.

Mount Servo

Heads up! At this point, it is best to ensure that the servo is going to sweep the full 90 dgrees in a symmetrical fashion. The Sweep example sketch, which comes with the Arduino IDE by default, can help you out with this. Make sure the servo is in its center position when you mount the laser enclosure. Any error can throw off the whole system.

With the laser wired to the shield, push the laser through the hole in the top platform and into laser mount. Place the O-ring over exposed part of the laser to hold it in place. This can be a little finicky, so you can use hot glue to hold it in place.

Place Laser

Attach the GPS receiver tot he indent made on top of the case. Again, make sure the wires stay inside the enclosure.

Attach GPS

Attach the XBee Sheild to the RedBoard, if you haven’t do so already, connect the wires, and you are good to go.

Full Base

Click image for larger view.

Target

Place the bare RedBoard in target case so that the USB port is facing the opening, and place 3 2-56 ¾” Machine screws into any three available holes. Use the corresponding nuts to secure them in place from the back.

Attach the 9V Battery holder using 3 1-72 ½” flathead screws, and secure them using the corresponding nuts on the back.

Mounted Parts

There is a cavity made for the GPS receiver sunk into the base. Use a glue gun or other adhesive method to hold it in place. Once everything is attached, place the XBee Shield back on the RedBoard and connect everything as shown in the Electronics Assembly section.

Full Target

Code

Here is the basic code to get this system functioning. You will need to upload the files to their respective systems. There is a lot of room for you to play around with these to improve the speed or accuracy of the system. You will also need to include these libraries, which, depending on what version of the Arduino IDE you have installed, may already be included as a default library.

For help installing external Arduino libraries, visit this tutorial. Once all the libraies are installed, program each sketch from below on to the respective RedBoard.

Target Code

language:c
/*GPS Vector Pointer Target
   This sketch simiulates any system that has a GPS beacon and has the ability to
   broadcast this information for other systems to pick up. This could be a plane/drone
   a car/rover or even a solar panel on a space elevator climber. This recieves updating GPS
   coordinates and from an attached GPS reciever, parses the incoming NEMA data and
   send that information using an Xbee connection to the base station.
*/


/*We need to include a couple outside librarys. TinyGPS.h enables a set of tools to
   parse NEMA data into usable GPS info such as latitude and longitude. SoftwareSerial.h gives
   this sketch the ability to use standard DIO pins as serial ports to communicate between
   other microcontrollers. in this case we need one for reciving NEMA data and one
   to communicate using the Xbee. The standard UART on the redboard is reserved for programming
   and as a serial connection to the consol for Control and information purposes.
*/
#include <TinyGPS.h>
#include <SoftwareSerial.h>

//At this point we will define the pins used for serial communication, we
// do this so its easy to change them if needed.
#define gpsRXPIN 5
#define gpsTXPIN 4//this one is unused and doesnt have a conection
#define XbeeRXPIN 2//in this case we will also not use this pin
#define XbeeTXPIN 3

//Next we define the objects used in this sketch this includes two SoftwareSerial objects
//one for refering to the GPS connection and one for the Xbee connection. we also create an
//object that allows us to access the TinyGPS library
SoftwareSerial tGPS (gpsRXPIN, gpsTXPIN);
SoftwareSerial XBee (XbeeRXPIN, XbeeTXPIN); // RX, TX
TinyGPS gps;

//Global variables and functions are declared here, this allows them to be called anywhere
//within the code and is helpful for passing data out of functions. Dont get in the habit \
// of using these though because as your code gets longer its easy to lose track of where
//you are changing these variables and can lead to a headach when a problem arises.
float TargetLat;
float TargetLon;
int Status = 0;
//Function headers can be placed here so that functions can be placed below your setup
//and loop function for a more logical flow of information.
void SendGPSLocation(float Lat, float Lon, int Status);
void getGPS( float* lat, float* lon, int* Status);

void setup() {
  //This function is run before the your program begins to loop, here we define the status
  //of pins that are used for inputs and outputs
  pinMode(gpsRXPIN, INPUT);
  pinMode(XbeeTXPIN, OUTPUT);
  //Next communication begins between the three systems along for the baud rate for each
  //some of these can handle a larger baud rate but you need to make sure they match what
  //they are communicating with
  tGPS.begin(9600);
  Serial.begin(9600);
  XBee.begin(9600);
  while (!Serial) {}
  //a message is printed to the console showing that everything is initailized and
  //the program is now functioning
  Serial.println("Hello");

}

void loop()
//This
{
  // Recieves NEMA data from GPS reciever and Parses Latitude and longitude data
  //returns information using pointers including info on stagnant data

  //because only one Software serial port can be read at the same time we must tell
  //the redboard what to listen to. Here we tell it to listen to the tGPS serial object
  //then call the function that will recieve and parse the signal from the GPS reciver
  tGPS.listen();
  getGPS(&TargetLat, &TargetLon, &Status);
  //Print status to console to know if you are getting good data or not.
  //No Lock = 0, Old Data(>5 sec old) = 1, Good Data = 2
  Serial.println(Status);
  Serial.println(TargetLon);
  Serial.println(TargetLat);
  //we dont want to waste precious processing space or battery power by sending bad data
  //back to the base station so only when the Status variable = 2 for good data we will send
  //the information to the base station
  if (Status == 2)
    //if the data is up to data, send it to base station
  {
    //Switch Software serial port to the Xbee
    XBee.listen();
    //wait for it to become availible(might be unneccesary
    while (!XBee) {}
    //call the function that turns the info into a string and sends it to base station
    SendGPSLocation(TargetLat, TargetLon, Status);
    //wait for 2 seconds to ensure base station does not get overloaded
    delay(1000);
  }



}


void SendGPSLocation(float Lat, float Lon, int Status)
/* this sketch will send values from one modual to another(starting by sending values to XTCU)
  This will eventually send parsed GPS data from the target modual to the base station modual
*/
{
  // Convert GPS data from float into string
  String latData = String(Lat, 5);
  String lonData = String(Lon, 5);


  //Concatinate needed data into one string that begins with $ so the parser knows when data starts
  String GPSdata = "$";

  GPSdata += latData;
  GPSdata += ",";
  GPSdata += lonData;
  //Send Data as string "xx.yyyyy,-xxx,yyyyy" not able to handle changing signs
  //but since this is a demo project thats ok
  XBee.println(GPSdata);
  //Print GPS string to console for debugging
  Serial.println(GPSdata);

}


void getGPS( float* lat, float* lon, int* Status)
/*This function switches the softserial pin to the one used for GPS then recieves NEMA data from a GPS
  reciver which is passed into a TinyGPS Object and parsed using its internal functions for $GPRMC info. This function uses
  pointers to pass infomation to pass back to parent function which includes Latitude, longitude,( velocity,
  heading) and the status of the GPS signal.

  function call where variables can be nammed whatever they want as long as they have &:
  getGPS(&latitude, &longitude, &Status);
*/
{
  //Initilize pin to recieve NEMA (have to do it here because we need to switch between
  //software serial pins (if time permits interrupts could be used)
  //pinMode(gpsRXPIN, INPUT);
  // tGPS.begin(9600);
  //define local variables
  float flat;
  float flon;
  unsigned long fix_age;

  //look for serial data from GPS and loop untill the end of NEMA string
  while (tGPS.available())
  {
    //Serial.println("YO");
    int c = tGPS.read();
    if (gps.encode(c));
    {}
  }
  //(is this the correct order for this?^^)

  //Pulled parsed data from gps object
  gps.f_get_position(&flat, &flon, &fix_age);
  *lat = flat;
  *lon = flon;
  //  float falt = gps.f_altitude(); // +/- altitude in meters
  //  float fc = gps.f_course(); // course in degrees
  //  float fmps = gps.f_speed_mps(); // speed in m/sec

  // check if data is relavent
  if (fix_age == TinyGPS::GPS_INVALID_AGE)
    //No fix detected;
  {
    *Status = 0;
  }

  else if (fix_age > 5000)
    //Warning: possible stale data!;
  {
    *Status = 1;
  }

  else
    //Data is current;
  {
    *Status = 2;
  }

}

Base Code

language:c
/* GPS Vector Pointer Base Station
  By: Dustin Larsen
  Abstract Eagle Technologies
  Date: March 20th, 2016
  (Beerware license): This code is public domain but you enjoy the project and we meet someday buy me a beer.

    This sketch controls the Base station functionality and includes the ability to
    recieve GPS coordinates from the target object and compare it to the GPS coordinates
    of the Base station GPS Location. The location of the base station will be calculated
    using a function that increases its accuracy over time by storing all previous values.
    The direction vector between the base station and the target object will then be calculated
    and a servo will be commanded to point a LASER in the direction of the target object.
*/

// gives the ability to use standard DIO pins as serial ports to communicate between other microcontrollers.
#include <SoftwareSerial.h>
//enables a set of tools to parse NEMA data into usable GPS info such as latitude and longitude
#include <TinyGPS.h>
//Enables the use of the servo Library to easily control an analog servo
#include <Servo.h>;


//pins are defined here so they can be easily referenced and changed if needed
#define gpsRXPIN 5
#define gpsTXPIN 4
#define XbeeRXPIN 2
#define XbeeTXPIN 3
#define ServoPIN 9


//define the objects for the included librarys used in this sketch
SoftwareSerial bGPS (gpsRXPIN, gpsTXPIN);
SoftwareSerial XBee (XbeeRXPIN, XbeeTXPIN);
TinyGPS gps;
Servo servo1;



//Global variables are declared here, this allows them to be called anywhere
//within the code and is helpful for passing data out of functions.
float baseLat = 0;
float baseLon = 0;
float baseavgLat;
float baseavgLon;
float targetLat = 0;
float targetLon = 0;
int Status = 0;

//Function headers introduced so functions can be called from anywhere in your sketch for a more logical flow of information.
void getGPS( float* lat, float* lon, int* Status);
void RecieveGPSLocation(float* latData, float* lonData);
void ServoPointCommand(double baseLat, double baseLon, double targetLat, double targetLon);

void setup() {


 //define the status of pins that are used for inputs and outputs
  pinMode(XbeeRXPIN, INPUT);
  pinMode(gpsRXPIN, INPUT);

 //Begin communication with the XBee, the GPS reciver and the Serial console
  XBee.begin(9600);
  bGPS.begin(9600);
  Serial.begin(9600);
  //while (!Serial) {}
  //a message is printed to the console showing that everything is initailized and
  //the program is now functioning
  Serial.println("goodnight moon!");
 }

void loop() {

  //Software serial can only look at one input at a time so we must tell it what to listen to
  //here the sketch switches software serial to Xbee
  XBee.listen();
  //wait for buffer to fill
  delay(2);
  //recieve and parse target GPS location
  RecieveGPSLocation(&targetLat, &targetLon);


  //Switches software serial to GPS
  bGPS.listen();
  //wait for buffer to fill
  delay(2);
  //loops through getGPS function so that it does not stop listening before
  //current data can be gathered
  int  count = 15;
  while ( count > 0) {
    getGPS( &baseLat, &baseLon, &Status);
    count-- ;
    //if data up to date break out of the loop and reset the count
    if (Status == 2)
    {
      bothGPSknown();
      count = 0;
      break;//redundant?
    }
  }
}

void bothGPSknown()
{
  //once both sets of coordinates are known stop listening to GPS and attach
  //the servo so that it does not recieve noise from GPS reciver(It will twich randomly if you dont do this)
  XBee.listen();
  servo1.attach(ServoPIN);
  //Average the the current base data with the existing, this will increase the accuracy over time since
  //the base hardware will not move even if the GPS data jumps around
  baseavgLat = (baseLat + baseavgLat) / 2;
  baseavgLon = (baseLon + baseavgLon) / 2;

//Print out info to Serial Console
  Serial.print("Base Latitude:");
  Serial.println(baseavgLat, 5);
  Serial.print("Base Longitude:");
  Serial.println(baseavgLon, 5);
  Serial.print("Target Latitude:");
  Serial.println(targetLat, 5);
  Serial.print("Target Longitude:");
  Serial.println(targetLon, 5);
  //passes this data GPS data to control servo
  ServoPointCommand(baseavgLat, baseavgLon, targetLat, targetLon);
  //wait after pointing angle commanded
  delay(1000);
  //Detach servo to prevent jittering while not in use
  servo1.detach();
  //Define status of data as stale
  Status = 1;
}

void RecieveGPSLocation(float* latData, float* lonData)
/*
   This function looks for a current GPS value to be recieved from target which then reads nthe
   compound string and places latitude and longitude data into their respective strings
   then converts those strings to float to pass variables back to main loop using pointers
*/
{
  //declares and clears variables used in this function
  String GPSdata = "";
  char inChar;
  String A = "";

  //reads buffer till string identifier is seen
  while ( inChar != '$')
  {
    inChar = XBee.read();
  }
  //once data string is identified loop till "\n" is seen which identifies the end of the data

  while ( inChar != '\n' ) {
    //wait for buffer to fill
    delay(1);
    //read next character
    inChar = XBee.read();
    //concatinate into GPSdata string
    GPSdata += inChar;
  }



  //Parse Latitude data from string and send it back to main loop
  A = GPSdata.substring(0,  9);
  *latData = A.toFloat();
  //Clear string A
  A = "";
  //Parse Longitude data from string and send it back to main loop
  A = GPSdata.substring(9);
  *lonData = A.toFloat();

}

void getGPS( float* lat, float* lon, int* Status)
/*This function switches the softwareserial pin to the one used for the GPS reciver then recieves the NEMA data
  which is passed into a TinyGPS Object and parsed using its internal functions for $GPRMC info. This function uses
  pointers to pass infomation to pass back to parent function which includes Latitude, longitude,and Status of the GPS signal.

  function call where variables can be nammed whatever they want as long as they have &:
  getGPS(&latitude, &longitude, &Status);
*/
{
  //define local variables
  float flat;
  float flon;
  unsigned long fix_age;

  //look for serial data from GPS and loop untill the end of NEMA string
  while (bGPS.available())
  {
    int c = bGPS.read();
    if (gps.encode(c));
    {
    }
    delay(2); //this delay is a fine lie, may have problems later
  }

  // Use tinyGPS library to parse information
  gps.f_get_position(&flat, &flon, &fix_age);
  *lat = flat;
  *lon = flon;

  // check if data is relavent and print update to serial port
  if (fix_age == TinyGPS::GPS_INVALID_AGE)
    //No fix detected;
  {
    *Status = 0;
    //delay(10);
    //Serial.println("");
    Serial.println("no GPS data recieved from base");//doesnt work when I take out print functions
  }

  else if (fix_age > 5000)
    //Warning: possible stale data!;
  {
    *Status = 1;
    // delay(10);
    Serial.println("Stale GPS data recieved from base");
  }

  else
    //Data is current;
  {
    *Status = 2;
    //delay(10);
    //Serial.println("");
    Serial.println("GPS data recieved from base");
  }

}

void ServoPointCommand(float baseLat, float baseLon, float targetLat, float targetLon)
/* THis function will take the cordinates of the base station and the target object
    then calculate the angle between then using the inverse tangent function.
*/
{
  //Define Local variables
  float latDiff, lonDiff, theta;
  double servoPosition;

  //Calculate difference
  latDiff = (targetLat - baseLat);
  lonDiff = (targetLon - baseLon);
  //Calculate angle
  theta =   atan2 (latDiff, lonDiff);
  theta = theta * 180 / 3.145;

  //Print result to console
  Serial.println("latDiff");
  Serial.println(latDiff);
  Serial.println("lonDiff");
  Serial.println(lonDiff);
  Serial.println("theta");
  Serial.println(theta);

  //Map the calculated angle into a value the servo will understand
  servoPosition = map(theta, -180, 0, 0, 180);
  servoPosition = constrain(servoPosition, 0, 180);
  servo1.write(servoPosition);

}

Operation

To ensure the system aligns with the earth’s frame of reference and is in the correct orientation, use the compass to line the arrow on the Base Station top with true North. Once powered up, both systems will sit idle as they acquire a satellite lock. Once both have established a lock, which may take up to a minute, the servo will point to where it interprets the target object is. This will update continuously to point at the most recent location of the target object. If the angle is substantially off or the servo is maxed out in one direction you might need to make sure the whole system is pointing in the right direction since it is limited in which direction it works.

Warning! Laser can be harful to eyes so if you are the one holding the target object it would be a good safety measure to have laser glasses for 532nm wavelength.

Final Base and Target

Final Base (right) and Target (left).

Resources and Going Further

Thanks for Reading!

The code for this project can be found on the GitHub Repository.

For more GPS fun, check out these other SparkFun tutorials:

GPS Shield Hookup Guide

This tutorial shows how to get started with the SparkFun GPS Shield and read and parse NMEA data with a common GPS receiver.

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.

MG2639 Cellular Shield Hookup Guide

Learn how to equip your Arduino with an MG2639 Cell Shield and use it to send SMS or TCP via GPRS.

GPS Logger Shield Hookup Guide

How to assemble and hookup the SparkFun GPS Logger Shield. Never lose track of your Arduino again!

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

Viewing all 1123 articles
Browse latest View live